Programs & Examples On #Sitemapnode

Loop through array of values with Arrow Function

In short:

someValues.forEach((element) => {
    console.log(element);
});

If you care about index, then second parameter can be passed to receive the index of current element:

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

How to convert all tables in database to one collation?

You can use this BASH script:

#!/bin/bash

USER="YOUR_DATABASE_USER"
PASSWORD="YOUR_USER_PASSWORD"
DB_NAME="DATABASE_NAME"
CHARACTER_SET="utf8" # your default character set
COLLATE="utf8_general_ci" # your default collation

tables=`mysql -u $USER -p$PASSWORD -e "SELECT tbl.TABLE_NAME FROM information_schema.TABLES tbl WHERE tbl.TABLE_SCHEMA = '$DB_NAME' AND tbl.TABLE_TYPE='BASE TABLE'"`

for tableName in $tables; do
    if [[ "$tableName" != "TABLE_NAME" ]] ; then
        mysql -u $USER -p$PASSWORD -e "ALTER TABLE $DB_NAME.$tableName DEFAULT CHARACTER SET $CHARACTER_SET COLLATE $COLLATE;"
        echo "$tableName - done"
    fi
done

How to Configure SSL for Amazon S3 bucket

It is not possible directly with S3, but you can create a Cloud Front distribution from you bucket. Then go to certificate manager and request a certificate. Amazon gives them for free. Ones you have successfully confirmed the certification, assign it to your Cloud Front distribution. Also remember to set the rule to re-direct http to https.

I'm hosting couple of static websites on Amazon S3, like my personal website to which I have assigned the SSL certificate as they have the Cloud Front distribution.

A child container failed during start java.util.concurrent.ExecutionException

I try with http servlet and I find this issue when I write duplicated @WebServlet ,I encountered with this issue.After I remove or change @WebServlet value it is working.

1.Class

