Programs & Examples On #Object oriented database

Parse HTML table to Python list?

You should use some HTML parsing library like lxml:

from lxml import etree
s = """<table>
  <tr><th>Event</th><th>Start Date</th><th>End Date</th></tr>
  <tr><td>a</td><td>b</td><td>c</td></tr>
  <tr><td>d</td><td>e</td><td>f</td></tr>
  <tr><td>g</td><td>h</td><td>i</td></tr>
</table>
"""
table = etree.HTML(s).find("body/table")
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
    values = [col.text for col in row]
    print dict(zip(headers, values))

prints

{'End Date': 'c', 'Start Date': 'b', 'Event': 'a'}
{'End Date': 'f', 'Start Date': 'e', 'Event': 'd'}
{'End Date': 'i', 'Start Date': 'h', 'Event': 'g'}

How to fetch JSON file in Angular 2

For example, in your component before you declare your @Component

const en = require('../assets/en.json');

How to do a LIKE query with linq?

Try using string.Contains () combined with EndsWith.

var results = from c in db.Customers
              where c.FullName.Contains (FirstName) && c.FullName.EndsWith (LastName)
              select c;

RESTful Authentication

The 'very insightful' article mentioned by @skrebel ( http://www.berenddeboer.net/rest/authentication.html ) discusses a convoluted but really broken method of authentication.

You may try to visit the page (which is supposed to be viewable only to authenticated user) http://www.berenddeboer.net/rest/site/authenticated.html without any login credentials.

(Sorry I can't comment on the answer.)

I would say REST and authentication simply do not mix. REST means stateless but 'authenticated' is a state. You cannot have them both at the same layer. If you are a RESTful advocate and frown upon states, then you have to go with HTTPS (i.e. leave the security issue to another layer).

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

This is due to the series df[cat] containing elements that have varying data types e.g.(strings and/or floats). This could be due to the way the data is read, i.e. numbers are read as float and text as strings or the datatype was float and changed after the fillna operation.

In other words

pandas data type 'Object' indicates mixed types rather than str type

so using the following line:

df[cat] = le.fit_transform(df[cat].astype(str))


should help

What does <value optimized out> mean in gdb?

It means you compiled with e.g. gcc -O3 and the gcc optimiser found that some of your variables were redundant in some way that allowed them to be optimised away. In this particular case you appear to have three variables a, b, c with the same value and presumably they can all be aliassed to a single variable. Compile with optimisation disabled, e.g. gcc -O0, if you want to see such variables (this is generally a good idea for debug builds in any case).

Using PHP variables inside HTML tags?

I recommend using the short ' instead of ". If you do so, you wont longer have to escape the double quote (\").

In that case you would write

echo '<a href="http://www.whatever.com/'. $param .'">Click Here</a>';

But look onto nicolaas' answer "what you really should do" to learn how to produce cleaner code.

WebDriver - wait for element using Java

Above wait statement is a nice example of Explicit wait.

As Explicit waits are intelligent waits that are confined to a particular web element(as mentioned in above x-path).

By Using explicit waits you are basically telling WebDriver at the max it is to wait for X units(whatever you have given as timeoutInSeconds) of time before it gives up.

Regular expression search replace in Sublime Text 2

Note that if you use more than 9 capture groups you have to use the syntax ${10}.

$10 or \10 or \{10} will not work.

Calculate mean and standard deviation from a vector of samples in C++ using Boost

If performance is important to you, and your compiler supports lambdas, the stdev calculation can be made faster and simpler: In tests with VS 2012 I've found that the following code is over 10 X quicker than the Boost code given in the chosen answer; it's also 5 X quicker than the safer version of the answer using standard libraries given by musiphil.

Note I'm using sample standard deviation, so the below code gives slightly different results (Why there is a Minus One in Standard Deviations)

double sum = std::accumulate(std::begin(v), std::end(v), 0.0);
double m =  sum / v.size();

double accum = 0.0;
std::for_each (std::begin(v), std::end(v), [&](const double d) {
    accum += (d - m) * (d - m);
});

double stdev = sqrt(accum / (v.size()-1));

MySQL Error #1133 - Can't find any matching row in the user table

I encountered this issue, but in my case the password for the 'phpmyadmin' user did not match the contents of /etc/phpmyadmin/config-db.php

Once I updated the password for the 'phpmyadmin' user the error went away.

These are the steps I took:

  1. Log in to mysql as root: mysql -uroot -pYOUR_ROOT_PASS
  2. Change to the 'mysql' db: use mysql;
  3. Update the password for the 'phpmyadmin' user: UPDATE mysql.user SET Password=PASSWORD('YOUR_PASS_HERE') WHERE User='phpmyadmin' AND Host='localhost';
  4. Flush privileges: FLUSH PRIVILEGES;

DONE!! It worked for me.

iloc giving 'IndexError: single positional indexer is out-of-bounds'

This happens when you index a row/column with a number that is larger than the dimensions of your dataframe. For instance, getting the eleventh column when you have only three.

import pandas as pd

df = pd.DataFrame({'Name': ['Mark', 'Laura', 'Adam', 'Roger', 'Anna'],
                   'City': ['Lisbon', 'Montreal', 'Lisbon', 'Berlin', 'Glasgow'],
                   'Car': ['Tesla', 'Audi', 'Porsche', 'Ford', 'Honda']})

You have 5 rows and three columns:

    Name      City      Car
0   Mark    Lisbon    Tesla
1  Laura  Montreal     Audi
2   Adam    Lisbon  Porsche
3  Roger    Berlin     Ford
4   Anna   Glasgow    Honda

Let's try to index the eleventh column (it doesn't exist):

df.iloc[:, 10] # there is obviously no 11th column

IndexError: single positional indexer is out-of-bounds

If you are a beginner with Python, remember that df.iloc[:, 10] would refer to the eleventh column.

How do I consume the JSON POST data in an Express application

@Daniel Thompson mentions that he had forgotten to add {"Content-Type": "application/json"} in the request. He was able to change the request, however, changing requests is not always possible (we are working on the server here).

In my case I needed to force content-type: text/plain to be parsed as json.

If you cannot change the content-type of the request, try using the following code:

app.use(express.json({type: '*/*'}));

Instead of using express.json() globally, I prefer to apply it only where needed, for instance in a POST request:

app.post('/mypost', express.json({type: '*/*'}), (req, res) => {
  // echo json
  res.json(req.body);
});

Add new attribute (element) to JSON object using JavaScript

thanks for this post. I want to add something that can be useful.

For IE, it is good to use

object["property"] = value;

syntax because some special words in IE can give you an error.

An example:

object.class = 'value';

this fails in IE, because "class" is a special word. I spent several hours with this.

How to scroll UITableView to specific position

it should work using - (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated using it this way:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[yourTableView scrollToRowAtIndexPath:indexPath 
                     atScrollPosition:UITableViewScrollPositionTop 
                             animated:YES];

atScrollPosition could take any of these values:

typedef enum {
UITableViewScrollPositionNone,
UITableViewScrollPositionTop,
UITableViewScrollPositionMiddle,
UITableViewScrollPositionBottom
} UITableViewScrollPosition;

I hope this helps you

Cheers

Better way to cast object to int

You have several options:

  • (int) — Cast operator. Works if the object already is an integer at some level in the inheritance hierarchy or if there is an implicit conversion defined.

  • int.Parse()/int.TryParse() — For converting from a string of unknown format.

  • int.ParseExact()/int.TryParseExact() — For converting from a string in a specific format

  • Convert.ToInt32() — For converting an object of unknown type. It will use an explicit and implicit conversion or IConvertible implementation if any are defined.

  • as int? — Note the "?". The as operator is only for reference types, and so I used "?" to signify a Nullable<int>. The "as" operator works like Convert.To____(), but think TryParse() rather than Parse(): it returns null rather than throwing an exception if the conversion fails.

Of these, I would prefer (int) if the object really is just a boxed integer. Otherwise use Convert.ToInt32() in this case.

Note that this is a very general answer: I want to throw some attention to Darren Clark's response because I think it does a good job addressing the specifics here, but came in late and wasn't voted as well yet. He gets my vote for "accepted answer", anyway, for also recommending (int), for pointing out that if it fails (int)(short) might work instead, and for recommending you check your debugger to find out the actual runtime type.

How to set custom ActionBar color / style?

You can change action bar color on this way:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/green_action_bar</item>
</style>

Thats all you need for changing action bar color.

Plus if you want to change the status bar color just add the line:

 <item name="android:colorPrimaryDark">@color/green_dark_action_bar</item>

Here is a screenshot taken from developer android site to make it more clear, and here is a link to read more about customizing the color palete

enter image description here

assign function return value to some variable using javascript

You could simply return a value from the function:

var response = 0;

function doSomething() {
    // some code
    return 10;
}
response = doSomething();

How do I merge a specific commit from one branch into another in Git?

If BranchA has not been pushed to a remote then you can reorder the commits using rebase and then simply merge. It's preferable to use merge over rebase when possible because it doesn't create duplicate commits.

git checkout BranchA
git rebase -i HEAD~113
... reorder the commits so the 10 you want are first ...
git checkout BranchB
git merge [the 10th commit]

Build Maven Project Without Running Unit Tests

I like short version: mvn clean install -DskipTests

It's work too: mvn clean install -DskipTests=true

If you absolutely must, you can also use the maven.test.skip property to skip compiling the tests. maven.test.skip is honored by Surefire, Failsafe and the Compiler Plugin. mvn clean install -Dmaven.test.skip=true

and you can add config in maven.xml

<project>
      [...]
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.16</version>
            <configuration>
              <skipTests>true</skipTests>
            </configuration>
          </plugin>
        </plugins>
      </build>
      [...]
    </project>

What's the most useful and complete Java cheat sheet?

  1. I have personally found the dzone cheatsheet on core java to be really handy in the beginning. However the needs change as we grow and get used to things.

  2. There are a few listed (at the end of the post) in on this java learning resources article too

  3. For the most practical use, in recent past I have found Java API doc to be the best place to cheat code and learn new api. This helps specially when you want to focus on latest version of java.

  4. mkyong - is one my fav places to cheat a lot of code for quick start - http://www.mkyong.com/

  5. And last but not the least, Stackoverflow is king of all small handy code snippets. Just google a stuff you are trying and there is a chance that a page will be top of search results, most of my google search results end at stackoverflow. Many of the common questions are available here - https://stackoverflow.com/questions/tagged/java?sort=frequent

iOS 7 - Failing to instantiate default view controller

1st option

if you want to set your custom storyboard instead of a default view controller.

Change this attribute from info.plist file

<key>UISceneStoryboardFile</key> <string>Onboarding</string>

Onboarding would be your storyboard name

to open this right-click on info.plist file and open as a source code

2nd option

1- Click on your project

2- Select your project from the target section

3- Move to Deployment interface section

4- Change your storyboard section from Main Interface field

Please remember set your storyboard initial view controller

how to run mysql in ubuntu through terminal

If you want to run your scripts, then

mysql -u root -p < yourscript.sql

What does the symbol \0 mean in a string-literal?

Banging my usual drum solo of JUST TRY IT, here's how you can answer questions like that in the future:

$ cat junk.c
#include <stdio.h>

char* string = "Hello\0";

int main(int argv, char** argc)
{
    printf("-->%s<--\n", string);
}
$ gcc -S junk.c
$ cat junk.s

... eliding the unnecessary parts ...

.LC0:
    .string "Hello"
    .string ""

...

.LC1:
    .string "-->%s<--\n"

...

Note here how the string I used for printf is just "-->%s<---\n" while the global string is in two parts: "Hello" and "". The GNU assembler also terminates strings with an implicit NUL character, so the fact that the first string (.LC0) is in those two parts indicates that there are two NULs. The string is thus 7 bytes long. Generally if you really want to know what your compiler is doing with a certain hunk of code, isolate it in a dummy example like this and see what it's doing using -S (for GNU -- MSVC has a flag too for assembler output but I don't know it off-hand). You'll learn a lot about how your code works (or fails to work as the case may be) and you'll get an answer quickly that is 100% guaranteed to match the tools and environment you're working in.

JavaScript TypeError: Cannot read property 'style' of null

This happens because document.write would overwrite your existing code therefore place your div before your javascript code. e.g.:

CSS:

#mydiv { 
  visibility:hidden;
 }

Inside your html file

<div id="mydiv">
   <p>Hello world</p>
</div>
<script type="text/javascript">
   document.getElementById('mydiv').style.visibility='visible';
</script>

Hope this was helpful

Anonymous method in Invoke call

Actually you do not need to use delegate keyword. Just pass lambda as parameter:

control.Invoke((MethodInvoker)(() => {this.Text = "Hi"; }));

How to remove the left part of a string?

This is very similar in technique to other answers, but with no repeated string operations, ability to tell if the prefix was there or not, and still quite readable:

parts = the_string.split(prefix_to_remove, 1):
    if len(parts) == 2:
        #  do things with parts[1]
        pass

Fastest way to count number of occurrences in a Python list

a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
print a.count("1")

It's probably optimized heavily at the C level.

Edit: I randomly generated a large list.

In [8]: len(a)
Out[8]: 6339347

In [9]: %timeit a.count("1")
10 loops, best of 3: 86.4 ms per loop

Edit edit: This could be done with collections.Counter

a = Counter(your_list)
print a['1']

Using the same list in my last timing example

In [17]: %timeit Counter(a)['1']
1 loops, best of 3: 1.52 s per loop

My timing is simplistic and conditional on many different factors, but it gives you a good clue as to performance.

Here is some profiling

In [24]: profile.run("a.count('1')")
         3 function calls in 0.091 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.091    0.091 <string>:1(<module>)
        1    0.091    0.091    0.091    0.091 {method 'count' of 'list' objects}

        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}



In [25]: profile.run("b = Counter(a); b['1']")
         6339356 function calls in 2.143 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.143    2.143 <string>:1(<module>)
        2    0.000    0.000    0.000    0.000 _weakrefset.py:68(__contains__)
        1    0.000    0.000    0.000    0.000 abc.py:128(__instancecheck__)
        1    0.000    0.000    2.143    2.143 collections.py:407(__init__)
        1    1.788    1.788    2.143    2.143 collections.py:470(update)
        1    0.000    0.000    0.000    0.000 {getattr}
        1    0.000    0.000    0.000    0.000 {isinstance}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}
  6339347    0.356    0.000    0.356    0.000 {method 'get' of 'dict' objects}