@WebServlet("/display")
public class MyFirst extends HttpServlet {

2.Class

@WebServlet("/display")
public class MySecond extends HttpServlet {

Using a Python subprocess call to invoke a Python script

The subprocess call is a very literal-minded system call. it can be used for any generic process...hence does not know what to do with a Python script automatically.

Try

call ('python somescript.py')

If that doesn't work, you might want to try an absolute path, and/or check permissions on your Python script...the typical fun stuff.

UPDATE and REPLACE part of a string

For anyone want to replace your script.

update dbo.[TABLE_NAME] set COLUMN_NAME= replace(COLUMN_NAME, 'old_value', 'new_value') where COLUMN_NAME like %CONDITION%

RegEx pattern any two letters followed by six numbers

Depending on if your regex flavor supports it, I might use:

\b[A-Z]{2}\d{6}\b    # Ensure there are "word boundaries" on either side, or

(?<![A-Z])[A-Z]{2}\d{6}(?!\d) # Ensure there isn't a uppercase letter before
                              # and that there is not a digit after

Field 'browser' doesn't contain a valid alias configuration

Changed my entry to

entry: path.resolve(__dirname, './src/js/index.js'),

and it worked.

Why doesn't os.path.join() work in this case?

I'd recommend to strip from the second and the following strings the string os.path.sep, preventing them to be interpreted as absolute paths:

first_path_str = '/home/build/test/sandboxes/'
original_other_path_to_append_ls = [todaystr, '/new_sandbox/']
other_path_to_append_ls = [
    i_path.strip(os.path.sep) for i_path in original_other_path_to_append_ls
]
output_path = os.path.join(first_path_str, *other_path_to_append_ls)

Java, reading a file from current directory?

Thanks @Laurence Gonsalves your answer helped me a lot. your current directory will working directory of proccess so you have to give full path start from your src directory like mentioned below:

public class Run {
public static void main(String[] args) {
    File inputFile = new File("./src/main/java/input.txt");
    try {
        Scanner reader = new Scanner(inputFile);
        while (reader.hasNextLine()) {
            String data = reader.nextLine();
            System.out.println(data);
            
        }
        reader.close();
    } catch (FileNotFoundException e) {
        System.out.println("scanner error");
        e.printStackTrace();
    }
}

}

While my input.txt file is in same directory.

enter image description here

Using OpenGl with C#?

I would also recommend the Tao Framework. But one additional note:

Take a look at these tutorials: http://www.taumuon.co.uk/jabuka/

Include .so library in apk in android studio

I've tried the solution presented in the accepted answer and it did not work for me. I wanted to share what DID work for me as it might help someone else. I've found this solution here.

Basically what you need to do is put your .so files inside a a folder named lib (Note: it is not libs and this is not a mistake). It should be in the same structure it should be in the APK file.

In my case it was:
Project:
|--lib:
|--|--armeabi:
|--|--|--.so files.

So I've made a lib folder and inside it an armeabi folder where I've inserted all the needed .so files. I then zipped the folder into a .zip (the structure inside the zip file is now lib/armeabi/*.so) I renamed the .zip file into armeabi.jar and added the line compile fileTree(dir: 'libs', include: '*.jar') into dependencies {} in the gradle's build file.

This solved my problem in a rather clean way.

git remote prune – didn't show as many pruned branches as I expected

When you use git push origin :staleStuff, it automatically removes origin/staleStuff, so when you ran git remote prune origin, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune to get rid of branches you have removed.


So what exactly git remote prune does? Main idea: local branches (not tracking branches) are not touched by git remote prune command and should be removed manually.

Now, a real-world example for better understanding:

You have a remote repository with 2 branches: master and feature. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):

  • refs/heads/master (short name master)
  • refs/heads/feature (short name feature)
  • refs/remotes/origin/master (short name origin/master)
  • refs/remotes/origin/feature (short name origin/feature)

Now, a typical scenario:

  1. Some other developer finishes all work on the feature, merges it into master and removes feature branch from remote repository.
  2. By default, when you do git fetch (or git pull), no references are removed from your local repository, so you still have all those 4 references.
  3. You decide to clean them up, and run git remote prune origin.
  4. git detects that feature branch no longer exists, so refs/remotes/origin/feature is a stale branch which should be removed.
  5. Now you have 3 references, including refs/heads/feature, because git remote prune does not remove any refs/heads/* references.

It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge configuration parameter. This parameter is not really required for anything to work (probably except git pull), so it might be missing.

(updated with example & useful info from comments)

What's the difference between 'r+' and 'a+' when open file in python?

If you have used them in C, then they are almost same as were in C.

From the manpage of fopen() function : -

  • r+ : - Open for reading and writing. The stream is positioned at the beginning of the file.

  • a+ : - Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subse- quent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.

Retrieving Data from SQL Using pyodbc

You are so close!

import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=SQLSRV01;DATABASE=DATABASE;UID=USER;PWD=PASSWORD')
cursor = cnxn.cursor()

cursor.execute("SELECT WORK_ORDER.TYPE,WORK_ORDER.STATUS, WORK_ORDER.BASE_ID, WORK_ORDER.LOT_ID FROM WORK_ORDER")
for row in cursor.fetchall():
    print row

(the "columns()" function collects meta-data about the columns in the named table, as opposed to the actual data).

How to modify STYLE attribute of element with known ID using JQuery

Use the CSS function from jQuery to set styles to your items :

$('#buttonId').css({ "background-color": 'brown'});

Date vs DateTime

No there isn't. DateTime represents some point in time that is composed of a date and a time. However, you can retrieve the date part via the Date property (which is another DateTime with the time set to 00:00:00).

And you can retrieve individual date properties via Day, Month and Year.

PSEXEC, access denied errors

For a different command I decided to change the network from public to work.
After trying to use the psexec command again it worked again.
So to get psexec to work try to change your network type from public to work or home.

C# 4.0: Convert pdf to byte[] and vice versa

using (FileStream fs = new FileStream("sample.pdf", FileMode.Open, FileAccess.Read))
            {
                byte[] bytes = new byte[fs.Length];
                int numBytesToRead = (int)fs.Length;
                int numBytesRead = 0;
                while (numBytesToRead > 0)
                {
                    // Read may return anything from 0 to numBytesToRead.
                    int n = fs.Read(bytes, numBytesRead, numBytesToRead);

                    // Break when the end of the file is reached.
                    if (n == 0)
                    {
                        break;
                    }

                    numBytesRead += n;
                    numBytesToRead -= n;
                }
                numBytesToRead = bytes.Length;
}

XML Schema How to Restrict Attribute by Enumeration

The numerical value seems to be missing from your price definition. Try the following:

<xs:simpleType name="curr">
  <xs:restriction base="xs:string">
    <xs:enumeration value="pounds" />
    <xs:enumeration value="euros" />
    <xs:enumeration value="dollars" />
  </xs:restriction>
</xs:simpleType>



<xs:element name="price">
        <xs:complexType>
            <xs:extension base="xs:decimal">
              <xs:attribute name="currency" type="curr"/>
            </xs:extension>
        </xs:complexType>
</xs:element>

Filtering lists using LINQ

Have a look at the Except method, which you use like this:

var resultingList = 
    listOfOriginalItems.Except(listOfItemsToLeaveOut, equalityComparer)

You'll want to use the overload I've linked to, which lets you specify a custom IEqualityComparer. That way you can specify how items match based on your composite key. (If you've already overridden Equals, though, you shouldn't need the IEqualityComparer.)

Edit: Since it appears you're using two different types of classes, here's another way that might be simpler. Assuming a List<Person> called persons and a List<Exclusion> called exclusions:

var exclusionKeys = 
        exclusions.Select(x => x.compositeKey);
var resultingPersons = 
        persons.Where(x => !exclusionKeys.Contains(x.compositeKey));

In other words: Select from exclusions just the keys, then pick from persons all the Person objects that don't have any of those keys.

ERROR 1049 (42000): Unknown database

Its a common error which happens when we try to access a database which doesn't exist. So create the database using

CREATE DATABASE blog_development;

The error commonly occours when we have dropped the database using

DROP DATABASE blog_development;

and then try to access the database.

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

I used the Visual Studio 2008 Uninstall tool and it worked fine for me.

You can use this tool to uninstall Visual Studio 2008 official release and Visual Studio 2008 Release candidate (Only English version).

Found here, on the MSDN Forum: MSDN forum topic.

I found this answer here

Be sure you run the tool with admin-rights.

What is the syntax for an inner join in LINQ to SQL?

To extend the expression chain syntax answer by Clever Human:

If you wanted to do things (like filter or select) on fields from both tables being joined together -- instead on just one of those two tables -- you could create a new object in the lambda expression of the final parameter to the Join method incorporating both of those tables, for example:

var dealerInfo = DealerContact.Join(Dealer, 
                              dc => dc.DealerId,
                              d => d.DealerId,
                              (dc, d) => new { DealerContact = dc, Dealer = d })
                          .Where(dc_d => dc_d.Dealer.FirstName == "Glenn" 
                              && dc_d.DealerContact.City == "Chicago")
                          .Select(dc_d => new {
                              dc_d.Dealer.DealerID,
                              dc_d.Dealer.FirstName,
                              dc_d.Dealer.LastName,
                              dc_d.DealerContact.City,
                              dc_d.DealerContact.State });

The interesting part is the lambda expression in line 4 of that example:

(dc, d) => new { DealerContact = dc, Dealer = d }

...where we construct a new anonymous-type object which has as properties the DealerContact and Dealer records, along with all of their fields.

We can then use fields from those records as we filter and select the results, as demonstrated by the remainder of the example, which uses dc_d as a name for the anonymous object we built which has both the DealerContact and Dealer records as its properties.

Sorting list based on values from another list

The most obvious solution to me is to use the key keyword arg.

>>> X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
>>> Y = [ 0,   1,   1,    0,   1,   2,   2,   0,   1]
>>> keydict = dict(zip(X, Y))
>>> X.sort(key=keydict.get)
>>> X
['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']

Note that you can shorten this to a one-liner if you care to:

>>> X.sort(key=dict(zip(X, Y)).get)

As Wenmin Mu and Jack Peng have pointed out, this assumes that the values in X are all distinct. That's easily managed with an index list:

>>> Z = ["A", "A", "C", "C", "C", "F", "G", "H", "I"]
>>> Z_index = list(range(len(Z)))
>>> Z_index.sort(key=keydict.get)
>>> Z = [Z[i] for i in Z_index]
>>> Z
['A', 'C', 'H', 'A', 'C', 'C', 'I', 'F', 'G']

Since the decorate-sort-undecorate approach described by Whatang is a little simpler and works in all cases, it's probably better most of the time. (This is a very old answer!)

How to get the total number of rows of a GROUP BY query?

You have to use rowCount — Returns the number of rows affected by the last SQL statement

$query = $dbh->prepare("SELECT * FROM table_name");
$query->execute();
$count =$query->rowCount();
echo $count;

Angular redirect to login page

1. Create a guard as seen below. 2. Install ngx-cookie-service to get cookies returned by external SSO. 3. Create ssoPath in environment.ts (SSO Login redirection). 4. Get the state.url and use encodeURIComponent.

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from 
  '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { environment } from '../../../environments/environment.prod';

@Injectable()
export class AuthGuardService implements CanActivate {
  private returnUrl: string;
  constructor(private _router: Router, private cookie: CookieService) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (this.cookie.get('MasterSignOn')) {
      return true;
    } else {
      let uri = window.location.origin + '/#' + state.url;
      this.returnUrl = encodeURIComponent(uri);      
      window.location.href = environment.ssoPath +  this.returnUrl ;   
      return false;      
    }
  }
}

Remove the title bar in Windows Forms

You can set the Property FormBorderStyle to none in the designer, or in code:

this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

Modifying a query string without reloading the page

Then the history API is exactly what you are looking for. If you wish to support legacy browsers as well, then look for a library that falls back on manipulating the URL's hash tag if the browser doesn't provide the history API.

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

class Program
{
    static void Main(string[] args)
    {

        int transactionDate = 20201010;
        int? transactionTime = 210000;

        var agreementDate = DateTime.Today;
        var previousDate = agreementDate.AddDays(-1);

        var agreementHour = 22;
        var agreementMinute = 0;
        var agreementSecond = 0;

        var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
        var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);

        DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));

        Console.WriteLine("Selected Date : " + selectedDate.ToString());
        Console.WriteLine("Start Date : " + startDate.ToString());
        Console.WriteLine("End Date : " + endDate.ToString());

        if (selectedDate > startDate && selectedDate <= endDate)
            Console.WriteLine("Between two dates..");
        else if (selectedDate <= startDate)
            Console.WriteLine("Less than or equal to the start date!");
        else if (selectedDate > endDate)
            Console.WriteLine("Greater than end date!");
        else
            Console.WriteLine("Out of date ranges!");
    }
}

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

  1. Stop your Apache server from running.
  2. Download the most recent version of XAMPP that contains a release of PHP 5.2.* from the SourceForge site linked at the apachefriends website.
  3. Rename the PHP file in your current installation (MAC OSX: /xamppfiles/modules/libphp.so) to something else (just in case).
  4. Copy the PHP file located in the same directory tree from the older XAMPP installation that you just downloaded, and place it in the directory of the file you just renamed.
  5. Start the Apache server, and generate a fresh version of phpinfo().
  6. Once you confirm that the PHP version has been lowered, delete the remaining files from the older XAMPP install.
  7. Fun ensues.

I just confirmed that this works when using a version of PHP 5.2.9 from XAMPP for OS X 1.0.1 (April 2009), and surgically moving it to XAMPP for OS X 1.7.2 (August 2009).

android:layout_height 50% of the screen size

You can use android:weightSum="2" on the parent layout combined with android:layout_height="1" on the child layout.

           <LinearLayout
                android:layout_height="match_parent"
                android:layout_width="wrap_content"
                android:weightSum="2"
                >

                <ImageView
                    android:layout_height="1"
                    android:layout_width="wrap_content" />

            </LinearLayout>

"Proxy server connection failed" in google chrome

Internet explorer has a reset to factory button and luckily so does chrome! try the link below and let us know. the other option is to stop chrome and delete the c:\users\%username%\appdata\local\google folder entirely then reinstall chrome but this will loose all you local settings and data.

Google doc on how to factory reset: https://support.google.com/chrome/answer/3296214?hl=en

Unable to add window -- token null is not valid; is your activity running?

In my case, I was inflating a PopupMenu at the very beginning of the activity i.e on onCreate()... I fixed it by putting it in a Handler

  new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                PopupMenu popuMenu=new PopupMenu(SplashScreen.this,binding.progressBar);
                popuMenu.inflate(R.menu.bottom_nav_menu);
                popuMenu.show();
            }
        },100);

python location on mac osx

[GCC 4.2.1 (Apple Inc. build 5646)] is the version of GCC that the Python(s) were built with, not the version of Python itself. That information should be on the previous line. For example:

# Apple-supplied Python 2.6 in OS X 10.6
$ /usr/bin/python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 

# python.org Python 2.7.2 (also built with newer gcc)
$ /usr/local/bin/python
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

Items in /usr/bin should always be or link to files supplied by Apple in OS X, unless someone has been ill-advisedly changing things there. To see exactly where the /usr/local/bin/python is linked to:

$ ls -l /usr/local/bin/python
lrwxr-xr-x  1 root  wheel  68 Jul  5 10:05 /usr/local/bin/python@ -> ../../../Library/Frameworks/Python.framework/Versions/2.7/bin/python

In this case, that is typical for a python.org installed Python instance or it could be one built from source.

Spring get current ApplicationContext

Add this to your code

@Autowired
private ApplicationContext _applicationContext;

//Add below line in your calling method
MyClass class = (MyClass) _applicationContext.getBean("myClass");

// Or you can simply use this, put the below code in your controller data member declaration part.
@Autowired
private MyClass myClass;

This will simply inject myClass into your application

Add a "sort" to a =QUERY statement in Google Spreadsheets

You can use ORDER BY clause to sort data rows by values in columns. Something like

=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C, D")

If you’d like to order by some columns descending, others ascending, you can add desc/asc, ie:

=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C desc, D")

Can the "IN" operator use LIKE-wildcards (%) in Oracle?

Not 100% what you were looking for, but kind of an inside-out way of doing it:

SQL> CREATE TABLE mytable (id NUMBER, status VARCHAR2(50));

Table created.

SQL> INSERT INTO mytable VALUES (1,'Finished except pouring water on witch');

1 row created.

SQL> INSERT INTO mytable VALUES (2,'Finished except clicking ruby-slipper heels');

1 row created.

SQL> INSERT INTO mytable VALUES (3,'You shall (not?) pass');

1 row created.

SQL> INSERT INTO mytable VALUES (4,'Done');

1 row created.

SQL> INSERT INTO mytable VALUES (5,'Done with it.');

1 row created.

SQL> INSERT INTO mytable VALUES (6,'In Progress');

1 row created.

SQL> INSERT INTO mytable VALUES (7,'In progress, OK?');

1 row created.

SQL> INSERT INTO mytable VALUES (8,'In Progress Check Back In Three Days'' Time');

1 row created.

SQL> SELECT *
  2  FROM   mytable m
  3  WHERE  +1 NOT IN (INSTR(m.status,'Done')
  4            ,       INSTR(m.status,'Finished except')
  5            ,       INSTR(m.status,'In Progress'));

        ID STATUS
---------- --------------------------------------------------
         3 You shall (not?) pass
         7 In progress, OK?

SQL>

Change bootstrap navbar background color and font color

No need for the specificity .navbar-default in your CSS. Background color requires background-color:#cc333333 (or just background:#cc3333). Finally, probably best to consolidate all your customizations into a single class, as below:

.navbar-custom {
    color: #FFFFFF;
    background-color: #CC3333;
}

..

<div id="menu" class="navbar navbar-default navbar-custom">

Example: http://www.bootply.com/OusJAAvFqR#

Do I need to pass the full path of a file in another directory to open()?

Here's a snippet that will walk the file tree for you:

indir = '/home/des/test'
for root, dirs, filenames in os.walk(indir):
    for f in filenames:
        print(f)
        log = open(indir + f, 'r')

SVN icon overlays not showing properly

This is, unfortunately a quite common problem on Windows where the icons are either not updated or rather disappearing. I find it quite annoying. It usually is fixed by either refreshing the Windows folder (F5) or, by doing a SVN Clean up,

Right click on the folder ->  TortoiseSVN -> Clean up... 
Select Clean up working copy status

I have never been able to solve this permanently, this is only a work-around. Keeping TortoiseSVN on the latest version may or may not help.

Note that the clean up will only clean up your local working copy, it wont do anything to the actual repository. Its a safe operation.


Apparently this is not enough according to your comment. Do you have lots of other programs that are also using overlay icons? If so maybe you can find a solution in this thread: TortoiseSVN icons not showing up under Windows 7? The second most voted answer also deals with network drives etc. Its a good read.


Also, have you rebooted your computer after the install? From the TortoiseSVN FAQ:

You rebooted your PC of course after the installation? If you haven't please do so now. TortoiseSVN is a windows Explorer Shell extension and will be loaded together with Explorer.

...

Otherwise, try doing a repair install (and reboot of course).

Inconsistent Accessibility: Parameter type is less accessible than method

The problem doesn't seem to be with the variable but rather with the declaration of ACTInterface. Is ACTInterface declared as internal by any chance?

async/await - when to return a Task vs void?

I think you can use async void for kicking off background operations as well, so long as you're careful to catch exceptions. Thoughts?

class Program {

    static bool isFinished = false;

    static void Main(string[] args) {

        // Kick off the background operation and don't care about when it completes
        BackgroundWork();

        Console.WriteLine("Press enter when you're ready to stop the background operation.");
        Console.ReadLine();
        isFinished = true;
    }

    // Using async void to kickoff a background operation that nobody wants to be notified about when it completes.
    static async void BackgroundWork() {
        // It's important to catch exceptions so we don't crash the appliation.
        try {
            // This operation will end after ten interations or when the app closes. Whichever happens first.
            for (var count = 1; count <= 10 && !isFinished; count++) {
                await Task.Delay(1000);
                Console.WriteLine($"{count} seconds of work elapsed.");
            }
            Console.WriteLine("Background operation came to an end.");
        } catch (Exception x) {
            Console.WriteLine("Caught exception:");
            Console.WriteLine(x.ToString());
        }
    }
}

How to show a GUI message box from a bash script in linux?

There is also dialog and the KDE version kdialog. dialog is used by slackware, so it might not be immediately available on other distributions.

How do you revert to a specific tag in Git?

Git tags are just pointers to the commit. So you use them the same way as you do HEAD, branch names or commit sha hashes. You can use tags with any git command that accepts commit/revision arguments. You can try it with git rev-parse tagname to display the commit it points to.

In your case you have at least these two alternatives:

  1. Reset the current branch to specific tag:

    git reset --hard tagname
    
  2. Generate revert commit on top to get you to the state of the tag:

    git revert tag
    

This might introduce some conflicts if you have merge commits though.

Inversion of Control vs Dependency Injection

IoC is a generic term meaning that rather than having the application call the implementations provided by a library (also know as toolkit), a framework calls the implementations provided by the application.

DI is a form of IoC, where implementations are passed into an object through constructors/setters/service lookups, which the object will 'depend' on in order to behave correctly.

IoC without using DI, for example would be the Template pattern because the implementation can only be changed through sub-classing.

DI frameworks are designed to make use of DI and can define interfaces (or Annotations in Java) to make it easy to pass in the implementations.

IoC containers are DI frameworks that can work outside of the programming language. In some you can configure which implementations to use in metadata files (e.g. XML) which are less invasive. With some you can do IoC that would normally be impossible like inject an implementation at pointcuts.

See also this Martin Fowler's article.

jquery find class and get the value

var myVar = $("#start").find('myClass').val();

needs to be

var myVar = $("#start").find('.myClass').val();

Remember the CSS selector rules require "." if selecting by class name. The absence of "." is interpreted to mean searching for <myclass></myclass>.

Addition for BigDecimal

You can also do it like this:

BigDecimal A = new BigDecimal("10000000000");
BigDecimal B = new BigDecimal("20000000000");
BigDecimal C = new BigDecimal("30000000000");
BigDecimal resultSum = (A).add(B).add(C);
System.out.println("A+B+C= " + resultSum);

Prints:

A+B+C= 60000000000

C# "internal" access modifier when doing unit testing

If you want to test private methods, have a look at PrivateObject and PrivateType in the Microsoft.VisualStudio.TestTools.UnitTesting namespace. They offer easy to use wrappers around the necessary reflection code.

Docs: PrivateType, PrivateObject

For VS2017 & 2019, you can find these by downloading the MSTest.TestFramework nuget

how to drop database in sqlite?

If you want to delete database programatically you can use deleteDatabase from Context class:

deleteDatabase(String name)
Delete an existing private SQLiteDatabase associated with this Context's application package.

nodeJs callbacks simple example

A callback function is simply a function you pass into another function so that function can call it at a later time. This is commonly seen in asynchronous APIs; the API call returns immediately because it is asynchronous, so you pass a function into it that the API can call when it's done performing its asynchronous task.

The simplest example I can think of in JavaScript is the setTimeout() function. It's a global function that accepts two arguments. The first argument is the callback function and the second argument is a delay in milliseconds. The function is designed to wait the appropriate amount of time, then invoke your callback function.

setTimeout(function () {
  console.log("10 seconds later...");
}, 10000);

You may have seen the above code before but just didn't realize the function you were passing in was called a callback function. We could rewrite the code above to make it more obvious.

var callback = function () {
  console.log("10 seconds later...");
};
setTimeout(callback, 10000);

Callbacks are used all over the place in Node because Node is built from the ground up to be asynchronous in everything that it does. Even when talking to the file system. That's why a ton of the internal Node APIs accept callback functions as arguments rather than returning data you can assign to a variable. Instead it will invoke your callback function, passing the data you wanted as an argument. For example, you could use Node's fs library to read a file. The fs module exposes two unique API functions: readFile and readFileSync.

The readFile function is asynchronous while readFileSync is obviously not. You can see that they intend you to use the async calls whenever possible since they called them readFile and readFileSync instead of readFile and readFileAsync. Here is an example of using both functions.

Synchronous:

var data = fs.readFileSync('test.txt');
console.log(data);

The code above blocks thread execution until all the contents of test.txt are read into memory and stored in the variable data. In node this is typically considered bad practice. There are times though when it's useful, such as when writing a quick little script to do something simple but tedious and you don't care much about saving every nanosecond of time that you can.

Asynchronous (with callback):

var callback = function (err, data) {
  if (err) return console.error(err);
  console.log(data);
};
fs.readFile('test.txt', callback);

First we create a callback function that accepts two arguments err and data. One problem with asynchronous functions is that it becomes more difficult to trap errors so a lot of callback-style APIs pass errors as the first argument to the callback function. It is best practice to check if err has a value before you do anything else. If so, stop execution of the callback and log the error.

Synchronous calls have an advantage when there are thrown exceptions because you can simply catch them with a try/catch block.

try {
  var data = fs.readFileSync('test.txt');
  console.log(data);
} catch (err) {
  console.error(err);
}

In asynchronous functions it doesn't work that way. The API call returns immediately so there is nothing to catch with the try/catch. Proper asynchronous APIs that use callbacks will always catch their own errors and then pass those errors into the callback where you can handle it as you see fit.

In addition to callbacks though, there is another popular style of API that is commonly used called the promise. If you'd like to read about them then you can read the entire blog post I wrote based on this answer here.

Svn switch from trunk to branch

  • Short version of (correct) tzaman answer will be (for fresh SVN)

    svn switch ^/branches/v1p2p3
    
  • --relocate switch is deprecated anyway, when it needed you'll have to use svn relocate command

  • Instead of creating snapshot-branch (ReadOnly) you can use tags (conventional RO labels for history)

On Windows, the caret character (^) must be escaped:

svn switch ^^/branches/v1p2p3

Escape a string in SQL Server so that it is safe to use in LIKE expression

Rather than escaping all characters in a string that have particular significance in the pattern syntax given that you are using a leading wildcard in the pattern it is quicker and easier just to do.

SELECT * 
FROM YourTable
WHERE CHARINDEX(@myString , YourColumn) > 0

In cases where you are not using a leading wildcard the approach above should be avoided however as it cannot use an index on YourColumn.

Additionally in cases where the optimum execution plan will vary according to the number of matching rows the estimates may be better when using LIKE with the square bracket escaping syntax when compared to both CHARINDEX and the ESCAPE keyword.

How can I apply a function to every row/column of a matrix in MATLAB?

Building on Alex's answer, here is a more generic function:

applyToGivenRow = @(func, matrix) @(row) func(matrix(row, :));
newApplyToRows = @(func, matrix) arrayfun(applyToGivenRow(func, matrix), 1:size(matrix,1), 'UniformOutput', false)';
takeAll = @(x) reshape([x{:}], size(x{1},2), size(x,1))';
genericApplyToRows = @(func, matrix) takeAll(newApplyToRows(func, matrix));

Here is a comparison between the two functions:

>> % Example
myMx = [1 2 3; 4 5 6; 7 8 9];
myFunc = @(x) [mean(x), std(x), sum(x), length(x)];
>> genericApplyToRows(myFunc, myMx)

ans =

     2     1     6     3
     5     1    15     3
     8     1    24     3

>> applyToRows(myFunc, myMx)
??? Error using ==> arrayfun
Non-scalar in Uniform output, at index 1, output 1.
Set 'UniformOutput' to false.

Error in ==> @(func,matrix)arrayfun(applyToGivenRow(func,matrix),1:size(matrix,1))'

How to detect when WIFI Connection has been established in Android?

I have two methods to detect WIFI connection receiving the application context:

1)my old method

public boolean isConnectedWifi1(Context context) {
    try {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();           
        if (networkInfo != null) {
            NetworkInfo[] netInfo = connectivityManager.getAllNetworkInfo();
            for (NetworkInfo ni : netInfo) {
                if ((ni.getTypeName().equalsIgnoreCase("WIFI"))
                        && ni.isConnected()) {
                    return true;
                }                   
            }
        }
        return false;
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }
    return false;
}

2)my New method (I´m currently using this method):

public boolean isConnectedWifi(Context context) {
         ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);     
         return networkInfo.isConnected();
}

Open File Dialog, One Filter for Multiple Excel Extensions?

If you want to merge the filters (eg. CSV and Excel files), use this formula:

OpenFileDialog of = new OpenFileDialog();
of.Filter = "CSV files (*.csv)|*.csv|Excel Files|*.xls;*.xlsx";

Or if you want to see XML or PDF files in one time use this:

of.Filter = @" XML or PDF |*.xml;*.pdf";

Module is not available, misspelled or forgot to load (but I didn't)

I had the same error but i resolved it, it was a syntax error in the AngularJS provider

Order a List (C#) by many fields?

Your object should implement the IComparable interface.

With it your class becomes a new function called CompareTo(T other). Within this function you can make any comparison between the current and the other object and return an integer value about if the first is greater, smaller or equal to the second one.

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

Removing address bar from browser (to view on Android)

I hope it also useful

window.addEventListener("load", function() 
{
    if(!window.pageYOffset)
    { 
        hideAddressBar(); 
    }
    window.addEventListener("orientationchange", hideAddressBar);
});

How to install node.js as windows service?

https://nssm.cc/ service helper good for create windows service by batch file i use from nssm & good working for any app & any file

startsWith() and endsWith() functions in PHP

The substr function can return false in many special cases, so here is my version, which deals with these issues:

function startsWith( $haystack, $needle ){
  return $needle === ''.substr( $haystack, 0, strlen( $needle )); // substr's false => empty string
}

function endsWith( $haystack, $needle ){
  $len = strlen( $needle );
  return $needle === ''.substr( $haystack, -$len, $len ); // ! len=0
}

Tests (true means good):

var_dump( startsWith('',''));
var_dump( startsWith('1',''));
var_dump(!startsWith('','1'));
var_dump( startsWith('1','1'));
var_dump( startsWith('1234','12'));
var_dump(!startsWith('1234','34'));
var_dump(!startsWith('12','1234'));
var_dump(!startsWith('34','1234'));
var_dump('---');
var_dump( endsWith('',''));
var_dump( endsWith('1',''));
var_dump(!endsWith('','1'));
var_dump( endsWith('1','1'));
var_dump(!endsWith('1234','12'));
var_dump( endsWith('1234','34'));
var_dump(!endsWith('12','1234'));
var_dump(!endsWith('34','1234'));

Also, the substr_compare function also worth looking. http://www.php.net/manual/en/function.substr-compare.php

jQuery function after .append

Although Marcus Ekwall is absolutely right about the synchronicity of append, I have also found that in odd situations sometimes the DOM isn't completely rendered by the browser when the next line of code runs.

In this scenario then shadowdiver solutions is along the correct lines - with using .ready - however it is a lot tidier to chain the call to your original append.

$('#root')
  .append(html)
  .ready(function () {
    // enter code here
  });

Java Calendar, getting current month value, clarification needed

Calendar.getInstance().get(Calendar.MONTH);

is zero based, 10 is November. From the javadoc;

public static final int MONTH Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

Calendar.getInstance().get(Calendar.JANUARY);

is not a sensible thing to do, the value for JANUARY is 0, which is the same as ERA, you are effectively calling;

Calendar.getInstance().get(Calendar.ERA);

How to include a font .ttf using CSS?

You can use font face like this:

@font-face {
  font-family:"Name-Of-Font";
  src: url("yourfont.ttf") format("truetype");
}

What is the default value for enum variable?

You can use this snippet :-D

using System;
using System.Reflection;

public static class EnumUtils
{
    public static T GetDefaultValue<T>()
        where T : struct, Enum
    {
        return (T)GetDefaultValue(typeof(T));
    }

    public static object GetDefaultValue(Type enumType)
    {
        var attribute = enumType.GetCustomAttribute<DefaultValueAttribute>(inherit: false);
        if (attribute != null)
            return attribute.Value;

        var innerType = enumType.GetEnumUnderlyingType();
        var zero = Activator.CreateInstance(innerType);
        if (enumType.IsEnumDefined(zero))
            return zero;

        var values = enumType.GetEnumValues();
        return values.GetValue(0);
    }
}

Example:

using System;

public enum Enum1
{
    Foo,
    Bar,
    Baz,
    Quux
}
public enum Enum2
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 0
}
public enum Enum3
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}
[DefaultValue(Enum4.Bar)]
public enum Enum4
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}

public static class Program 
{
    public static void Main() 
    {
        var defaultValue1 = EnumUtils.GetDefaultValue<Enum1>();
        Console.WriteLine(defaultValue1); // Foo

        var defaultValue2 = EnumUtils.GetDefaultValue<Enum2>();
        Console.WriteLine(defaultValue2); // Quux

        var defaultValue3 = EnumUtils.GetDefaultValue<Enum3>();
        Console.WriteLine(defaultValue3); // Foo

        var defaultValue4 = EnumUtils.GetDefaultValue<Enum4>();
        Console.WriteLine(defaultValue4); // Bar
    }
}

Get year, month or day from numpy datetime64

This is how I do it.

import numpy as np

def dt2cal(dt):
    """
    Convert array of datetime64 to a calendar array of year, month, day, hour,
    minute, seconds, microsecond with these quantites indexed on the last axis.

    Parameters
    ----------
    dt : datetime64 array (...)
        numpy.ndarray of datetimes of arbitrary shape

    Returns
    -------
    cal : uint32 array (..., 7)
        calendar array with last axis representing year, month, day, hour,
        minute, second, microsecond
    """

    # allocate output 
    out = np.empty(dt.shape + (7,), dtype="u4")
    # decompose calendar floors
    Y, M, D, h, m, s = [dt.astype(f"M8[{x}]") for x in "YMDhms"]
    out[..., 0] = Y + 1970 # Gregorian Year
    out[..., 1] = (M - Y) + 1 # month
    out[..., 2] = (D - M) + 1 # dat
    out[..., 3] = (dt - D).astype("m8[h]") # hour
    out[..., 4] = (dt - h).astype("m8[m]") # minute
    out[..., 5] = (dt - m).astype("m8[s]") # second
    out[..., 6] = (dt - s).astype("m8[us]") # microsecond
    return out

It's vectorized across arbitrary input dimensions, it's fast, its intuitive, it works on numpy v1.15.4, it doesn't use pandas.

I really wish numpy supported this functionality, it's required all the time in application development. I always get super nervous when I have to roll my own stuff like this, I always feel like I'm missing an edge case.

How to set a tkinter window to a constant size

If you want a window as a whole to have a specific size, you can just give it the size you want with the geometry command. That's really all you need to do.

For example:

mw.geometry("500x500")

Though, you'll also want to make sure that the widgets inside the window resize properly, so change how you add the frame to this:

back.pack(fill="both", expand=True)

Parse an URL in JavaScript

Try this:

var url = window.location;
var urlAux = url.split('=');
var img_id = urlAux[1]

Django database query: How to get object by id?

You can also use get_object_or_404 django shortcut. It raises a 404 error if object is not found.

docker : invalid reference format

I had a similar problem. Issue I was having was $(pwd) has a space in there which was throwing docker run off.

Change the directory name to not have spaces in there, and it should work if this is the problem

How to add,set and get Header in request of HttpClient?

You can use HttpPost, there are methods to add Header to the Request.

DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://localhost";
HttpPost httpPost = new HttpPost(url);

httpPost.addHeader("header-name" , "header-value");

HttpResponse response = httpclient.execute(httpPost);

Custom HTTP headers : naming conventions

The question bears re-reading. The actual question asked is not similar to vendor prefixes in CSS properties, where future-proofing and thinking about vendor support and official standards is appropriate. The actual question asked is more akin to choosing URL query parameter names. Nobody should care what they are. But name-spacing the custom ones is a perfectly valid -- and common, and correct -- thing to do.

Rationale:
It is about conventions among developers for custom, application-specific headers -- "data relevant to their account" -- which have nothing to do with vendors, standards bodies, or protocols to be implemented by third parties, except that the developer in question simply needs to avoid header names that may have other intended use by servers, proxies or clients. For this reason, the "X-Gzip/Gzip" and "X-Forwarded-For/Forwarded-For" examples given are moot. The question posed is about conventions in the context of a private API, akin to URL query parameter naming conventions. It's a matter of preference and name-spacing; concerns about "X-ClientDataFoo" being supported by any proxy or vendor without the "X" are clearly misplaced.

There's nothing special or magical about the "X-" prefix, but it helps to make it clear that it is a custom header. In fact, RFC-6648 et al help bolster the case for use of an "X-" prefix, because -- as vendors of HTTP clients and servers abandon the prefix -- your app-specific, private-API, personal-data-passing-mechanism is becoming even better-insulated against name-space collisions with the small number of official reserved header names. That said, my personal preference and recommendation is to go a step further and do e.g. "X-ACME-ClientDataFoo" (if your widget company is "ACME").

IMHO the IETF spec is insufficiently specific to answer the OP's question, because it fails to distinguish between completely different use cases: (A) vendors introducing new globally-applicable features like "Forwarded-For" on the one hand, vs. (B) app developers passing app-specific strings to/from client and server. The spec only concerns itself with the former, (A). The question here is whether there are conventions for (B). There are. They involve grouping the parameters together alphabetically, and separating them from the many standards-relevant headers of type (A). Using the "X-" or "X-ACME-" prefix is convenient and legitimate for (B), and does not conflict with (A). The more vendors stop using "X-" for (A), the more cleanly-distinct the (B) ones will become.

Example:
Google (who carry a bit of weight in the various standards bodies) are -- as of today, 20141102 in this slight edit to my answer -- currently using "X-Mod-Pagespeed" to indicate the version of their Apache module involved in transforming a given response. Is anyone really suggesting that Google should use "Mod-Pagespeed", without the "X-", and/or ask the IETF to bless its use?

Summary:
If you're using custom HTTP Headers (as a sometimes-appropriate alternative to cookies) within your app to pass data to/from your server, and these headers are, explicitly, NOT intended ever to be used outside the context of your application, name-spacing them with an "X-" or "X-FOO-" prefix is a reasonable, and common, convention.

How to get number of entries in a Lua table?

local function CountedTable(x)
    assert(type(x) == 'table', 'bad parameter #1: must be table')

    local new_t = {}
    local mt = {}

    -- `all` will represent the number of both
    local all = 0
    for k, v in pairs(x) do
        all = all + 1
    end

    mt.__newindex = function(t, k, v)
        if v == nil then
            if rawget(x, k) ~= nil then
                all = all - 1
            end
        else
            if rawget(x, k) == nil then
                all = all + 1
            end
        end

        rawset(x, k, v)
    end

    mt.__index = function(t, k)
        if k == 'totalCount' then return all
        else return rawget(x, k) end
    end

    return setmetatable(new_t, mt)
end

local bar = CountedTable { x = 23, y = 43, z = 334, [true] = true }

assert(bar.totalCount == 4)
assert(bar.x == 23)
bar.x = nil
assert(bar.totalCount == 3)
bar.x = nil
assert(bar.totalCount == 3)
bar.x = 24
bar.x = 25
assert(bar.x == 25)
assert(bar.totalCount == 4)

Detecting Back Button/Hash Change in URL

Use the jQuery hashchange event plugin instead. Regarding your full ajax navigation, try to have SEO friendly ajax. Otherwise your pages shown nothing in browsers with JavaScript limitations.

Get specific ArrayList item

Time to familiarize yourself with the ArrayList API and more:

ArrayList at Java 6 API Documentation

For your immediate question:

mainList.get(3);

Font-awesome, input type 'submit'

You can use button classes btn-link and btn-xs with type submit, which will make a small invisible button with an icon inside of it. Example:

<button class="btn btn-link btn-xs" type="submit" name="action" value="delete">
    <i class="fa fa-times text-danger"></i>
</button>

Kotlin unresolved reference in IntelliJ

Happened to me today.

My issue was that I had too many tabs open (I didn't know they were open) with source code on them.

If you close all the tabs, maybe you will unconfuse IntelliJ into indexing the dependencies correctly

Using os.walk() to recursively traverse directories in Python

This does it for folder names:

def printFolderName(init_indent, rootFolder):
    fname = rootFolder.split(os.sep)[-1]
    root_levels = rootFolder.count(os.sep)
    # os.walk treats dirs breadth-first, but files depth-first (go figure)
    for root, dirs, files in os.walk(rootFolder):
        # print the directories below the root
        levels = root.count(os.sep) - root_levels
        indent = ' '*(levels*2)
        print init_indent + indent + root.split(os.sep)[-1]

What is the id( ) function used for?

I have an idea to use value of id() in logging.
It's cheap to get and it's quite short.
In my case I use tornado and id() would like to have an anchor to group messages scattered and mixed over file by web socket.

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

I experienced the same problem in VS2008 when I tried to add a X64 build to a project converted from VS2003.

I looked at everything found when searching for this error on Google (Target machine, VC++Directories, DUMPBIN....) and everything looked OK.

Finally I created a new test project and did the same changes and it seemed to work.

Doing a diff between the vcproj files revealed the problem....

My converted project had /MACHINE:i386 set as additional option set under Linker->Command Line. Thus there was two /MACHINE options set (both x64 and i386) and the additional one took preference.

Removing this and setting it properly under Linker->Advanced->Target Machine made the problem disappeared.

How to loop and render elements in React.js without an array of objects to map?

I think this is the easiest way to loop in react js

<ul>
    {yourarray.map((item)=><li>{item}</li>)}
</ul>

compare differences between two tables in mysql

You can construct the intersection manually using UNION. It's easy if you have some unique field in both tables, e.g. ID:

SELECT * FROM T1
WHERE ID NOT IN (SELECT ID FROM T2)

UNION

SELECT * FROM T2
WHERE ID NOT IN (SELECT ID FROM T1)

If you don't have a unique value, you can still expand the above code to check for all fields instead of just the ID, and use AND to connect them (e.g. ID NOT IN(...) AND OTHER_FIELD NOT IN(...) etc)

Cannot convert lambda expression to type 'string' because it is not a delegate type

I think you are missing using System.Linq; from this system class.

and also add using System.Data.Entity; to the code

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

You can see some reports in SSMS:

Right-click the instance name / reports / standard / top sessions

You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.

You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.

This article looks promising.

Some stackoverflow goodness from Mr. Ozar.

edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.

Text in Border CSS HTML

Text in Border with transparent text background

_x000D_
_x000D_
.box{
    background-image: url("https://i.stack.imgur.com/N39wV.jpg");
    width: 350px;
    padding: 10px;
}

/*begin first box*/
.first{
    width: 300px;
    height: 100px;
    margin: 10px;
    border-width: 0 2px 0 2px;
    border-color: #333;
    border-style: solid;
    position: relative;
}

.first span {
    position: absolute;
    display: flex;
    right: 0;
    left: 0;
    align-items: center;
}
.first .foo{
    top: -8px;
}
.first .bar{
    bottom: -8.5px;
}
.first span:before{
    margin-right: 15px;
}
.first span:after {
    margin-left: 15px;
}
.first span:before , .first span:after {
    content: ' ';
    height: 2px;
    background: #333;
    display: block;
    width: 50%;
}


/*begin second box*/
.second{
    width: 300px;
    height: 100px;
    margin: 10px;
    border-width: 2px 0 2px 0;
    border-color: #333;
    border-style: solid;
    position: relative;
}

.second span {
    position: absolute;
    top: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
}
.second .foo{
    left: -15px;
}
.second .bar{
    right: -15.5px;
}
.second span:before{
    margin-bottom: 15px;
}
.second span:after {
    margin-top: 15px;
}
.second span:before , .second span:after {
    content: ' ';
    width: 2px;
    background: #333;
    display: block;
    height: 50%;
}
_x000D_
<div class="box">
    <div class="first">
        <span class="foo">FOO</span>
        <span class="bar">BAR</span>
    </div>

   <br>

    <div class="second">
        <span class="foo">FOO</span>
        <span class="bar">BAR</span>
    </div>
</div>
_x000D_
_x000D_
_x000D_

How to get integer values from a string in Python?

def function(string):  
    final = ''  
    for i in string:  
        try:   
            final += str(int(i))   
        except ValueError:  
            return int(final)  
print(function("4983results should get"))  

How to use Google App Engine with my own naked domain (not subdomain)?

You must try like this, Application Settings > Add Domain...

select rows in sql with latest date for each ID repeated multiple times

Have you tried the following:

SELECT ID, COUNT(*), max(date)
FROM table 
GROUP BY ID;

How to set up default schema name in JPA configuration?

If you are using (org.springframework.jdbc.datasource.DriverManagerDataSource) in ApplicationContext.xml to specify Database details then use below simple property to specify the schema.

<property name="schema" value="schemaName" />

Convert Little Endian to Big Endian

Below is an other approach that was useful for me

convertLittleEndianByteArrayToBigEndianByteArray (byte littlendianByte[], byte bigEndianByte[], int ArraySize){
    int i =0;

    for(i =0;i<ArraySize;i++){
      bigEndianByte[i] = (littlendianByte[ArraySize-i-1] << 7 & 0x80) | (littlendianByte[ArraySize-i-1] << 5 & 0x40) |
                            (littlendianByte[ArraySize-i-1] << 3 & 0x20) | (littlendianByte[ArraySize-i-1] << 1 & 0x10) |
                            (littlendianByte[ArraySize-i-1] >>1 & 0x08) | (littlendianByte[ArraySize-i-1] >> 3 & 0x04) |
                            (littlendianByte[ArraySize-i-1] >>5 & 0x02) | (littlendianByte[ArraySize-i-1] >> 7 & 0x01) ;
    }
}

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

It looks like a bug http://code.google.com/p/android/issues/detail?id=939.

Finally I have to write something like this:

 <stroke android:width="3dp"
         android:color="#555555"
         />

 <padding android:left="1dp"
          android:top="1dp"
          android:right="1dp"
          android:bottom="1dp"
          /> 

 <corners android:radius="1dp"
  android:bottomRightRadius="2dp" android:bottomLeftRadius="0dp" 
  android:topLeftRadius="2dp" android:topRightRadius="0dp"/> 

I have to specify android:bottomRightRadius="2dp" for left-bottom rounded corner (another bug here).

Executing Javascript code "on the spot" in Chrome?

I'm not sure how far it will get you, but you can execute JavaScript one line at a time from the Developer Tool Console.

Error : ORA-01704: string literal too long

The split work until 4000 chars depending on the characters that you are inserting. If you are inserting special characters it can fail. The only secure way is to declare a variable.

How can I check if two segments intersect?

Checking if line segments intersect is very easy with Shapely library using intersects method:

from shapely.geometry import LineString

line = LineString([(0, 0), (1, 1)])
other = LineString([(0, 1), (1, 0)])
print(line.intersects(other))
# True

enter image description here

line = LineString([(0, 0), (1, 1)])
other = LineString([(0, 1), (1, 2)])
print(line.intersects(other))
# False

enter image description here

PHP class: Global variable as property in class

Try to avoid globals, instead you can use something like this

class myClass() {
 private $myNumber;

 public function setNumber($number) {
  $this->myNumber = $number;
 }
}

Now you can call

$class = new myClass();
$class->setNumber('1234');

Increase max execution time for php

Try to set a longer max_execution_time:

<IfModule mod_php5.c>
    php_value max_execution_time 300
</IfModule>

<IfModule mod_php7.c>
    php_value max_execution_time 300
</IfModule>

Convert DataSet to List

var myData = ds.Tables[0].AsEnumerable().Select(r => new Employee {
    Name = r.Field<string>("Name"),
    Age = r.Field<int>("Age")
});
var list = myData.ToList(); // For if you really need a List and not IEnumerable

How to know if an object has an attribute in Python

I would like to suggest avoid this:

try:
    doStuff(a.property)
except AttributeError:
    otherStuff()

The user @jpalecek mentioned it: If an AttributeError occurs inside doStuff(), you are lost.

Maybe this approach is better:

try:
    val = a.property
except AttributeError:
    otherStuff()
else:
    doStuff(val)

Jenkins - how to build a specific branch

I can see many good answers to the question, but I still would like to share this method, by using Git parameter as follows:

Add Git parameter

When building the pipeline you will be asked to choose the branch: Choose branch to build

After that through the groovy code you could specify the branch you want to clone:

git branch:BRANCH[7..-1], url: 'https://github.com/YourName/YourRepo.git' , credentialsId: 'github' 

Note that I'm using a slice from 7 to the last character to shrink "origin/" and get the branch name.

Also in case you configured a webhooks trigger it still work and it will take the default branch you specified(master in our case).

How to disable a particular checkstyle rule for a particular line of code?

Every answer refering to SuppressWarningsFilter is missing an important detail. You can only use the all-lowercase id if it's defined as such in your checkstyle-config.xml. If not you must use the original module name.

For instance, if in my checkstyle-config.xml I have:

<module name="NoWhitespaceBefore"/>

I cannot use:

@SuppressWarnings({"nowhitespacebefore"})

I must, however, use:

@SuppressWarnings({"NoWhitespaceBefore"})

In order for the first syntax to work, the checkstyle-config.xml should have:

<module name="NoWhitespaceBefore">
  <property name="id" value="nowhitespacebefore"/>
</module>

This is what worked for me, at least in the CheckStyle version 6.17.

C# List<string> to string with delimiter

You can also do this with linq if you'd like

var names = new List<string>() { "John", "Anna", "Monica" };
var joinedNames = names.Aggregate((a, b) => a + ", " + b);

Although I prefer the non-linq syntax in Quartermeister's answer and I think Aggregate might perform slower (probably more string concatenation operations).

Where does linux store my syslog?

syslog() generates a log message, which will be distributed by syslogd.

The file to configure syslogd is /etc/syslog.conf. This file will tell your where the messages are logged.

How to change options in this file ? Here you go http://www.bo.infn.it/alice/alice-doc/mll-doc/duix/admgde/node74.html

how to use sqltransaction in c#

Well, I don't understand why are you used transaction in case when you make a select.

Transaction is useful when you make changes (add, edit or delete) data from database.

Remove transaction unless you use insert, update or delete statements

Load different application.yml in SpringBoot Test

Lu55 Option 1 how to...

Add test only application.yml inside a seperated resources folder.

+-- main
¦   +-- java
¦   +-- resources
¦       +-- application.yml
+-- test
    +-- java
    +-- resources
        +-- application.yml

In this project structure the application.yml under main is loaded if the code under main is running, the application.yml under test is used in a test.

To setup this structure add a new Package folder test/recources if not present.

Eclipse right click on your project -> Properties -> Java Build Path -> Source Tab -> (Dialog ont the rigth side) "Add Folder ..."

Inside Source Folder Selection -> mark test -> click on "Create New Folder ..." button -> type "resources" inside the Textfeld -> Click the "Finish" button.

After pushing the "Finisch" button you can see the sourcefolder {projectname}/src/test/recources (new)

Optional: Arrange folder sequence for the Project Explorer view. Klick on Order and Export Tab mark and move {projectname}/src/test/recources to bottom. Apply and Close

!!! Clean up Project !!!
Eclipse -> Project -> Clean ...

Now there is a separated yaml for test and the main application.

Change navbar text color Bootstrap

The syntax is :

.nav navbar-nav .navbar-right > li > a {
   color: blue;
}

how do you view macro code in access?

EDIT: Per Michael Dillon's answer, SaveAsText does save the commands in a macro without having to go through converting to VBA. I don't know what happened when I tested that, but it didn't produce useful text in the resulting file.

So, I learned something new today!

ORIGINAL POST: To expand the question, I wondered if there was a way to retrieve the contents of a macro from code, and it doesn't appear that there is (at least not in A2003, which is what I'm running).

There are two collections through which you can access stored Macros:

  CurrentDB.Containers("Scripts").Documents
  CurrentProject.AllMacros

The properties that Intellisense identifies for the two collections are rather different, because the collections are of different types. The first (i.e., traditional, pre-A2000 way) is via a documents collection, and the methods/properties/members of all documents are the same, i.e., not specific to Macros.

Likewise, the All... collections of CurrentProject return collections where the individual items are of type Access Object. The result is that Intellisense gives you methods/properties/members that may not exist for the particular document/object.

So far as I can tell, there is no way to programatically retrieve the contents of a macro.

This would stand to reason, as macros aren't of much use to anyone who would have the capability of writing code to examine them programatically.

But if you just want to evaluate what the macros do, one alternative would be to convert them to VBA, which can be done programmatically thus:

  Dim varItem As Variant
  Dim strMacroName As String

  For Each varItem In CurrentProject.AllMacros
    strMacroName = varItem.Name
    'Debug.Print strMacroName
    DoCmd.SelectObject acMacro, strMacroName, True
    DoCmd.RunCommand acCmdConvertMacrosToVisualBasic
    Application.SaveAsText acModule, "Converted Macro- " & strMacroName, _
      CurrentProject.Path & "\" & "Converted Macro- " & strMacroName & ".txt"
  Next varItem

Then you could use the resulting text files for whatever you needed to do.

Note that this has to be run interactively in Access because it uses DoCmd.RunCommand, and you have to click OK for each macro -- tedious for databases with lots of macros, but not too onerous for a normal app, which shouldn't have more than a handful of macros.

Benefits of EBS vs. instance-store (and vice-versa)

I've had the exact same experience as Eric at my last position. Now in my new job, I'm going through the same process I performed at my last job... rebuilding all their AMIs for EBS backed instances - and possibly as 32bit machines (cheaper - but can't use same AMI on 32 and 64 machines).

EBS backed instances launch quickly enough that you can begin to make use of the Amazon AutoScaling API which lets you use CloudWatch metrics to trigger the launch of additional instances and register them to the ELB (Elastic Load Balancer), and also to shut them down when no longer required.

This kind of dynamic autoscaling is what AWS is all about - where the real savings in IT infrastructure can come into play. It's pretty much impossible to do autoscaling right with the old s3 "InstanceStore"-backed instances.

How to specify a local file within html using the file: scheme?

For apache look up SymLink or you can solve via the OS with Symbolic Links or on linux set up a library link/etc

My answer is one method specifically to windows 10.

So my method involves mapping a network drive to U:/ (e.g. I use G:/ for Google Drive)

open cmd and type hostname (example result: LAPTOP-G666P000, you could use your ip instead, but using a static hostname for identifying yourself makes more sense if your network stops)

Press Windows_key + E > right click 'This PC' > press N (It's Map Network drive, NOT add a network location)

If you are right clicking the shortcut on the desktop you need to press N then enter

Fill out U: or G: or Z: or whatever you want Example Address: \\LAPTOP-G666P000\c$\Users\username\

Then you can use <a href="file:///u:/2ndFile.html"><button type="submit">Local file</button> like in your question


related: You can also use this method for FTPs, and setup multiple drives for different relative paths on that same network.

related2: I have used http://localhost/c$ etc before on some WAMP/apache servers too before, you can use .htaccess for control/security but I recommend to not do so on a live/production machine -- or any other symlink documentroot example you can google

for each inside a for each - Java

for (Tweet : tweets){ ...

should really be

for(Tweet tweet: tweets){...

How to change navbar/container width? Bootstrap 3

just simple:

.navbar{
    width:65% !important;
    margin:0px auto;
    left:0;
    right:0;
    padding:0;
}

or,

.navbar.navbar-fixed-top{
    width:65% !important;
    margin:0px auto;
    left:0;
    right:0;
    padding:0;
}

Hope it works (at least, for future searchers)

Add my custom http header to Spring RestTemplate request / extend RestTemplate

Add a "User-Agent" header to your request.

Some servers attempt to block spidering programs and scrapers from accessing their server because, in earlier days, requests did not send a user agent header.

You can either try to set a custom user agent value or use some value that identifies a Browser like "Mozilla/5.0 Firefox/26.0"

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();

headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("user-agent", "Mozilla/5.0 Firefox/26.0");
headers.set("user-key", "your-password-123"); // optional - in case you auth in headers
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<Game[]> respEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Game[].class);

logger.info(respEntity.toString());

How can you float: right in React Native?

You are not supposed to use floats in React Native. React Native leverages the flexbox to handle all that stuff.

In your case, you will probably want the container to have an attribute

justifyContent: 'flex-end'

And about the text taking the whole space, again, you need to take a look at your container.

Here is a link to really great guide on flexbox: A Complete Guide to Flexbox

Xcode error: Code signing is required for product type 'Application' in SDK 'iOS 10.0'

With Xcode-8.1 & iOS-10.1

  1. Add your Apple ID in Xcode Preferences > Accounts > Add Apple ID:

Step 1

  1. Enable signing to Automatically && Select Team that you have created before:

Step 2

  1. Change the Bundle Identifier:

Step 3

  1. Code Signing to iOS Developer:

Step 4

  1. Provision profile to Automatic:

Step 5

You can now run your project on a device!

Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?

Good to see someone's chimed in about Lucene - because I've no idea about that.

Sphinx, on the other hand, I know quite well, so let's see if I can be of some help.

  • Result relevance ranking is the default. You can set up your own sorting should you wish, and give specific fields higher weightings.
  • Indexing speed is super-fast, because it talks directly to the database. Any slowness will come from complex SQL queries and un-indexed foreign keys and other such problems. I've never noticed any slowness in searching either.
  • I'm a Rails guy, so I've no idea how easy it is to implement with Django. There is a Python API that comes with the Sphinx source though.
  • The search service daemon (searchd) is pretty low on memory usage - and you can set limits on how much memory the indexer process uses too.
  • Scalability is where my knowledge is more sketchy - but it's easy enough to copy index files to multiple machines and run several searchd daemons. The general impression I get from others though is that it's pretty damn good under high load, so scaling it out across multiple machines isn't something that needs to be dealt with.
  • There's no support for 'did-you-mean', etc - although these can be done with other tools easily enough. Sphinx does stem words though using dictionaries, so 'driving' and 'drive' (for example) would be considered the same in searches.
  • Sphinx doesn't allow partial index updates for field data though. The common approach to this is to maintain a delta index with all the recent changes, and re-index this after every change (and those new results appear within a second or two). Because of the small amount of data, this can take a matter of seconds. You will still need to re-index the main dataset regularly though (although how regularly depends on the volatility of your data - every day? every hour?). The fast indexing speeds keep this all pretty painless though.

I've no idea how applicable to your situation this is, but Evan Weaver compared a few of the common Rails search options (Sphinx, Ferret (a port of Lucene for Ruby) and Solr), running some benchmarks. Could be useful, I guess.

I've not plumbed the depths of MySQL's full-text search, but I know it doesn't compete speed-wise nor feature-wise with Sphinx, Lucene or Solr.

How can I auto hide alert box after it showing it?

impossible with javascript. Just as another alternative to suggestions from other answers: consider using jGrowl: http://archive.plugins.jquery.com/project/jGrowl

What properties does @Column columnDefinition make redundant?

My Answer: All of the following should be overridden (i.e. describe them all within columndefinition, if appropriate):

  • length
  • precision
  • scale
  • nullable
  • unique

i.e. the column DDL will consist of: name + columndefinition and nothing else.

Rationale follows.


  1. Annotation containing the word "Column" or "Table" is purely physical - properties only used to control DDL/DML against database.

  2. Other annotation purely logical - properties used in-memory in java to control JPA processing.

  3. That's why sometimes it appears the optionality/nullability is set twice - once via @Basic(...,optional=true) and once via @Column(...,nullable=true). Former says attribute/association can be null in the JPA object model (in-memory), at flush time; latter says DB column can be null. Usually you'd want them set the same - but not always, depending on how the DB tables are setup and reused.

In your example, length and nullable properties are overridden and redundant.


So, when specifying columnDefinition, what other properties of @Column are made redundant?

  1. In JPA Spec & javadoc:

    • columnDefinition definition: The SQL fragment that is used when generating the DDL for the column.

    • columnDefinition default: Generated SQL to create a column of the inferred type.

    • The following examples are provided:

      @Column(name="DESC", columnDefinition="CLOB NOT NULL", table="EMP_DETAIL")
      @Column(name="EMP_PIC", columnDefinition="BLOB NOT NULL")
      
    • And, err..., that's it really. :-$ ?!

    Does columnDefinition override other properties provided in the same annotation?

    The javadoc and JPA spec don't explicity address this - spec's not giving great protection. To be 100% sure, test with your chosen implementation.

  2. The following can be safely implied from examples provided in the JPA spec

    • name & table can be used in conjunction with columnDefinition, neither are overridden
    • nullable is overridden/made redundant by columnDefinition
  3. The following can be fairly safely implied from the "logic of the situation" (did I just say that?? :-P ):

    • length, precision, scale are overridden/made redundant by the columnDefinition - they are integral to the type
    • insertable and updateable are provided separately and never included in columnDefinition, because they control SQL generation in-memory, before it is emmitted to the database.
  4. That leaves just the "unique" property. It's similar to nullable - extends/qualifies the type definition, so should be treated integral to type definition. i.e. should be overridden.


Test My Answer For columns "A" & "B", respectively:

  @Column(name="...", table="...", insertable=true, updateable=false,
          columndefinition="NUMBER(5,2) NOT NULL UNIQUE"

  @Column(name="...", table="...", insertable=false, updateable=true,
          columndefinition="NVARCHAR2(100) NULL"
  • confirm generated table has correct type/nullability/uniqueness
  • optionally, do JPA insert & update: former should include column A, latter column B

How to force Chrome browser to reload .css file while debugging in Visual Studio?

You can copy paste this script into Chrome console and it forces your CSS scripts to reload every 3 seconds. Sometimes I find it useful when I'm improving CSS styles.

var nodes = document.querySelectorAll('link');
[].forEach.call(nodes, function (node) {
    node.href += '?___ref=0';
});
var i = 0;
setInterval(function () {
    i++;

    [].forEach.call(nodes, function (node) {
        node.href = node.href.replace(/\?\_\_\_ref=[0-9]+/, '?___ref=' + i);
    });
    console.log('refreshed: ' + i);
},3000);

Getting View's coordinates relative to the root layout

I wrote myself two utility methods that seem to work in most conditions, handling scroll, translation and scaling, but not rotation. I did this after trying to use offsetDescendantRectToMyCoords() in the framework, which had inconsistent accuracy. It worked in some cases but gave wrong results in others.

"point" is a float array with two elements (the x & y coordinates), "ancestor" is a viewgroup somewhere above the "descendant" in the tree hierarchy.

First a method that goes from descendant coordinates to ancestor:

public static void transformToAncestor(float[] point, final View ancestor, final View descendant) {
    final float scrollX = descendant.getScrollX();
    final float scrollY = descendant.getScrollY();
    final float left = descendant.getLeft();
    final float top = descendant.getTop();
    final float px = descendant.getPivotX();
    final float py = descendant.getPivotY();
    final float tx = descendant.getTranslationX();
    final float ty = descendant.getTranslationY();
    final float sx = descendant.getScaleX();
    final float sy = descendant.getScaleY();

    point[0] = left + px + (point[0] - px) * sx + tx - scrollX;
    point[1] = top + py + (point[1] - py) * sy + ty - scrollY;

    ViewParent parent = descendant.getParent();
    if (descendant != ancestor && parent != ancestor && parent instanceof View) {
        transformToAncestor(point, ancestor, (View) parent);
    }
}

Next the inverse, from ancestor to descendant:

public static void transformToDescendant(float[] point, final View ancestor, final View descendant) {
    ViewParent parent = descendant.getParent();
    if (descendant != ancestor && parent != ancestor && parent instanceof View) {
        transformToDescendant(point, ancestor, (View) parent);
    }

    final float scrollX = descendant.getScrollX();
    final float scrollY = descendant.getScrollY();
    final float left = descendant.getLeft();
    final float top = descendant.getTop();
    final float px = descendant.getPivotX();
    final float py = descendant.getPivotY();
    final float tx = descendant.getTranslationX();
    final float ty = descendant.getTranslationY();
    final float sx = descendant.getScaleX();
    final float sy = descendant.getScaleY();

    point[0] = px + (point[0] + scrollX - left - tx - px) / sx;
    point[1] = py + (point[1] + scrollY - top - ty - py) / sy;
}

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

If you really need to go this way, then this is what you can do. There are probably better ways of doing it, but this is all that I have at the moment. I did no database calls, I just used dummy data. Please modify the code to fit in with your scenario. I used jQuery to populate the HTML table.

In my controller I have the an action method called GetEmployees that returns a JSON result with all the employees. This is where you would call your repository to return the users from a database:

public ActionResult GetEmployees()
{
     List<User> userList = new List<User>();

     User user1 = new User
     {
          Id = 1,
          FirstName = "First name 1",
          LastName = "Last name 1"
     };

     User user2 = new User
     {
          Id = 2,
          FirstName = "First name 2",
          LastName = "Last name 2"
     };

     userList.Add(user1);
     userList.Add(user2);

     return Json(userList, JsonRequestBehavior.AllowGet);
}

The User class looks like this:

public class User
{
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
}

In your view you could have the following:

<div id="users">
     <table></table>
</div>

<script>

     $(document).ready(function () {

          var url = '/Home/GetEmployees';

          $.getJSON(url, function (data) {

               $.each(data, function (key, val) {

                    var user = '<tr><td>' + val.FirstName + '</td></tr>';

                    $('#users table').append(user);

               });
          });
     });

</script>

Regarding the code above: var url = '/Home/GetEmployees'; Home is the controller and GetEmployees is the action method that you defined above.

I hope this helps.

UPDATE:

This is how I would have done it..

I always create a view model class for a view. In this case I would have called it something like UserListViewModel:

public class UserListViewModel
{
     IEnumerable<User> Users { get; set; }
}

In my controller I would populate this Users list from a call to the database returning all the users:

public ActionResult List()
{
     UserListViewModel viewModel = new UserListViewModel
     {
          Users = userRepository.GetAllUsers()
     };

     return View(viewModel);
}

And in my view I would have the following:

<table>

@foreach(User user in Model.Users)
{
     <tr>
          <td>First Name:</td>
          <td>user.FirstName</td>
     </tr>
}

</table>

Equivalent of typedef in C#

No, there's no true equivalent of typedef. You can use 'using' directives within one file, e.g.

using CustomerList = System.Collections.Generic.List<Customer>;

but that will only impact that source file. In C and C++, my experience is that typedef is usually used within .h files which are included widely - so a single typedef can be used over a whole project. That ability does not exist in C#, because there's no #include functionality in C# that would allow you to include the using directives from one file in another.

Fortunately, the example you give does have a fix - implicit method group conversion. You can change your event subscription line to just:

gcInt.MyEvent += gcInt_MyEvent;

:)

PLS-00428: an INTO clause is expected in this SELECT statement

In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.

The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.

DECLARE
   PROD_ROW_ID   VARCHAR (10) := NULL;
   VIS_ROW_ID    NUMBER;
   DSC           VARCHAR (512);
BEGIN
   SELECT ROW_ID
     INTO VIS_ROW_ID
     FROM SIEBEL.S_PROD_INT
    WHERE PART_NUM = 'S0146404';

   BEGIN
      SELECT    RTRIM (VIS.SERIAL_NUM)
             || ','
             || RTRIM (PLANID.DESC_TEXT)
             || ','
             || CASE
                   WHEN PLANID.HIGH = 'TEST123'
                   THEN
                      CASE
                         WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
                         THEN
                            'Y'
                         ELSE
                            'N'
                      END
                   ELSE
                      'N'
                END
             || ','
             || 'GB'
             || ','
             || RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
        INTO DSC
        FROM SIEBEL.S_LST_OF_VAL PLANID
             INNER JOIN SIEBEL.S_PROD_INT PROD
                ON PROD.PART_NUM = PLANID.VAL
             INNER JOIN SIEBEL.S_ASSET NETFLIX
                ON PROD.PROD_ID = PROD.ROW_ID
             INNER JOIN SIEBEL.S_ASSET VIS
                ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
             INNER JOIN SIEBEL.S_PROD_INT VISPROD
                ON VIS.PROD_ID = VISPROD.ROW_ID
       WHERE     PLANID.TYPE = 'Test Plan'
             AND PLANID.ACTIVE_FLG = 'Y'
             AND VISPROD.PART_NUM = VIS_ROW_ID
             AND PROD.STATUS_CD = 'Active'
             AND VIS.SERIAL_NUM IS NOT NULL;
   END;
END;
/

References

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/

Altering user-defined table types in SQL Server

Simon Zeinstra has found the solution!

But, I used Visual Studio community 2015 and I didn't even have to use schema compare.

Using SQL Server Object Explorer, I found my user-defined table type in the DB. I right-mouse clicked on the table-type and selected . This opened a code tab in the IDE with the TSQL code visible and editable. I simply changed the definition (in my case just increased the size of an nvarchar field) and clicked the Update Database button in the top-left of the tab.

Hey Presto! - a quick check in SSMS and the udtt definition has been modified.

Brilliant - thanks Simon.

CSS width of a <span> tag

Use the attribute 'display' as in the example:

<span style="background: gray; width: 100px; display:block;">hello</span>
<span style="background: gray; width: 200px; display:block;">world</span>

How to get JSON response from http.Get

You need upper case property names in your structs in order to be used by the json packages.

Upper case property names are exported properties. Lower case property names are not exported.

You also need to pass the your data object by reference (&data).

package main

import "os"
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"

type tracks struct {
    Toptracks []toptracks_info
}

type toptracks_info struct {
    Track []track_info
    Attr  []attr_info
}

type track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []streamable_info
    Artist     []artist_info
    Attr       []track_attr_info
}

type attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type streamable_info struct {
    Text      string
    Fulltrack string
}

type artist_info struct {
    Name string
    Mbid string
    Url  string
}

type track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"

    res, err := http.Get(url)

    if err != nil {
        panic(err.Error())
    }

    body, err := ioutil.ReadAll(res.Body)

    if err != nil {
        panic(err.Error())
    }

    var data tracks
    json.Unmarshal(body, &data)
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

Using a Glyphicon as an LI bullet point (Bootstrap 3)

If anyone is coming here looking to do this with Font Awesome Icons (like I was) view here: https://fontawesome.com/how-to-use/on-the-web/styling/icons-in-a-list

<ul class="fa-ul">
  <li><i class="fa-li fa fa-check-square"></i>List icons</li>
  <li><i class="fa-li fa fa-check-square"></i>can be used</li>
  <li><i class="fa-li fa fa-spinner fa-spin"></i>as bullets</li>
  <li><i class="fa-li fa fa-square"></i>in lists</li>
</ul>

The fa-ul and fa-li classes easily replace default bullets in unordered lists.

Can't import org.apache.http.HttpResponse in Android Studio

HttpClient was deprecated in Android 5.1 and is removed from the Android SDK in Android 6.0. While there is a workaround to continue using HttpClient in Android 6.0 with Android Studio, you really need to move to something else. That "something else" could be:

Or, depending upon the nature of your HTTP work, you might choose a library that supports higher-order operations (e.g., Retrofit for Web service APIs).

In a pinch, you could enable the legacy APIs, by having useLibrary 'org.apache.http.legacy' in your android closure in your module's build.gradle file. However, Google has been advising people for years to stop using Android's built-in HttpClient, and so at most, this should be a stop-gap move, while you work on a more permanent shift to another API.

You should not use <Link> outside a <Router>

Make it simple:

render(<BrowserRouter><Main /></BrowserRouter>, document.getElementById('root'));

and don't forget: import { BrowserRouter } from "react-router-dom";

Oracle client and networking components were not found

1.Go to My Computer Properties
2.Then click on Advance setting.
3.Go to Environment variable
4.Set the path to

 F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2\perl\site\5.8.3;F:\oracle\product\10.2.0\db_2\perl\site\5.8.3\lib;F:\oracle\product\10.2.0\db_2\sysman\admin\scripts;

change your drive and folder depending on your requirement...

Java best way for string find and replace?

One possibility, reducing the longer form before expanding all:

string.replaceAll("Milan Vasic", "Milan").replaceAll("Milan", "Milan Vasic")

Another way, treating Vasic as optional:

string.replaceAll("Milan( Vasic)?", "Milan Vasic")

Others have described solutions based on lookahead or alternation.

How to add an Access-Control-Allow-Origin header

The accepted answer doesn't work for me unfortunately, since my site CSS files @import the font CSS files, and these are all stored on a Rackspace Cloud Files CDN.

Since the Apache headers are never generated (since my CSS is not on Apache), I had to do several things:

  1. Go to the Cloud Files UI and add a custom header (Access-Control-Allow-Origin with value *) for each font-awesome file
  2. Change the Content-Type of the woff and ttf files to font/woff and font/ttf respectively

See if you can get away with just #1, since the second requires a bit of command line work.

To add the custom header in #1:

  • view the cloud files container for the file
  • scroll down to the file
  • click the cog icon
  • click Edit Headers
  • select Access-Control-Allow-Origin
  • add the single character '*' (without the quotes)
  • hit enter
  • repeat for the other files

If you need to continue and do #2, then you'll need a command line with CURL

curl -D - --header "X-Auth-Key: your-auth-key-from-rackspace-cloud-control-panel" --header "X-Auth-User: your-cloud-username" https://auth.api.rackspacecloud.com/v1.0

From the results returned, extract the values for X-Auth-Token and X-Storage-Url

curl -X POST \
  -H "Content-Type: font/woff" \
  --header "X-Auth-Token: returned-x-auth-token" returned-x-storage-url/name-of-your-container/fonts/fontawesome-webfont.woff

curl -X POST \
  -H "Content-Type: font/ttf" \
  --header "X-Auth-Token: returned-x-auth-token" returned-x-storage-url/name-of-your-container/fonts/fontawesome-webfont.ttf

Of course, this process only works if you're using the Rackspace CDN. Other CDNs may offer similar facilities to edit object headers and change content types, so maybe you'll get lucky (and post some extra info here).

TypeScript enum to object array

Here's the simple function with correct typing I use

/**
 * Helper to produce an array of enum values.
 * @param enumeration Enumeration object.
 */
export function enumToArray<T, G extends keyof T = keyof T>(enumeration: T): T[G][] {
  // tslint:disable: comment-format

  // enum Colors {
  //   WHITE = 0,
  //   BLACK = 1,
  // }
  // Object.values(Colors) will produce ['WHITE', 'BLACK', 0, 1]

  // So, simply slice the second half
  const enumValues = Object.values(enumeration);
  return enumValues.slice(enumValues.length / 2, enumValues.length) as T[G][];
}

Usage example:

enum Colors {
  Red = 1,
  Blue = 2,
}
enumToArray(Colors)

How do I align views at the bottom of the screen?

In case you have a hierarchy like this:

<ScrollView> 
  |-- <RelativeLayout> 
    |-- <LinearLayout>

First, apply android:fillViewport="true" to the ScrollView and then apply android:layout_alignParentBottom="true" to the LinearLayout.

This worked for me perfectly.

<ScrollView
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:scrollbars="none"
    android:fillViewport="true">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:id="@+id/linearLayoutHorizontal"
            android:layout_alignParentBottom="true">
        </LinearLayout>
    </RelativeLayout>
</ScrollView>

Can we execute a java program without a main() method?

You should also be able to accomplish a similar thing using the premain method of a Java agent.

The manifest of the agent JAR file must contain the attribute Premain-Class. The value of this attribute is the name of the agent class. The agent class must implement a public static premain method similar in principle to the main application entry point. After the Java Virtual Machine (JVM) has initialized, each premain method will be called in the order the agents were specified, then the real application main method will be called. Each premain method must return in order for the startup sequence to proceed.

Vim for Windows - What do I type to save and exit from a file?

A faster way to

  • Save
  • and quit

would be

:x

If you have opened multiple files you may need to do a

:xa

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

What is the difference between ports 465 and 587?

SMTP protocol: smtps (port 465) v. msa (port 587)

Ports 465 and 587 are intended for email client to email server communication - sending out email using SMTP protocol.

Port 465 is for smtps
SSL encryption is started automatically before any SMTP level communication.

Port 587 is for msa
It is almost like standard SMTP port. MSA should accept email after authentication (e.g. after SMTP AUTH). It helps to stop outgoing spam when netmasters of DUL ranges can block outgoing connections to SMTP port (port 25).
SSL encryption may be started by STARTTLS command at SMTP level if server supports it and your ISP does not filter server's EHLO reply (reported 2014).


Port 25 is used by MTA to MTA communication (mail server to mail server). It may be used for client to server communication but it is not currently the most recommended. Standard SMTP port accepts email from other mail servers to its "internal" mailboxes without authentication.

TypeError: Object of type 'bytes' is not JSON serializable

I guess the answer you need is referenced here Python sets are not json serializable

Not all datatypes can be json serialized . I guess pickle module will serve your purpose.

How do you comment an MS-access Query?

if you are trying to add a general note to the overall object (query or table etc..)

Access 2016 go to navigation pane, highlight object, right click, select object / table properties, add a note in the description window i.e. inventory "table last last updated 05/31/17"

What's the best way to share data between activities?

There is a new and better way to share data between activities, and it is LiveData. Notice in particular this quote from the Android developer's page:

The fact that LiveData objects are lifecycle-aware means that you can share them between multiple activities, fragments, and services. To keep the example simple, you can implement the LiveData class as a singleton

The implication of this is huge - any model data can be shared in a common singleton class inside a LiveData wrapper. It can be injected from the activities into their respective ViewModel for the sake of testability. And you no longer need to worry about weak references to prevent memory leaks.

How to create a signed APK file using Cordova command line interface?

First Check your version code and version name if you are updating your app. And make sure you have a previous keystore.

If you are updating app then follow step 1,3,4.

Step 1:

Goto your cordova project for generate our release build:

D:\projects\Phonegap\Example> cordova build --release android

Then, we can find our unsigned APK file in platforms/android/ant-build. In our example, the file was

if u used ant-build

yourproject/platforms/android/ant-build/Example-release-unsigned.apk

OR

if u used gradle-build

yourProject/platforms/android/build/outputs/apk/Example-release-unsigned.apk

Step 2:

Key Generation:

Syntax:

keytool -genkey -v -keystore <keystoreName>.keystore -alias <Keystore AliasName> -keyalg <Key algorithm> -keysize <Key size> -validity <Key Validity in Days>

if keytool command not recognize do this step

Check that the directory the keytool executable is in is on your path. (For example, on my Windows 7 machine, it's in C:\Program Files (x86)\Java\jre6\bin.)

Example:

keytool -genkey -v -keystore NAME-mobileapps.keystore -alias NAMEmobileapps -keyalg RSA -keysize 2048 -validity 10000


keystore password? : xxxxxxx
What is your first and last name? :  xxxxxx
What is the name of your organizational unit? :  xxxxxxxx
What is the name of your organization? :  xxxxxxxxx
What is the name of your City or Locality? :  xxxxxxx
What is the name of your State or Province? :  xxxxx
What is the two-letter country code for this unit? :  xxx

Then the Key store has been generated with name as NAME-mobileapps.keystore

Step 3:

Place the generated keystore in D:\projects\Phonegap\Example\platforms\android\ant-build

To sign the unsigned APK, run the jarsigner tool which is also included in the JDK:

Syntax:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore <keystorename <Unsigned APK file> <Keystore Alias name>

If it doesn't reconize do these steps

(1) Right click on "This PC" > right-click Properties > Advanced system settings > Environment Variables > select PATH then EDIT.

(2) Add your jdk bin folder path to environment variables, it should look like this:

"C:\Program Files\Java\jdk1.8.0_40\bin".

Example:

D:\projects\Phonegap\Example\platforms\android\ant-build> jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore NAME-mobileapps.keystore Example-release-unsigned.apk xxxxxmobileapps

Enter KeyPhrase as 'xxxxxxxx'

This signs the apk in place.

Step 4:

Finally, we need to run the zip align tool to optimize the APK:

if zipalign not recognize then

(1) goto your android sdk path and find zipalign it is usually in android-sdk\build-tools\23.0.3

(2) Copy zipalign file paste into your generate release apk folder usually in below path

yourproject/platforms/android/ant-build/Example-release-unsigned.apk

D:\projects\Phonegap\Example\platforms\android\ant-build> zipalign -v 4 Example-release-unsigned.apk Example.apk 

OR

D:\projects\Phonegap\Example\platforms\android\ant-build> C:\Phonegap\adt-bundle-windows-x86_64-20140624\sdk\build-tools\android-4.4W\zipalign -v 4 Example-release-unsigned.apk Example.apk

Now we have our final release binary called example.apk and we can release this on the Google Play Store.

How to get selected value of a html select with asp.net

If you would use asp:dropdownlist you could select it easier by testSelect.Text.

Now you'd have to do a Request.Form["testSelect"] to get the value after pressed btnTes.

Hope it helps.

EDIT: You need to specify a name of the select (not only ID) to be able to Request.Form["testSelect"]

How to use glOrtho() in OpenGL?

Minimal runnable example

glOrtho: 2D games, objects close and far appear the same size:

enter image description here

glFrustrum: more real-life like 3D, identical objects further away appear smaller:

enter image description here

main.c

#include <stdlib.h>

#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

static int ortho = 0;

static void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();
    if (ortho) {
    } else {
        /* This only rotates and translates the world around to look like the camera moved. */
        gluLookAt(0.0, 0.0, -3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    }
    glColor3f(1.0f, 1.0f, 1.0f);
    glutWireCube(2);
    glFlush();
}

static void reshape(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    if (ortho) {
        glOrtho(-2.0, 2.0, -2.0, 2.0, -1.5, 1.5);
    } else {
        glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
    }
    glMatrixMode(GL_MODELVIEW);
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    if (argc > 1) {
        ortho = 1;
    }
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(100, 100);
    glutCreateWindow(argv[0]);
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glShadeModel(GL_FLAT);
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();
    return EXIT_SUCCESS;
}

GitHub upstream.

Compile:

gcc -ggdb3 -O0 -o main -std=c99 -Wall -Wextra -pedantic main.c -lGL -lGLU -lglut

Run with glOrtho:

./main 1

Run with glFrustrum:

./main

Tested on Ubuntu 18.10.

Schema

Ortho: camera is a plane, visible volume a rectangle:

enter image description here

Frustrum: camera is a point,visible volume a slice of a pyramid:

enter image description here

Image source.

Parameters

We are always looking from +z to -z with +y upwards:

glOrtho(left, right, bottom, top, near, far)
  • left: minimum x we see
  • right: maximum x we see
  • bottom: minimum y we see
  • top: maximum y we see
  • -near: minimum z we see. Yes, this is -1 times near. So a negative input means positive z.
  • -far: maximum z we see. Also negative.

Schema:

Image source.

How it works under the hood

In the end, OpenGL always "uses":

glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

If we use neither glOrtho nor glFrustrum, that is what we get.

glOrtho and glFrustrum are just linear transformations (AKA matrix multiplication) such that:

  • glOrtho: takes a given 3D rectangle into the default cube
  • glFrustrum: takes a given pyramid section into the default cube

This transformation is then applied to all vertexes. This is what I mean in 2D:

Image source.

The final step after transformation is simple:

  • remove any points outside of the cube (culling): just ensure that x, y and z are in [-1, +1]
  • ignore the z component and take only x and y, which now can be put into a 2D screen

With glOrtho, z is ignored, so you might as well always use 0.

One reason you might want to use z != 0 is to make sprites hide the background with the depth buffer.

Deprecation

glOrtho is deprecated as of OpenGL 4.5: the compatibility profile 12.1. "FIXED-FUNCTION VERTEX TRANSFORMATIONS" is in red.

So don't use it for production. In any case, understanding it is a good way to get some OpenGL insight.

Modern OpenGL 4 programs calculate the transformation matrix (which is small) on the CPU, and then give the matrix and all points to be transformed to OpenGL, which can do the thousands of matrix multiplications for different points really fast in parallel.

Manually written vertex shaders then do the multiplication explicitly, usually with the convenient vector data types of the OpenGL Shading Language.

Since you write the shader explicitly, this allows you to tweak the algorithm to your needs. Such flexibility is a major feature of more modern GPUs, which unlike the old ones that did a fixed algorithm with some input parameters, can now do arbitrary computations. See also: https://stackoverflow.com/a/36211337/895245

With an explicit GLfloat transform[] it would look something like this:

glfw_transform.c

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#define GLEW_STATIC
#include <GL/glew.h>

#include <GLFW/glfw3.h>

static const GLuint WIDTH = 800;
static const GLuint HEIGHT = 600;
/* ourColor is passed on to the fragment shader. */
static const GLchar* vertex_shader_source =
    "#version 330 core\n"
    "layout (location = 0) in vec3 position;\n"
    "layout (location = 1) in vec3 color;\n"
    "out vec3 ourColor;\n"
    "uniform mat4 transform;\n"
    "void main() {\n"
    "    gl_Position = transform * vec4(position, 1.0f);\n"
    "    ourColor = color;\n"
    "}\n";
static const GLchar* fragment_shader_source =
    "#version 330 core\n"
    "in vec3 ourColor;\n"
    "out vec4 color;\n"
    "void main() {\n"
    "    color = vec4(ourColor, 1.0f);\n"
    "}\n";
static GLfloat vertices[] = {
/*   Positions          Colors */
     0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
    -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
     0.0f,  0.5f, 0.0f, 0.0f, 0.0f, 1.0f
};

/* Build and compile shader program, return its ID. */
GLuint common_get_shader_program(
    const char *vertex_shader_source,
    const char *fragment_shader_source
) {
    GLchar *log = NULL;
    GLint log_length, success;
    GLuint fragment_shader, program, vertex_shader;

    /* Vertex shader */
    vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL);
    glCompileShader(vertex_shader);
    glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
    glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &log_length);
    log = malloc(log_length);
    if (log_length > 0) {
        glGetShaderInfoLog(vertex_shader, log_length, NULL, log);
        printf("vertex shader log:\n\n%s\n", log);
    }
    if (!success) {
        printf("vertex shader compile error\n");
        exit(EXIT_FAILURE);
    }

    /* Fragment shader */
    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL);
    glCompileShader(fragment_shader);
    glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
    glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &log_length);
    if (log_length > 0) {
        log = realloc(log, log_length);
        glGetShaderInfoLog(fragment_shader, log_length, NULL, log);
        printf("fragment shader log:\n\n%s\n", log);
    }
    if (!success) {
        printf("fragment shader compile error\n");
        exit(EXIT_FAILURE);
    }

    /* Link shaders */
    program = glCreateProgram();
    glAttachShader(program, vertex_shader);
    glAttachShader(program, fragment_shader);
    glLinkProgram(program);
    glGetProgramiv(program, GL_LINK_STATUS, &success);
    glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
    if (log_length > 0) {
        log = realloc(log, log_length);
        glGetProgramInfoLog(program, log_length, NULL, log);
        printf("shader link log:\n\n%s\n", log);
    }
    if (!success) {
        printf("shader link error");
        exit(EXIT_FAILURE);
    }

    /* Cleanup. */
    free(log);
    glDeleteShader(vertex_shader);
    glDeleteShader(fragment_shader);
    return program;
}

int main(void) {
    GLint shader_program;
    GLint transform_location;
    GLuint vbo;
    GLuint vao;
    GLFWwindow* window;
    double time;

    glfwInit();
    window = glfwCreateWindow(WIDTH, HEIGHT, __FILE__, NULL, NULL);
    glfwMakeContextCurrent(window);
    glewExperimental = GL_TRUE;
    glewInit();
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glViewport(0, 0, WIDTH, HEIGHT);

    shader_program = common_get_shader_program(vertex_shader_source, fragment_shader_source);

    glGenVertexArrays(1, &vao);
    glGenBuffers(1, &vbo);
    glBindVertexArray(vao);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    /* Position attribute */
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    /* Color attribute */
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(1);
    glBindVertexArray(0);

    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();
        glClear(GL_COLOR_BUFFER_BIT);

        glUseProgram(shader_program);
        transform_location = glGetUniformLocation(shader_program, "transform");
        /* THIS is just a dummy transform. */
        GLfloat transform[] = {
            0.0f, 0.0f, 0.0f, 0.0f,
            0.0f, 0.0f, 0.0f, 0.0f,
            0.0f, 0.0f, 1.0f, 0.0f,
            0.0f, 0.0f, 0.0f, 1.0f,
        };
        time = glfwGetTime();
        transform[0] = 2.0f * sin(time);
        transform[5] = 2.0f * cos(time);
        glUniformMatrix4fv(transform_location, 1, GL_FALSE, transform);

        glBindVertexArray(vao);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        glBindVertexArray(0);
        glfwSwapBuffers(window);
    }
    glDeleteVertexArrays(1, &vao);
    glDeleteBuffers(1, &vbo);
    glfwTerminate();
    return EXIT_SUCCESS;
}

GitHub upstream.

Compile and run:

gcc -ggdb3 -O0 -o glfw_transform.out -std=c99 -Wall -Wextra -pedantic glfw_transform.c -lGL -lGLU -lglut -lGLEW -lglfw -lm
./glfw_transform.out

Output:

enter image description here

The matrix for glOrtho is really simple, composed only of scaling and translation:

scalex, 0,      0,      translatex,
0,      scaley, 0,      translatey,
0,      0,      scalez, translatez,
0,      0,      0,      1

as mentioned in the OpenGL 2 docs.

The glFrustum matrix is not too hard to calculate by hand either, but starts getting annoying. Note how frustum cannot be made up with only scaling and translations like glOrtho, more info at: https://gamedev.stackexchange.com/a/118848/25171

The GLM OpenGL C++ math library is a popular choice for calculating such matrices. http://glm.g-truc.net/0.9.2/api/a00245.html documents both an ortho and frustum operations.

How to remove the underline for anchors(links)?

The css is

text-decoration: none;

and

text-decoration: underline;

CSS table column autowidth

You could specify the width of all but the last table cells and add a table-layout:fixed and a width to the table.

You could set

table tr ul.actions {margin: 0; white-space:nowrap;}

(or set this for the last TD as Sander suggested instead).

This forces the inline-LIs not to break. Unfortunately this does not lead to a new width calculation in the containing UL (and this parent TD), and therefore does not autosize the last TD.

This means: if an inline element has no given width, a TD's width is always computed automatically first (if not specified). Then its inline content with this calculated width gets rendered and the white-space-property is applied, stretching its content beyond the calculated boundaries.

So I guess it's not possible without having an element within the last TD with a specific width.

What is 'Currying'?

Currying is translating a function from callable as f(a, b, c) into callable as f(a)(b)(c).

Otherwise currying is when you break down a function that takes multiple arguments into a series of functions that take part of the arguments.

Literally, currying is a transformation of functions: from one way of calling into another. In JavaScript, we usually make a wrapper to keep the original function.

Currying doesn’t call a function. It just transforms it.

Let’s make curry function that performs currying for two-argument functions. In other words, curry(f) for two-argument f(a, b) translates it into f(a)(b)

function curry(f) { // curry(f) does the currying transform
  return function(a) {
    return function(b) {
      return f(a, b);
    };
  };
}

// usage
function sum(a, b) {
  return a + b;
}

let carriedSum = curry(sum);

alert( carriedSum(1)(2) ); // 3

As you can see, the implementation is a series of wrappers.