Change bootstrap navbar collapse breakpoint without using LESS

Navbars can utilize .navbar-toggler, .navbar-collapse, and .navbar-expand{-sm|-md|-lg|-xl} classes to change when their content collapses behind a button. In combination with other utilities, you can easily choose when to show or hide particular elements.

For navbars that never collapse, add the .navbar-expand class on the navbar. For navbars that always collapse, don’t add any .navbar-expand class.

For example :

<nav class="navbar navbar-expand-lg"></nav>

Mobile menu is showing in large screen.

Reference : https://getbootstrap.com/docs/4.0/components/navbar/

Business logic in MVC

Model = code for CRUD database operations.

Controller = responds to user actions, and passes the user requests for data retrieval or delete/update to the model, subject to the business rules specific to an organization. These business rules could be implemented in helper classes, or if they are not too complex, just directly in the controller actions. The controller finally asks the view to update itself so as to give feedback to the user in the form of a new display, or a message like 'updated, thanks', etc.,

View = UI that is generated based on a query on the model.

There are no hard and fast rules regarding where business rules should go. In some designs they go into model, whereas in others they are included with the controller. But I think it is better to keep them with the controller. Let the model worry only about database connectivity.

The remote certificate is invalid according to the validation procedure

.NET is seeing an invalid SSL certificate on the other end of the connection. There is a workaround for it, but obviously not recommended for production code:

// Put this somewhere that is only once - like an initialization method
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateCertificate);
...

static bool ValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
   return true;
}

How to create full compressed tar file using Python?

To build a .tar.gz (aka .tgz) for an entire directory tree:

import tarfile
import os.path

def make_tarfile(output_filename, source_dir):
    with tarfile.open(output_filename, "w:gz") as tar:
        tar.add(source_dir, arcname=os.path.basename(source_dir))

This will create a gzipped tar archive containing a single top-level folder with the same name and contents as source_dir.

how to parse JSON file with GSON

In case you need to parse it from a file, I find the best solution to use a HashMap<String, String> to use it inside your java code for better manipultion.

Try out this code:

public HashMap<String, String> myMethodName() throws FileNotFoundException
{
    String path = "absolute path to your file";
    BufferedReader bufferedReader = new BufferedReader(new FileReader(path));

    Gson gson = new Gson();
    HashMap<String, String> json = gson.fromJson(bufferedReader, HashMap.class);
    return json;
}

html select option SELECTED

Just use the array of options, to see, which option is currently selected.

$options = array( 'one', 'two', 'three' );

$output = '';
for( $i=0; $i<count($options); $i++ ) {
  $output .= '<option ' 
             . ( $_GET['sel'] == $options[$i] ? 'selected="selected"' : '' ) . '>' 
             . $options[$i] 
             . '</option>';
}

Sidenote: I would define a value to be some kind of id for each element, else you may run into problems, when two options have the same string representation.

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

If you want a REAL cloned object/array in JS with cloned references of all attributes and sub-objects:

export function clone(arr) {
    return JSON.parse(JSON.stringify(arr))
}

ALL other operations do not create clones, because they just change the base address of the root element, not of the included objects.

Except you traverse recursive through the object-tree.

For a simple copy, these are OK. For storage address relevant operations I suggest (and in most all other cases, because this is fast!) to type convert into string and back in a complete new object.

Backup a single table with its data from a database in sql server 2008

Put the table in its own filegroup. You can then use regular SQL Server built in backup to backup the filegroup in which in effect backs up the table.

To backup a filegroup see: https://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/back-up-files-and-filegroups-sql-server

To create a table on a non-default filegroup (its easy) see: Create a table on a filegroup other than the default

how to fix stream_socket_enable_crypto(): SSL operation failed with code 1

edit your .env and add this line after mail config lines

MAIL_ENCRYPTION=""

Save and try to send email

What does @@variable mean in Ruby?

@ - Instance variable of a class
@@ - Class variable, also called as static variable in some cases

A class variable is a variable that is shared amongst all instances of a class. This means that only one variable value exists for all objects instantiated from this class. If one object instance changes the value of the variable, that new value will essentially change for all other object instances.

Another way of thinking of thinking of class variables is as global variables within the context of a single class. Class variables are declared by prefixing the variable name with two @ characters (@@). Class variables must be initialized at creation time

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

   private void ExceptionTest()
    {
        try
        {
            int j = 0;
            int i = 5;
            i = 1 / j;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
            var stList = ex.StackTrace.ToString().Split('\\');
            Console.WriteLine("Exception occurred at " + stList[stList.Count() - 1]);
        }
    }

Seems to work for me

MySQL stored procedure vs function, which would I use when?

One significant difference is that you can include a function in your SQL queries, but stored procedures can only be invoked with the CALL statement:

UDF Example:

CREATE FUNCTION hello (s CHAR(20))
   RETURNS CHAR(50) DETERMINISTIC
   RETURN CONCAT('Hello, ',s,'!');
Query OK, 0 rows affected (0.00 sec)

CREATE TABLE names (id int, name varchar(20));
INSERT INTO names VALUES (1, 'Bob');
INSERT INTO names VALUES (2, 'John');
INSERT INTO names VALUES (3, 'Paul');

SELECT hello(name) FROM names;
+--------------+
| hello(name)  |
+--------------+
| Hello, Bob!  |
| Hello, John! |
| Hello, Paul! |
+--------------+
3 rows in set (0.00 sec)

Sproc Example:

delimiter //

CREATE PROCEDURE simpleproc (IN s CHAR(100))
BEGIN
   SELECT CONCAT('Hello, ', s, '!');
END//
Query OK, 0 rows affected (0.00 sec)

delimiter ;

CALL simpleproc('World');
+---------------------------+
| CONCAT('Hello, ', s, '!') |
+---------------------------+
| Hello, World!             |
+---------------------------+
1 row in set (0.00 sec)

How to get text of an input text box during onKeyPress?

easy...

In your keyPress event handler, write

void ValidateKeyPressHandler(object sender, KeyPressEventArgs e)
{
    var tb = sender as TextBox;
    var startPos = tb.SelectionStart;
    var selLen= tb.SelectionLength;

    var afterEditValue = tb.Text.Remove(startPos, selLen)
                .Insert(startPos, e.KeyChar.ToString()); 
    //  ... more here
}

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

With default Github repository import it is possible, but just make sure the two factor authentication is not enabled in Gitlab.

Thanks

Imshow: extent and aspect

You can do it by setting the aspect of the image manually (or by letting it auto-scale to fill up the extent of the figure).

By default, imshow sets the aspect of the plot to 1, as this is often what people want for image data.

In your case, you can do something like:

import matplotlib.pyplot as plt
import numpy as np

grid = np.random.random((10,10))

fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(6,10))

ax1.imshow(grid, extent=[0,100,0,1])
ax1.set_title('Default')

ax2.imshow(grid, extent=[0,100,0,1], aspect='auto')
ax2.set_title('Auto-scaled Aspect')

ax3.imshow(grid, extent=[0,100,0,1], aspect=100)
ax3.set_title('Manually Set Aspect')

plt.tight_layout()
plt.show()

enter image description here

CSS table-cell equal width

Replace

  <div style="display:table;">
    <div style="display:table-cell;"></div>
    <div style="display:table-cell;"></div>
  </div>

with

  <table>
    <tr><td>content cell1</td></tr>
    <tr><td>content cell1</td></tr>
  </table>

Look at all the issues surrounding trying to make divs perform like tables. They had to add table-xxx to mimic table layouts

Tables are supported and work very well in all browsers. Why ditch them? the fact that they had to mimic them is proof they did their job and well.

In my opinion use the best tool for the job and if you want tabulated data or something that resembles tabulated data tables just work.

Very Late reply I know but worth voicing.

Getting error in console : Failed to load resource: net::ERR_CONNECTION_RESET

I had a similar issue using Apache 2.4 and PHP 7.

My client sent a lot of requests when refreshing (hard reloading) my application page in the browser and every time some of the last requests resulted in this error in console:

GET http://example.com/api/v1/my/resource net::ERR_CONNECTION_RESET

It turned out that my client was reaching the maximum amount of threads that was allowed. The threads exceeding this configured ceiling are simply not handled by Apache at all resulting in the connection reset error response.

The amount of threads can be easily raised by setting the ThreadsPerChild value for the module in question.
The easiest way to make such change is to uncomment the Server-pool management config file conf/extra/httpd-mpm.conf and then editing the preset values in the file to desired values.

1) Uncomment the Server-pool management file

# Server-pool management (MPM specific)
Include conf/extra/httpd-mpm.conf

2) Open and edit the file conf/extra/httpd-mpm.conf and raise the amount of threads

In my case I had to change the threads for the mpm_winnt_module:

# raised the amount of threads for mpm_winnt_module to 250
<IfModule mpm_winnt_module>
    ThreadsPerChild        250
    MaxConnectionsPerChild   0
</IfModule>

A comprehensive explanation on these Server-pool management configuration settings can be found in this post on StackOverflow.

add to array if it isn't there already

if (!in_array($value, $a))
  $a[]=$value;

How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

We demonstrate features of lmfit while solving both problems.

Given

import lmfit

import numpy as np

import matplotlib.pyplot as plt


%matplotlib inline
np.random.seed(123)
# General Functions
def func_log(x, a, b, c):
    """Return values from a general log function."""
    return a * np.log(b * x) + c


# Data
x_samp = np.linspace(1, 5, 50)
_noise = np.random.normal(size=len(x_samp), scale=0.06)
y_samp = 2.5 * np.exp(1.2 * x_samp) + 0.7 + _noise
y_samp2 = 2.5 * np.log(1.2 * x_samp) + 0.7 + _noise

Code

Approach 1 - lmfit Model

Fit exponential data

regressor = lmfit.models.ExponentialModel()                # 1    
initial_guess = dict(amplitude=1, decay=-1)                # 2
results = regressor.fit(y_samp, x=x_samp, **initial_guess)
y_fit = results.best_fit    

plt.plot(x_samp, y_samp, "o", label="Data")
plt.plot(x_samp, y_fit, "k--", label="Fit")
plt.legend()

enter image description here

Approach 2 - Custom Model

Fit log data

regressor = lmfit.Model(func_log)                          # 1
initial_guess = dict(a=1, b=.1, c=.1)                      # 2
results = regressor.fit(y_samp2, x=x_samp, **initial_guess)
y_fit = results.best_fit

plt.plot(x_samp, y_samp2, "o", label="Data")
plt.plot(x_samp, y_fit, "k--", label="Fit")
plt.legend()

enter image description here


Details

  1. Choose a regression class
  2. Supply named, initial guesses that respect the function's domain

You can determine the inferred parameters from the regressor object. Example:

regressor.param_names
# ['decay', 'amplitude']

To make predictions, use the ModelResult.eval() method.

model = results.eval
y_pred = model(x=np.array([1.5]))

Note: the ExponentialModel() follows a decay function, which accepts two parameters, one of which is negative.

enter image description here

See also ExponentialGaussianModel(), which accepts more parameters.

Install the library via > pip install lmfit.

How to print a stack trace in Node.js?

In case someone is still looking for this like I was, then there is a module we can use called "stack-trace". It is really popular. NPM Link

Then walk through the trace.

  var stackTrace = require('stack-trace');
  .
  .
  .
  var trace = stackTrace.get();
  trace.map(function (item){ 
    console.log(new Date().toUTCString() + ' : ' +  item.toString() );  
  });

Or just simply print the trace:

var stackTrace = require('stack-trace');
.
.
.
var trace = stackTrace.get();
trace.toString();

Get the date of next monday, tuesday, etc

Sorry, I didn't notice the PHP tag - however someone else might be interested in a VB solution:

Module Module1

    Sub Main()
        Dim d As Date = Now
        Dim nextFriday As Date = DateAdd(DateInterval.Weekday, DayOfWeek.Friday - d.DayOfWeek(), Now)
        Console.WriteLine("next friday is " & nextFriday)
        Console.ReadLine()
    End Sub

End Module

SQL permissions for roles

USE DataBaseName; GO --------- CREATE ROLE --------- CREATE ROLE Doctors ; GO  ---- Assign Role To users -------  CREATE USER [Username] FOR LOGIN [Domain\Username] EXEC sp_addrolemember N'Doctors', N'Username'  ----- GRANT Permission to Users Assinged with this Role----- GRANT ALL ON Table1, Table2, Table3 TO Doctors; GO 

Django 1.7 - "No migrations to apply" when run migrate after makemigrations

I had this same problem. Make sure the app's migrations folder is created (YOURAPPNAME/ migrations). Delete the folder and enter the commands:

python manage.py migrate --fake
python manage.py makemigrations <app_name>
python manage.py migrate --fake-initial

I inserted this lines in each class in models.py:

class Meta:
    app_label = '<app_name>'

This solved my problem.

Saving an image in OpenCV

hopefully this will save images form your webcam

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main()
{
   VideoCapture cap(0);

   Mat save_img;

   cap >> save_img;

   char Esc = 0;

   while (Esc != 27 && cap.isOpened()) {        
    bool Frame = cap.read(save_img);        
    if (!Frame || save_img.empty()) {       
        cout << "error: frame not read from webcam\n";      
        break;                                              
    }
    namedWindow("save_img", CV_WINDOW_NORMAL);  
    imshow("imgOriginal", save_img);            
    Esc = waitKey(1);
}
imwrite("test.jpg",save_img); 
}

How can I make IntelliJ IDEA update my dependencies from Maven?

For some reason IntelliJ (at least in version 2019.1.2) ignores dependencies in local .m2 directory. None of above solutions worked for me. The only thing finally forced IntelliJ to discover local dependencies was:

  1. Close project
  2. Open project clicking on pom.xml (not on a project directory)
  3. Click Open as Project

List item

  1. Click Delete Existing Project and Import