  • The result of curry(func) is a wrapper function(a).
  • When it is called like sum(1), the argument is saved in the Lexical Environment, and a new wrapper is returned function(b).
  • Then sum(1)(2) finally calls function(b) providing 2, and it passes the call to the original multi-argument sum.

How can I convert a series of images to a PDF from the command line on linux?

Use convert from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)

Adding elements to object

To append to an object use Object.assign

var ElementList ={}

function addElement (ElementList, element) {
    let newList = Object.assign(ElementList, element)
    return newList
}
console.log(ElementList)

Output:

{"element":{"id":10,"quantity":1},"element":{"id":11,"quantity":2}}

Jackson JSON: get node name from json-tree

JsonNode root = mapper.readTree(json);
root.at("/some-node").fields().forEachRemaining(e -> {
                              System.out.println(e.getKey()+"---"+ e.getValue());

        });

In one line Jackson 2+

Is it possible to declare two variables of different types in a for loop?

C++17: Yes! You should use a structured binding declaration. The syntax has been supported in gcc and clang since gcc-7 and clang-4.0 (clang live example). This allows us to unpack a tuple like so:

for (auto [i, f, s] = std::tuple{1, 1.0, std::string{"ab"}}; i < N; ++i, f += 1.5) {
    // ...
}

The above will give you:

  • int i set to 1
  • double f set to 1.0
  • std::string s set to "ab"

Make sure to #include <tuple> for this kind of declaration.

You can specify the exact types inside the tuple by typing them all out as I have with the std::string, if you want to name a type. For example:

auto [vec, i32] = std::tuple{std::vector<int>{3, 4, 5}, std::int32_t{12}}

A specific application of this is iterating over a map, getting the key and value,

std::unordered_map<K, V> m = { /*...*/ };
for (auto& [key, value] : m) {
   // ...
}

See a live example here


C++14: You can do the same as C++11 (below) with the addition of type-based std::get. So instead of std::get<0>(t) in the below example, you can have std::get<int>(t).


C++11: std::make_pair allows you to do this, as well as std::make_tuple for more than two objects.

for (auto p = std::make_pair(5, std::string("Hello World")); p.first < 10; ++p.first) {
    std::cout << p.second << std::endl;
}

std::make_pair will return the two arguments in a std::pair. The elements can be accessed with .first and .second.

For more than two objects, you'll need to use a std::tuple

for (auto t = std::make_tuple(0, std::string("Hello world"), std::vector<int>{});
        std::get<0>(t) < 10;
        ++std::get<0>(t)) {
    std::cout << std::get<1>(t) << std::endl; // cout Hello world
    std::get<2>(t).push_back(std::get<0>(t)); // add counter value to the vector
}