enter image description here

Get most recent row for given ID

Building on @xQbert's answer's, you can avoid the subquery AND make it generic enough to filter by any ID

SELECT id, signin, signout
FROM dTable
INNER JOIN(
  SELECT id, MAX(signin) AS signin
  FROM dTable
  GROUP BY id
) AS t1 USING(id, signin)

java.sql.SQLException: Exhausted Resultset

Problem behind the error: If you are trying to access Oracle database you will not able to access inserted data until the transaction has been successful and to complete the transaction you have to fire a commit query after inserting the data into the table. Because Oracle database is not on auto commit mode by default.

Solution:

Go to SQL PLUS and follow the following queries..

SQL*Plus: Release 11.2.0.1.0 Production on Tue Nov 28 15:29:43 2017

Copyright (c) 1982, 2010, Oracle.  All rights reserved.

Enter user-name: scott
Enter password:

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> desc empdetails;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 ENO                                                NUMBER(38)
 ENAME                                              VARCHAR2(20)
 SAL                                                FLOAT(126)

SQL> insert into empdetails values(1010,'John',45000.00);

1 row created.

SQL> commit;

Commit complete.

Refreshing Web Page By WebDriver When Waiting For Specific Condition

One important thing to note is that the driver.navigate().refresh() call sometimes seems to be asynchronous, meaning it does not wait for the refresh to finish, it just "kicks off the refresh" and doesn't block further execution while the browser is reloading the page.

While this only seems to happen in a minority of cases, we figured that it's better to make sure this works 100% by adding a manual check whether the page really started reloading.

Here's the code I wrote for that in our base page object class:

public void reload() {
    // remember reference to current html root element
    final WebElement htmlRoot = getDriver().findElement(By.tagName("html"));

    // the refresh seems to sometimes be asynchronous, so this sometimes just kicks off the refresh,
    // but doesn't actually wait for the fresh to finish
    getDriver().navigate().refresh();

    // verify page started reloading by checking that the html root is not present anymore
    final long startTime = System.currentTimeMillis();
    final long maxLoadTime = TimeUnit.SECONDS.toMillis(getMaximumLoadTime());
    boolean startedReloading = false;
    do {
        try {
            startedReloading = !htmlRoot.isDisplayed();
        } catch (ElementNotVisibleException | StaleElementReferenceException ex) {
            startedReloading = true;
        }
    } while (!startedReloading && (System.currentTimeMillis() - startTime < maxLoadTime));

    if (!startedReloading) {
        throw new IllegalStateException("Page " + getName() + " did not start reloading in " + maxLoadTime + "ms");
    }

    // verify page finished reloading
    verify();
}

Some notes:

  • Since you're reloading the page, you can't just check existence of a given element, because the element will be there before the reload starts and after it's done as well. So sometimes you might get true, but the page didn't even start loading yet.
  • When the page reloads, checking WebElement.isDisplayed() will throw a StaleElementReferenceException. The rest is just to cover all bases
  • getName(): internal method that gets the name of the page
  • getMaximumLoadTime(): internal method that returns how long page should be allowed to load in seconds
  • verify(): internal method makes sure the page actually loaded

Again, in a vast majority of cases, the do/while loop runs a single time because the code beyond navigate().refresh() doesn't get executed until the browser actually reloaded the page completely, but we've seen cases where it actually takes seconds to get through that loop because the navigate().refresh() didn't block until the browser finished loading.

Get access to parent control from user control - C#

According to Ruskins answer and the comments here I came up with the following (recursive) solution:

public static T GetParentOfType<T>(this Control control) where T : class
{
    if (control?.Parent == null)
        return null;

    if (control.Parent is T parent)
        return parent;

    return GetParentOfType<T>(control.Parent);
}

Can you style an html radio button to look like a checkbox?

Yes it can be done using this css, i've hidden the default radio button and made a custom radio button that looks like a checkbox.

_x000D_
_x000D_
.css-prp
{
  color: #17CBF2;
  font-family: arial;
}


.con1 {
  display: block;
  position: relative;
  padding-left: 25px;
  margin-bottom: 12px;
  cursor: pointer;
  font-size: 15px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* Hide the browser's default radio button */
.con1 input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
}

/* Create a custom radio button */
.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 18px;
  width: 18px;
  background-color: lightgrey;
  border-radius: 10%;
}

/* When the radio button is checked, add a blue background */
.con1 input:checked ~ .checkmark {
  background-color: #17CBF2;
}
_x000D_
<label class="con1"><span>Yes</span>
  <input type="radio" name="radio1" checked>
  <span class="checkmark"></span>
</label>
<label class="con1"><span>No</span>
  <input type="radio" name="radio1">
  <span class="checkmark"></span>
</label>
_x000D_
_x000D_
_x000D_

DataGridView.Clear()

dataGridView1.DataSource=null;

Laravel - Eloquent or Fluent random row

This works just fine,

$model=Model::all()->random(1)->first();

you can also change argument in random function to get more than one record.

Note: not recommended if you have huge data as this will fetch all rows first and then returns random value.

Finding Number of Cores in Java

This works on Windows with Cygwin installed:

System.getenv("NUMBER_OF_PROCESSORS")

What are database normal forms and can you give examples?

1NF: Only one value per column

2NF: All the non primary key columns in the table should depend on the entire primary key.

3NF: All the non primary key columns in the table should depend DIRECTLY on the entire primary key.

I have written an article in more detail over here

Adding double quote delimiters into csv file

This is actually pretty easy in Excel (or any spreadsheet application).

You'll want to use the =CONCATENATE() function as shown in the formula bar in the following screenshot:

Step 1 involves adding quotes in column B,

Step 2 involves specifying the function and then copying it down column C (by now your spreadsheet should look like the screenshot),

enter image description here

Step 3 (if you need the text outside of the formula) involves copying column C, right-clicking on column D, choosing Paste Special >> Paste Values. Column D should then contain the text that was calculated in column C.

Onchange open URL via select - jQuery

JS Fiddle Example

$('#userNav').change(function() {
window.location = $(':selected',this).attr('href')
});




<select id="userNav">
<option></option>
<option href="http://google.com">Goolge</option>
<option href="http://duckduckgo.com">Go Go duck</option>
</select>

This works for the href in an option that is selected

How do you do Impersonation in .NET?