std::make_tuple is a variadic template that will construct a tuple of any number of arguments (with some technical limitations of course). The elements can be accessed by index with std::get<INDEX>(tuple_object)

Within the for loop bodies you can easily alias the objects, though you still need to use .first or std::get for the for loop condition and update expression

for (auto t = std::make_tuple(0, std::string("Hello world"), std::vector<int>{});
        std::get<0>(t) < 10;
        ++std::get<0>(t)) {
    auto& i = std::get<0>(t);
    auto& s = std::get<1>(t);
    auto& v = std::get<2>(t);
    std::cout << s << std::endl; // cout Hello world
    v.push_back(i); // add counter value to the vector
}

C++98 and C++03 You can explicitly name the types of a std::pair. There is no standard way to generalize this to more than two types though:

for (std::pair<int, std::string> p(5, "Hello World"); p.first < 10; ++p.first) {
    std::cout << p.second << std::endl;
}

Postgresql SQL: How check boolean field with null and True,False Value?

There are 3 states for boolean in PG: true, false and unknown (null). Explained here: Postgres boolean datatype

Therefore you need only query for NOT TRUE:

SELECT * from table_name WHERE boolean_column IS NOT TRUE;

What is an 'undeclared identifier' error and how do I fix it?

It is like Using the function without declaring it. header file will contain the function printf(). Include the header file in your program this is the solution for that. Some user defined functions may also through error when not declared before using it. If it is used globally no probs.

How do I get the path of the current executed file in Python?

You have simply called:

path = os.path.abspath(os.path.dirname(sys.argv[0]))

instead of:

path = os.path.dirname(os.path.abspath(sys.argv[0]))

abspath() gives you the absolute path of sys.argv[0] (the filename your code is in) and dirname() returns the directory path without the filename.

Set environment variables from file of key/value pairs

I found the most efficient way is:

export $(xargs < .env)

Explanation

When we have a .env file like this:

key=val
foo=bar

run xargs < .env will get key=val foo=bar

so we will get an export key=val foo=bar and it's exactly what we need!

Limitation

  1. It doesn't handle cases where the values have spaces in them. Commands such as env produce this format. – @Shardj

Programmatically change the src of an img tag

You can use both jquery and javascript method: if you have two images for example:

<img class="image1" src="image1.jpg" alt="image">
<img class="image2" src="image2.jpg" alt="image">

1)Jquery Method->

$(".image2").attr("src","image1.jpg");

2)Javascript Method->

var image = document.getElementsByClassName("image2");
image.src = "image1.jpg"

For this type of issue jquery is the simple one to use.

How to Apply Gradient to background view of iOS Swift App

Try This , It's working for me,

  var gradientView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 35))
  let gradientLayer:CAGradientLayer = CAGradientLayer()
  gradientLayer.frame.size = self.gradientView.frame.size
  gradientLayer.colors = 
  [UIColor.white.cgColor,UIColor.red.withAlphaComponent(1).cgColor] 
  //Use diffrent colors
  gradientView.layer.addSublayer(gradientLayer)

enter image description here

You can add starting and end point of gradient color.

    gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.0)
    gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)

enter image description here

For more detail description refer Best Answer or you can follow CAGradientLayer From Apple

Hopes This is help for some one.

String to byte array in php

In PHP, strings are bytestreams. What exactly are you trying to do?

Re: edit

Ps. Why do I need this at all!? Well I need to send via fputs() bytearray to server written in java...

fputs takes a string as argument. Most likely, you just need to pass your string to it. On the Java side of things, you should decode the data in whatever encoding, you're using in php (the default is iso-8859-1).

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:

1 - Enable TCP/IP

We can enable TCP/IP protocol with WMI:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocol " _
    & "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")

if tcpProtocols.Count = 1 then
    ' set tcpProtocol = tcpProtocols(0)
    ' I wish this worked, but unfortunately 
    ' there's no int-indexed Item property in this type

    ' Doing this instead
    for each tcpProtocol in tcpProtocols
        dim setEnableResult
            setEnableResult = tcpProtocol.SetEnable()
            if setEnableResult <> 0 then 
                Wscript.Echo "Failed!"
            end if
    next
end if

2 - Open the right ports in the firewall

I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)

3 - Modify TCP/IP properties enable a IP address

We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocolProperty " _
    & "where InstanceName='SQLEXPRESS' and " _
    & "ProtocolName='Tcp' and IPAddressName='IPAll'")

for each tcpProperty in tcpProperties
    dim setValueResult, requestedValue

    if tcpProperty.PropertyName = "TcpPort" then
        requestedValue = "3456"
    elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
        requestedValue = ""
    end if

    setValueResult = tcpProperty.SetStringValue(requestedValue)
    if setValueResult = 0 then 
        Wscript.Echo "" & tcpProperty.PropertyName & " set."
    else
        Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
    end if
next

Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.

Just a reminder that when working with WMI, WBEMTest.exe is your best friend!

4 - Enable mixed mode authentication in sql server

I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:

  1. Use LoginMode property of Microsoft.SqlServer.Management.Smo.Server class, as described here.

  2. Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS, so for my SQL Server 2008 R2 Express instance the right registry key was HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer.

5 - Change user (sa) default password

You got this one covered.

6 - Finally (connect to the instance)

Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.

SQLCMD -U sa -P newPassword -S 192.168.0.120,3456

Please let me know if this works for you (fingers crossed!).

How to edit one specific row in Microsoft SQL Server Management Studio 2008?

Use the "Edit top 200" option, then click on "Show SQL panel", modify your query with your WHERE clause, and execute the query. You'll be able to edit the results.

How to avoid "StaleElementReferenceException" in Selenium?

Kenny's solution is deprecated use this, i'm using actions class to double click but you can do anything.

new FluentWait<>(driver).withTimeout(30, TimeUnit.SECONDS).pollingEvery(5, TimeUnit.SECONDS)
                    .ignoring(StaleElementReferenceException.class)
                    .until(new Function() {

                    @Override
                    public Object apply(Object arg0) {
                        WebElement e = driver.findelement(By.xpath(locatorKey));
                        Actions action = new Actions(driver);
                        action.moveToElement(e).doubleClick().perform();
                        return true;
                    }
                });

Convert.ToDateTime: how to set format

You can use Convert.ToDateTime is it is shown at How to convert a Datetime string to a current culture datetime string

DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;

var result = Convert.ToDateTime("12/01/2011", usDtfi)

AngularJS + JQuery : How to get dynamic content working in angularjs

Another Solution in Case You Don't Have Control Over Dynamic Content

This works if you didn't load your element through a directive (ie. like in the example in the commented jsfiddles).

Wrap up Your Content

Wrap your content in a div so that you can select it if you are using JQuery. You an also opt to use native javascript to get your element.

<div class="selector">
    <grid-filter columnname="LastNameFirstName" gridname="HomeGrid"></grid-filter>
</div>

Use Angular Injector

You can use the following code to get a reference to $compile if you don't have one.

$(".selector").each(function () {
    var content = $(this);
    angular.element(document).injector().invoke(function($compile) {
        var scope = angular.element(content).scope();
        $compile(content)(scope);
    });
});

Summary

The original post seemed to assume you had a $compile reference handy. It is obviously easy when you have the reference, but I didn't so this was the answer for me.

One Caveat of the previous code

If you are using a asp.net/mvc bundle with minify scenario you will get in trouble when you deploy in release mode. The trouble comes in the form of Uncaught Error: [$injector:unpr] which is caused by the minifier messing with the angular javascript code.

Here is the way to remedy it:

Replace the prevous code snippet with the following overload.

...
angular.element(document).injector().invoke(
[
    "$compile", function($compile) {
        var scope = angular.element(content).scope();
        $compile(content)(scope);
    }
]);
...

This caused a lot of grief for me before I pieced it together.

state provider and route provider in angularJS

You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
  _x000D_
  $stateProvider_x000D_
    .state('state1', {_x000D_
      url: "/state1",_x000D_
      templateUrl: "partials/state1.html",_x000D_
      controller: 'YourCtrl'_x000D_
    })_x000D_
    _x000D_
    .state('state2', {_x000D_
      url: "/state2",_x000D_
      templateUrl: "partials/state2.html",_x000D_
      controller: 'YourOtherCtrl'_x000D_
    });_x000D_
    $urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_

You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

Foreach value from POST from form

First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters

In addition, you don't have to use variable variable names (that sounds odd), instead:

foreach($_POST as $key => $value) {
  echo "POST parameter '$key' has '$value'";
}

To ensure that you have only parameters beginning with 'item_name' you can check it like so:

$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
  // do something
}

Automatically open default email client and pre-populate content

JQuery:

$(function () {
      $('.SendEmail').click(function (event) {
        var email = '[email protected]';
        var subject = 'Test';
        var emailBody = 'Hi Sample,';
        var attach = 'path';
        document.location = "mailto:"+email+"?subject="+subject+"&body="+emailBody+
            "?attach="+attach;
      });
    });

HTML:

 <button class="SendEmail">Send Email</button>

Display current time in 12 hour format with AM/PM

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.S aa");
String formattedDate = dateFormat.format(new Date()).toString();
System.out.println(formattedDate);

Output: 11-Sep-13 12.25.15.375 PM

Oracle PL/SQL : remove "space characters" from a string

Shorter version of:

REGEXP_REPLACE( my_value, '[[:space:]]', '' )

Would be:

REGEXP_REPLACE( my_value, '\s')

Neither of the above statements will remove "null" characters.

To remove "nulls" encase the statement with a replace

Like so:

REPLACE(REGEXP_REPLACE( my_value, '\s'), CHR(0))

Node.js: get path from the request

var http = require('http');
var url  = require('url');
var fs   = require('fs');

var neededstats = [];

http.createServer(function(req, res) {
    if (req.url == '/index.html' || req.url == '/') {
        fs.readFile('./index.html', function(err, data) {
            res.end(data);
        });
    } else {
        var p = __dirname + '/' + req.params.filepath;
        fs.stat(p, function(err, stats) {
            if (err) {
                throw err;
            }
            neededstats.push(stats.mtime);
            neededstats.push(stats.size);
            res.send(neededstats);
        });
    }
}).listen(8080, '0.0.0.0');
console.log('Server running.');

I have not tested your code but other things works

If you want to get the path info from request url

 var url_parts = url.parse(req.url);
 console.log(url_parts);
 console.log(url_parts.pathname);

1.If you are getting the URL parameters still not able to read the file just correct your file path in my example. If you place index.html in same directory as server code it would work...

2.if you have big folder structure that you want to host using node then I would advise you to use some framework like expressjs

If you want raw solution to file path

var http = require("http");
var url = require("url");

function start() {
function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}

http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}

exports.start = start;

source : http://www.nodebeginner.org/

Counting the number of non-NaN elements in a numpy ndarray in Python

np.count_nonzero(~np.isnan(data))

~ inverts the boolean matrix returned from np.isnan.

np.count_nonzero counts values that is not 0\false. .sum should give the same result. But maybe more clearly to use count_nonzero

Testing speed:

In [23]: data = np.random.random((10000,10000))

In [24]: data[[np.random.random_integers(0,10000, 100)],:][:, [np.random.random_integers(0,99, 100)]] = np.nan

In [25]: %timeit data.size - np.count_nonzero(np.isnan(data))
1 loops, best of 3: 309 ms per loop

In [26]: %timeit np.count_nonzero(~np.isnan(data))
1 loops, best of 3: 345 ms per loop

In [27]: %timeit data.size - np.isnan(data).sum()
1 loops, best of 3: 339 ms per loop

data.size - np.count_nonzero(np.isnan(data)) seems to barely be the fastest here. other data might give different relative speed results.

Why dividing two integers doesn't get a float?

Dividing two integers will result in an integer (whole number) result.

You need to cast one number as a float, or add a decimal to one of the numbers, like a/350.0.

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

Here's a summary of Dimitris Andreou's link.

Remember sum of i-th powers, where i=1,2,..,k. This reduces the problem to solving the system of equations

a1 + a2 + ... + ak = b1

a12 + a22 + ... + ak2 = b2

...

a1k + a2k + ... + akk = bk

Using Newton's identities, knowing bi allows to compute

c1 = a1 + a2 + ... ak

c2 = a1a2 + a1a3 + ... + ak-1ak

...

ck = a1a2 ... ak

If you expand the polynomial (x-a1)...(x-ak) the coefficients will be exactly c1, ..., ck - see Viète's formulas. Since every polynomial factors uniquely (ring of polynomials is an Euclidean domain), this means ai are uniquely determined, up to permutation.

This ends a proof that remembering powers is enough to recover the numbers. For constant k, this is a good approach.

However, when k is varying, the direct approach of computing c1,...,ck is prohibitely expensive, since e.g. ck is the product of all missing numbers, magnitude n!/(n-k)!. To overcome this, perform computations in Zq field, where q is a prime such that n <= q < 2n - it exists by Bertrand's postulate. The proof doesn't need to be changed, since the formulas still hold, and factorization of polynomials is still unique. You also need an algorithm for factorization over finite fields, for example the one by Berlekamp or Cantor-Zassenhaus.

High level pseudocode for constant k:

  • Compute i-th powers of given numbers
  • Subtract to get sums of i-th powers of unknown numbers. Call the sums bi.
  • Use Newton's identities to compute coefficients from bi; call them ci. Basically, c1 = b1; c2 = (c1b1 - b2)/2; see Wikipedia for exact formulas
  • Factor the polynomial xk-c1xk-1 + ... + ck.
  • The roots of the polynomial are the needed numbers a1, ..., ak.

For varying k, find a prime n <= q < 2n using e.g. Miller-Rabin, and perform the steps with all numbers reduced modulo q.

EDIT: The previous version of this answer stated that instead of Zq, where q is prime, it is possible to use a finite field of characteristic 2 (q=2^(log n)). This is not the case, since Newton's formulas require division by numbers up to k.

How to add directory to classpath in an application run profile in IntelliJ IDEA?

You can try -Xbootclasspath/a:path option of java application launcher. By description it specifies "a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path."

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

I found that the selected answer works for the browser apps but I was having issues with the code working in non browser apps that implement a UIWebView.

The problem for me was a user on the Twitter app would click a link that would take them to my site through a UIWebView in the Twitter app. Then when they clicked a button from my site Twitter tries to be fancy and only complete the window.location if the site is reachable. So what happens is a UIAlertView pops up saying are you sure you want to continue and then immediately redirects to the App Store without a second popup.

My solution involves iframes. This avoids the UIAlertView being presented allowing for a simple and elegant user experience.

jQuery

var redirect = function (location) {
    $('body').append($('<iframe></iframe>').attr('src', location).css({
        width: 1,
        height: 1,
        position: 'absolute',
        top: 0,
        left: 0
    }));
};

setTimeout(function () {
    redirect('http://itunes.apple.com/app/id');
}, 25);

redirect('custom-uri://');

Javascript

var redirect = function (location) {
    var iframe = document.createElement('iframe');
    iframe.setAttribute('src', location);
    iframe.setAttribute('width', '1px');
    iframe.setAttribute('height', '1px');
    iframe.setAttribute('position', 'absolute');
    iframe.setAttribute('top', '0');
    iframe.setAttribute('left', '0');
    document.documentElement.appendChild(iframe);
    iframe.parentNode.removeChild(iframe);
    iframe = null;
};

setTimeout(function () {
    redirect('http://itunes.apple.com/app/id');
}, 25);

redirect('custom-uri://');

EDIT:

Add position absolute to the iframe so when inserted there isn't a random bit of whitespace at the bottom of the page.

Also it's important to note that I have not found a need for this approach with Android. Using window.location.href should work fine.