Here's my vb.net port of Matt Johnson's answer. I added an enum for the logon types. LOGON32_LOGON_INTERACTIVE was the first enum value that worked for sql server. My connection string was just trusted. No user name / password in the connection string.

  <PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
  Public Class Impersonation
    Implements IDisposable

    Public Enum LogonTypes
      ''' <summary>
      ''' This logon type is intended for users who will be interactively using the computer, such as a user being logged on  
      ''' by a terminal server, remote shell, or similar process.
      ''' This logon type has the additional expense of caching logon information for disconnected operations; 
      ''' therefore, it is inappropriate for some client/server applications,
      ''' such as a mail server.
      ''' </summary>
      LOGON32_LOGON_INTERACTIVE = 2

      ''' <summary>
      ''' This logon type is intended for high performance servers to authenticate plaintext passwords.
      ''' The LogonUser function does not cache credentials for this logon type.
      ''' </summary>
      LOGON32_LOGON_NETWORK = 3

      ''' <summary>
      ''' This logon type is intended for batch servers, where processes may be executing on behalf of a user without 
      ''' their direct intervention. This type is also for higher performance servers that process many plaintext
      ''' authentication attempts at a time, such as mail or Web servers. 
      ''' The LogonUser function does not cache credentials for this logon type.
      ''' </summary>
      LOGON32_LOGON_BATCH = 4

      ''' <summary>
      ''' Indicates a service-type logon. The account provided must have the service privilege enabled. 
      ''' </summary>
      LOGON32_LOGON_SERVICE = 5

      ''' <summary>
      ''' This logon type is for GINA DLLs that log on users who will be interactively using the computer. 
      ''' This logon type can generate a unique audit record that shows when the workstation was unlocked. 
      ''' </summary>
      LOGON32_LOGON_UNLOCK = 7

      ''' <summary>
      ''' This logon type preserves the name and password in the authentication package, which allows the server to make 
      ''' connections to other network servers while impersonating the client. A server can accept plaintext credentials 
      ''' from a client, call LogonUser, verify that the user can access the system across the network, and still 
      ''' communicate with other servers.
      ''' NOTE: Windows NT:  This value is not supported. 
      ''' </summary>
      LOGON32_LOGON_NETWORK_CLEARTEXT = 8

      ''' <summary>
      ''' This logon type allows the caller to clone its current token and specify new credentials for outbound connections.
      ''' The new logon session has the same local identifier but uses different credentials for other network connections. 
      ''' NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
      ''' NOTE: Windows NT:  This value is not supported. 
      ''' </summary>
      LOGON32_LOGON_NEW_CREDENTIALS = 9
    End Enum

    <DllImport("advapi32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
    Private Shared Function LogonUser(lpszUsername As [String], lpszDomain As [String], lpszPassword As [String], dwLogonType As Integer, dwLogonProvider As Integer, ByRef phToken As SafeTokenHandle) As Boolean
    End Function

    Public Sub New(Domain As String, UserName As String, Password As String, Optional LogonType As LogonTypes = LogonTypes.LOGON32_LOGON_INTERACTIVE)
      Dim ok = LogonUser(UserName, Domain, Password, LogonType, 0, _SafeTokenHandle)
      If Not ok Then
        Dim errorCode = Marshal.GetLastWin32Error()
        Throw New ApplicationException(String.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode))
      End If

      WindowsImpersonationContext = WindowsIdentity.Impersonate(_SafeTokenHandle.DangerousGetHandle())
    End Sub

    Private ReadOnly _SafeTokenHandle As New SafeTokenHandle
    Private ReadOnly WindowsImpersonationContext As WindowsImpersonationContext

    Public Sub Dispose() Implements System.IDisposable.Dispose
      Me.WindowsImpersonationContext.Dispose()
      Me._SafeTokenHandle.Dispose()
    End Sub

    Public NotInheritable Class SafeTokenHandle
      Inherits SafeHandleZeroOrMinusOneIsInvalid

      <DllImport("kernel32.dll")> _
      <ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)> _
      <SuppressUnmanagedCodeSecurity()> _
      Private Shared Function CloseHandle(handle As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
      End Function

      Public Sub New()
        MyBase.New(True)
      End Sub

      Protected Overrides Function ReleaseHandle() As Boolean
        Return CloseHandle(handle)
      End Function
    End Class

  End Class

You need to Use with a Using statement to contain some code to run impersonated.

Angular 2: How to style host element of the component?

For anyone looking to style child elements of a :host here is an example of how to use ::ng-deep

:host::ng-deep <child element>

e.g :host::ng-deep span { color: red; }

As others said /deep/ is deprecated

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

It turns out that the cause was that this project wasn't being considered by Eclipse to actually be a Java EE project at all; it was an old project from 3.1, and the Eclipse 3.5 we are using now requires several "natures" to be set in the project configuration file.

<natures>
    <nature>org.eclipse.jdt.core.javanature</nature>
    <nature>InCode.inCodeNature</nature>
    <nature>org.eclipse.dltk.javascript.core.nature</nature>
    <nature>net.sf.eclipsecs.core.CheckstyleNature</nature>
    <nature>org.eclipse.wst.jsdt.core.jsNature</nature>
    <nature>org.eclipse.wst.common.project.facet.core.nature</nature>
    <nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
    <nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
</natures>

I was able to find the cause by creating a new "Dynamic Web Project" which properly read its JSP files, and diffing against the config of the older project.

The only way I could find to add these was by editing the .project file, but after re-opening the project, everything magically worked. The settings referenced by pribeiro, above, weren't necessary since the project already conformed to the default settings.

Both pribeiro and nitind's answers gave me ideas to jumpstart my search, thanks.

Is there a way of editing these "natures" from within the UI?

Check if returned value is not null and if so assign it, in one line, with one method call

Same principle as Loki's answer but shorter. Just keep in mind that shorter doesn't automatically mean better.

dinner = Optional.ofNullable(cage.getChicken())
  .orElse(getFreerangeChicken());

Note: This usage of Optional is explicitly discouraged by the architects of the JDK and the designers of the Optional feature. You are allocating a fresh object and immediately throwing it away every time. But on the other hand it can be quite readable.

Tensorflow: Using Adam optimizer

I was having a similar problem. (No problems training with GradientDescent optimizer, but error raised when using to Adam Optimizer, or any other optimizer with its own variables)

Changing to an interactive session solved this problem for me.

sess = tf.Session()

into

sess = tf.InteractiveSession()

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

HttpContext.Current.Session is null when routing requests

I was missing a reference to System.web.mvc dll in the session adapter, and adding the same fixed the issue.

Hopefully it will help someone else going through same scenario.

Font Awesome 5 font-family issue

Requiring 900 weight is not a weirdness but a intentional restriction added by FontAwesome (since they share the same unicode but just different font-weight) so that you are not hacking your way into using the 'solid' and 'light' icons, most of which are available only in the paid 'Pro' version.

Name does not exist in the current context

I also faced a similar issue, the problem was the form was inside a folder and the file .aspx.designer.cs I had the namespace referencing specifically to that directory; which caused the error to appear in several components:

El nombre no existe en el contexto actual

This in your case, a possible solution is to leave the namespace line of the Members_Jobs.aspx.designer.cs file specified globally, ie change this

namespace stman.Members {

For this

namespace stman {

It's what helped me solve the problem.

I hope to be helpful

Kubernetes service external ip pending

same issue:

os>kubectl get svc right-sabertooth-wordpress

NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S)
right-sabertooth-wordpress LoadBalancer 10.97.130.7 "pending" 80:30454/TCP,443:30427/TCP

os>minikube service list

|-------------|----------------------------|--------------------------------|

| NAMESPACE | NAME | URL |

|-------------|----------------------------|--------------------------------|

| default | kubernetes | No node port |

| default | right-sabertooth-mariadb | No node port |

| default | right-sabertooth-wordpress | http://192.168.99.100:30454 |

| | | http://192.168.99.100:30427 |

| kube-system | kube-dns | No node port |

| kube-system | tiller-deploy | No node port |

|-------------|----------------------------|--------------------------------|

It is, however,accesible via that http://192.168.99.100:30454.

How to use SharedPreferences in Android to store, fetch and edit values

Singleton Shared Preferences Class. it may help for others in future.

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

public class SharedPref
{
    private static SharedPreferences mSharedPref;
    public static final String NAME = "NAME";
    public static final String AGE = "AGE";
    public static final String IS_SELECT = "IS_SELECT";

    private SharedPref()
    {

    }

    public static void init(Context context)
    {
        if(mSharedPref == null)
            mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
    }

    public static String read(String key, String defValue) {
        return mSharedPref.getString(key, defValue);
    }

    public static void write(String key, String value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putString(key, value);
        prefsEditor.commit();
    }

    public static boolean read(String key, boolean defValue) {
        return mSharedPref.getBoolean(key, defValue);
    }

    public static void write(String key, boolean value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putBoolean(key, value);
        prefsEditor.commit();
    }

    public static Integer read(String key, int defValue) {
        return mSharedPref.getInt(key, defValue);
    }

    public static void write(String key, Integer value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putInt(key, value).commit();
    }
}

Simply call SharedPref.init() on MainActivity once

SharedPref.init(getApplicationContext());

To Write data

SharedPref.write(SharedPref.NAME, "XXXX");//save string in shared preference.
SharedPref.write(SharedPref.AGE, 25);//save int in shared preference.
SharedPref.write(SharedPref.IS_SELECT, true);//save boolean in shared preference.

To Read Data

String name = SharedPref.read(SharedPref.NAME, null);//read string in shared preference.
int age = SharedPref.read(SharedPref.AGE, 0);//read int in shared preference.
boolean isSelect = SharedPref.read(SharedPref.IS_SELECT, false);//read boolean in shared preference.

How to recognize swipe in all 4 directions

UISwipeGestureRecognizer has a direction property that has the following definition:

var direction: UISwipeGestureRecognizerDirection

The permitted direction of the swipe for this gesture recognizer.


The problem with Swift 3.0.1 (and below) is that even if UISwipeGestureRecognizerDirection conforms to OptionSet, the following snippet will compile but won't produce any positive expected result:

// This compiles but does not work
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(gestureHandler))
gesture.direction = [.right, .left, .up, .down]
self.addGestureRecognizer(gesture)

As a workaround, you will have to create a UISwipeGestureRecognizer for each desired direction.


The following Playground code shows how to implement several UISwipeGestureRecognizer for the same UIView and the same selector using Array's map method:

import UIKit
import PlaygroundSupport

class SwipeableView: UIView {
    convenience init() {
        self.init(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        backgroundColor = .red

        [UISwipeGestureRecognizerDirection.right, .left, .up, .down].map({
            let gesture = UISwipeGestureRecognizer(target: self, action: #selector(gestureHandler))
            gesture.direction = $0
            self.addGestureRecognizer(gesture)
        })
    }

    func gestureHandler(sender: UISwipeGestureRecognizer) {
        switch sender.direction {
        case [.left]:   frame.origin.x -= 10
        case [.right]:  frame.origin.x += 10
        case [.up]:     frame.origin.y -= 10
        case [.down]:   frame.origin.y += 10
        default:        break
        }
    }
}

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        view.addSubview(SwipeableView())
    }
}

let controller = ViewController()
PlaygroundPage.current.liveView = controller

Finding the number of days between two dates

$diff = strtotime('2019-11-25') - strtotime('2019-11-10');
echo abs(round($diff / 86400));

Plain Old CLR Object vs Data Transfer Object

I wrote an article for that topic: DTO vs Value Object vs POCO.

In short:

  • DTO != Value Object
  • DTO ? POCO
  • Value Object ? POCO

Use .corr to get the correlation between two columns

Without actual data it is hard to answer the question but I guess you are looking for something like this:

Top15['Citable docs per Capita'].corr(Top15['Energy Supply per Capita'])

That calculates the correlation between your two columns 'Citable docs per Capita' and 'Energy Supply per Capita'.

To give an example:

import pandas as pd

df = pd.DataFrame({'A': range(4), 'B': [2*i for i in range(4)]})

   A  B
0  0  0
1  1  2
2  2  4
3  3  6

Then

df['A'].corr(df['B'])

gives 1 as expected.

Now, if you change a value, e.g.

df.loc[2, 'B'] = 4.5

   A    B
0  0  0.0
1  1  2.0
2  2  4.5
3  3  6.0

the command

df['A'].corr(df['B'])

returns

0.99586

which is still close to 1, as expected.

If you apply .corr directly to your dataframe, it will return all pairwise correlations between your columns; that's why you then observe 1s at the diagonal of your matrix (each column is perfectly correlated with itself).

df.corr()

will therefore return

          A         B
A  1.000000  0.995862
B  0.995862  1.000000

In the graphic you show, only the upper left corner of the correlation matrix is represented (I assume).

There can be cases, where you get NaNs in your solution - check this post for an example.

If you want to filter entries above/below a certain threshold, you can check this question. If you want to plot a heatmap of the correlation coefficients, you can check this answer and if you then run into the issue with overlapping axis-labels check the following post.

Angular2 get clicked element id

For TypeScript users:

    toggle(event: Event): void {
        let elementId: string = (event.target as Element).id;
        // do something with the id... 
    }

Unable to execute dex: Multiple dex files define

The Solution for me was just to do following things:

  1. ->lib directory in your project and delete any multiple elements.
  2. Project->Properties->Java build Path and delete any Dependency Library was added automatically and not by you! ->Apply
  3. Restart Eclipse IDE
  4. Now Clean the project.
  5. Run/Debug on Device/Emulator the project ... Good Luck

How to lazy load images in ListView in Android

I can recommend a different way that works like a charm: Android Query.

You can download that JAR file from here

AQuery androidAQuery = new AQuery(this);

As an example:

androidAQuery.id(YOUR IMAGEVIEW).image(YOUR IMAGE TO LOAD, true, true, getDeviceWidth(), ANY DEFAULT IMAGE YOU WANT TO SHOW);

It's very fast and accurate, and using this you can find many more features like animation when loading, getting a bitmap (if needed), etc.

git push says "everything up-to-date" even though I have local changes

I have faced same issue. As I didn't add changes to staging area. And I directly tried to push the code to remote repo using command :

git push origin master

And it shows the message Everything up-to-date.

to fix this this issue, try these steps

  1. git add .
  2. git commit -m "Bug Fixed"
  3. git push -u origin master

React-Redux: Actions must be plain objects. Use custom middleware for async actions

The error is simply asking you to insert a Middleware in between which would help to handle async operations.

You could do that by :

npm i redux-thunk

        Inside index.js

import thunk from "redux-thunk" 
        
...createStore(rootReducers, applyMiddleware(thunk));

Now, async operations will work inside your functions.

Get selected text from a drop-down list (select box) using jQuery

For the text of the selected item, use:

$('select[name="thegivenname"] option:selected').text();

For the value of the selected item, use:

$('select[name="thegivenname"] option:selected').val();

C# List<string> to string with delimiter

You can use String.Join. If you have a List<string> then you can call ToArray first:

List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());

In .NET 4 you don't need the ToArray anymore, since there is an overload of String.Join that takes an IEnumerable<string>.

Results:


John, Anna, Monica

Get AVG ignoring Null or Zero values

You already attempt to filter out NULL values with NOT NULL. I have changed this to IS NOT NULL in the WHERE clause so it will execute. We can refactor this by removing the ISNULL function in the AVG method. Also, I doubt you'll actually need bigint so we can remove the cast.

SELECT distinct
     AVG(a.SecurityW) as Average1
     ,AVG(a.TransferW) as Average2
     ,AVG(a.StaffW) as Average3
FROM Table1 a,  Table2 b
WHERE a.SecurityW <> 0 AND a.SecurityW IS NOT NULL
AND a.TransferW<> 0 AND a.TransferWIS IS NOT NULL
AND a.StaffW<> 0 AND a.StaffWIS IS NOT NULL
AND MONTH(a.ActualTime) = 4
AND YEAR(a.ActualTime) = 2013

Remove an entire column from a data.frame in R

The posted answers are very good when working with data.frames. However, these tasks can be pretty inefficient from a memory perspective. With large data, removing a column can take an unusually long amount of time and/or fail due to out of memory errors. Package data.table helps address this problem with the := operator:

library(data.table)
> dt <- data.table(a = 1, b = 1, c = 1)
> dt[,a:=NULL]
     b c
[1,] 1 1

I should put together a bigger example to show the differences. I'll update this answer at some point with that.

CSS to set A4 paper size

https://github.com/cognitom/paper-css seems to solve all my needs.

Paper CSS for happy printing

Front-end printing solution - previewable and live-reloadable!

Python: finding an element in a list

I found this by adapting some tutos. Thanks to google, and to all of you ;)

def findall(L, test):
    i=0
    indices = []
    while(True):
        try:
            # next value in list passing the test
            nextvalue = filter(test, L[i:])[0]

            # add index of this value in the index list,
            # by searching the value in L[i:] 
            indices.append(L.index(nextvalue, i))

            # iterate i, that is the next index from where to search
            i=indices[-1]+1
        #when there is no further "good value", filter returns [],
        # hence there is an out of range exeption
        except IndexError:
            return indices

A very simple use:

a = [0,0,2,1]
ind = findall(a, lambda x:x>0))

[2, 3]

P.S. scuse my english

Best way to change the background color for an NSView

I tested the following and it worked for me (in Swift):

view.wantsLayer = true
view.layer?.backgroundColor = NSColor.blackColor().colorWithAlphaComponent(0.5).CGColor

'Invalid update: invalid number of rows in section 0

Here is some code from above added with actual action code (point 1 and 2);

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in

        // 1. remove object from your array
        scannedItems.remove(at: indexPath.row)
        // 2. reload the table, otherwise you get an index out of bounds crash
        self.tableView.reloadData()

        completionHandler(true)
    }
    deleteAction.backgroundColor = .systemOrange
    let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
    configuration.performsFirstActionWithFullSwipe = true
    return configuration
}

How can I get a specific number child using CSS?

For modern browsers, use td:nth-child(2) for the second td, and td:nth-child(3) for the third. Remember that these retrieve the second and third td for every row.

If you need compatibility with IE older than version 9, use sibling combinators or JavaScript as suggested by Tim. Also see my answer to this related question for an explanation and illustration of his method.

Android Webview - Completely Clear the Cache

Make sure you use below method for the form data not be displayed as autopop when clicked on input fields.

getSettings().setSaveFormData(false);

Passing data between controllers in Angular JS?

FYI The $scope Object has the $emit, $broadcast, $on AND The $rootScope Object has the identical $emit, $broadcast, $on

read more about publish/subscribe design pattern in angular here

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

I got this error loading a http:// URL where the server replied with a redirect to https. After changing the URL I pass to WKWebView to https://... it worked.

How can I get the MAC and the IP address of a connected client in PHP?

under linux using iptables you can log to a file each request to web server with mac address and ip. from php lookup last item with ip address and get mac address.

As stated remember that the mac address is from last router on the trace.

appending list but error 'NoneType' object has no attribute 'append'

I think what you want is this:

last_list=[]
if p.last_name != None and p.last_name != "":
    last_list.append(p.last_name)
print last_list

Your current if statement:

if p.last_name == None or p.last_name == "":
    pass

Effectively never does anything. If p.last_name is none or the empty string, it does nothing inside the loop. If p.last_name is something else, the body of the if statement is skipped.

Also, it looks like your statement pan_list.append(p.last) is a typo, because I see neither pan_list nor p.last getting used anywhere else in the code you have posted.

How to change line width in IntelliJ (from 120 character)

It may be useful to notice that very good answers given above may not be enough. It is because of one more tick is required here:

enter image description here

Difference between numpy.array shape (R, 1) and (R,)

The data structure of shape (n,) is called a rank 1 array. It doesn't behave consistently as a row vector or a column vector which makes some of its operations and effects non intuitive. If you take the transpose of this (n,) data structure, it'll look exactly same and the dot product will give you a number and not a matrix. The vectors of shape (n,1) or (1,n) row or column vectors are much more intuitive and consistent.

PHP preg replace only allow numbers

You could also use T-Regx library:

pattern('\D')->remove($c)

T-Regx also:

  • Throws exceptions on fail (not false, null or warnings)
  • Has automatic delimiters (delimiters are not required!)
  • Has a lot cleaner api

How do I draw a grid onto a plot in Python?

You want to use pyplot.grid:

x = numpy.arange(0, 1, 0.05)
y = numpy.power(x, 2)

fig = plt.figure()
ax = fig.gca()
ax.set_xticks(numpy.arange(0, 1, 0.1))
ax.set_yticks(numpy.arange(0, 1., 0.1))
plt.scatter(x, y)
plt.grid()
plt.show()

ax.xaxis.grid and ax.yaxis.grid can control grid lines properties.

Enter image description here

Testing if a list of integer is odd or even

--simple codes--

        #region odd / even numbers  order by desc

        //declaration of integer
        int TotalCount = 50;
        int loop;

        Console.WriteLine("\n---------Odd Numbers -------\n");

        for (loop = TotalCount; loop >= 0; loop--)
        {
            if (loop % 2 == 0)
            {
                Console.WriteLine("Even numbers : #{0}", loop);
            }
        }

        Console.WriteLine("\n---------Even Numbers -------\n");

        for (loop = TotalCount; loop >= 0; loop--)
        {
            if (loop % 2 != 0)
            {
                Console.WriteLine("odd numbers : #{0}", loop);
            }
        }

        Console.ReadLine();

        #endregion

Is there any difference between a GUID and a UUID?

The simple answer is: **no difference, they are the same thing.

2020-08-20 Update: While GUIDs (as used by Microsoft) and UUIDs (as defined by RFC4122) look similar and serve similar purposes, there are subtle-but-occasionally-important differences. Specifically, some Microsoft GUID docs allow GUIDs to contain any hex digit in any position, while RFC4122 requires certain values for the version and variant fields. Also, [per that same link], GUIDs should be all-upper case, whereas UUIDs should be "output as lower case characters and are case insensitive on input". This can lead to incompatibilities between code libraries (such as this).

(Original answer follows)


Treat them as a 16 byte (128 bits) value that is used as a unique value. In Microsoft-speak they are called GUIDs, but call them UUIDs when not using Microsoft-speak.

Even the authors of the UUID specification and Microsoft claim they are synonyms:

  • From the introduction to IETF RFC 4122 "A Universally Unique IDentifier (UUID) URN Namespace": "a Uniform Resource Name namespace for UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier)."

  • From the ITU-T Recommendation X.667, ISO/IEC 9834-8:2004 International Standard: "UUIDs are also known as Globally Unique Identifiers (GUIDs), but this term is not used in this Recommendation."

  • And Microsoft even claims a GUID is specified by the UUID RFC: "In Microsoft Windows programming and in Windows operating systems, a globally unique identifier (GUID), as specified in [RFC4122], is ... The term universally unique identifier (UUID) is sometimes used in Windows protocol specifications as a synonym for GUID."

But the correct answer depends on what the question means when it says "UUID"...

The first part depends on what the asker is thinking when they are saying "UUID".

Microsoft's claim implies that all UUIDs are GUIDs. But are all GUIDs real UUIDs? That is, is the set of all UUIDs just a proper subset of the set of all GUIDs, or is it the exact same set?

Looking at the details of the RFC 4122, there are four different "variants" of UUIDs. This is mostly because such 16 byte identifiers were in use before those specifications were brought together in the creation of a UUID specification. From section 4.1.1 of RFC 4122, the four variants of UUID are:

  1. Reserved, Network Computing System backward compatibility
  2. The variant specified in RFC 4122 (of which there are five sub-variants, which are called "versions")
  3. Reserved, Microsoft Corporation backward compatibility
  4. Reserved for future definition.

According to RFC 4122, all UUID variants are "real UUIDs", then all GUIDs are real UUIDs. To the literal question "is there any difference between GUID and UUID" the answer is definitely no for RFC 4122 UUIDs: no difference (but subject to the second part below).

But not all GUIDs are variant 2 UUIDs (e.g. Microsoft COM has GUIDs which are variant 3 UUIDs). If the question was "is there any difference between GUID and variant 2 UUIDs", then the answer would be yes -- they can be different. Someone asking the question probably doesn't know about variants and they might be only thinking of variant 2 UUIDs when they say the word "UUID" (e.g. they vaguely know of the MAC address+time and the random number algorithms forms of UUID, which are both versions of variant 2). In which case, the answer is yes different.

So the answer, in part, depends on what the person asking is thinking when they say the word "UUID". Do they mean variant 2 UUID (because that is the only variant they are aware of) or all UUIDs?

The second part depends on which specification being used as the definition of UUID.

If you think that was confusing, read the ITU-T X.667 ISO/IEC 9834-8:2004 which is supposed to be aligned and fully technically compatible with RFC 4122. It has an extra sentence in Clause 11.2 that says, "All UUIDs conforming to this Recommendation | International Standard shall have variant bits with bit 7 of octet 7 set to 1 and bit 6 of octet 7 set to 0". Which means that only variant 2 UUID conform to that Standard (those two bit values mean variant 2). If that is true, then not all GUIDs are conforming ITU-T/ISO/IEC UUIDs, because conformant ITU-T/ISO/IEC UUIDs can only be variant 2 values.

Therefore, the real answer also depends on which specification of UUID the question is asking about. Assuming we are clearly talking about all UUIDs and not just variant 2 UUIDs: there is no difference between GUID and IETF's UUIDs, but yes difference between GUID and conforming ITU-T/ISO/IEC's UUIDs!

Binary encodings could differ

When encoded in binary (as opposed to the human-readable text format), the GUID may be stored in a structure with four different fields as follows. This format differs from the [UUID standard] 8 only in the byte order of the first 3 fields.

Bits  Bytes Name   Endianness  Endianness
                   (GUID)      RFC 4122

32    4     Data1  Native      Big
16    2     Data2  Native      Big
16    2     Data3  Native      Big
64    8     Data4  Big         Big

MVC4 input field placeholder

An alternative to using a plugin is using an editor template. What you need to do is to create a template file in Shared\EditorTemplates folder and call it String.cshtml. Then put this in that file:

@Html.TextBox("",ViewData.TemplateInfo.FormattedModelValue, 
    new { placeholder = ViewData.ModelMetadata.Watermark })

Then use it in your view like this:

@Html.EditorFor(m=>Model.UnitPercent)

The downside, this works for properties of type string, and you will have to create a template for each type that you want support for a watermark.

Error: stray '\240' in program

SOLUTION: DELETE THAT LINE OF CODE [*IF YOU COPIED IT FROM ANOTHER SOURCE DOCUMENT] AND TYPE IT YOURSELF.

Error: stray '\240' in program is simply a character encoding error message.

From my experience, it is just a matter of character encoding. For example, if you copy a piece of code from a web page or you first write it in a text editor before copying and pasting in an IDE, it can come with the character encoding of the source document or editor.

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap

The problem is that when we use application/x-www-form-urlencoded, Spring doesn't understand it as a RequestBody. So, if we want to use this we must remove the @RequestBody annotation.

Then try the following:

@RequestMapping(value = "/{email}/authenticate", method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, 
        produces = {MediaType.APPLICATION_ATOM_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody  Representation authenticate(@PathVariable("email") String anEmailAddress, MultiValueMap paramMap) throws Exception {
   if(paramMap == null && paramMap.get("password") == null) {
        throw new IllegalArgumentException("Password not provided");
    }
    return null;
}

Note that removed the annotation @RequestBody

answer: Http Post request with content type application/x-www-form-urlencoded not working in Spring

How do I find out what version of WordPress is running?

On the Admin Panel Dashboard, you can find a box called "Right Now". There you can see the version of the WordPress installation. I have seen this result in WordPress 3.2.1. You can also see this in version 3.7.1

WordPress Version 3.7.1

UPDATE:

In WP Version 3.8.3

WordPress Version 3.8.3

In WP Version 3.9.1 Admin Side, You can see the version by clicking the WP logo which is located at the left-top position.

WordPress Version 3.9.1

You can use yoursitename/readme.html

In the WordPress Admin Footer at the Right side, you will see the version info(Version 3.9.1).

In WP 4

You can get the WordPress version using the following code:

<?php bloginfo('version'); ?>

The below file is having all version details

wp-includes/version.php   

Update for WP 4.1.5

In WP 4.1.5, If it was the latest WP version in the footer right part, it will show the version as it is. If not, it will show the latest WP version with the link to update.

Check the below screenshot.

WP 4.1.5

Sort Dictionary by keys

I tried all of the above, in a nutshell all you need is

let sorted = dictionary.sorted { $0.key < $1.key }
let keysArraySorted = Array(sorted.map({ $0.key }))
let valuesArraySorted = Array(sorted.map({ $0.value }))

Excel - find cell with same value in another worksheet and enter the value to the left of it

Assuming employee numbers are in the first column and their names are in the second:

=VLOOKUP(A1, Sheet2!A:B, 2,false)

Try reinstalling `node-sass` on node 0.12?

I removed all the /node_modules folder then ran npm install and it worked.

I have node v5.5.0, npm 3.3.12

Origin http://localhost is not allowed by Access-Control-Allow-Origin

You've got two ways to go forward:

JSONP


If this API supports JSONP, the easiest way to fix this issue is to add &callback to the end of the URL. You can also try &callback=. If that doesn't work, it means the API does not support JSONP, so you must try the other solution.

Proxy Script


You can create a proxy script on the same domain as your website in order to avoid the cross-origin issues. This will only work with HTTP URLs, not HTTPS URLs, but it shouldn't be too difficult to modify if you need that.

<?php
// File Name: proxy.php
if (!isset($_GET['url'])) {
    die(); // Don't do anything if we don't have a URL to work with
}
$url = urldecode($_GET['url']);
$url = 'http://' . str_replace('http://', '', $url); // Avoid accessing the file system
echo file_get_contents($url); // You should probably use cURL. The concept is the same though

Then you just call this script with jQuery. Be sure to urlencode the URL.

$.ajax({
    url      : 'proxy.php?url=http%3A%2F%2Fapi.master18.tiket.com%2Fsearch%2Fautocomplete%2Fhotel%3Fq%3Dmah%26token%3D90d2fad44172390b11527557e6250e50%26secretkey%3D83e2f0484edbd2ad6fc9888c1e30ea44%26output%3Djson',
    type     : 'GET',
    dataType : 'json'
}).done(function(data) {
    console.log(data.results.result[1].category); // Do whatever you want here
});

The Why


You're getting this error because of XMLHttpRequest same origin policy, which basically boils down to a restriction of ajax requests to URLs with a different port, domain or protocol. This restriction is in place to prevent cross-site scripting (XSS) attacks.

More Information

Our solutions by pass these problems in different ways.

JSONP uses the ability to point script tags at JSON (wrapped in a javascript function) in order to receive the JSON. The JSONP page is interpreted as javascript, and executed. The JSON is passed to your specified function.

The proxy script works by tricking the browser, as you're actually requesting a page on the same origin as your page. The actual cross-origin requests happen server-side.

Max value of Xmx and Xms in Eclipse?

I am guessing you are using a 32 bit eclipse with 32 bit JVM. It wont allow heapsize above what you have specified.

Using a 64-bit Eclipse with a 64-bit JVM helps you to start up eclipse with much larger memory. (I am starting with -Xms1024m -Xmx4000m)

How do I get the size of a java.sql.ResultSet?

Give column a name..

String query = "SELECT COUNT(*) as count FROM

Reference that column from the ResultSet object into an int and do your logic from there..

PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, item.getProductId());
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
    int count = resultSet.getInt("count");
    if (count >= 1) {
        System.out.println("Product ID already exists.");
    } else {
        System.out.println("New Product ID.");
    }
}

Check if a Postgres JSON array contains a string

You could use @> operator to do this something like

SELECT info->>'name'
FROM rabbits
WHERE info->'food' @> '"carrots"';

Line break in SSRS expression

In my case, Environment.NewLine was working fine while previewing the report in Visual Studio. But when I tried to publish the rdl to Dynamics 365 CE, I received the error "The report server has RDLSandboxing enabled and the Value expression for the text box 'Textbox10' contains a reference to a type, namespace, or member 'Environment' that is not allowed."

So I had to replace Environment.NewLine with vbcrlf.

window.close() doesn't work - Scripts may close only the windows that were opened by it

The below code worked for me :)

window.open('your current page URL', '_self', '');
window.close();

powershell 2.0 try catch how to access the exception

Try something like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    Write-Host $_.Exception.ToString()
}

The exception is in the $_ variable. You might explore $_ like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    $_ | fl * -Force
}

I think it will give you all the info you need.

My rule: if there is some data that is not displayed, try to use -force.

SQLite select where empty?

You can do this with the following:

int counter = 0;
String sql = "SELECT projectName,Owner " + "FROM Project WHERE Owner= ?";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setString(1, "");
ResultSet rs = prep.executeQuery();
while (rs.next()) {
    counter++;
}
System.out.println(counter);

This will give you the no of rows where the column value is null or blank.

RecyclerView inside ScrollView is not working

This does the trick:

recyclerView.setNestedScrollingEnabled(false);

JSONObject - How to get a value?

This may be helpful while searching keys present in nested objects and nested arrays. And this is a generic solution to all cases.

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MyClass
{
    public static Object finalresult = null;
    public static void main(String args[]) throws JSONException
    {
        System.out.println(myfunction(myjsonstring,key));
    }

    public static Object myfunction(JSONObject x,String y) throws JSONException
    {
        JSONArray keys =  x.names();
        for(int i=0;i<keys.length();i++)
        {
            if(finalresult!=null)
            {
                return finalresult;                     //To kill the recursion
            }

            String current_key = keys.get(i).toString();

            if(current_key.equals(y))
            {
                finalresult=x.get(current_key);
                return finalresult;
            }

            if(x.get(current_key).getClass().getName().equals("org.json.JSONObject"))
            {
                myfunction((JSONObject) x.get(current_key),y);
            }
            else if(x.get(current_key).getClass().getName().equals("org.json.JSONArray"))
            {
                for(int j=0;j<((JSONArray) x.get(current_key)).length();j++)
                {
                    if(((JSONArray) x.get(current_key)).get(j).getClass().getName().equals("org.json.JSONObject"))
                    {
                        myfunction((JSONObject)((JSONArray) x.get(current_key)).get(j),y);
                    }
                }
            }
        }
        return null;
    }
}

Possibilities:

  1. "key":"value"
  2. "key":{Object}
  3. "key":[Array]

Logic :

  • I check whether the current key and search key are the same, if so I return the value of that key.
  • If it is an object, I send the value recursively to the same function.
  • If it is an array, I check whether it contains an object, if so I recursively pass the value to the same function.

avrdude: stk500v2_ReceiveMessage(): timeout

This isn't really a fixing solution but it may help others. Unlike Nick had said for me it was due to code in my program. I have the mega ADK model. The issue was tied to a switch statement for processing and parsing the returned byte[] from the usb connection to the Android. Its very strange because it would compile perfectly every time but would fail as the OP had stated. I commented it out and it worked fine.

Unable to cast object of type 'System.DBNull' to type 'System.String`

There is another way to workaround this issue. How about modify your store procedure? by using ISNULL(your field, "") sql function , you can return empty string if the return value is null.

Then you have your clean code as original version.

Getting one value from a tuple

For anyone in the future looking for an answer, I would like to give a much clearer answer to the question.

# for making a tuple
my_tuple = (89, 32)
my_tuple_with_more_values = (1, 2, 3, 4, 5, 6)

# to concatenate tuples
another_tuple = my_tuple + my_tuple_with_more_values
print(another_tuple)
# (89, 32, 1, 2, 3, 4, 5, 6)

# getting a value from a tuple is similar to a list
first_val = my_tuple[0]
second_val = my_tuple[1]

# if you have a function called my_tuple_fun that returns a tuple,
# you might want to do this
my_tuple_fun()[0]
my_tuple_fun()[1]

# or this
v1, v2 = my_tuple_fun()

Hope this clears things up further for those that need it.

Why doesn't Dijkstra's algorithm work for negative weight edges?

Consider the graph shown below with the source as Vertex A. First try running Dijkstra’s algorithm yourself on it.

enter image description here

When I refer to Dijkstra’s algorithm in my explanation I will be talking about the Dijkstra's Algorithm as implemented below,

Dijkstra’s algorithm

So starting out the values (the distance from the source to the vertex) initially assigned to each vertex are,

initialization

We first extract the vertex in Q = [A,B,C] which has smallest value, i.e. A, after which Q = [B, C]. Note A has a directed edge to B and C, also both of them are in Q, therefore we update both of those values,

first iteration

Now we extract C as (2<5), now Q = [B]. Note that C is connected to nothing, so line16 loop doesn't run.

second iteration

Finally we extract B, after which Q is Phi. Note B has a directed edge to C but C isn't present in Q therefore we again don't enter the for loop in line16,

3rd?

So we end up with the distances as

no change guys

Note how this is wrong as the shortest distance from A to C is 5 + -10 = -5, when you go a to b to c.

So for this graph Dijkstra's Algorithm wrongly computes the distance from A to C.

This happens because Dijkstra's Algorithm does not try to find a shorter path to vertices which are already extracted from Q.

What the line16 loop is doing is taking the vertex u and saying "hey looks like we can go to v from source via u, is that (alt or alternative) distance any better than the current dist[v] we got? If so lets update dist[v]"

Note that in line16 they check all neighbors v (i.e. a directed edge exists from u to v), of u which are still in Q. In line14 they remove visited notes from Q. So if x is a visited neighbour of u, the path source to u to x is not even considered as a possible shorter way from source to v.

In our example above, C was a visited neighbour of B, thus the path A to B to C was not considered, leaving the current shortest path A to C unchanged.

This is actually useful if the edge weights are all positive numbers, because then we wouldn't waste our time considering paths that can't be shorter.

So I say that when running this algorithm if x is extracted from Q before y, then its not possible to find a path - not possible which is shorter. Let me explain this with an example,

As y has just been extracted and x had been extracted before itself, then dist[y] > dist[x] because otherwise y would have been extracted before x. (line 13 min distance first)

And as we already assumed that the edge weights are positive, i.e. length(x,y)>0. So the alternative distance (alt) via y is always sure to be greater, i.e. dist[y] + length(x,y)> dist[x]. So the value of dist[x] would not have been updated even if y was considered as a path to x, thus we conclude that it makes sense to only consider neighbors of y which are still in Q (note comment in line16)

But this thing hinges on our assumption of positive edge length, if length(u,v)<0 then depending on how negative that edge is we might replace the dist[x] after the comparison in line18.

So any dist[x] calculation we make will be incorrect if x is removed before all vertices v - such that x is a neighbour of v with negative edge connecting them - is removed.

Because each of those v vertices is the second last vertex on a potential "better" path from source to x, which is discarded by Dijkstra’s algorithm.

So in the example I gave above, the mistake was because C was removed before B was removed. While that C was a neighbour of B with a negative edge!

Just to clarify, B and C are A's neighbours. B has a single neighbour C and C has no neighbours. length(a,b) is the edge length between the vertices a and b.

JavaScript - Get Portion of URL Path

There is a useful Web API method called URL

_x000D_
_x000D_
const url = new URL('http://www.somedomain.com/account/search?filter=a#top');_x000D_
console.log(url.pathname.split('/'));_x000D_
const params = new URLSearchParams(url.search)_x000D_
console.log(params.get("filter"))
_x000D_
_x000D_
_x000D_

Android 'Unable to add window -- token null is not for an application' exception

I solved this error by add below user-permission in AndroidManifest.xml

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

Also, Initialize Alert dialog with Activity Name:

AlertDialog.Builder builder = new AlertDialog.Builder(YourActivity.this);

For More Details, visit==> How to create Alert Dialog in Android

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

I faced same error but in a different way.

When you curl a page with a specific SSL protocol.

curl --sslv3 https://example.com

If --sslv3 is not supported by the target server then the error will be

curl: (35) TCP connection reset by peer

With the supported protocol, error will be gone.

curl --tlsv1.2 https://example.com

Reverse order of foreach list items

<?php
    $j=1; 


      array_reverse($skills_nav);   


    foreach ( $skills_nav as $skill ) {
        $a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
        $a .= $skill->name;                 
        $a .= '</a></li>';
        echo $a;
        echo "\n";
        $j++;
    }
?> 

How to solve Permission denied (publickey) error when using Git?

I was struggling with same problem that's what i did and i was able clone the repo. I followed these procedure for iMac.

First Step : Checking if we already have the public SSH key.

  1. Open Terminal.
  2. Enter ls -al ~/.ssh to see if existing SSH keys are present:

Check the directory listing to see if you already have a public SSH key.Default public are one of the following d_dsa.pub,id_ecdsa.pub,id_ed25519.pub,id_rsa.pub

If you don't find then go to step 2 otherwise follow step 3

Step 2 : Generating public SSH key

  1. Open Terminal.
  2. Enter followong command with you valid email address that you use for github ssh-keygen -t rsa -b 4096 -C "[email protected]"
  3. You will see following in terminal Generating public/private rsa key pair. When it prompts to"Enter a file in which to save the key," press Enter. This accepts the default file location. When it prompts to Enter a file in which to save the key (/Users/you/.ssh/id_rsa): [Press enter] Just press enter again. At the prompt, type a secure passphrase.
  4. Enter passphrase (empty for no passphrase): [Type a passphrase] press enter if you don't want to Enter same passphrase again: [Type passphrase again] press enter again

This will generate id_rsa.pub

Step 3: Adding your SSH key to the ssh-agent

  1. Interminal type eval "$(ssh-agent -s)"
  2. Add your SSH key to the ssh-agent. If you are using an existing SSH key rather than generating a new SSH key, you'll need to replace id_rsa in the command with the name of your existing private key file. Enter this command $ ssh-add -K ~/.ssh/id_rsa

Now copy the SSH key and also add it to you github account

  1. In terminal enter this command with your ssh file name pbcopy < ~/.ssh/id_rsa.pub This will copy the file to your clipboard Now open you github account Go to Settings > SSH and GPG keys > New SSH key Enter title and paste the key from clipboard and save it. Voila you're done.

Passing parameter using onclick or a click binding with KnockoutJS

A generic answer on how to handle click events with KnockoutJS...

Not a straight up answer to the question as asked, but probably an answer to the question most Googlers landing here have: use the click binding from KnockoutJS instead of onclick. Like this:

_x000D_
_x000D_
function Item(parent, txt) {_x000D_
  var self = this;_x000D_
  _x000D_
  self.doStuff = function(data, event) {_x000D_
    console.log(data, event);_x000D_
    parent.log(parent.log() + "\n  data = " + ko.toJSON(data));_x000D_
  };_x000D_
  _x000D_
  self.doOtherStuff = function(customParam, data, event) {_x000D_
    console.log(data, event);_x000D_
    parent.log(parent.log() + "\n  data = " + ko.toJSON(data) + ", customParam = " + customParam);_x000D_
  };_x000D_
  _x000D_
  self.txt = ko.observable(txt);_x000D_
}_x000D_
_x000D_
function RootVm(items) {_x000D_
  var self = this;_x000D_
  _x000D_
  self.doParentStuff = function(data, event) {_x000D_
    console.log(data, event);_x000D_
    self.log(self.log() + "\n  data = " + ko.toJSON(data));_x000D_
  };_x000D_
  _x000D_
  self.items = ko.observableArray([_x000D_
    new Item(self, "John Doe"),_x000D_
    new Item(self, "Marcus Aurelius")_x000D_
  ]);_x000D_
  self.log = ko.observable("Started logging...");_x000D_
}_x000D_
_x000D_
ko.applyBindings(new RootVm());
_x000D_
.parent { background: rgba(150, 150, 200, 0.5); padding: 2px; margin: 5px; }_x000D_
button { margin: 2px 0; font-family: consolas; font-size: 11px; }_x000D_
pre { background: #eee; border: 1px solid #ccc; padding: 5px; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>_x000D_
_x000D_
<div data-bind="foreach: items">_x000D_
  <div class="parent">_x000D_
    <span data-bind="text: txt"></span><br>_x000D_
    <button data-bind="click: doStuff">click: doStuff</button><br>_x000D_
    <button data-bind="click: $parent.doParentStuff">click: $parent.doParentStuff</button><br>_x000D_
    <button data-bind="click: $root.doParentStuff">click: $root.doParentStuff</button><br>_x000D_
    <button data-bind="click: function(data, event) { $parent.log($parent.log() + '\n  data = ' + ko.toJSON(data)); }">click: function(data, event) { $parent.log($parent.log() + '\n  data = ' + ko.toJSON(data)); }</button><br>_x000D_
    <button data-bind="click: doOtherStuff.bind($data, 'test 123')">click: doOtherStuff.bind($data, 'test 123')</button><br>_x000D_
    <button data-bind="click: function(data, event) { doOtherStuff('test 123', $data, event); }">click: function(data, event) { doOtherStuff($data, 'test 123', event); }</button><br>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
Click log:_x000D_
<pre data-bind="text: log"></pre>
_x000D_
_x000D_
_x000D_


**A note about the actual question...*

The actual question has one interesting bit:

// Uh oh! Modifying the DOM....
place.innerHTML = "somthing"

Don't do that! Don't modify the DOM like that when using an MVVM framework like KnockoutJS, especially not the piece of the DOM that is your own parent. If you would do this the button would disappear (if you replace your parent's innerHTML you yourself will be gone forever ever!).

Instead, modify the View Model in your handler instead, and have the View respond. For example:

_x000D_
_x000D_
function RootVm() {_x000D_
  var self = this;_x000D_
  self.buttonWasClickedOnce = ko.observable(false);_x000D_
  self.toggle = function(data, event) {_x000D_
    self.buttonWasClickedOnce(!self.buttonWasClickedOnce());_x000D_
  };_x000D_
}_x000D_
_x000D_
ko.applyBindings(new RootVm());
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div  data-bind="visible: !buttonWasClickedOnce()">_x000D_
    <button data-bind="click: toggle">Toggle!</button>_x000D_
  </div>_x000D_
  <div data-bind="visible: buttonWasClickedOnce">_x000D_
    Can be made visible with toggle..._x000D_
    <button data-bind="click: toggle">Untoggle!</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to convert a single char into an int

You can utilize the fact that the character encodings for digits are all in order from 48 (for '0') to 57 (for '9'). This holds true for ASCII, UTF-x and practically all other encodings (see comments below for more on this).

Therefore the integer value for any digit is the digit minus '0' (or 48).

char c = '1';
int i = c - '0'; // i is now equal to 1, not '1'

is synonymous to

char c = '1';
int i = c - 48; // i is now equal to 1, not '1'

However I find the first c - '0' far more readable.

How can I find the first occurrence of a sub-string in a python string?

Quick Overview: index and find

Next to the find method there is as well index. find and index both yield the same result: returning the position of the first occurrence, but if nothing is found index will raise a ValueError whereas find returns -1. Speedwise, both have the same benchmark results.

s.find(t)    #returns: -1, or index where t starts in s
s.index(t)   #returns: Same as find, but raises ValueError if t is not in s

Additional knowledge: rfind and rindex:

In general, find and index return the smallest index where the passed-in string starts, and rfind and rindex return the largest index where it starts Most of the string searching algorithms search from left to right, so functions starting with r indicate that the search happens from right to left.

So in case that the likelihood of the element you are searching is close to the end than to the start of the list, rfind or rindex would be faster.

s.rfind(t)   #returns: Same as find, but searched right to left
s.rindex(t)  #returns: Same as index, but searches right to left

Source: Python: Visual QuickStart Guide, Toby Donaldson

How do I fix the indentation of selected lines in Visual Studio

For the Mac users.

For selecting all of the code in the document => cmd+A

For formatting selected code => cmd+K, cmd+F

How to log a method's execution time exactly in milliseconds?

Here are two one-line macros that I use:

#define TICK   NSDate *startTime = [NSDate date]
#define TOCK   NSLog(@"Time: %f", -[startTime timeIntervalSinceNow])

Use it like this:

TICK;

/* ... Do Some Work Here ... */

TOCK;

NoClassDefFoundError on Maven dependency

By default, Maven doesn't bundle dependencies in the JAR file it builds, and you're not providing them on the classpath when you're trying to execute your JAR file at the command-line. This is why the Java VM can't find the library class files when trying to execute your code.

You could manually specify the libraries on the classpath with the -cp parameter, but that quickly becomes tiresome.

A better solution is to "shade" the library code into your output JAR file. There is a Maven plugin called the maven-shade-plugin to do this. You need to register it in your POM, and it will automatically build an "uber-JAR" containing your classes and the classes for your library code too when you run mvn package.

To simply bundle all required libraries, add the following to your POM:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.2.4</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  ...
</project>

Once this is done, you can rerun the commands you used above:

$ mvn package
$ java -cp target/bil138_4-0.0.1-SNAPSHOT.jar tr.edu.hacettepe.cs.b21127113.bil138_4.App

If you want to do further configuration of the shade plugin in terms of what JARs should be included, specifying a Main-Class for an executable JAR file, and so on, see the "Examples" section on the maven-shade-plugin site.

Using python map and other functional tools

Here's an overview of the parameters to the map(function, *sequences) function:

  • function is the name of your function.
  • sequences is any number of sequences, which are usually lists or tuples. map will iterate over them simultaneously and give the current values to function. That's why the number of sequences should equal the number of parameters to your function.

It sounds like you're trying to iterate for some of function's parameters but keep others constant, and unfortunately map doesn't support that. I found an old proposal to add such a feature to Python, but the map construct is so clean and well-established that I doubt something like that will ever be implemented.

Use a workaround like global variables or list comprehensions, as others have suggested.

How do I assign a port mapping to an existing Docker container?

Editing hostconfig.json seems to not working now. It only ends with that port being exposed but not published to host. Commiting and recreating containers is not the best approach to me. No one mentioned docker network?

The best solution would be using reversed proxy within the same network

  1. Create a new network if your previous container not in any named ones.

    docker network create my_network

  2. Join your existing container to the created network

    docker network connect my_network my_existing_container

  3. Start a reversed proxy service(e.g. nginx) publishing the ports you need, joining the same network

    docker run -d --name nginx --network my_network -p 9000:9000 nginx

    Optionally remove the default.conf in nginx

    docker exec nginx rm /etc/nginx/conf.d/default.conf

  4. Create a new nginx config

    server
    {
        listen 9000;
    
        location / {
            proxy_pass http://my_existing_container:9000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }
    }
    

    Copy the config to nginx container.

    docker cp ./my_conf.conf nginx:/etc/nginx/conf.d/my_conf.conf

  5. Restart nginx

    docker restart nginx

Advantages: To publish new ports, you can safely stop/update/recreate nginx container as you wish without touching the business container. If you need zero down time for nginx, it is possible to add more reversed proxy services joining the same network. Besides, a container can join more than one network.

Edit:

To reverse proxy non-http services, the config file is a bit different. Here is a simple example:

upstream my_service {
    server my_existing_container:9000;
}

server {
    listen 9000;
    proxy_pass my_service;
}

git diff between cloned and original remote repository

This example might help someone:

Note "origin" is my alias for remote "What is on Github"
Note "mybranch" is my alias for my branch "what is local" that I'm syncing with github
--your branch name is 'master' if you didn't create one. However, I'm using the different name mybranch to show where the branch name parameter is used.


What exactly are my remote repos on github?

$ git remote -v
origin  https://github.com/flipmcf/Playground.git (fetch)
origin  https://github.com/flipmcf/Playground.git (push)

Add the "other github repository of the same code" - we call this a fork:

$ git remote add someOtherRepo https://github.com/otherUser/Playground.git

$git remote -v
origin  https://github.com/flipmcf/Playground.git (fetch)
origin  https://github.com/flipmcf/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (fetch)

make sure our local repo is up to date:

$ git fetch

Change some stuff locally. let's say file ./foo/bar.py

$ git status
# On branch mybranch
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   foo/bar.py

Review my uncommitted changes

$ git diff mybranch
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index b4fb1be..516323b 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.

Commit locally.

$ git commit foo/bar.py -m"I changed stuff"
[myfork 9f31ff7] I changed stuff
1 files changed, 2 insertions(+), 1 deletions(-)

Now, I'm different than my remote (on github)

$ git status
# On branch mybranch
# Your branch is ahead of 'origin/mybranch' by 1 commit.
#
nothing to commit (working directory clean)

Diff this with remote - your fork: (this is frequently done with git diff master origin)

$ git diff mybranch origin
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index 516323b..b4fb1be 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.

(git push to apply these to remote)

How does my remote branch differ from the remote master branch?

$ git diff origin/mybranch origin/master

How does my local stuff differ from the remote master branch?

$ git diff origin/master

How does my stuff differ from someone else's fork, master branch of the same repo?

$git diff mybranch someOtherRepo/master

Get the name of an object's type

Use constructor.name when you can, and regex function when I can't.

Function.prototype.getName = function(){
  if (typeof this.name != 'undefined')
    return this.name;
  else
    return /function (.+)\(/.exec(this.toString())[1];
};

Draw on HTML5 Canvas using a mouse

Googled this ("html5 canvas paint program"). Looks like what you need.

http://dev.opera.com/articles/view/html5-canvas-painting/

jQuery ajax success error

Try to set response dataType property directly:

dataType: 'text'

and put

die(''); 

in the end of your php file. You've got error callback cause jquery cannot parse your response. In anyway, you may use a "complete:" callback, just to make sure your request has been processed.

Delete specific values from column with where condition?

You can also use REPLACE():

UPDATE Table
   SET Column = REPLACE(Column, 'Test123', 'Test')

Ignore .pyc files in git repository

If you want to ignore '.pyc' files globally (i.e. if you do not want to add the line to .gitignore file in every git directory), try the following:

$ cat ~/.gitconfig 
[core]
    excludesFile = ~/.gitignore
$ cat ~/.gitignore
**/*.pyc

[Reference]
https://git-scm.com/docs/gitignore

  • Patterns which a user wants Git to ignore in all situations (e.g., backup or temporary files generated by the user’s editor of choice) generally go into a file specified by core.excludesFile in the user’s ~/.gitconfig.

  • A leading "**" followed by a slash means match in all directories. For example, "**/foo" matches file or directory "foo" anywhere, the same as pattern "foo". "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo".

Get ASCII value at input word

char ch='A';

System.out.println((int)ch);

Convert string to Color in C#

 Color red = Color.FromName("Red");   

The MSDN doesn't say one way or another, so there's a good chance that it is case-sensitive. (UPDATE: Apparently, it is not.)

As far as I can tell, ColorTranslator.FromHtml is also.

If Color.FromName cannot find a match, it returns new Color(0,0,0);

If ColorTranslator.FromHtml cannot find a match, it throws an exception.

UPDATE:

Since you're using Microsoft.Xna.Framework.Graphics.Color, this gets a bit tricky:

using XColor = Microsoft.Xna.Framework.Graphics.Color;
using CColor = System.Drawing.Color;

 CColor clrColor = CColor.FromName("Red"); 
 XColor xColor = new XColor(clrColor.R, clrColor.G, clrColor.B, clrColor.A);

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

For other future users who do not want to make their controllers asynchronous, or cannot access the HttpContext, or are using dotnet core (this answer is the first I found on Google trying to do this), the following worked for me:

[HttpPut("{pathId}/{subPathId}"),
public IActionResult Put(int pathId, int subPathId, [FromBody] myViewModel viewModel)
{

    var body = new StreamReader(Request.Body);
    //The modelbinder has already read the stream and need to reset the stream index
    body.BaseStream.Seek(0, SeekOrigin.Begin); 
    var requestBody = body.ReadToEnd();
    //etc, we use this for an audit trail
}

How to zoom in/out an UIImage object when user pinches screen?

Keep in mind that you're NEVER zooming in on a UIImage. EVER.

Instead, you're zooming in and out on the view that displays the UIImage.

In this particular case, you chould choose to create a custom UIView with custom drawing to display the image, a UIImageView which displays the image for you, or a UIWebView which will need some additional HTML to back it up.

In all cases, you'll need to implement touchesBegan, touchesMoved, and the like to determine what the user is trying to do (zoom, pan, etc.).

How to export a MySQL database to JSON?

Using MySQL Shell you can out put directly to JSON using only terminal

echo "Your SQL query" | mysqlsh --sql --result-format=json --uri=[username]@localhost/[schema_name]

what is the difference between GROUP BY and ORDER BY in sql

ORDER BY alters the order in which items are returned.

GROUP BY will aggregate records by the specified columns which allows you to perform aggregation functions on non-grouped columns (such as SUM, COUNT, AVG, etc).

How do I check whether a checkbox is checked in jQuery?

1) If your HTML markup is:

<input type="checkbox"  />

attr used:

$(element).attr("checked"); // Will give you undefined as initial value of checkbox is not set

If prop is used:

$(element).prop("checked"); // Will give you false whether or not initial value is set

2) If your HTML markup is:

 <input type="checkbox"  checked="checked" />// May be like this also  checked="true"

attr used:

$(element).attr("checked") // Will return checked whether it is checked="true"

Prop used:

$(element).prop("checked") // Will return true whether checked="checked"

Printing the value of a variable in SQL Developer

Go to the DBMS Output window (View->DBMS Output).

How do I build JSON dynamically in javascript?

As myJSON is an object you can just set its properties, for example:

myJSON.list1 = ["1","2"];

If you dont know the name of the properties, you have to use the array access syntax:

myJSON['list'+listnum] = ["1","2"];

If you want to add an element to one of the properties, you can do;

myJSON.list1.push("3");

How to connect to local instance of SQL Server 2008 Express

I used (LocalDB)\MSSQLLocalDB as the server name, I was then able to see all the local databases.

What does "Content-type: application/json; charset=utf-8" really mean?

I was using HttpClient and getting back response header with content-type of application/json, I lost characters such as foreign languages or symbol that used unicode since HttpClient is default to ISO-8859-1. So, be explicit as possible as mentioned by @WesternGun to avoid any possible problem.

There is no way handle that due to server doesn't handle requested-header charset (method.setRequestHeader("accept-charset", "UTF-8");) for me and I had to retrieve response data as draw bytes and convert it into String using UTF-8. So, it is recommended to be explicit and avoid assumption of default value.

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

Anyone who is looking to do this in Ubuntu/linux using php -

Ubuntu comes with libre office installed default. Anyone can use the shell command to use the headless libre office for this.

shell_exec('/usr/bin/libreoffice --headless --convert-to pdf:writer_pdf_Export --outdir /var/www/html/demo/public_html/src/var/output /var/www/html/demo/public_html/src/var/source/sample.doc');

Hope it helps others like me.

Using Gradle to build a jar with dependencies

Simple sulution

jar {
    manifest {
        attributes 'Main-Class': 'cova2.Main'
    } 
    doFirst {
        from { configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) } }
    }
}

Make xargs execute the command once for each line of input

It seems I don't have enough reputation to add a comment to Tobia's answer above, so I am adding this "answer" to help those of us wanting to experiment with xargs the same way on the Windows platforms.

Here is a windows batch file that does the same thing as Tobia's quickly coded "show" script:

@echo off
REM
REM  cool trick of using "set" to echo without new line
REM  (from:  http://www.psteiner.com/2012/05/windows-batch-echo-without-new-line.html)
REM
if "%~1" == "" (
    exit /b
)

<nul set /p=Args:  "%~1"
shift

:start
if not "%~1" == "" (
    <nul set /p=, "%~1"
    shift
    goto start
)
echo.

What is default color for text in textview?

You could use TextView.setTag/getTag to store original color before making changes. I would suggest to create an unique id resource in ids.xml to differentiate other tags if you have.

before setting to other colors:

if (textView.getTag(R.id.txt_default_color) == null) {
    textView.setTag(R.id.txt_default_color, textView.currentTextColor)
}

Changing back:

textView.getTag(R.id.txt_default_color) as? Int then {
    textView.setTextColor(this)
}

SQL Update with row_number()

If table does not have relation, just copy all in new table with row number and remove old and rename new one with old one.

Select   RowNum = ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) , * INTO cdm.dbo.SALES2018 from 
(
select * from SALE2018) as SalesSource

Peak signal detection in realtime timeseries data

I allowed myself to create a javascript version of it. Might it be helpful. The javascript should be direct transcription of the Pseudocode given above. Available as npm package and github repo:

Javascript translation:

// javascript port of: https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/48895639#48895639

function sum(a) {
    return a.reduce((acc, val) => acc + val)
}

function mean(a) {
    return sum(a) / a.length
}

function stddev(arr) {
    const arr_mean = mean(arr)
    const r = function(acc, val) {
        return acc + ((val - arr_mean) * (val - arr_mean))
    }
    return Math.sqrt(arr.reduce(r, 0.0) / arr.length)
}

function smoothed_z_score(y, params) {
    var p = params || {}
    // init cooefficients
    const lag = p.lag || 5
    const threshold = p.threshold || 3.5
    const influence = p.influece || 0.5

    if (y === undefined || y.length < lag + 2) {
        throw ` ## y data array to short(${y.length}) for given lag of ${lag}`
    }
    //console.log(`lag, threshold, influence: ${lag}, ${threshold}, ${influence}`)

    // init variables
    var signals = Array(y.length).fill(0)
    var filteredY = y.slice(0)
    const lead_in = y.slice(0, lag)
    //console.log("1: " + lead_in.toString())

    var avgFilter = []
    avgFilter[lag - 1] = mean(lead_in)
    var stdFilter = []
    stdFilter[lag - 1] = stddev(lead_in)
    //console.log("2: " + stdFilter.toString())

    for (var i = lag; i < y.length; i++) {
        //console.log(`${y[i]}, ${avgFilter[i-1]}, ${threshold}, ${stdFilter[i-1]}`)
        if (Math.abs(y[i] - avgFilter[i - 1]) > (threshold * stdFilter[i - 1])) {
            if (y[i] > avgFilter[i - 1]) {
                signals[i] = +1 // positive signal
            } else {
                signals[i] = -1 // negative signal
            }
            // make influence lower
            filteredY[i] = influence * y[i] + (1 - influence) * filteredY[i - 1]
        } else {
            signals[i] = 0 // no signal
            filteredY[i] = y[i]
        }

        // adjust the filters
        const y_lag = filteredY.slice(i - lag, i)
        avgFilter[i] = mean(y_lag)
        stdFilter[i] = stddev(y_lag)
    }

    return signals
}

module.exports = smoothed_z_score

What is "android.R.layout.simple_list_item_1"?

This is a part of the android OS. Here is the actual version of the defined XML file.

simple_list_item_1:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    style="?android:attr/listItemFirstLineStyle"
    android:paddingTop="2dip"
    android:paddingBottom="3dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

simple_list_item_2:

<TwoLineListItem xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingTop="2dip"
    android:paddingBottom="2dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView android:id="@android:id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        style="?android:attr/listItemFirstLineStyle"/>

    <TextView android:id="@android:id/text2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@android:id/text1"
        style="?android:attr/listItemSecondLineStyle" />

</TwoLineListItem> 

Which regular expression operator means 'Don't' match this character?

^ used at the beginning of a character range, or negative lookahead/lookbehind assertions.

>>> re.match('[^f]', 'foo')
>>> re.match('[^f]', 'bar')
<_sre.SRE_Match object at 0x7f8b102ad6b0>
>>> re.match('(?!foo)...', 'foo')
>>> re.match('(?!foo)...', 'bar')
<_sre.SRE_Match object at 0x7f8b0fe70780>

Python Image Library fails with message "decoder JPEG not available" - PIL

For those on Mac OS Mountain Lion, I followed the anwser of zeantsoi, but it doesn't work.

I finally ended up with the solution of this post: http://appelfreelance.com/2010/06/libjpeg-pil-snow-leopard-python2-6-_jpeg_resync_to_restart/

Now, I'm happily running my script for jpeg !

Google Maps shows "For development purposes only"

try this code it doesn't show “For development purposes only”

<iframe src="http://maps.google.com/maps?q=25.3076008,51.4803216&z=16&output=embed" height="450" width="600"></iframe>

XMLHttpRequest cannot load an URL with jQuery

In new jQuery 1.5 you can use:

$.ajax({
    type: "GET",
    url: "http://localhost:99000/Services.svc/ReturnPersons",
    dataType: "jsonp",
    success: readData(data),
    error: function (xhr, ajaxOptions, thrownError) {
      alert(xhr.status);
      alert(thrownError);
    }
})

How to store an array into mysql?

I'd prefer to normalize your table structure more, something like;

COMMENTS
-------
id (pk)
title
comment
userId


USERS
-----
id (pk)
name
email


COMMENT_VOTE
------------
commentId (pk)
userId (pk)
rating (float)

Now it's easier to maintain! And MySQL only accept one vote per user and comment.

How to add title to subplots in Matplotlib?

If you want to make it shorter, you could write :

import matplolib.pyplot as plt
for i in range(4):
    plt.subplot(2,2,i+1).set_title('Subplot n°{}' .format(i+1))
plt.show()

It makes it maybe less clear but you don't need more lines or variables

using jQuery .animate to animate a div from right to left?

If you know the width of the child element you are animating, you can use and animate a margin offset as well. For example, this will animate from left:0 to right:0

CSS:

.parent{
width:100%;
position:relative;
}

#itemToMove{
position:absolute;
width:150px;
right:100%;
margin-right:-150px;
}

Javascript:

$( "#itemToMove" ).animate({
"margin-right": "0",
"right": "0"
}, 1000 );

How to Create a circular progressbar in Android which rotates on it?

With the Material Components Library you can use the CircularProgressIndicator:

Something like:

<com.google.android.material.progressindicator.CircularProgressIndicator
    app:indicatorColor="@color/...."
    app:trackColor="@color/...."
    app:circularRadius="64dp"/>

You can use these attributes:

  • circularRadius: defines the radius of the circular progress indicator
  • trackColor: the color used for the progress track. If not defined, it will be set to the indicatorColor and apply the android:disabledAlpha from the theme.
  • indicatorColor: the single color used for the indicator in determinate/indeterminate mode. By default it uses theme primary color

enter image description here

Use progressIndicator.setProgressCompat((int) value, true); to update the value in the indicator.

Note: it requires at least the version 1.3.0-alpha04.

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

You can set the value of the element to blank

document.getElementById('elementId').value='';

Request exceeded the limit of 10 internal redirects due to probable configuration error

This error occurred to me when I was debugging the PHP header() function:

header('Location: /aaa/bbb/ccc'); // error

If I use a relative path it works:

header('Location: aaa/bbb/ccc'); // success, but not what I wanted

However when I use an absolute path like /aaa/bbb/ccc, it gives the exact error:

Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

It appears the header function redirects internally without going HTTP at all which is weird. After some tests and trials, I found the solution of adding exit after header():

header('Location: /aaa/bbb/ccc');
exit;

And it works properly.

Handling warning for possible multiple enumeration of IEnumerable

If you only need to check the first element you can peek on it without iterating the whole collection:

public List<object> Foo(IEnumerable<object> objects)
{
    object firstObject;
    if (objects == null || !TryPeek(ref objects, out firstObject))
        throw new ArgumentException();

    var list = DoSomeThing(firstObject);
    var secondList = DoSomeThingElse(objects);
    list.AddRange(secondList);

    return list;
}

public static bool TryPeek<T>(ref IEnumerable<T> source, out T first)
{
    if (source == null)
        throw new ArgumentNullException(nameof(source));

    IEnumerator<T> enumerator = source.GetEnumerator();
    if (!enumerator.MoveNext())
    {
        first = default(T);
        source = Enumerable.Empty<T>();
        return false;
    }

    first = enumerator.Current;
    T firstElement = first;
    source = Iterate();
    return true;

    IEnumerable<T> Iterate()
    {
        yield return firstElement;
        using (enumerator)
        {
            while (enumerator.MoveNext())
            {
                yield return enumerator.Current;
            }
        }
    }
}

How do I use JDK 7 on Mac OSX?

As of December 2017, previously posted links don't work, but JDK 7 can still be downloaded from Oracle Archives (login required):

http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

You need to add sudo . I did the following to get it installed :

sudo apt-get install libsm6 libxrender1 libfontconfig1

and then did that (optional! maybe you won't need it)

sudo python3 -m pip install opencv-contrib-python

FINALLY got it done !

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

Q:Can't bind to 'pSelectableRow' since it isn't a known property of 'tr'.

A:you need to configure the primeng tabulemodule in ngmodule

Computed / calculated / virtual / derived columns in PostgreSQL

Up to Postgres 11 generated columns are not supported - as defined in the SQL standard and implemented by some RDBMS including DB2, MySQL and Oracle. Nor the similar "computed columns" of SQL Server.

STORED generated columns are introduced with Postgres 12. Trivial example:

CREATE TABLE tbl (
  int1    int
, int2    int
, product bigint GENERATED ALWAYS AS (int1 * int2) STORED
);

db<>fiddle here

VIRTUAL generated columns may come with one of the next iterations. (Not in Postgres 13, yet) .

Related:


Until then, you can emulate VIRTUAL generated columns with a function using attribute notation (tbl.col) that looks and works much like a virtual generated column. That's a bit of a syntax oddity which exists in Postgres for historic reasons and happens to fit the case. This related answer has code examples:

The expression (looking like a column) is not included in a SELECT * FROM tbl, though. You always have to list it explicitly.

Can also be supported with a matching expression index - provided the function is IMMUTABLE. Like:

CREATE FUNCTION col(tbl) ... AS ...  -- your computed expression here
CREATE INDEX ON tbl(col(tbl));

Alternatives

Alternatively, you can implement similar functionality with a VIEW, optionally coupled with expression indexes. Then SELECT * can include the generated column.

"Persisted" (STORED) computed columns can be implemented with triggers in a functionally identical way.

Materialized views are a closely related concept, implemented since Postgres 9.3.
In earlier versions one can manage MVs manually.

boolean in an if statement

Since the checked value is Boolean it's preferred to use it directly for less coding and at all it did same ==true

How to change button text or link text in JavaScript?

document.getElementById(button_id).innerHTML = 'Lock';

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

As has been discussed elsewhere, the .length property reference is failing because theHref is undefined. However, be aware of any solution which involves comparing theHref to undefined, which is not a keyword in JavaScript and can be redefined.

For a full discussion of checking for undefined variables, see Detecting an undefined object property and the first answer in particular.

How to 'update' or 'overwrite' a python list

What about replace the item if you know the position:

aList[0]=2014

Or if you don't know the position loop in the list, find the item and then replace it

aList = [123, 'xyz', 'zara', 'abc']
    for i,item in enumerate(aList):
      if item==123:
        aList[i]=2014
        break
    
    print aList

How can I add JAR files to the web-inf/lib folder in Eclipse?

They are automatically added to the project classpath if its a web project. Sometimes it does not work properly, a refresh or close/open of the project helps.

if its not a web project you can right click on the library and go to "Build Path" -> "Add to Build Path"

How to update and order by using ms sql

As stated in comments below, you can use also the SET ROWCOUNT clause, but just for SQL Server 2014 and older.

SET ROWCOUNT 10

UPDATE messages
SET status = 10 
WHERE status = 0 

SET ROWCOUNT 0

More info: http://msdn.microsoft.com/en-us/library/ms188774.aspx

Or with a temp table

DECLARE @t TABLE (id INT)
INSERT @t (id)
SELECT TOP 10 id
FROM messages
WHERE status = 0
ORDER BY priority DESC

UPDATE messages
SET status = 10
WHERE id IN (SELECT id FROM @t)

Passing Multiple route params in Angular2

As detailed in this answer, mayur & user3869623's answer's are now relating to a deprecated router. You can now pass multiple parameters as follows:

To call router:

this.router.navigate(['/myUrlPath', "someId", "another ID"]);

In routes.ts:

{ path: 'myUrlpath/:id1/:id2', component: componentToGoTo},

JavaScript adding decimal numbers issue

Testing this Javascript:

var arr = [1234563995.721, 12345691212.718, 1234568421.5891, 12345677093.49284];

var sum = 0;
for( var i = 0; i < arr.length; i++ ) {
    sum += arr[i];
}

alert( "fMath(sum) = " + Math.round( sum * 1e12 ) / 1e12 );
alert( "fFixed(sum) = " + sum.toFixed( 5 ) );

Conclusion

Dont use Math.round( (## + ## + ... + ##) * 1e12) / 1e12

Instead, use ( ## + ## + ... + ##).toFixed(5) )

In IE 9, toFixed works very well.

How to get all columns' names for all the tables in MySQL?

<?php
        $table = 'orders';
        $query = "SHOW COLUMNS FROM $table";
        if($output = mysql_query($query)):
            $columns = array();
            while($result = mysql_fetch_assoc($output)):
                $columns[] = $result['Field'];
            endwhile;
        endif;
        echo '<pre>';
        print_r($columns);
        echo '</pre>';
?>

matplotlib: how to draw a rectangle on image

You can add a Rectangle patch to the matplotlib Axes.

For example (using the image from the tutorial here):

import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image

im = Image.open('stinkbug.png')

# Create figure and axes
fig, ax = plt.subplots()

# Display the image
ax.imshow(im)

# Create a Rectangle patch
rect = patches.Rectangle((50, 100), 40, 30, linewidth=1, edgecolor='r', facecolor='none')

# Add the patch to the Axes
ax.add_patch(rect)

plt.show()

enter image description here

Declaring variables in Excel Cells

I also just found out how to do this with the Excel Name Manager (Formulas > Defined Names Section > Name Manager).

You can define a variable that doesn't have to "live" within a cell and then you can use it in formulas.

Excel Name Manager

NUnit vs. MbUnit vs. MSTest vs. xUnit.net

NUnit is probably the most supported by the 3rd party tools. It's also been around longer than the other three.

I personally don't care much about unit test frameworks, mocking libraries are IMHO much more important (and lock you in much more). Just pick one and stick with it.

how to add value to a tuple?

Tuples are immutable and not supposed to be changed - that is what the list type is for. You could replace each tuple by originalTuple + (newElement,), thus creating a new tuple. For example:

t = (1,2,3)
t = t + (1,)
print t
(1,2,3,1)

But I'd rather suggest to go with lists from the beginning, because they are faster for inserting items.

And another hint: Do not overwrite the built-in name list in your program, rather call the variable l or some other name. If you overwrite the built-in name, you can't use it anymore in the current scope.

Finding and removing non ascii characters from an Oracle Varchar2

Try the following:

-- To detect
select 1 from dual
where regexp_like(trim('xx test text æ¸¬è© ¦ “xmx” number²'),'['||chr(128)||'-'||chr(255)||']','in')

-- To strip out
select regexp_replace(trim('xx test text æ¸¬è© ¦ “xmxmx” number²'),'['||chr(128)||'-'||chr(255)||']','',1,0,'in')
from dual

DD/MM/YYYY Date format in Moment.js

for anyone who's using react-moment:

simply use format prop to your needed format:

const now = new Date()
<Moment format="DD/MM/YYYY">{now}</Moment>

How to compare if two structs, slices or maps are equal?

Here's how you'd roll your own function http://play.golang.org/p/Qgw7XuLNhb

func compare(a, b T) bool {
  if &a == &b {
    return true
  }
  if a.X != b.X || a.Y != b.Y {
    return false
  }
  if len(a.Z) != len(b.Z) || len(a.M) != len(b.M) {
    return false
  }
  for i, v := range a.Z {
    if b.Z[i] != v {
      return false
    }
  }
  for k, v := range a.M {
    if b.M[k] != v {
      return false
    }
  }
  return true
}

In Tkinter is there any way to make a widget not visible?

I was not using grid or pack.
I used just place for my widgets as their size and positioning was fixed.
I wanted to implement hide/show functionality on frame.
Here is demo

from tkinter import *
window=Tk()
window.geometry("1366x768+1+1")
def toggle_graph_visibility():
    graph_state_chosen=show_graph_checkbox_value.get()
    if graph_state_chosen==0:
        frame.place_forget()
    else:
        frame.place(x=1025,y=165)
score_pixel = PhotoImage(width=300, height=430)
show_graph_checkbox_value = IntVar(value=1)
frame=Frame(window,width=300,height=430)
graph_canvas = Canvas(frame, width = 300, height = 430,scrollregion=(0,0,300,300))
my_canvas=graph_canvas.create_image(20, 20, anchor=NW, image=score_pixel)
vbar=Scrollbar(frame,orient=VERTICAL)
vbar.config(command=graph_canvas.yview)
vbar.pack(side=RIGHT,fill=Y)
graph_canvas.config(yscrollcommand=vbar.set)
graph_canvas.pack(side=LEFT,expand=True,fill=BOTH)
frame.place(x=1025,y=165)
Checkbutton(window, text="show graph",variable=show_graph_checkbox_value,command=toggle_graph_visibility).place(x=900,y=165)
window.mainloop()

Note that in above example when 'show graph' is ticked then there is vertical scrollbar.
Graph disappears when checkbox is unselected.
I was fitting some bar graph in that area which I have not shown to keep example simple.
Most important thing to learn from above is the use of frame.place_forget() to hide and frame.place(x=x_pos,y=y_pos) to show back the content.

assign value using linq

You can create a extension method:

public static IEnumerable<T> Do<T>(this IEnumerable<T> self, Action<T> action) {
    foreach(var item in self) {
        action(item);
        yield return item;
    }
}

And then use it in code:

listofCompany.Do(d=>d.Id = 1);
listofCompany.Where(d=>d.Name.Contains("Inc")).Do(d=>d.Id = 1);

CR LF notepad++ removal

"View -> Show Symbol -> uncheck Show All characters" may not work if you have pending update for notepad++. So update Notepad++ and then View -> Show Symbol -> uncheck Show All characters

Hope this is helpful!