Access XAMPP Localhost from Internet

you have to open a port of the service in you router then try you puplic ip out of your all network cause if you try it from your network , the puplic ip will always redirect you to your router but from the outside it will redirect to the server you have

What's the difference between size_t and int in C++?

It's because size_t can be anything other than an int (maybe a struct). The idea is that it decouples it's job from the underlying type.

Extract substring from a string

you can use this code

    public static String getSubString(String mainString, String lastString, String startString) {
    String endString = "";
    int endIndex = mainString.indexOf(lastString);
    int startIndex = mainString.indexOf(startString);
    Log.d("message", "" + mainString.substring(startIndex, endIndex));
    endString = mainString.substring(startIndex, endIndex);
    return endString;
}

in this mainString is a Super string.like "I_AmANDROID.Devloper" and lastString is a string like"." and startString is like"_". so this function returns "AmANDROID". enjoy your code time.:)

Tensorflow: Using Adam optimizer

The AdamOptimizer class creates additional variables, called "slots", to hold values for the "m" and "v" accumulators.

See the source here if you're curious, it's actually quite readable: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/adam.py#L39 . Other optimizers, such as Momentum and Adagrad use slots too.

These variables must be initialized before you can train a model.

The normal way to initialize variables is to call tf.initialize_all_variables() which adds ops to initialize the variables present in the graph when it is called.

(Aside: unlike its name suggests, initialize_all_variables() does not initialize anything, it only add ops that will initialize the variables when run.)

What you must do is call initialize_all_variables() after you have added the optimizer:

...build your model...
# Add the optimizer
train_op = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
# Add the ops to initialize variables.  These will include 
# the optimizer slots added by AdamOptimizer().
init_op = tf.initialize_all_variables()

# launch the graph in a session
sess = tf.Session()
# Actually intialize the variables
sess.run(init_op)
# now train your model
for ...:
  sess.run(train_op)

Nodejs convert string into UTF-8

I had the same problem, when i loaded a text file via fs.readFile(), I tried to set the encodeing to UTF8, it keeped the same. my solution now is this:

myString = JSON.parse( JSON.stringify( myString ) )

after this an Ö is realy interpreted as an Ö.

How to open warning/information/error dialog in Swing?

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class ErrorDialog {

  public static void main(String argv[]) {
    String message = "\"The Comedy of Errors\"\n"
        + "is considered by many scholars to be\n"
        + "the first play Shakespeare wrote";
    JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",
        JOptionPane.ERROR_MESSAGE);
  }
}

Header and footer in CodeIgniter

Here's what I do:

<?php

/**
 * /application/core/MY_Loader.php
 *
 */
class MY_Loader extends CI_Loader {
    public function template($template_name, $vars = array(), $return = FALSE)
    {
        $content  = $this->view('templates/header', $vars, $return);
        $content .= $this->view($template_name, $vars, $return);
        $content .= $this->view('templates/footer', $vars, $return);

        if ($return)
        {
            return $content;
        }
    }
}

For CI 3.x:

class MY_Loader extends CI_Loader {
    public function template($template_name, $vars = array(), $return = FALSE)
    {
        if($return):
        $content  = $this->view('templates/header', $vars, $return);
        $content .= $this->view($template_name, $vars, $return);
        $content .= $this->view('templates/footer', $vars, $return);

        return $content;
    else:
        $this->view('templates/header', $vars);
        $this->view($template_name, $vars);
        $this->view('templates/footer', $vars);
    endif;
    }
}

Then, in your controller, this is all you have to do:

<?php
$this->load->template('body');

Adding headers when using httpClient.GetAsync

A later answer, but because no one gave this solution...

If you do not want to set the header on the HttpClient instance by adding it to the DefaultRequestHeaders, you could set headers per request.

But you will be obliged to use the SendAsync() method.

This is the right solution if you want to reuse the HttpClient -- which is a good practice for

Use it like this:

using (var requestMessage =
            new HttpRequestMessage(HttpMethod.Get, "https://your.site.com"))
{
    requestMessage.Headers.Authorization =
        new AuthenticationHeaderValue("Bearer", your_token);
    httpClient.SendAsync(requestMessage);
}

javascript create empty array of a given size

As of ES5 (when this answer was given):

If you want an empty array of undefined elements, you could simply do

var whatever = new Array(5);

this would give you

[undefined, undefined, undefined, undefined, undefined]

and then if you wanted it to be filled with empty strings, you could do

whatever.fill('');

which would give you

["", "", "", "", ""]

And if you want to do it in one line:

var whatever = Array(5).fill('');

Can't push to the heroku

You need to follow the instructions displayed here, on your case follow scala configuration:

https://devcenter.heroku.com/articles/getting-started-with-scala#introduction

After setting up the getting started pack, tweak around the default config and apply to your local repository. It should work, just like mine using NodeJS.

HTH! :)

Is it possible to do a sparse checkout without checking out the whole repository first?

In 2020 there is a simpler way to deal with sparse-checkout without having to worry about .git files. Here is how I did it:

git clone <URL> --no-checkout <directory>
cd <directory>
git sparse-checkout init --cone # to fetch only root files
git sparse-checkout set apps/my_app libs/my_lib # etc, to list sub-folders to checkout
# they are checked out immediately after this command, no need to run git pull

Note that it requires git version 2.25 installed. Read more about it here: https://github.blog/2020-01-17-bring-your-monorepo-down-to-size-with-sparse-checkout/

UPDATE:

The above git clone command will still clone the repo with its full history, though without checking the files out. If you don't need the full history, you can add --depth parameter to the command, like this:

# create a shallow clone,
# with only 1 (since depth equals 1) latest commit in history
git clone <URL> --no-checkout <directory> --depth 1

Quickest way to find missing number in an array of numbers

This is not a search problem. The employer is wondering if you have a grasp of a checksum. You might need a binary or for loop or whatever if you were looking for multiple unique integers, but the question stipulates "one random empty slot." In this case we can use the stream sum. The condition: "The numbers are randomly added to the array" is meaningless without more detail. The question does not assume the array must start with the integer 1 and so tolerate with the offset start integer.

int[] test = {2,3,4,5,6,7,8,9,10,  12,13,14 };

/*get the missing integer*/

int max = test[test.length - 1];
int min = test[0];
int sum = Arrays.stream(test).sum();
int actual = (((max*(max+1))/2)-min+1);
//Find:

//the missing value
System.out.println(actual - sum);
//the slot
System.out.println(actual - sum - min);

Success time: 0.18 memory: 320576 signal:0

Reading file using relative path in python project

Relative paths are relative to current working directory. If you do not your want your path to be, it must be absolute.

But there is an often used trick to build an absolute path from current script: use its __file__ special attribute:

from pathlib import Path

path = Path(__file__).parent / "../data/test.csv"
with path.open() as f:
    test = list(csv.reader(f))

This requires python 3.4+ (for the pathlib module).

If you still need to support older versions, you can get the same result with:

import csv
import os.path

my_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(my_path, "../data/test.csv")
with open(path) as f:
    test = list(csv.reader(f))

[2020 edit: python3.4+ should now be the norm, so I moved the pathlib version inspired by jpyams' comment first]

How to use callback with useState hook in react

Another way to achieve this:

_x000D_
_x000D_
const [Name, setName] = useState({val:"", callback: null});_x000D_
React.useEffect(()=>{_x000D_
  console.log(Name)_x000D_
  const {callback} = Name;_x000D_
  callback && callback();_x000D_
}, [Name]);_x000D_
setName({val:'foo', callback: ()=>setName({val: 'then bar'})})
_x000D_
_x000D_
_x000D_

docker container ssl certificates

You can use relative path to mount the volume to container:

docker run -v `pwd`/certs:/container/path/to/certs ...

Note the back tick on the pwd which give you the present working directory. It assumes you have the certs folder in current directory that the docker run is executed. Kinda great for local development and keep the certs folder visible to your project.

ViewPager and fragments — what's the right way to store fragment's state?

I came up with this simple and elegant solution. It assumes that the activity is responsible for creating the Fragments, and the Adapter just serves them.

This is the adapter's code (nothing weird here, except for the fact that mFragments is a list of fragments maintained by the Activity)

class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {

    public MyFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        TabFragment fragment = (TabFragment)mFragments.get(position);
        return fragment.getTitle();
    }
} 

The whole problem of this thread is getting a reference of the "old" fragments, so I use this code in the Activity's onCreate.

    if (savedInstanceState!=null) {
        if (getSupportFragmentManager().getFragments()!=null) {
            for (Fragment fragment : getSupportFragmentManager().getFragments()) {
                mFragments.add(fragment);
            }
        }
    }

Of course you can further fine tune this code if needed, for example making sure the fragments are instances of a particular class.

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

How to include js and CSS in JSP with spring MVC

You should put the folder containing css and js files into "webapp/resources". If you've put them in "src/main/java", you must change it. It worked for me.

Differences between "BEGIN RSA PRIVATE KEY" and "BEGIN PRIVATE KEY"

See https://polarssl.org/kb/cryptography/asn1-key-structures-in-der-and-pem (search the page for "BEGIN RSA PRIVATE KEY") (archive link for posterity, just in case).

BEGIN RSA PRIVATE KEY is PKCS#1 and is just an RSA key. It is essentially just the key object from PKCS#8, but without the version or algorithm identifier in front. BEGIN PRIVATE KEY is PKCS#8 and indicates that the key type is included in the key data itself. From the link:

The unencrypted PKCS#8 encoded data starts and ends with the tags:

-----BEGIN PRIVATE KEY-----
BASE64 ENCODED DATA
-----END PRIVATE KEY-----

Within the base64 encoded data the following DER structure is present:

PrivateKeyInfo ::= SEQUENCE {
  version         Version,
  algorithm       AlgorithmIdentifier,
  PrivateKey      BIT STRING
}

AlgorithmIdentifier ::= SEQUENCE {
  algorithm       OBJECT IDENTIFIER,
  parameters      ANY DEFINED BY algorithm OPTIONAL
}

So for an RSA private key, the OID is 1.2.840.113549.1.1.1 and there is a RSAPrivateKey as the PrivateKey key data bitstring.

As opposed to BEGIN RSA PRIVATE KEY, which always specifies an RSA key and therefore doesn't include a key type OID. BEGIN RSA PRIVATE KEY is PKCS#1:

RSA Private Key file (PKCS#1)

The RSA private key PEM file is specific for RSA keys.

It starts and ends with the tags:

-----BEGIN RSA PRIVATE KEY-----
BASE64 ENCODED DATA
-----END RSA PRIVATE KEY-----

Within the base64 encoded data the following DER structure is present:

RSAPrivateKey ::= SEQUENCE {
  version           Version,
  modulus           INTEGER,  -- n
  publicExponent    INTEGER,  -- e
  privateExponent   INTEGER,  -- d
  prime1            INTEGER,  -- p
  prime2            INTEGER,  -- q
  exponent1         INTEGER,  -- d mod (p-1)
  exponent2         INTEGER,  -- d mod (q-1)
  coefficient       INTEGER,  -- (inverse of q) mod p
  otherPrimeInfos   OtherPrimeInfos OPTIONAL
}

Creating and writing lines to a file

' Create The Object
Set FSO = CreateObject("Scripting.FileSystemObject")

' How To Write To A File
Set File = FSO.CreateTextFile("C:\foo\bar.txt",True)
File.Write "Example String"
File.Close

' How To Read From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Do Until File.AtEndOfStream
    Line = File.ReadLine
    WScript.Echo(Line)
Loop
File.Close

' Another Method For Reading From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Set Text = File.ReadAll
WScript.Echo(Text)
File.Close

Updating user data - ASP.NET Identity

OK... I spent hours trying to figure why userManager.updateAsync would not persist the user data that we edit ... until I reached the following conclusion:

The confusion arises from the fact that we create the UserManager in one line like this:

var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new MyDbContext()));

...then we use manager.UpdateAsync( user ); but that will update the user in the context, and then we will need to save changes to the dbcontext of the Identity. So, the question is how to get the Identity DBcontext in the easiest way.

To solve this, we should not create the UserManager in one line ... and here is how I do it:

var store = new UserStore<ApplicationUser>(new MyDbContext());
var manager = new UserManager(store);

then after updating the user by calling

manager.UpdateAsync(user);

then you go to the context

var ctx = store.context;

then

ctx.saveChanges();

wahooooooo...persisted :)

Hope this will help someone who pulled their hair for a few hours :P

Check empty string in Swift?

I can recommend add small extension to String or Array that looks like

extension Collection {
    public var isNotEmpty: Bool {
        return !self.isEmpty
    }
}

With it you can write code that is easier to read. Compare this two lines

if !someObject.someParam.someSubParam.someString.isEmpty {}

and

if someObject.someParam.someSubParam.someString.isNotEmpty {}

It is easy to miss ! sign in the beginning of fist line.

No newline at end of file

The reason this convention came into practice is because on UNIX-like operating systems a newline character is treated as a line terminator and/or message boundary (this includes piping between processes, line buffering, etc.).

Consider, for example, that a file with just a newline character is treated as a single, empty line. Conversely, a file with a length of zero bytes is actually an empty file with zero lines. This can be confirmed according to the wc -l command.

Altogether, this behavior is reasonable because there would be no other way to distinguish between an empty text file versus a text file with a single empty line if the \n character was merely a line-separator rather than a line-terminator. Thus, valid text files should always end with a newline character. The only exception is if the text file is intended to be empty (no lines).

How can I detect the encoding/codepage of a text file

Looking for different solution, I found that

https://code.google.com/p/ude/

this solution is kinda heavy.

I needed some basic encoding detection, based on 4 first bytes and probably xml charset detection - so I've took some sample source code from internet and added slightly modified version of

http://lists.w3.org/Archives/Public/www-validator/2002Aug/0084.html

written for Java.

    public static Encoding DetectEncoding(byte[] fileContent)
    {
        if (fileContent == null)
            throw new ArgumentNullException();

        if (fileContent.Length < 2)
            return Encoding.ASCII;      // Default fallback

        if (fileContent[0] == 0xff
            && fileContent[1] == 0xfe
            && (fileContent.Length < 4
                || fileContent[2] != 0
                || fileContent[3] != 0
                )
            )
            return Encoding.Unicode;

        if (fileContent[0] == 0xfe
            && fileContent[1] == 0xff
            )
            return Encoding.BigEndianUnicode;

        if (fileContent.Length < 3)
            return null;

        if (fileContent[0] == 0xef && fileContent[1] == 0xbb && fileContent[2] == 0xbf)
            return Encoding.UTF8;

        if (fileContent[0] == 0x2b && fileContent[1] == 0x2f && fileContent[2] == 0x76)
            return Encoding.UTF7;

        if (fileContent.Length < 4)
            return null;

        if (fileContent[0] == 0xff && fileContent[1] == 0xfe && fileContent[2] == 0 && fileContent[3] == 0)
            return Encoding.UTF32;

        if (fileContent[0] == 0 && fileContent[1] == 0 && fileContent[2] == 0xfe && fileContent[3] == 0xff)
            return Encoding.GetEncoding(12001);

        String probe;
        int len = fileContent.Length;

        if( fileContent.Length >= 128 ) len = 128;
        probe = Encoding.ASCII.GetString(fileContent, 0, len);

        MatchCollection mc = Regex.Matches(probe, "^<\\?xml[^<>]*encoding[ \\t\\n\\r]?=[\\t\\n\\r]?['\"]([A-Za-z]([A-Za-z0-9._]|-)*)", RegexOptions.Singleline);
        // Add '[0].Groups[1].Value' to the end to test regex

        if( mc.Count == 1 && mc[0].Groups.Count >= 2 )
        {
            // Typically picks up 'UTF-8' string
            Encoding enc = null;

            try {
                enc = Encoding.GetEncoding( mc[0].Groups[1].Value );
            }catch (Exception ) { }

            if( enc != null )
                return enc;
        }

        return Encoding.ASCII;      // Default fallback
    }

It's enough to read probably first 1024 bytes from file, but I'm loading whole file.