Programs & Examples On #Termios

Reading and writing to serial port in C on Linux

Some receivers expect EOL sequence, which is typically two characters \r\n, so try in your code replace the line

unsigned char cmd[] = {'I', 'N', 'I', 'T', ' ', '\r', '\0'};

with

unsigned char cmd[] = "INIT\r\n";

BTW, the above way is probably more efficient. There is no need to quote every character.

How can I set a custom baud rate on Linux?

There is an serial I/O chip on your motherboard's CPU (16650 UART). This chip uses 8-bit port as control and data bus, and thus you can issue a command to it through writing to this chip through the control and data bus.

Usually, an application did the following steps on the serial port

  1. Set baud rate, parity, encoding, flow control, and starting / ending sequence length during program start. This setup can be done via ioctl to the serial device or 'stty' command. In fact, the stty command uses ioctl to that serial device.
  2. Write characters of data to the serial device and the driver will be writing data charaters to the UART chip through its 8-bit data bus.

In short, you can specify the baud rate only in the STTY command, and then all other options would be kept as default, and it should enough to connect to ohter devices.

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

I'm doing something like the following code. It works for USB-devices and also the stupid serial8250-devuices that we all have 30 of - but only a couple of them realy works.

Basically I use concept from previous answers. First enumerate all tty-devices in /sys/class/tty/. Devices that does not contain a /device subdir is filtered away. /sys/class/tty/console is such a device. Then the devices actually containing a devices in then accepted as valid serial-port depending on the target of the driver-symlink fx.

$ ls -al /sys/class/tty/ttyUSB0//device/driver
lrwxrwxrwx 1 root root 0 sep  6 21:28 /sys/class/tty/ttyUSB0//device/driver -> ../../../bus/platform/drivers/usbserial

and for ttyS0

$ ls -al /sys/class/tty/ttyS0//device/driver
lrwxrwxrwx 1 root root 0 sep  6 21:28 /sys/class/tty/ttyS0//device/driver -> ../../../bus/platform/drivers/serial8250

All drivers driven by serial8250 must be probes using the previously mentioned ioctl.

        if (ioctl(fd, TIOCGSERIAL, &serinfo)==0) {
            // If device type is no PORT_UNKNOWN we accept the port
            if (serinfo.type != PORT_UNKNOWN)
                the_port_is_valid

Only port reporting a valid device-type is valid.

The complete source for enumerating the serialports looks like this. Additions are welcome.

#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <linux/serial.h>

#include <iostream>
#include <list>

using namespace std;

static string get_driver(const string& tty) {
    struct stat st;
    string devicedir = tty;

    // Append '/device' to the tty-path
    devicedir += "/device";

    // Stat the devicedir and handle it if it is a symlink
    if (lstat(devicedir.c_str(), &st)==0 && S_ISLNK(st.st_mode)) {
        char buffer[1024];
        memset(buffer, 0, sizeof(buffer));

        // Append '/driver' and return basename of the target
        devicedir += "/driver";

        if (readlink(devicedir.c_str(), buffer, sizeof(buffer)) > 0)
            return basename(buffer);
    }
    return "";
}

static void register_comport( list<string>& comList, list<string>& comList8250, const string& dir) {
    // Get the driver the device is using
    string driver = get_driver(dir);

    // Skip devices without a driver
    if (driver.size() > 0) {
        string devfile = string("/dev/") + basename(dir.c_str());

        // Put serial8250-devices in a seperate list
        if (driver == "serial8250") {
            comList8250.push_back(devfile);
        } else
            comList.push_back(devfile); 
    }
}

static void probe_serial8250_comports(list<string>& comList, list<string> comList8250) {
    struct serial_struct serinfo;
    list<string>::iterator it = comList8250.begin();

    // Iterate over all serial8250-devices
    while (it != comList8250.end()) {

        // Try to open the device
        int fd = open((*it).c_str(), O_RDWR | O_NONBLOCK | O_NOCTTY);

        if (fd >= 0) {
            // Get serial_info
            if (ioctl(fd, TIOCGSERIAL, &serinfo)==0) {
                // If device type is no PORT_UNKNOWN we accept the port
                if (serinfo.type != PORT_UNKNOWN)
                    comList.push_back(*it);
            }
            close(fd);
        }
        it ++;
    }
}

list<string> getComList() {
    int n;
    struct dirent **namelist;
    list<string> comList;
    list<string> comList8250;
    const char* sysdir = "/sys/class/tty/";

    // Scan through /sys/class/tty - it contains all tty-devices in the system
    n = scandir(sysdir, &namelist, NULL, NULL);
    if (n < 0)
        perror("scandir");
    else {
        while (n--) {
            if (strcmp(namelist[n]->d_name,"..") && strcmp(namelist[n]->d_name,".")) {

                // Construct full absolute file path
                string devicedir = sysdir;
                devicedir += namelist[n]->d_name;

                // Register the device
                register_comport(comList, comList8250, devicedir);
            }
            free(namelist[n]);
        }
        free(namelist);
    }

    // Only non-serial8250 has been added to comList without any further testing
    // serial8250-devices must be probe to check for validity
    probe_serial8250_comports(comList, comList8250);

    // Return the lsit of detected comports
    return comList;
}


int main() {
    list<string> l = getComList();

    list<string>::iterator it = l.begin();
    while (it != l.end()) {
        cout << *it << endl;
        it++;
    }

    return 0;   
}

Import cycle not allowed

Here is an illustration of your first import cycle problem.

                  project/controllers/account
                     ^                    \    
                    /                      \
                   /                        \ 
                  /                         \/
         project/components/mux <--- project/controllers/base

As you can see with my bad ASCII chart is that you are creating an import cycle when project/components/mux imports project/controllers/account. Since Go does not support circular dependencies you get the import cycle not allowed error during compile time.

Mongoose: Get full list of users

If you'd like to send the data to a view pass the following in.

    server.get('/usersList', function(req, res) {
        User.find({}, function(err, users) {
           res.render('/usersList', {users: users});
        });
    });

Inside your view you can loop through the data using the variable users

How to check if datetime happens to be Saturday or Sunday in SQL Server 2008

This expression

SELECT (((DATEPART(DW, @my_date_var) - 1 ) + @@DATEFIRST ) % 7)

will always return a number between 0 and 6 where

0 -> Sunday
1 -> Monday
2 -> Tuesday
3 -> Wednesday
4 -> Thursday
5 -> Friday
6 -> Saturday

Independently from @@DATEFIRST

So a weekend day is tested like this

SELECT (CASE
           WHEN (((DATEPART(DW, @my_date_var) - 1 ) + @@DATEFIRST ) % 7) IN (0,6)
           THEN 1
           ELSE 0
       END) AS is_weekend_day

Force DOM redraw/refresh on Chrome/Mac

We recently encountered this and discovered that promoting the affected element to a composite layer with translateZ fixed the issue without needing extra javascript.

.willnotrender { 
   transform: translateZ(0); 
}

As these painting issues show up mostly in Webkit/Blink, and this fix mostly targets Webkit/Blink, it's preferable in some cases. Especially since many JavaScript solutions cause a reflow and repaint, not just a repaint.

Formatting code in Notepad++

Here is a list of the available shortcuts in Notepad++.

In case your desired functionality is not available, you are able to define own macros and assign them to a custom shortcut (i am not used to use macros).

UPDATE: I will post the shortcuts here in case the link gets invalid:

Shortcut    Command

Ctrl-C  Copy
Ctrl-X  Cut
Ctrl-V  Paste
Ctrl-Z  Undo
Ctrl-Y  Redo
Ctrl-A  Select All
Ctrl-F  Launch Find Dialog
Ctrl-H  Launch Find / Replace Dialog
Ctrl-D  Duplicate Current Line
Ctrl-L  Delete Current Line
Ctrl-T  Switch the current line position with the previous line position
F3  Find Next
Shft-F3 Find Previous
Ctrl-Shft-F Find in Files
Ctrl-F3 Find (volatil) Next
Ctrl-Shft-F3    Find (volatil) Previous
Ctrl-Shft-I Incremental Search
Ctrl-S  Save File
Ctrl-Alt-S  Save As
Ctrl-Shft-S Save All
Ctrl-O  Open File
Ctrl-N  New File
Ctrl-F2 Toggle Bookmark
F2  Go To Next Bookmark 
Shft-F2 Go To Previous Bookmark
Ctrl-G  Launch GoToLine Dialog
Ctrl-W  Close Current Document
Alt-Shft-Arrow keys or Alt + Left mouse click   Column Mode Select
F5  Launch Run Dialog
Ctrl-Space  Launch CallTip ListBox
Alt-Space   Launch Word Completion ListBox
Tab (selection of several lines)    Insert Tabulation or Space (Indent)
Shft-Tab (selection of several lines)   Remove Tabulation or Space (outdent)
Ctrl-(Keypad-/Keypad+) or Ctrl + mouse wheel butto  Zoom in (+ or up) and Zoom out (- or down)
Ctrl-Keypad/    Restore the original size from zoom 
F11 Toggle Full Screen Mode
Ctrl-Tab    Next Document
Ctrl-Shft-Tab   Previous Document
Ctrl-Shft-Up    Move Current Line Up
Ctrl-Shft-Down  Move Current Line Down
Ctrl-Alt-F  Collapse the Current Level
Ctrl-Alt-Shft-F Uncollapse the Current Level
Alt-0   Fold All
Alt-(1~8)   Collapse the Level (1~8)
Alt-Shft-0  Unfold All
Alt-Shft-(1~8)  Uncollapse the Level (1~8)
Ctrl-BackSpace  Delete to start of word
Ctrl-Delete Delete to end of word
Ctrl-Shft-BackSpace Delete to start of line
Ctrl-Shft-Delete    Delete to end of line
Ctrl-U  Convert to lower case
Ctrl-Shft-U Convert to UPPER CASE
Ctrl-B  Go to matching brace
Ctrl-Shft-R Start to record /Stop recording the macro
Ctrl-Shft-P Play recorded macro
Ctrl-Q  Block comment/uncomment
Ctrl-Shft-Q Stream comment
Ctrl-Shft-T Copy current line to clipboard
Ctrl-P  Print
Alt-F4  Exit
Ctrl-I  Split Lines
Ctrl-J  Join Lines
Ctrl-Alt-R  Text Direction RTL
Ctrl-Alt-L  Text Direction LT
F1  About

How do I get the project basepath in CodeIgniter

Obviously you mean the baseurl. If so:

base url: URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash.

Root in codeigniter specifically means that the position where you can append your controller to your url.

For example, if the root is localhost/ci_installation/index.php/, then to access the mycont controller you should go to localhost/ci_installation/index.php/mycont.

So, instead of writing such a long link you can (after loading "url" helper) , replace the term localhost/ci_installation/index.php/ by base_url() and this function will return the same string url.

NOTE: if you hadn't appended index.php/ to your base_url in your config.php, then if you use base_url(), it will return something like that localhost/ci_installation/mycont. And that will not work, because you have to access your controllers from index.php, instead of that you can place a .htaccess file to your codeigniter installation position. Cope that the below code to it:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /imguplod/index.php/$1 [L]

And it should work :)

Empty an array in Java / processing

You can simply assign null to the reference. (This will work for any type of array, not just ints)

int[] arr = new int[]{1, 2, 3, 4};
arr = null;

This will 'clear out' the array. You can also assign a new array to that reference if you like:

int[] arr = new int[]{1, 2, 3, 4};
arr = new int[]{6, 7, 8, 9};

If you are worried about memory leaks, don't be. The garbage collector will clean up any references left by the array.

Another example:

float[] arr = ;// some array that you want to clear
arr = new float[arr.length];

This will create a new float[] initialized to the default value for float.

Postgresql: password authentication failed for user "postgres"

When you install postgresql no password is set for user postgres, you have to explicitly set it on Unix by using the command:

sudo passwd postgres

It will ask your sudo password and then promt you for new postgres user password. Source

How to make Java 6, which fails SSL connection with "SSL peer shut down incorrectly", succeed like Java 7?

Remove "SSLv2ClientHello" from the enabled protocols on the client SSLSocket or HttpsURLConnection.

How can git be installed on CENTOS 5.5?

I've tried few methods from this question and they all failed on my CentOs, either because of the wrong repos or missing files.

Here is the method which works for me (when installing version 1.7.8):

    yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel
    wget http://git-core.googlecode.com/files/git-1.7.8.tar.gz
    tar -xzvf ./git-1.7.8.tar.gz
    cd ./git-1.7.8
    ./configure
    make
    make install 

You may want to download a different version from here: http://code.google.com/p/git-core/downloads/list

How to exit from ForEach-Object in PowerShell

There are differences between foreach and foreach-object.

A very good description you can find here: MS-ScriptingGuy

For testing in PS, here you have scripts to show the difference.

ForEach-Object:

# Omit 5.
1..10 | ForEach-Object {
if ($_ -eq 5) {return}
# if ($_ -ge 5) {return} # Omit from 5.
Write-Host $_
}
write-host "after1"
# Cancels whole script at 15, "after2" not printed.
11..20 | ForEach-Object {
if ($_ -eq 15) {continue}
Write-Host $_
}
write-host "after2"
# Cancels whole script at 25, "after3" not printed.
21..30 | ForEach-Object {
if ($_ -eq 25) {break}
Write-Host $_
}
write-host "after3"

foreach

# Ends foreach at 5.
foreach ($number1 in (1..10)) {
if ($number1 -eq 5) {break}
Write-Host "$number1"
}
write-host "after1"
# Omit 15. 
foreach ($number2 in (11..20)) {
if ($number2 -eq 15) {continue}
Write-Host "$number2"
}
write-host "after2"
# Cancels whole script at 25, "after3" not printed.
foreach ($number3 in (21..30)) {
if ($number3 -eq 25) {return}
Write-Host "$number3"
}
write-host "after3"

How to get DropDownList SelectedValue in Controller in MVC

Model

Very basic model with Gender field. GetGenderSelectItems() returns select items needed to populate DropDownList.

public enum Gender 
{
    Male, Female
}

public class MyModel
{
    public Gender Gender { get; set; }

    public static IEnumerable<SelectListItem> GetGenderSelectItems()
    {
        yield return new SelectListItem { Text = "Male", Value = "Male" };
        yield return new SelectListItem { Text = "Female", Value = "Female" };
    }
}

View

Please make sure you wrapped your @Html.DropDownListFor in a form tag.

@model MyModel

@using (Html.BeginForm("MyController", "MyAction", FormMethod.Post)
{
   @Html.DropDownListFor(m => m.Gender, MyModel.GetGenderSelectItems())
   <input type="submit" value="Send" />
}

Controller

Your .cshtml Razor view name should be the same as controller action name and folder name should match controller name e.g Views\MyController\MyAction.cshtml.

public class MyController : Controller 
{
    public ActionResult MyAction()
    {
        // shows your form when you load the page
        return View();
    }

    [HttpPost]
    public ActionResult MyAction(MyModel model)
    {
        // the value is received in the controller.
        var selectedGender = model.Gender;
        return View(model);
    }
}

Going further

Now let's make it strongly-typed and enum independent:

var genderSelectItems = Enum.GetValues(typeof(Gender))
    .Cast<string>()
    .Select(genderString => new SelectListItem 
    {
        Text = genderString,
        Value = genderString,
    }).AsEnumerable();

How to add spacing between UITableViewCell

I think the most straight forward solution if your just looking for a little space and probably least expensive would be to simply set the cell border color to your tables background color then set the border width to get desired result!

    cell.layer.borderColor = blueColor.CGColor
    cell.layer.borderWidth = 3

Requested bean is currently in creation: Is there an unresolvable circular reference?

In general, the most appropriated way to avoid this problem, (also because of better Mockito integration in JUnit) is to use the Setter/Field Injection as described at https://www.baeldung.com/circular-dependencies-in-spring and at https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html

@Component("bean1")
@Scope("view")
public class Bean1 {
    private Bean2 bean2;

    @Autowired
    public void setBean2(Bean2 bean2) {
        this.bean2 = bean2;
    }
}

@Component("bean2")
@Scope("view")
public class Bean2 {
    private Bean1 bean1;

    @Autowired
    public void setBean1(Bean1 bean1) {
        this.bean1 = bean1;
    }
}

SCCM 2012 application install "Failed" in client Software Center

I'm assuming you figured this out already but:

Technical Reference for Log Files in Configuration Manager

That's a list of client-side logs and what they do. They are located in Windows\CCM\Logs

AppEnforce.log will show you the actual command-line executed and the resulting exit code for each Deployment Type (only for the new style ConfigMgr Applications)

This is my go-to for troubleshooting apps. Haven't really found any other logs that are exceedingly useful.

How to find files that match a wildcard string in Java?

Consider DirectoryScanner from Apache Ant:

DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"**/*.java"});
scanner.setBasedir("C:/Temp");
scanner.setCaseSensitive(false);
scanner.scan();
String[] files = scanner.getIncludedFiles();

You'll need to reference ant.jar (~ 1.3 MB for ant 1.7.1).

How to Use Order By for Multiple Columns in Laravel 4?

You can do as @rmobis has specified in his answer, [Adding something more into it]

Using order by twice:

MyTable::orderBy('coloumn1', 'DESC')
    ->orderBy('coloumn2', 'ASC')
    ->get();

and the second way to do it is,

Using raw order by:

MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
    ->get();

Both will produce same query as follow,

SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC

As @rmobis specified in comment of first answer you can pass like an array to order by column like this,

$myTable->orders = array(
    array('column' => 'coloumn1', 'direction' => 'desc'), 
    array('column' => 'coloumn2', 'direction' => 'asc')
);

one more way to do it is iterate in loop,

$query = DB::table('my_tables');

foreach ($request->get('order_by_columns') as $column => $direction) {
    $query->orderBy($column, $direction);
}

$results = $query->get();

Hope it helps :)

Is there a way to suppress JSHint warning for one given line?

The "evil" answer did not work for me. Instead, I used what was recommended on the JSHints docs page. If you know the warning that is thrown, you can turn it off for a block of code. For example, I am using some third party code that does not use camel case functions, yet my JSHint rules require it, which led to a warning. To silence it, I wrote:

/*jshint -W106 */
save_state(id);
/*jshint +W106 */

How to read specific lines from a file (by line number)?

How about this:

>>> with open('a', 'r') as fin: lines = fin.readlines()
>>> for i, line in enumerate(lines):
      if i > 30: break
      if i == 26: dox()
      if i == 30: doy()

Python Set Comprehension

primes = {x for x in range(2, 101) if all(x%y for y in range(2, min(x, 11)))}

I simplified the test a bit - if all(x%y instead of if not any(not x%y

I also limited y's range; there is no point in testing for divisors > sqrt(x). So max(x) == 100 implies max(y) == 10. For x <= 10, y must also be < x.

pairs = {(x, x+2) for x in primes if x+2 in primes}

Instead of generating pairs of primes and testing them, get one and see if the corresponding higher prime exists.

How do I remove the height style from a DIV using jQuery?

to remove the height:

$('div#someDiv').css('height', '');
$('div#someDiv').css('height', null);

like John pointed out, set height to auto:

$('div#someDiv').css('height', 'auto');

(checked with jQuery 1.4)

Amazon S3 upload file and get URL

You can work it out for yourself given the bucket and the file name you specify in the upload request.

e.g. if your bucket is mybucket and your file is named myfilename:

https://mybucket.s3.amazonaws.com/myfilename

The s3 bit will be different depending on which region your bucket is in. For example, I use the south-east asia region so my urls are like:

https://mybucket.s3-ap-southeast-1.amazonaws.com/myfilename

Auto-click button element on page load using jQuery

JavaScript Pure:

<script type="text/javascript">
document.getElementById("modal").click();
</script>

JQuery:

<script type="text/javascript">
$(document).ready(function(){
    $("#modal").trigger('click'); 
});
</script>

or

<script type="text/javascript">
$(document).ready(function(){
    $("#modal").click(); 
});
</script>

How to export a CSV to Excel using Powershell

Ups, I entirely forgot this question. In the meantime I got a solution.
This Powershell script converts a CSV to XLSX in the background

Gimmicks are

  • Preserves all CSV values as plain text like =B1+B2 or 0000001.
    You don't see #Name or anything like that. No autoformating is done.
  • Automatically chooses the right delimiter (comma or semicolon) according to your regional setting
  • Autofit columns

PowerShell Code

### Set input and output path
$inputCSV = "C:\somefolder\input.csv"
$outputXLSX = "C:\somefolder\output.xlsx"

### Create a new Excel Workbook with one empty sheet
$excel = New-Object -ComObject excel.application 
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)

### Build the QueryTables.Add command
### QueryTables does the same as when clicking "Data » From Text" in Excel
$TxtConnector = ("TEXT;" + $inputCSV)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)

### Set the delimiter (, or ;) according to your regional settings
$query.TextFileOtherDelimiter = $Excel.Application.International(5)

### Set the format to delimited and text for every column
### A trick to create an array of 2s is used with the preceding comma
$query.TextFileParseType  = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1

### Execute & delete the import query
$query.Refresh()
$query.Delete()

### Save & close the Workbook as XLSX. Change the output extension for Excel 2003
$Workbook.SaveAs($outputXLSX,51)
$excel.Quit()

How do I filter an array with TypeScript in Angular 2?

You need to put your code into ngOnInit and use the this keyword:

ngOnInit() {
  this.booksByStoreID = this.books.filter(
          book => book.store_id === this.store.id);
}

You need ngOnInit because the input store wouldn't be set into the constructor:

ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

(https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html)

In your code, the books filtering is directly defined into the class content...

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

I'v done things like this using the Checksum(*) function

In essance it creates a row level checksum on all the columns data, you could then compare the checksum of each row for each table to each other, use a left join, to find rows that are different.

Hope that made sense...

Better with an example....

select *
from 
( select checksum(*) as chk, userid as k from UserAccounts) as t1
left join 
( select checksum(*) as chk, userid as k from UserAccounts) as t2 on t1.k = t2.k
where t1.chk <> t2.chk 

TypeError: 'bool' object is not callable

Actually you can fix it with following steps -

  1. Do cls.__dict__
  2. This will give you dictionary format output which will contain {'isFilled':True} or {'isFilled':False} depending upon what you have set.
  3. Delete this entry - del cls.__dict__['isFilled']
  4. You will be able to call the method now.

In this case, we delete the entry which overrides the method as mentioned by BrenBarn.

Resize a picture to fit a JLabel

i have done the following and it worked perfectly

try {
        JFileChooser jfc = new JFileChooser();
        jfc.showOpenDialog(null);
        File f = jfc.getSelectedFile();
        Image bi = ImageIO.read(f);
        image1.setText("");
        image1.setIcon(new ImageIcon(bi.getScaledInstance(int width, int width, int width)));

    } catch (Exception e) {
    } 

How to format a duration in java? (e.g format H:MM:SS)

If you don't want to drag in libraries, it's simple enough to do yourself using a Formatter, or related shortcut eg. given integer number of seconds s:

  String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60));

Ajax using https on an http page

Check out the opensource Forge project. It provides a JavaScript TLS implementation, along with some Flash to handle the actual cross-domain requests:

http://github.com/digitalbazaar/forge/blob/master/README

In short, Forge will enable you to make XmlHttpRequests from a web page loaded over http to an https site. You will need to provide a Flash cross-domain policy file via your server to enable the cross-domain requests. Check out the blog posts at the end of the README to get a more in-depth explanation for how it works.

However, I should mention that Forge is better suited for requests between two different https-domains. The reason is that there's a potential MiTM attack. If you load the JavaScript and Flash from a non-secure site it could be compromised. The most secure use is to load it from a secure site and then use it to access other sites (secure or otherwise).

Styles.Render in MVC4

src="@url.content("~/Folderpath/*.css")" should render styles

Android Studio error: "Environment variable does not point to a valid JVM installation"

It started happening to me when I changed variables for Android Studio. Go to your studio64.exe.vmoptions file (located in c:\users\userName\.AndroidStudio{version}\ and comments the arguments.

Why can't I do <img src="C:/localfile.jpg">?

starts with file:/// and ends with filename should work:

<img src="file:///C:/Users/91860/Desktop/snow.jpg" alt="Snow" style="width:100%;">

How to outline text in HTML / CSS

There are some webkit css properties that should work on Chrome/Safari at least:

-webkit-text-stroke-width: 2px;
-webkit-text-stroke-color: black;

That's a 2px wide black text outline.

How to get difference between two rows for a column field?

If you really want to be sure of orders, use "Row_Number()" and compare next record of current record (take a close look at "on" clause)

T1.ID + 1 = T2.ID

You are basically joining next row with current row, without specifying "min" or doing "top". If you have a small number of records, other solutions by "Dems" or "Quassanoi" will work fine.

with T2 as (
    select  ID = ROW_NUMBER() over (order by rowInt),
            rowInt, Value
    from    myTable
)
select  T1.RowInt, T1.Value, Diff = IsNull(T2.Value, 0) - T1.Value
from    (   SELECT  ID = ROW_NUMBER() over (order by rowInt), *
            FROM    myTable ) T1
        left join T2 on T1.ID + 1 = T2.ID
ORDER BY T1.ID

How to update single value inside specific array item in redux

I'm afraid that using map() method of an array may be expensive since entire array is to be iterated. Instead, I combine a new array that consists of three parts:

  • head - items before the modified item
  • the modified item
  • tail - items after the modified item

Here the example I've used in my code (NgRx, yet the machanism is the same for other Redux implementations):

// toggle done property: true to false, or false to true

function (state, action) {
    const todos = state.todos;
    const todoIdx = todos.findIndex(t => t.id === action.id);

    const todoObj = todos[todoIdx];
    const newTodoObj = { ...todoObj, done: !todoObj.done };

    const head = todos.slice(0, todoIdx - 1);
    const tail = todos.slice(todoIdx + 1);
    const newTodos = [...head, newTodoObj, ...tail];
}

<hr> tag in Twitter Bootstrap not functioning correctly?

You may want one of these, so to correspond to the Bootstrap layout:

<div class="col-xs-12">
    <hr >
</div>

<!-- or -->

<div class="col-xs-12">
    <hr style="border-style: dashed; border-top-width: 2px;">
</div>

<!-- or -->

<div class="col-xs-12">
    <hr class="col-xs-1" style="border-style: dashed; border-top-width: 2px;">
</div>

Without a DIV grid element included, layout may brake on different devices.

Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded

U can use

  $(document).on('click','p.class',function(e){
   e.preventDefault();
      //Code 
   });

Read response headers from API response - Angular 5 + TypeScript

You can get headers using below code

let main_headers = {}
this.http.post(url,
  {email: this.username, password: this.password},
  {'headers' : new HttpHeaders ({'Content-Type' : 'application/json'}), 'responseType': 'text', observe:'response'})
  .subscribe(response => {
    const keys = response.headers.keys();
    let headers = keys.map(key => {
      `${key}: ${response.headers.get(key)}`
        main_headers[key] = response.headers.get(key)
       }
      );
  });

later we can get the required header form the json object.

header_list['X-Token']

Stretch and scale a CSS image in the background - with CSS only

I agree with the image in absolute div with 100% width and height. Make sure you set 100% width and height for the body in the CSS and set margins and padding to zero. Another issue you will find with this method is that when selecting text, the selection area can sometimes encompass the background image, which has the unfortunate effect of making the full page have the selected state. You can get round this by using the user-select:none CSS rule, like so:

<html>
    <head>
        <style type="text/css">

            html,body {
                height: 100%;
                width: 100%
                margin: none;
                padding: none;
            }

            #background {
                width: 100%;
                height: 100%;
                position: fixed;
                left: 0px;
                top: 0px;
                z-index: -99999;
                -webkit-user-select: none;
                -khtml-user-select: none;
                -moz-user-select: none;
                -o-user-select: none;
                user-select: none;
            }

            #background img {
                width: 100%;
                height: 100%;
            }

            #main{ z-index:10;}
        </style>
    </head>
    <body>
        <div id="main">
            content here
        </div>
        <div id="background"><img src="bg.jpg"></div>
    </body>
</html>

Again, Internet Explorer is the bad guy here, because it doesn't recognise the user-select option - not even Internet Explorer 10 preview supports it, so you have the option of either using JavaScript to prevent background image selection (for example, http://www.felgall.com/jstip35.htm ) or using CSS 3 background-stretch method.

Also, for SEO I would put the background image at the bottom of the page, but if the background image takes too long to load (that is, with a white background initially), you could move to the top of the page.

Given the lat/long coordinates, how can we find out the city/country?

I've used Geocoder, a good Python library that supports multiple providers, including Google, Geonames, and OpenStreetMaps, to mention just a few. I've tried using the GeoPy library, and it often gets timeouts. Developing your own code for GeoNames is not the best use of your time and you may end up getting unstable code. Geocoder is very simple to use in my experience, and has good enough documentation. Below is some sample code for looking up city by latitude and longitude, or finding latitude/longitude by city name.

import geocoder

g = geocoder.osm([53.5343609, -113.5065084], method='reverse')
print g.json['city'] # Prints Edmonton

g = geocoder.osm('Edmonton, Canada')
print g.json['lat'], g.json['lng'] # Prints 53.5343609, -113.5065084

Toggle button using two image on different state

You can try something like this. Here on click of image button I toggle the imageview.

holder.imgitem.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            if(!onclick){
            mSparseBooleanArray.put((Integer) view.getTag(), true);
            holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_delete_overlay_com);
            onclick=true;}
            else if(onclick)
            {
                 mSparseBooleanArray.put((Integer) view.getTag(), false);
                  holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_selection_com);

            onclick=false;
            }
        }
    });

Regex empty string or email

Don't match an email with a regex. It's extremely ugly and long and complicated and your regex parser probably can't handle it anyway. Try to find a library routine for matching them. If you only want to solve the practical problem of matching an email address (that is, if you want wrong code that happens to (usually) work), use the regular-expressions.info link someone else submitted.

As for the empty string, ^$ is mentioned by multiple people and will work fine.

Python name 'os' is not defined

The problem is that you forgot to import os. Add this line of code:

import os

And everything should be fine. Hope this helps!

Laravel: How do I parse this json data in view blade?

You can use json decode then you get php array,and use that value as your own way

<?php 
$leads = json_decode($leads, true);
dd($leads);

npm install won't install devDependencies

Make sure your package.json is valid...

I had the following error...

npm WARN Invalid name: "blah blah blah"

and that, similarly, caused devDependencies not to be installed.

FYI, changing the package.json "name" to blah-blah-blah fixed it.

How to determine the current shell I'm working on

Kindly use the below command:

ps -p $$ | tail -1 | awk '{print $4}'

How can I create a temp file with a specific extension with .NET?

This is a simple but effective way to generate incremental filenames. It will look in the current directly (you can easily point that somewhere else) and search for files with the base YourApplicationName*.txt (again you can easily change that). It will start at 0000 so that the first file name will be YourApplicationName0000.txt. if for some reason there are file names with junk between (meaning not numbers) the left and right parts, those files will be ignored by virtue of the tryparse call.

    public static string CreateNewOutPutFile()
    {
        const string RemoveLeft = "YourApplicationName";
        const string RemoveRight = ".txt";
        const string searchString = RemoveLeft + "*" + RemoveRight;
        const string numberSpecifier = "0000";

        int maxTempNdx = -1;

        string fileName;
        string [] Files = Directory.GetFiles(Directory.GetCurrentDirectory(), searchString);
        foreach( string file in Files)
        {
            fileName = Path.GetFileName(file);
            string stripped = fileName.Remove(fileName.Length - RemoveRight.Length, RemoveRight.Length).Remove(0, RemoveLeft.Length);
            if( int.TryParse(stripped,out int current) )
            {
                if (current > maxTempNdx)
                    maxTempNdx = current;
            }
        }
        maxTempNdx++;
        fileName = RemoveLeft + maxTempNdx.ToString(numberSpecifier) + RemoveRight;
        File.CreateText(fileName); // optional
        return fileName;
    }

Use dynamic variable names in `dplyr`

After a lot of trial and error, I found the pattern UQ(rlang::sym("some string here"))) really useful for working with strings and dplyr verbs. It seems to work in a lot of surprising situations.

Here's an example with mutate. We want to create a function that adds together two columns, where you pass the function both column names as strings. We can use this pattern, together with the assignment operator :=, to do this.

## Take column `name1`, add it to column `name2`, and call the result `new_name`
mutate_values <- function(new_name, name1, name2){
  mtcars %>% 
    mutate(UQ(rlang::sym(new_name)) :=  UQ(rlang::sym(name1)) +  UQ(rlang::sym(name2)))
}
mutate_values('test', 'mpg', 'cyl')

The pattern works with other dplyr functions as well. Here's filter:

## filter a column by a value 
filter_values <- function(name, value){
  mtcars %>% 
    filter(UQ(rlang::sym(name)) != value)
}
filter_values('gear', 4)

Or arrange:

## transform a variable and then sort by it 
arrange_values <- function(name, transform){
  mtcars %>% 
    arrange(UQ(rlang::sym(name)) %>%  UQ(rlang::sym(transform)))
}
arrange_values('mpg', 'sin')

For select, you don't need to use the pattern. Instead you can use !!:

## select a column 
select_name <- function(name){
  mtcars %>% 
    select(!!name)
}
select_name('mpg')

How to convert int to QString?

I always use QString::setNum().

int i = 10;
double d = 10.75;
QString str;
str.setNum(i);
str.setNum(d);

setNum() is overloaded in many ways. See QString class reference.

Setting values of input fields with Angular 6

You should use the following:

       <td><input id="priceInput-{{orderLine.id}}" type="number" [(ngModel)]="orderLine.price"></td>

You will need to add the FormsModule to your app.module in the inputs section as follows:

import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  ..

The use of the brackets around the ngModel are as follows:

  • The [] show that it is taking an input from your TS file. This input should be a public member variable. A one way binding from TS to HTML.

  • The () show that it is taking output from your HTML file to a variable in the TS file. A one way binding from HTML to TS.

  • The [()] are both (e.g. a two way binding)

See here for more information: https://angular.io/guide/template-syntax

I would also suggest replacing id="priceInput-{{orderLine.id}}" with something like this [id]="getElementId(orderLine)" where getElementId(orderLine) returns the element Id in the TS file and can be used anywere you need to reference the element (to avoid simple bugs like calling it priceInput1 in one place and priceInput-1 in another. (if you still need to access the input by it's Id somewhere else)

Local Storage vs Cookies

With localStorage, web applications can store data locally within the user's browser. Before HTML5, application data had to be stored in cookies, included in every server request. Large amounts of data can be stored locally, without affecting website performance. Although localStorage is more modern, there are some pros and cons to both techniques.

Cookies

Pros

  • Legacy support (it's been around forever)
  • Persistent data
  • Expiration dates

Cons

  • Each domain stores all its cookies in a single string, which can make parsing data difficult
  • Data is unencrypted, which becomes an issue because... ... though small in size, cookies are sent with every HTTP request Limited size (4KB)
  • SQL injection can be performed from a cookie

Local storage

Pros

  • Support by most modern browsers
  • Persistent data that is stored directly in the browser
  • Same-origin rules apply to local storage data
  • Is not sent with every HTTP request
  • ~5MB storage per domain (that's 5120KB)

Cons

  • Not supported by anything before: IE 8, Firefox 3.5, Safari 4, Chrome 4, Opera 10.5, iOS 2.0, Android 2.0
  • If the server needs stored client information you purposely have to send it.

localStorage usage is almost identical with the session one. They have pretty much exact methods, so switching from session to localStorage is really child's play. However, if stored data is really crucial for your application, you will probably use cookies as a backup in case localStorage is not available. If you want to check browser support for localStorage, all you have to do is run this simple script:

/* 
* function body that test if storage is available
* returns true if localStorage is available and false if it's not
*/
function lsTest(){
    var test = 'test';
    try {
        localStorage.setItem(test, test);
        localStorage.removeItem(test);
        return true;
    } catch(e) {
        return false;
    }
}

/* 
* execute Test and run our custom script 
*/
if(lsTest()) {
    // window.sessionStorage.setItem(name, 1); // session and storage methods are very similar
    window.localStorage.setItem(name, 1);
    console.log('localStorage where used'); // log
} else {
    document.cookie="name=1; expires=Mon, 28 Mar 2016 12:00:00 UTC";
    console.log('Cookie where used'); // log
}

"localStorage values on Secure (SSL) pages are isolated" as someone noticed keep in mind that localStorage will not be available if you switch from 'http' to 'https' secured protocol, where the cookie will still be accesible. This is kind of important to be aware of if you work with secure protocols.

How does setTimeout work in Node.JS?

setTimeout is a kind of Thread, it holds a operation for a given time and execute.

setTimeout(function,time_in_mills);

in here the first argument should be a function type; as an example if you want to print your name after 3 seconds, your code should be something like below.

setTimeout(function(){console.log('your name')},3000);

Key point to remember is, what ever you want to do by using the setTimeout method, do it inside a function. If you want to call some other method by parsing some parameters, your code should look like below:

setTimeout(function(){yourOtherMethod(parameter);},3000);

How do you set up use HttpOnly cookies in PHP

Note that PHP session cookies don't use httponly by default.

To do that:

$sess_name = session_name();
if (session_start()) {
    setcookie($sess_name, session_id(), null, '/', null, null, true);
}

A couple of items of note here:

  • You have to call session_name() before session_start()
  • This also sets the default path to '/', which is necessary for Opera but which PHP session cookies don't do by default either.

Configuring ObjectMapper in Spring

I am using Spring 3.2.4 and Jackson FasterXML 2.1.1.

I have created a custom JacksonObjectMapper that works with explicit annotations for each attribute of the Objects mapped:

package com.test;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class MyJaxbJacksonObjectMapper extends ObjectMapper {

public MyJaxbJacksonObjectMapper() {

    this.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
            .setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.ANY)
            .setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE)
            .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)
            .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE);

    this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    }
}

Then this is instantiated in the context-configuration (servlet-context.xml):

<mvc:annotation-driven>
    <mvc:message-converters>

        <beans:bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <beans:property name="objectMapper">
                <beans:bean class="com.test.MyJaxbJacksonObjectMapper" />
            </beans:property>
        </beans:bean>

    </mvc:message-converters>
</mvc:annotation-driven>

This works fine!

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

You can fix this issue without opening the storyboard as a source. This warning is triggered by UILabels if numberOfLines !=1 and deployment target is < 8.0

HOW TO FIND IT?

  1. Go to Issue Navigator (CMD+8) and Select latest built with the warning enter image description here
  2. Locate the warning(s) (search for "Automatic Preferred Max Layout") and press expand button on the right
    enter image description here
  3. Find the Object ID of the UILabel enter image description here
  4. Open the Storyboard and SEARCH (CMD+f) for the object. It will SELECT AND HIGHLIGHT the UILabel
  5. Set Preferred Width = 0 "Explicit" as others suggested

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

Could be because of restoring SQL Server 2012 version backup file into SQL Server 2008 R2 or even less.

Drawing an SVG file on a HTML5 canvas

As Simon says above, using drawImage shouldn't work. But, using the canvg library and:

var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
ctx.drawSvg(SVG_XML_OR_PATH_TO_SVG, dx, dy, dw, dh);

This comes from the link Simon provides above, which has a number of other suggestions and points out that you want to either link to, or download canvg.js and rgbcolor.js. These allow you to manipulate and load an SVG, either via URL or using inline SVG code between svg tags, within JavaScript functions.

Regex Explanation ^.*$

"^.*$"

literally just means select everything

"^"  // anchors to the beginning of the line
".*" // zero or more of any character
"$"  // anchors to end of line

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

In my case, I was fetching data from database, changing some column values and updating it in database but for updating I was using the same save query which was violating primary key constraints i.e duplicate values for primary key, so I had written a separate query for updating the columns and it solved my problem..!

Efficient way to Handle ResultSet in Java

RHT pretty much has it. Or you could use a RowSetDynaClass and let someone else do all the work :)

Python | change text color in shell

This is so simple to do on a PC: Windows OS: Send the os a command to change the text: import os

os.system('color a') #green text
print 'I like green' 
raw_input('do you?')

How to use WebRequest to POST some data and read response?

Here's what works for me. I'm sure it can be improved, so feel free to make suggestions or edit to make it better.

const string WEBSERVICE_URL = "http://localhost/projectname/ServiceName.svc/ServiceMethod";
//This string is untested, but I think it's ok.
string jsonData = "{ \"key1\" : \"value1\", \"key2\":\"value2\"  }"; 
try
{       
    var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
    if (webRequest != null)
    {
        webRequest.Method = "POST";
        webRequest.Timeout = 20000;
        webRequest.ContentType = "application/json";

    using (System.IO.Stream s = webRequest.GetRequestStream())
    {
        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s))
            sw.Write(jsonData);
    }

    using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
    {
        using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
        {
            var jsonResponse = sr.ReadToEnd();
            System.Diagnostics.Debug.WriteLine(String.Format("Response: {0}", jsonResponse));
        }
    }
}
}
catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine(ex.ToString());
}

How to add calendar events in Android?

Try this in your code:

Calendar cal = Calendar.getInstance();              
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", true);
intent.putExtra("rrule", "FREQ=YEARLY");
intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
intent.putExtra("title", "A Test Event from android app");
startActivity(intent);

jQuery: outer html()

Just use standard DOM functionality:

$('#xxx')[0].outerHTML

outerHTML is well supported - verify at Mozilla or caniuse.

Count number of tables in Oracle

THIS QUERY WILL FIND ALL THE OBJECTS COUNTS IN A SPECIFIC SCHEMA

select owner, object_type, count(*) from dba_objects where owner='owner_name' group by owner, object_type order by 3 desc;

Retrieving Property name from lambda expression

now in C# 6 you can simply use nameof like this nameof(User.UserId)

which has many benefits, among them is that this is done at compile time, not runtime.

https://msdn.microsoft.com/en-us/magazine/dn802602.aspx

how do you increase the height of an html textbox

  • With inline style:

    <input type="text" style="font-size: 18pt; height: 40px; width:280px; ">
    
  • or with apart CSS:

    HTML:

    <input type="text" id="txtbox">
    

    CSS:

    #txtbox {
        font-size: 18pt;
        height: 42px;
        width : 300px;
    }
    

Highcharts - how to have a chart with dynamic height?

Another good option is, to pass a renderTo HTML reference. If it is a string, the element by that id is used. Otherwise you can do:

chart: {
    renderTo: document.getElementById('container')
},

or with jquery:

chart: {
    renderTo: $('#container')[0]
},

Further information can be found here: https://api.highcharts.com/highstock/chart.renderTo

Code signing is required for product type Unit Test Bundle in SDK iOS 8.0

I fixed it by manually selecting a provisioning profile in the build settings for the test target.

Test target settings -> Build settings -> Code signing -> Code sign identity. Previously, it was set to "Don't code sign".

How to convert QString to std::string?

The simplest way would be QString::toStdString().

Difference between long and int data types

On platforms where they both have the same size the answer is nothing. They both represent signed 4 byte values.

However you cannot depend on this being true. The size of long and int are not definitively defined by the standard. It's possible for compilers to give the types different sizes and hence break this assumption.

Read all worksheets in an Excel workbook into an R list with data.frames

You can load the work book and then use lapply, getSheets and readWorksheet and do something like this.

wb.mtcars <- loadWorkbook(system.file("demoFiles/mtcars.xlsx", 
                          package = "XLConnect"))
sheet_names <- getSheets(wb.mtcars)
names(sheet_names) <- sheet_names

sheet_list <- lapply(sheet_names, function(.sheet){
    readWorksheet(object=wb.mtcars, .sheet)})

How do I add records to a DataGridView in VB.Net?

I think you should build a dataset/datatable in code and bind the grid to that.

What is the Eclipse shortcut for "public static void main(String args[])"?

To get public static void main(String[] args) line in eclipse without typing the whole line type "main" and press Ctrl + space then, you will get the option for the main method select it.

enter image description here

How can I detect window size with jQuery?

You make one div somewhere on the page and put this code:

<div id="winSize"></div>
<script>
    var WindowsSize=function(){
        var h=$(window).height(),
            w=$(window).width();
        $("#winSize").html("<p>Width: "+w+"<br>Height: "+h+"</p>");
    };
   $(document).ready(WindowsSize); 
   $(window).resize(WindowsSize); 
</script>

Here is a snippet:

_x000D_
_x000D_
var WindowsSize=function(){_x000D_
     var h=$(window).height(),_x000D_
      w=$(window).width();_x000D_
     $("#winSize").html("<p>Width: "+w+"<br>Height:"+h+"</p>");_x000D_
 };_x000D_
 $(document).ready(WindowsSize); _x000D_
 $(window).resize(WindowsSize); 
_x000D_
#winSize{_x000D_
  position:fixed;_x000D_
  bottom:1%;_x000D_
  right:1%;_x000D_
  border:rgba(0,0,0,0.8) 3px solid;_x000D_
  background:rgba(0,0,0,0.6);_x000D_
  padding:5px 10px;_x000D_
  color:#fff;_x000D_
  text-shadow:#000 1px 1px 1px,#000 -1px 1px 1px;_x000D_
  z-index:9999_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="winSize"></div>
_x000D_
_x000D_
_x000D_

Of course, adapt it to fit your needs! ;)

width:auto for <input> fields

Answer 1 - "response" gave a nice answer/link for it. To put it in short, "auto" is the default, so it is like removing any changes in the width of an element

Answer 2 - use width: 100% instead. It will fill the 100% of the parent container, in this case, the "form".

How to get current url in view in asp.net core 1.0

Use the AbsoluteUri property of the Uri, with .Net core you have to build the Uri from request like this,

 var location = new Uri($"{Request.Scheme}://{Request.Host}{Request.Path}{Request.QueryString}");

 var url = location.AbsoluteUri;

e.g. if the request url is 'http://www.contoso.com/catalog/shownew.htm?date=today' this will return the same url.

When maven says "resolution will not be reattempted until the update interval of MyRepo has elapsed", where is that interval specified?

How I got this problem,

When I changed from Eclipse Juno to Luna, and checkout my maven projects from SVN repo, I got the same issues while building the applications.

What I tried? I tried clean Local repository and then updating all the versions again using -U option. But my problem continued.

Then I went to Window --> Preferences -> Maven --> User Settings --> and clicked on Reindex button under Local Repository and wait for the reindex to happen.

That's all, the issue is resolved.

How to get the current loop index when using Iterator?

This would be the simplest solution!

std::vector<double> v (5);

for(auto itr = v.begin();itr != v.end();++itr){

 auto current_loop_index = itr - v.begin();

  std::cout << current_loop_index << std::endl;

}

Tested on gcc-9 with -std=c++11 flag

Output:

0
1
2
3
4

Error parsing yaml file: mapping values are not allowed here

Another cause is wrong indentation which means trying to create the wrong objects. I've just fixed one in a Kubernetes Ingress definition:

Wrong

- path: / 
    backend: 
      serviceName: <service_name> 
      servicePort: <port> 

Correct

- path: /
  backend:
    serviceName: <service_name>
    servicePort: <port>

How to find if element with specific id exists or not

You can simply use if(yourElement)

_x000D_
_x000D_
var a = document.getElementById("elemA");_x000D_
var b = document.getElementById("elemB");_x000D_
_x000D_
if(a)_x000D_
  console.log("elemA exists");_x000D_
else_x000D_
  console.log("elemA does not exist");_x000D_
  _x000D_
if(b)_x000D_
  console.log("elemB exists");_x000D_
else_x000D_
  console.log("elemB does not exist");
_x000D_
<div id="elemA"></div>
_x000D_
_x000D_
_x000D_

Fill an array with random numbers

Probably the cleanest way to do it in Java 8:

private int[] randomIntArray() {
   Random rand = new Random();
   return IntStream.range(0, 23).map(i -> rand.nextInt()).toArray();
}

What's the difference between "Solutions Architect" and "Applications Architect"?

Update 1/5/2018 - over the last 9 years, my thinking has evolved considerably on this topic. I tend to live a little closer to the bleeding edge in our industry than the majority (though certainly not pushing the boundaries nearly as much as a lot of really smart people out there). I've been an architect at varying levels from application, to solution, to enterprise, at multiple companies large and small. I've come to the conclusion that the future in our technology industry is one mostly without architects. If this sounds crazy to you, wait a few years and your company will probably catch up, or your competitors who figure it out will catch up with (and pass) you. The fundamental problem is that "architecture" is nothing more or less than the sum of all the decisions that have been made about your application/solution/portfolio. So the title "architect" really means "decider". That says a lot, also by what it doesn't say. It doesn't say "builder". Creating a career path / hierarchy that implicitly tells people "building" is lower than "deciding", and "deciders" are not directly responsible (by the difference in title) for "building". People who are still hanging on to their architect title will chafe at this and protest "but I am hands-on!" Great, if you're just a builder then give up your meaningless title and stop setting yourself apart from the other builders. Companies that emphasize "all builders are deciders, and all deciders are builders" will move faster than their competitors. We use the title "engineer" for everyone, and "engineer" means deciding and building.

Original answer:

For people who have never worked in a very large organization (or have, but it was a dysfunctional one), "architect" may have left a bad taste in their mouth. However, it is not only a legitimate role, but a highly strategic one for smart companies.

  • When an application becomes so vast and complex that dealing with the overall technical vision and planning, and translating business needs into technical strategy becomes a full-time job, that is an application architect. Application architects also often mentor and/or lead developers, and know the code of their responsible application(s) well.

  • When an organization has so many applications and infrastructure inter-dependencies that it is a full-time job to ensure their alignment and strategy without being involved in the code of any of them, that is a solution architect. Solution architect can sometimes be similar to an application architect, but over a suite of especially large applications that comprise a logical solution for a business.

  • When an organization becomes so large that it becomes a full-time job to coordinate the high-level planning for the solution architects, and frame the terms of the business technology strategy, that role is an enterprise architect. Enterprise architects typically work at an executive level, advising the CxO office and its support functions as well as the business as a whole.

There are also infrastructure architects, information architects, and a few others, but in terms of total numbers these comprise a smaller percentage than the "big three".

Note: numerous other answers have said there is "no standard" for these titles. That is not true. Go to any Fortune 1000 company's IT department and you will find these titles used consistently.

The two most common misconceptions about "architect" are:

  • An architect is simply a more senior/higher-earning developer with a fancy title
  • An architect is someone who is technically useless, hasn't coded in years but still throws around their weight in the business, making life difficult for developers

These misconceptions come from a lot of architects doing a pretty bad job, and organizations doing a terrible job at understanding what an architect is for. It is common to promote the top programmer into an architect role, but that is not right. They have some overlapping but not identical skillsets. The best programmer may often be, but is not always, an ideal architect. A good architect has a good understanding of many technical aspects of the IT industry; a better understanding of business needs and strategies than a developer needs to have; excellent communication skills and often some project management and business analysis skills. It is essential for architects to keep their hands dirty with code and to stay sharp technically. Good ones do.

Postgresql - select something where date = "01/01/11"

I think you want to cast your dt to a date and fix the format of your date literal:

SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

Or the standard version:

SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

The extract function doesn't understand "date" and it returns a number.

Access to file download dialog in Firefox

I was stuck with the same problem, but I found a solution. I did it the same way as this blog did.

Of course this was Java, I've translated it to Python:

fp = webdriver.FirefoxProfile()

fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir",getcwd())
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","text/csv")

browser = webdriver.Firefox(firefox_profile=fp)

In my example it was a CSV file. But when you need more, there are stored in the ~/.mozilla/$USER_PROFILE/mimeTypes.rdf

What to use now Google News API is deprecated?

Depending on your needs, you want to use their section feeds, their search feeds

http://news.google.com/news?q=apple&output=rss

or Bing News Search.

http://www.bing.com/toolbox/bingdeveloper/

CSS media query to target only iOS devices

Short answer No. CSS is not specific to brands.

Below are the articles to implement for iOS using media only.

https://css-tricks.com/snippets/css/media-queries-for-standard-devices/

http://stephen.io/mediaqueries/

Infact you can use PHP, Javascript to detect the iOS browser and according to that you can call CSS file. For instance

http://www.kevinleary.net/php-detect-ios-mobile-users/

How to linebreak an svg text within javascript?

I have adapted a bit the solution by @steco, switching the dependency from d3 to jquery and adding the height of the text element as parameter

function wrap(text, width, height) {
  text.each(function(idx,elem) {
    var text = $(elem);
    text.attr("dy",height);
        var words = text.text().split(/\s+/).reverse(),
        word,
        line = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat( text.attr("dy") ),
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (elem.getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

How do I use the nohup command without getting nohup.out?

sudo bash -c "nohup /opt/viptel/viptel_bin/log.sh $* &> /dev/null"  &

Redirecting the output of sudo causes sudo to reask for the password, thus an awkward mechanism is needed to do this variant.

How to calculate 1st and 3rd quartiles?

Building upon or rather correcting a bit on what Babak said....

np.percentile DOES VERY MUCH calculate the values of Q1, median, and Q3. Consider the sorted list below:

s1=[18,45,66,70,76,83,88,90,90,95,95,98]

running np.percentile(s1, [25, 50, 75]) returns the actual values from the list:

[69.  85.5  91.25]

However, the quartiles are Q1=68.0, Median=85.5, Q3=92.5, which is the correct thing to say

What we are missing here is the interpolation parameter of the np.percentile and related functions. By default the value of this argument is linear. This optional parameter specifies the interpolation method to use when the desired quantile lies between two data points i < j:
linear: i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j.
lower: i.
higher: j.
nearest: i or j, whichever is nearest.
midpoint: (i + j) / 2.

Thus running np.percentile(s1, [25, 50, 75], interpolation='midpoint') returns the actual results for the list:

[68. 85.5 92.5]

How do I write a "tab" in Python?

Here are some more exotic Python 3 ways to get "hello" TAB "alex" (tested with Python 3.6.10):

"hello\N{TAB}alex"

"hello\N{tab}alex"

"hello\N{TaB}alex"

"hello\N{HT}alex"

"hello\N{CHARACTER TABULATION}alex"

"hello\N{HORIZONTAL TABULATION}alex"

"hello\x09alex"

"hello\u0009alex"

"hello\U00000009alex"

Actually, instead of using an escape sequence, it is possible to insert tab symbol directly into the string literal. Here is the code with a tabulation character to copy and try:

"hello alex"

If the tab in the string above won't be lost anywhere during copying the string then "print(repr(< string from above >)" should print 'hello\talex'.

See respective Python documentation for reference.

Using Excel as front end to Access database (with VBA)

Just skip the excel part - the excel user forms are just a poor man's version of the way more robust Access forms. Also Access VBA is identical to Excel VBA - you just have to learn Access' object model. With a simple application you won't need to write much VBA anyways because in Access you can wire things together quite easily.

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

its awful oracle installer:

[INS-13001]

I got it as I used MY_PC as NETBIOS name instead of MYPC (Underscore is bad for it..)

Can be an historical reason.. but message is obscure.

How to search a Git repository by commit message?

git log --grep="Build 0051"

should do the trick

CSS z-index not working (position absolute)

I solved my z-index problem by making the body wrapper z-index:-1 and the body z-index:-2, and the other divs z-index:1.

And then the later divs didn't work unless I had z-index 200+. Even though I had position:relative on each element, with the body at default z-index it wouldn't work.

Hope this helps somebody.

How to delete a line from a text file in C#?

Why can't use this? First, create an array:

string[] lines = File.ReadAllLines(openFileDialog1.FileName);

Then look up the line you need to delete and replace it with "" :

lines[x].Replace(lines[x], "");

Done!

Using $setValidity inside a Controller

$setValidity needs to be called on the ngModelController. Inside the controller, I think that means $scope.myForm.file.$setValidity().

See also section "Custom Validation" on the Forms page, if you haven't already.

Also, for the first argument to $setValidity, use just 'filetype' and 'size'.

How to get the current directory in a C program?

Have you had a look at getcwd()?

#include <unistd.h>
char *getcwd(char *buf, size_t size);

Simple example:

#include <unistd.h>
#include <stdio.h>
#include <limits.h>

int main() {
   char cwd[PATH_MAX];
   if (getcwd(cwd, sizeof(cwd)) != NULL) {
       printf("Current working dir: %s\n", cwd);
   } else {
       perror("getcwd() error");
       return 1;
   }
   return 0;
}

AngularJS: How to run additional code after AngularJS has rendered a template?

You can use the 'jQuery Passthrough' module of the angular-ui utils. I successfully binded a jQuery touch carousel plugin to some images that I retrieve async from a web service and render them with ng-repeat.

Wait until an HTML5 video loads

call function on load:

<video onload="doWhatYouNeedTo()" src="demo.mp4" id="video">

get video duration

var video = document.getElementById("video");
var duration = video.duration;

DbEntityValidationException - How can I easily tell what caused the error?

The easiest solution is to override SaveChanges on your entities class. You can catch the DbEntityValidationException, unwrap the actual errors and create a new DbEntityValidationException with the improved message.

  1. Create a partial class next to your SomethingSomething.Context.cs file.
  2. Use the code at the bottom of this post.
  3. That's it. Your implementation will automatically use the overriden SaveChanges without any refactor work.

Your exception message will now look like this:

System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. The validation errors are: The field PhoneNumber must be a string or array type with a maximum length of '12'; The LastName field is required.

You can drop the overridden SaveChanges in any class that inherits from DbContext:

public partial class SomethingSomethingEntities
{
    public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (DbEntityValidationException ex)
        {
            // Retrieve the error messages as a list of strings.
            var errorMessages = ex.EntityValidationErrors
                    .SelectMany(x => x.ValidationErrors)
                    .Select(x => x.ErrorMessage);
    
            // Join the list to a single string.
            var fullErrorMessage = string.Join("; ", errorMessages);
    
            // Combine the original exception message with the new one.
            var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
    
            // Throw a new DbEntityValidationException with the improved exception message.
            throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
        }
    }
}

The DbEntityValidationException also contains the entities that caused the validation errors. So if you require even more information, you can change the above code to output information about these entities.

See also: http://devillers.nl/improving-dbentityvalidationexception/

Creating a LinkedList class from scratch

Sure, a Linked List is a bit confusing for programming n00bs, pretty much the temptation is to look at it as Russian Dolls, because that's what it seems like, a LinkedList Object in a LinkedList Object. But that's a touch difficult to visualize, instead look at it like a computer.

LinkedList = Data + Next Member

Where it's the last member of the list if next is NULL

So a 5 member LinkedList would be:

LinkedList(Data1, LinkedList(Data2, LinkedList(Data3, LinkedList(Data4, LinkedList(Data5, NULL)))))

But you can think of it as simply:

Data1 -> Data2 -> Data3 -> Data4 -> Data5 -> NULL

So, how do we find the end of this? Well, we know that the NULL is the end so:

public void append(LinkedList myNextNode) {
  LinkedList current = this; //Make a variable to store a pointer to this LinkedList
  while (current.next != NULL) { //While we're not at the last node of the LinkedList
    current = current.next; //Go further down the rabbit hole.
  }
  current.next = myNextNode; //Now we're at the end, so simply replace the NULL with another Linked List!
  return; //and we're done!
}

This is very simple code of course, and it will infinitely loop if you feed it a circularly linked list! But that's the basics.

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

I had this in VS 2012 where the "Section name" had been changed in a project, and I fixed it by deleting "app.config" in the project, then right-clicking on the project in the "Solution Explorer", selecting "Properties", then "Settings", then making a change to one of the settings, saving, and re-building. This created a new app.config with the correct information.

Convert .class to .java

I'm guessing that either the class name is wrong - be sure to use the fully-resolved class name, with all packages - or it's not in the CLASSPATH so javap can't find it.

Undo a particular commit in Git that's been pushed to remote repos

Identify the hash of the commit, using git log, then use git revert <commit> to create a new commit that removes these changes. In a way, git revert is the converse of git cherry-pick -- the latter applies the patch to a branch that's missing it, the former removes it from a branch that has it.

ionic build Android | error: No installed build tools found. Please install the Android build tools

FOR WINDOW: I have faced this type of issue. But after exploring it solved in my case. I am using window 10. just follow few steps below:

  1. download Android SKD Manager for windows. https://developer.android.com/studio at the end of this page. It is zip file. after extracting it will show tools directory.

  2. Go to drive C:\ create new folder 'android-sdk'. copy tools folder and past in
    C:\android-sdk

  3. open command prompt as Administrator. Go to cd " c:\android-sdk\tools\bin ". sdkmanager will be show here. type skdmanager, it will show like this [=======================================] 100% Computing updates...

  4. after that type "sdkmanager platform-tools" it will create platform-tools directory in C:\android-sdk

  5. Now set System environment variables: right click on PC select properties. system settings will popup. click on > Environment Variables. Environment Variables will popup.

  6. At this window System variables as like this. C:\android-sdk\platform-tools and C:\android-sdk\tools\bin

  7. run command to build tools sdkmanager "build-tools;27.0.3"

    Also make sure java path is defined. I hope it will solve problem.

Add text to textarea - Jquery

That should work. Better if you pass a function to val:

$('#replyBox').val(function(i, text) {
    return text + quote;
});

This way you avoid searching the element and calling val twice.

Is it worth using Python's re.compile?

Performance difference aside, using re.compile and using the compiled regular expression object to do match (whatever regular expression related operations) makes the semantics clearer to Python run-time.

I had some painful experience of debugging some simple code:

compare = lambda s, p: re.match(p, s)

and later I'd use compare in

[x for x in data if compare(patternPhrases, x[columnIndex])]

where patternPhrases is supposed to be a variable containing regular expression string, x[columnIndex] is a variable containing string.

I had trouble that patternPhrases did not match some expected string!

But if I used the re.compile form:

compare = lambda s, p: p.match(s)

then in

[x for x in data if compare(patternPhrases, x[columnIndex])]

Python would have complained that "string does not have attribute of match", as by positional argument mapping in compare, x[columnIndex] is used as regular expression!, when I actually meant

compare = lambda p, s: p.match(s)

In my case, using re.compile is more explicit of the purpose of regular expression, when it's value is hidden to naked eyes, thus I could get more help from Python run-time checking.

So the moral of my lesson is that when the regular expression is not just literal string, then I should use re.compile to let Python to help me to assert my assumption.

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)

Well try ini_set('memory_limit', '256M');

134217728 bytes = 128 MB

Or rewrite the code to consume less memory.

HTTP Basic Authentication credentials passed in URL and encryption

Not necessarily true. It will be encrypted on the wire however it still lands in the logs plain text

PHP: merge two arrays while keeping keys instead of reindexing?

Hello year 2010 question.

The OP.'s requirement is preserve keys (keep keys) and not overlap (I think overwrite). In some case such as numeric keys it is possible but if string keys it seems to be not possible.

If you use array_merge() the numeric keys will always re-index or renumbered.
If you use array_replace(), array_replace_recursive() it will be overlap or overwrite from the right to the left. The value with the same key on first array will be replaced with second array.
If you use $array1 + $array2 as the comment was mentioned, if the keys are same then it will keep the value from first array but drop the second array.

Custom function.

Here is my function that I just wrote to work on the same requirements. You are free to use for any purpose.

/**
 * Array custom merge. Preserve indexed array key (numbers) but overwrite string key (same as PHP's `array_merge()` function).
 * 
 * If the another array key is string, it will be overwrite the first array.<br>
 * If the another array key is integer, it will be add to first array depend on duplicated key or not. 
 * If it is not duplicate key with the first, the key will be preserve and add to the first array.
 * If it is duplicated then it will be re-index the number append to the first array.
 *
 * @param array $array1 The first array is main array.
 * @param array ...$arrays The another arrays to merge with the first.
 * @return array Return merged array.
 */
function arrayCustomMerge(array $array1, array ...$arrays): array
{
    foreach ($arrays as $additionalArray) {
        foreach ($additionalArray as $key => $item) {
            if (is_string($key)) {
                // if associative array.
                // item on the right will always overwrite on the left.
                $array1[$key] = $item;
            } elseif (is_int($key) && !array_key_exists($key, $array1)) {
                // if key is number. this should be indexed array.
                // and if array 1 is not already has this key.
                // add this array with the key preserved to array 1.
                $array1[$key] = $item;
            } else {
                // if anything else...
                // get all keys from array 1 (numbers only).
                $array1Keys = array_filter(array_keys($array1), 'is_int');
                // next key index = get max array key number + 1.
                $nextKeyIndex = (intval(max($array1Keys)) + 1);
                unset($array1Keys);
                // set array with the next key index.
                $array1[$nextKeyIndex] = $item;
                unset($nextKeyIndex);
            }
        }// endforeach; $additionalArray
        unset($item, $key);
    }// endforeach;
    unset($additionalArray);

    return $array1;
}// arrayCustomMerge

Testing.

<?php
$array1 = [
    'cat', 
    'bear', 
    'fruitred' => 'apple',
    3.1 => 'dog',
    null => 'null',
];
$array2 = [
    1 => 'polar bear',
    20 => 'monkey',
    'fruitred' => 'strawberry',
    'fruityellow' => 'banana',
    null => 'another null',
];

// require `arrayCustomMerge()` function here.

function printDebug($message)
{
    echo '<pre>';
    print_r($message);
    echo '</pre>' . PHP_EOL;
}

echo 'array1: <br>';
printDebug($array1);
echo 'array2: <br>';
printDebug($array2);


echo PHP_EOL . '<hr>' . PHP_EOL . PHP_EOL;


echo 'arrayCustomMerge:<br>';
$merged = arrayCustomMerge($array1, $array2);
printDebug($merged);


assert($merged[0] == 'cat', 'array key 0 should be \'cat\'');
assert($merged[1] == 'bear', 'array key 1 should be \'bear\'');
assert($merged['fruitred'] == 'strawberry', 'array key \'fruitred\' should be \'strawberry\'');
assert($merged[3] == 'dog', 'array key 3 should be \'dog\'');
assert(array_search('another null', $merged) !== false, '\'another null\' should be merged.');
assert(array_search('polar bear', $merged) !== false, '\'polar bear\' should be merged.');
assert($merged[20] == 'monkey', 'array key 20 should be \'monkey\'');
assert($merged['fruityellow'] == 'banana', 'array key \'fruityellow\' should be \'banana\'');
The results.
array1:

Array
(
    [0] => cat
    [1] => bear
    [fruitred] => apple
    [3] => dog
    [] => null
)

array2:

Array
(
    [1] => polar bear
    [20] => monkey
    [fruitred] => strawberry
    [fruityellow] => banana
    [] => another null
)

---
arrayCustomMerge:

Array
(
    [0] => cat
    [1] => bear
    [fruitred] => strawberry
    [3] => dog
    [] => another null
    [4] => polar bear
    [20] => monkey
    [fruityellow] => banana
)

Create a menu Bar in WPF?

<Container>
    <Menu>
        <MenuItem Header="File">
            <MenuItem Header="New">
               <MenuItem Header="File1"/>
               <MenuItem Header="File2"/>
               <MenuItem Header="File3"/>
            </MenuItem>
            <MenuItem Header="Open"/>
            <MenuItem Header="Save"/>
        </MenuItem>
    </Menu>
</Container>

Pandas - Compute z-score for all columns

When we are dealing with time-series, calculating z-scores (or anomalies - not the same thing, but you can adapt this code easily) is a bit more complicated. For example, you have 10 years of temperature data measured weekly. To calculate z-scores for the whole time-series, you have to know the means and standard deviations for each day of the year. So, let's get started:

Assume you have a pandas DataFrame. First of all, you need a DateTime index. If you don't have it yet, but luckily you do have a column with dates, just make it as your index. Pandas will try to guess the date format. The goal here is to have DateTimeIndex. You can check it out by trying:

type(df.index)

If you don't have one, let's make it.

df.index = pd.DatetimeIndex(df[datecolumn])
df = df.drop(datecolumn,axis=1)

Next step is to calculate mean and standard deviation for each group of days. For this, we use the groupby method.

mean = pd.groupby(df,by=[df.index.dayofyear]).aggregate(np.nanmean)
std = pd.groupby(df,by=[df.index.dayofyear]).aggregate(np.nanstd)

Finally, we loop through all the dates, performing the calculation (value - mean)/stddev; however, as mentioned, for time-series this is not so straightforward.

df2 = df.copy() #keep a copy for future comparisons 
for y in np.unique(df.index.year):
    for d in np.unique(df.index.dayofyear):
        df2[(df.index.year==y) & (df.index.dayofyear==d)] = (df[(df.index.year==y) & (df.index.dayofyear==d)]- mean.ix[d])/std.ix[d]
        df2.index.name = 'date' #this is just to look nicer

df2 #this is your z-score dataset.

The logic inside the for loops is: for a given year we have to match each dayofyear to its mean and stdev. We run this for all the years in your time-series.

Highlight a word with jQuery

Here's a variation that ignores and preserves case:

jQuery.fn.highlight = function (str, className) {
    var regex = new RegExp("\\b"+str+"\\b", "gi");

    return this.each(function () {
        this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";});
    });
};

T-SQL Substring - Last 3 Characters

SELECT RIGHT(column, 3)

That's all you need.

You can also do LEFT() in the same way.

Bear in mind if you are using this in a WHERE clause that the RIGHT() can't use any indexes.

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

This one's already accepted, but if there are any other dummies out there (like me) that didn't immediately get it from the presently accepted answer, here's a bit more detail.

The model class referenced by the ForeignKey needs to have a __unicode__ method within it, like here:

class Category(models.Model):
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return self.name

That made the difference for me, and should apply to the above scenario. This works on Django 1.0.2.

Running multiple async tasks and waiting for them all to complete

This is how I do it with an array Func<>:

var tasks = new Func<Task>[]
{
   () => myAsyncWork1(),
   () => myAsyncWork2(),
   () => myAsyncWork3()
};

await Task.WhenAll(tasks.Select(task => task()).ToArray()); //Async    
Task.WaitAll(tasks.Select(task => task()).ToArray()); //Or use WaitAll for Sync

Get current scroll position of ScrollView in React Native

I believe contentOffset will give you an object containing the top-left scroll offset:

http://facebook.github.io/react-native/docs/scrollview.html#contentoffset

Get only records created today in laravel

$today = Carbon\Carbon::now()->format('Y-m-d').'%';
->where('created_at', 'like', $today);

Hope it will help you

wampserver doesn't go green - stays orange

My problem was not related to skype as i didn't had it installed. The solution I found was that 2 .dll files(msvcp110.dll, msvcr110.dll) were missing from the directory :

C:\wamp\bin\apache\apache2.4.9\bin

So I copied these 2 files to all these locations just in case and restarted wamp it worked

C:\wamp
C:\wamp\bin\apache\apache2.4.9\bin
C:\wamp\bin\apache\apache2.4.9
C:\wamp\bin\mysql\mysql5.6.17
C:\wamp\bin\php\php5.5.12

I hope this helps someone out.

What is the difference between join and merge in Pandas?

One of the difference is that merge is creating a new index, and join is keeping the left side index. It can have a big consequence on your later transformations if you wrongly assume that your index isn't changed with merge.

For example:

import pandas as pd

df1 = pd.DataFrame({'org_index': [101, 102, 103, 104],
                    'date': [201801, 201801, 201802, 201802],
                    'val': [1, 2, 3, 4]}, index=[101, 102, 103, 104])
df1

       date  org_index  val
101  201801        101    1
102  201801        102    2
103  201802        103    3
104  201802        104    4

-

df2 = pd.DataFrame({'date': [201801, 201802], 'dateval': ['A', 'B']}).set_index('date')
df2

       dateval
date          
201801       A
201802       B

-

df1.merge(df2, on='date')

     date  org_index  val dateval
0  201801        101    1       A
1  201801        102    2       A
2  201802        103    3       B
3  201802        104    4       B

-

df1.join(df2, on='date')
       date  org_index  val dateval
101  201801        101    1       A
102  201801        102    2       A
103  201802        103    3       B
104  201802        104    4       B

How do I test which class an object is in Objective-C?

To test if object is an instance of class a:

[yourObject isKindOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of 
// given class or an instance of any class that inherits from that class.

or

[yourObject isMemberOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of a 
// given class.

To get object's class name you can use NSStringFromClass function:

NSString *className = NSStringFromClass([yourObject class]);

or c-function from objective-c runtime api:

#import <objc/runtime.h>

/* ... */

const char* className = class_getName([yourObject class]);
NSLog(@"yourObject is a: %s", className);

EDIT: In Swift

if touch.view is UIPickerView {
    // touch.view is of type UIPickerView
}

How to make a pure css based dropdown menu?

There is different ways to make dropdown menu using css. Here is simple code.

HTML Code

    <label class="dropdown">

  <div class="dd-button">
    Dropdown
  </div>

  <input type="checkbox" class="dd-input" id="test">

  <ul class="dd-menu">
    <li>Dropdown 1</li>
    <li>Dropdown 2</li>
  </ul>

</label>

CSS Code

body {
  color: #000000;
  font-family: Sans-Serif;
  padding: 30px;
  background-color: #f6f6f6;
}

a {
  text-decoration: none;
  color: #000000;
}

a:hover {
  color: #222222
}

/* Dropdown */

.dropdown {
  display: inline-block;
  position: relative;
}

.dd-button {
  display: inline-block;
  border: 1px solid gray;
  border-radius: 4px;
  padding: 10px 30px 10px 20px;
  background-color: #ffffff;
  cursor: pointer;
  white-space: nowrap;
}

.dd-button:after {
  content: '';
  position: absolute;
  top: 50%;
  right: 15px;
  transform: translateY(-50%);
  width: 0; 
  height: 0; 
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid black;
}

.dd-button:hover {
  background-color: #eeeeee;
}


.dd-input {
  display: none;
}

.dd-menu {
  position: absolute;
  top: 100%;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 0;
  margin: 2px 0 0 0;
  box-shadow: 0 0 6px 0 rgba(0,0,0,0.1);
  background-color: #ffffff;
  list-style-type: none;
}

.dd-input + .dd-menu {
  display: none;
} 

.dd-input:checked + .dd-menu {
  display: block;
} 

.dd-menu li {
  padding: 10px 20px;
  cursor: pointer;
  white-space: nowrap;
}

.dd-menu li:hover {
  background-color: #f6f6f6;
}

.dd-menu li a {
  display: block;
  margin: -10px -20px;
  padding: 10px 20px;
}

.dd-menu li.divider{
  padding: 0;
  border-bottom: 1px solid #cccccc;
}

More css code example

Multi-select dropdown list in ASP.NET

I like the Infragistics controls. The WebDropDown has what you need. The only drawback is they can be a bit spendy.

How to change the href for a hyperlink using jQuery

href in an attribute, so you can change it using pure JavaScript, but if you already have jQuery injected in your page, don't worry, I will show it both ways:

Imagine you have this href below:

<a id="ali" alt="Ali" href="http://dezfoolian.com.au">Alireza Dezfoolian</a>

And you like to change it the link...

Using pure JavaScript without any library you can do:

document.getElementById("ali").setAttribute("href", "https://stackoverflow.com");

But also in jQuery you can do:

$("#ali").attr("href", "https://stackoverflow.com");

or

$("#ali").prop("href", "https://stackoverflow.com");

In this case, if you already have jQuery injected, probably jQuery one look shorter and more cross-browser...but other than that I go with the JS one...

How to use PDO to fetch results array in PHP?

Take a look at the PDOStatement.fetchAll method. You could also use fetch in an iterator pattern.

Code sample for fetchAll, from the PHP documentation:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);

Results:

Array
(
    [0] => Array
        (
            [NAME] => pear
            [COLOUR] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [COLOUR] => pink
        )
)

How can I force Python's file.write() to use the same newline format in Windows as in Linux ("\r\n" vs. "\n")?

You can still use the textmode and force the linefeed-newline with the keyword argument newline

f = open("./foo",'w',newline='\n')

Tested with Python 3.4.2.

Edit: This does not work in Python 2.7.

Run certain code every n seconds

import threading

def printit():
  threading.Timer(5.0, printit).start()
  print "Hello, World!"

printit()

# continue with the rest of your code

https://docs.python.org/3/library/threading.html#timer-objects

How to copy a file along with directory structure/path using python?

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

What is the default access specifier in Java?

The default specifier depends upon context.

For classes, and interface declarations, the default is package private. This falls between protected and private, allowing only classes in the same package access. (protected is like this, but also allowing access to subclasses outside of the package.)

class MyClass   // package private
{
   int field;    // package private field

   void calc() {  // package private method

   }
}

For interface members (fields and methods), the default access is public. But note that the interface declaration itself defaults to package private.

interface MyInterface  // package private
{
   int field1;         // static final public

   void method1();     // public abstract
}

If we then have the declaration

public interface MyInterface2 extends MyInterface
{

}

Classes using MyInterface2 can then see field1 and method1 from the super interface, because they are public, even though they cannot see the declaration of MyInterface itself.

The default XML namespace of the project must be the MSBuild XML namespace

@DavidG's answer is correct, but I would like to add that if you're building from the command line, the equivalent solution is to make sure that you're using the appropriate version of msbuild (in this particular case, it needs to be version 15).

Run msbuild /? to see which version you're using or where msbuild to check which location the environment takes the executable from and update (or point to the right location of) the tools if necessary.

Download the latest MSBuild tool from here.

Is it possible to ping a server from Javascript?

To keep your requests fast, cache the server side results of the ping and update the ping file or database every couple of minutes(or however accurate you want it to be). You can use cron to run a shell command with your 8 pings and write the output into a file, the webserver will include this file into your view.

Android Device Chooser -- device not showing up

Disable debugging mode and developer options in your phone.

Start Android device monitor.

Now enable developer options and debugging mode in your phone.

You should be able to see your device listed after this in android device monitor. There after you should be able to see it under Android device chooser.

Creating and Naming Worksheet in Excel VBA

Are you committing the cell before pressing the button (pressing Enter)? The contents of the cell must be stored before it can be used to name a sheet.

A better way to do this is to pop up a dialog box and get the name you wish to use.

JNI and Gradle in Android Studio

In the module build.gradle, in the task field, I get an error unless I use:

def ndkDir = plugins.getPlugin('com.android.application').sdkHandler.getNdkFolder()

I see people using

def ndkDir = android.plugin.ndkFolder

and

def ndkDir = plugins.getPlugin('com.android.library').sdkHandler.getNdkFolder()

but neither of those worked until I changed it to the plugin I was actually importing.

How to list all tags along with the full message in git?

git tag -l --format='%(contents)'

or

git for-each-ref refs/tags/ --format='%(contents)'

will output full annotation message for every tag (including signature if its signed).

  • %(contents:subject) will output only first line
  • %(contents:body) will output annotation without first line and signature (useful text only)
  • %(contents:signature) will output only PGP-signature

See more in man git-for-each-ref “Field names” section.

Regular Expression to match only alphabetic characters

If you need to include non-ASCII alphabetic characters, and if your regex flavor supports Unicode, then

\A\pL+\z

would be the correct regex.

Some regex engines don't support this Unicode syntax but allow the \w alphanumeric shorthand to also match non-ASCII characters. In that case, you can get all alphabetics by subtracting digits and underscores from \w like this:

\A[^\W\d_]+\z

\A matches at the start of the string, \z at the end of the string (^ and $ also match at the start/end of lines in some languages like Ruby, or if certain regex options are set).

How to call a parent method from child class in javascript?

How about something based on Douglas Crockford idea:

    function Shape(){}

    Shape.prototype.name = 'Shape';

    Shape.prototype.toString = function(){
        return this.constructor.parent
            ? this.constructor.parent.toString() + ',' + this.name
            : this.name;
    };


    function TwoDShape(){}

    var F = function(){};

    F.prototype = Shape.prototype;

    TwoDShape.prototype = new F();

    TwoDShape.prototype.constructor = TwoDShape;

    TwoDShape.parent = Shape.prototype;

    TwoDShape.prototype.name = '2D Shape';


    var my = new TwoDShape();

    console.log(my.toString()); ===> Shape,2D Shape

python JSON object must be str, bytes or bytearray, not 'dict

import json
data = json.load(open('/Users/laxmanjeergal/Desktop/json.json'))
jtopy=json.dumps(data) #json.dumps take a dictionary as input and returns a string as output.
dict_json=json.loads(jtopy) # json.loads take a string as input and returns a dictionary as output.
print(dict_json["shipments"])

How to get all the AD groups for a particular user?

I would like to say that Microsoft LDAP has some special ways to search recursively for all of memberships of a user.

  1. The Matching Rule you can specify for the "member" attribute. In particular, using the Microsoft Exclusive LDAP_MATCHING_RULE_IN_CHAIN rule for "member" attribute allows recursive/nested membership searching. The rule is used when you add it after the member attribute. Ex. (member:1.2.840.113556.1.4.1941:= XXXXX )

  2. For the same Domain as the Account, The filter can use <SID=S-1-5-21-XXXXXXXXXXXXXXXXXXXXXXX> instead of an Accounts DistinguishedName attribute which is very handy to use cross domain if needed. HOWEVER it appears you need to use the ForeignSecurityPrincipal <GUID=YYYY> as it will not resolve your SID as it appears the <SID=> tag does not consider ForeignSecurityPrincipal object type. You can use the ForeignSecurityPrincipal DistinguishedName as well.

Using this knowledge, you can LDAP query those hard to get memberships, such as the "Domain Local" groups an Account is a member of but unless you looked at the members of the group, you wouldn't know if user was a member.

//Get Direct+Indirect Memberships of User (where SID is XXXXXX)

string str = "(& (objectCategory=group)(member:1.2.840.113556.1.4.1941:=<SID=XXXXXX>) )";

//Get Direct+Indirect **Domain Local** Memberships of User (where SID is XXXXXX)

string str2 = "(& (objectCategory=group)(|(groupType=-2147483644)(groupType=4))(member:1.2.840.113556.1.4.1941:=<SID=XXXXXX>) )";

//TAA DAA



Feel free to try these LDAP queries after substituting the SID of a user you want to retrieve all group memberships of. I figure this is similiar if not the same query as what the PowerShell Command Get-ADPrincipalGroupMembership uses behind the scenes. The command states "If you want to search for local groups in another domain, use the ResourceContextServer parameter to specify the alternate server in the other domain."

If you are familiar enough with C# and Active Directory, you should know how to perform an LDAP search using the LDAP queries provided.

Additional Documentation:

Are there dictionaries in php?

http://php.net/manual/en/language.types.array.php

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

Standard arrays can be used that way.

Why use @Scripts.Render("~/bundles/jquery")

Bundling is all about compressing several JavaScript or stylesheets files without any formatting (also referred as minified) into a single file for saving bandwith and number of requests to load a page.

As example you could create your own bundle:

bundles.Add(New ScriptBundle("~/bundles/mybundle").Include(
            "~/Resources/Core/Javascripts/jquery-1.7.1.min.js",
            "~/Resources/Core/Javascripts/jquery-ui-1.8.16.min.js",
            "~/Resources/Core/Javascripts/jquery.validate.min.js",
            "~/Resources/Core/Javascripts/jquery.validate.unobtrusive.min.js",
            "~/Resources/Core/Javascripts/jquery.unobtrusive-ajax.min.js",
            "~/Resources/Core/Javascripts/jquery-ui-timepicker-addon.js"))

And render it like this:

@Scripts.Render("~/bundles/mybundle")

One more advantage of @Scripts.Render("~/bundles/mybundle") over the native <script src="~/bundles/mybundle" /> is that @Scripts.Render() will respect the web.config debug setting:

  <system.web>
    <compilation debug="true|false" />

If debug="true" then it will instead render individual script tags for each source script, without any minification.

For stylesheets you will have to use a StyleBundle and @Styles.Render().

Instead of loading each script or style with a single request (with script or link tags), all files are compressed into a single JavaScript or stylesheet file and loaded together.

SQL Server String or binary data would be truncated

Yes,I am also face these kind of problem.

REMARKS VARCHAR(500)
to
REMARKS VARCHAR(1000)

Here, I've change REMARKS filed length from 500 to 1000

Why is vertical-align:text-top; not working in CSS

position:absolute;
top:0px; 
margin:5px;

Solved my problem.

How to get the Display Name Attribute of an Enum member via MVC Razor code?

I'm sorry to do this, but I couldn't use any of the other answers as-is and haven't time to duke it out in the comments.

Uses C# 6 syntax.

static class EnumExtensions
{
    /// returns the localized Name, if a [Display(Name="Localised Name")] attribute is applied to the enum member
    /// returns null if there isnt an attribute
    public static string DisplayNameOrEnumName(this Enum value)
    // => value.DisplayNameOrDefault() ?? value.ToString()
    {
        // More efficient form of ^ based on http://stackoverflow.com/a/17034624/11635
        var enumType = value.GetType();
        var enumMemberName = Enum.GetName(enumType, value);
        return enumType
            .GetEnumMemberAttribute<DisplayAttribute>(enumMemberName)
            ?.GetName() // Potentially localized
            ?? enumMemberName; // Or fall back to the enum name
    }

    /// returns the localized Name, if a [Display] attribute is applied to the enum member
    /// returns null if there is no attribute
    public static string DisplayNameOrDefault(this Enum value) =>
        value.GetEnumMemberAttribute<DisplayAttribute>()?.GetName();

    static TAttribute GetEnumMemberAttribute<TAttribute>(this Enum value) where TAttribute : Attribute =>
        value.GetType().GetEnumMemberAttribute<TAttribute>(value.ToString());

    static TAttribute GetEnumMemberAttribute<TAttribute>(this Type enumType, string enumMemberName) where TAttribute : Attribute =>
        enumType.GetMember(enumMemberName).Single().GetCustomAttribute<TAttribute>();
}

How can I select from list of values in Oracle

Hi it is also possible for Strings with XML-Table

SELECT trim(COLUMN_VALUE) str FROM xmltable(('"'||REPLACE('a1, b2, a2, c1', ',', '","')||'"'));

malloc an array of struct pointers

array is a slightly misleading name. For a dynamically allocated array of pointers, malloc will return a pointer to a block of memory. You need to use Chess* and not Chess[] to hold the pointer to your array.

Chess *array = malloc(size * sizeof(Chess));
array[i] = NULL;

and perhaps later:

/* create new struct chess */
array[i] = malloc(sizeof(struct chess));

/* set up its members */
array[i]->size = 0;
/* etc. */

How to connect SQLite with Java?

connection = DriverManager.getConnection("jdbc:sqlite:D:\\testdb.db");

Instead of this put

connection = DriverManager.getConnection("jdbc:sqlite:D:\\testdb");

"Untrusted App Developer" message when installing enterprise iOS Application

In iOS 9.1 and lower, go to Settings - General - Profiles - tap on your Profile - tap on Trust button.

How to remove a file from the index in git?

Depending on your workflow, this may be the kind of thing that you need rarely enough that there's little point in trying to figure out a command-line solution (unless you happen to be working without a graphical interface for some reason).

Just use one of the GUI-based tools that support index management, for example:

  • git gui <-- uses the Tk windowing framework -- similar style to gitk
  • git cola <-- a more modern-style GUI interface

These let you move files in and out of the index by point-and-click. They even have support for selecting and moving portions of a file (individual changes) to and from the index.


How about a different perspective: If you mess up while using one of the suggested, rather cryptic, commands:

  • git rm --cached [file]
  • git reset HEAD <file>

...you stand a real chance of losing data -- or at least making it hard to find. Unless you really need to do this with very high frequency, using a GUI tool is likely to be safer.


Working without the index

Based on the comments and votes, I've come to realize that a lot of people use the index all the time. I don't. Here's how:

  • Commit my entire working copy (the typical case): git commit -a
  • Commit just a few files: git commit (list of files)
  • Commit all but a few modified files: git commit -a then amend via git gui
  • Graphically review all changes to working copy: git difftool --dir-diff --tool=meld

Pretty-Print JSON Data to a File using Python

import json
def writeToFile(logData, fileName, openOption="w"):
  file = open(fileName, openOption)
  file.write(json.dumps(json.loads(logData), indent=4)) 
  file.close()  

A valid provisioning profile for this executable was not found... (again)

  1. Delete all certificates from the keychain of the account which you are trying to use provisioning profile
  2. Delete Derived data
  3. Clean the folder(cmd+sht+alt+k)
  4. Clean the project(cmd+sht+k)
  5. Build & Run

Assign null to a SqlParameter

Try this:

SqlParameter[] parameters = new SqlParameter[1];    
SqlParameter planIndexParameter = new SqlParameter("@AgeIndex", SqlDbType.Int);

planIndexParameter.IsNullable = true; // Add this line

planIndexParameter.Value = (AgeItem.AgeIndex== null) ? DBNull.Value : AgeItem.AgeIndex== ;
parameters[0] = planIndexParameter;

Is there a short cut for going back to the beginning of a file by vi editor?

To go end of the file: press ESC

1) type capital G (Capital G)

2) press shift + g (small g)

To go top of the file there are the following ways: press ESC

1) press 1G (Capital G)

2) press gg (small g) or 1gg

3) You can jump to the particular line number,e.g wanted to go 1 line number, press 1 + G

What is the best way to generate a unique and short file name in Java

I'd use Apache Commons Lang library (http://commons.apache.org/lang).

There is a class org.apache.commons.lang.RandomStringUtils that can be used to generate random strings of given length. Very handy not only for filename generation!

Here is the example:

String ext = "dat";
File dir = new File("/home/pregzt");
String name = String.format("%s.%s", RandomStringUtils.randomAlphanumeric(8), ext);
File file = new File(dir, name);

SQL Server : Arithmetic overflow error converting expression to data type int

Is the problem with SUM(billableDuration)? To find out, try commenting out that line and see if it works.

It could be that the sum is exceeding the maximum int. If so, try replacing it with SUM(CAST(billableDuration AS BIGINT)).

Trying to get property of non-object MySQLi result

$sql = "SELECT * FROM table";
$result = $conn->query($sql);

if (!$result) {
    trigger_error('Invalid query: ' . $conn->error);
}

check the error with mysqli_error() function

probably your query has some faults.

How to convert float value to integer in php?

Use round()

$float_val = 4.5;

echo round($float_val);

You can also set param for precision and rounding mode, for more info

Update (According to your updated question):

$float_val = 1.0000124668092E+14;
printf('%.0f', $float_val / 1E+14); //Output Rounds Of To 1000012466809201

How can I enable MySQL's slow query log without restarting MySQL?

These work

SET GLOBAL LOG_SLOW_TIME = 1;
SET GLOBAL LOG_QUERIES_NOT_USING_INDEXES = ON;

Broken on my setup 5.1.42

SET GLOBAL LOG_SLOW_QUERIES = ON;
SET GLOBAL SLOW_QUERY_LOG = ON;
set @@global.log_slow_queries=1;

http://bugs.mysql.com/bug.php?id=32565

Looks like the best way to do this is set log_slow_time very high thus "turning off" the slow query log. Lower log_slow_time to enable it. Use the same trick (set to OFF) for log_queries_not_using_indexes.

How to remove any URL within a string in Python

This solution caters for http, https and the other normal url type special characters :

import re
def remove_urls (vTEXT):
    vTEXT = re.sub(r'(https|http)?:\/\/(\w|\.|\/|\?|\=|\&|\%)*\b', '', vTEXT, flags=re.MULTILINE)
    return(vTEXT)


print( remove_urls("this is a test https://sdfs.sdfsdf.com/sdfsdf/sdfsdf/sd/sdfsdfs?bob=%20tree&jef=man lets see this too https://sdfsdf.fdf.com/sdf/f end"))

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

In my case I misspelled , I was referring as ngmodel istead of ngModel :) Hope It helps!

Expected - [(ngModel)] Actual - [(ngmodel)]

Get size of all tables in database

I added a few more columns on top of marc_s answer:

with fs
as
(
select i.object_id,
        p.rows AS RowCounts,
        SUM(a.total_pages) * 8 AS TotalSpaceKb
from     sys.indexes i INNER JOIN 
        sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id INNER JOIN 
         sys.allocation_units a ON p.partition_id = a.container_id
WHERE 
    i.OBJECT_ID > 255 
GROUP BY 
    i.object_id,
    p.rows
)

SELECT 
    t.NAME AS TableName,
    fs.RowCounts,
    fs.TotalSpaceKb,
    t.create_date,
    t.modify_date,
    ( select COUNT(1)
        from sys.columns c 
        where c.object_id = t.object_id ) TotalColumns    
FROM 
    sys.tables t INNER JOIN      
    fs  ON t.OBJECT_ID = fs.object_id
WHERE 
    t.NAME NOT LIKE 'dt%' 
    AND t.is_ms_shipped = 0
ORDER BY 
    t.Name

generate a random number between 1 and 10 in c

Here is a ready to run source code for random number generator using c taken from this site: http://www.random-number.com/random-number-c/ . The implementation here is more general (a function that gets 3 parameters: min,max and number of random numbers to generate)

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

// the random function
void RandomNumberGenerator(const int nMin, const int nMax, const int  nNumOfNumsToGenerate)
{
  int nRandonNumber = 0;
  for (int i = 0; i < nNumOfNumsToGenerate; i++)
  {
    nRandonNumber = rand()%(nMax-nMin) + nMin;
    printf("%d ", nRandonNumber);
  }
  printf("\n");
}

void main()
{
  srand(time(NULL));
  RandomNumberGenerator(1,70,5);
}

Get number days in a specified month using JavaScript?

Another possible option would be to use Datejs

Then you can do

Date.getDaysInMonth(2009, 9)     

Although adding a library just for this function is overkill, it's always nice to know all the options you have available to you :)

from jquery $.ajax to angular $http

We can implement ajax request by using http service in AngularJs, which helps to read/load data from remote server.

$http service methods are listed below,

 $http.get()
 $http.post()
 $http.delete()
 $http.head()
 $http.jsonp()
 $http.patch()
 $http.put()

One of the Example:

    $http.get("sample.php")
        .success(function(response) {
            $scope.getting = response.data; // response.data is an array
    }).error(){

        // Error callback will trigger
    });

http://www.drtuts.com/ajax-requests-angularjs/

What does question mark and dot operator ?. mean in C# 6.0?

It can be very useful when flattening a hierarchy and/or mapping objects. Instead of:

if (Model.Model2 == null
  || Model.Model2.Model3 == null
  || Model.Model2.Model3.Model4 == null
  || Model.Model2.Model3.Model4.Name == null)
{
  mapped.Name = "N/A"
}
else
{
  mapped.Name = Model.Model2.Model3.Model4.Name;
}

It can be written like (same logic as above)

mapped.Name = Model.Model2?.Model3?.Model4?.Name ?? "N/A";

DotNetFiddle.Net Working Example.

(the ?? or null-coalescing operator is different than the ? or null conditional operator).

It can also be used out side of assignment operators with Action. Instead of

Action<TValue> myAction = null;

if (myAction != null)
{
  myAction(TValue);
}

It can be simplified to:

myAction?.Invoke(TValue);

DotNetFiddle Example:

using System;

public class Program
{
  public static void Main()
  {
    Action<string> consoleWrite = null;

    consoleWrite?.Invoke("Test 1");

    consoleWrite = (s) => Console.WriteLine(s);

    consoleWrite?.Invoke("Test 2");
  }
}

Result:

Test 2

Pressed <button> selector

You can do this if you use an <a> tag instead of a button. I know it's not exactly what you asked for, but it might give you some other options if you cannot find a solution to this:

Borrowing from a demo from another answer here I produced this:

_x000D_
_x000D_
a {_x000D_
  display: block;_x000D_
  font-size: 18px;_x000D_
  border: 2px solid gray;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  text-align: center;_x000D_
  line-height: 100px;_x000D_
}_x000D_
_x000D_
a:active {_x000D_
  font-size: 18px;_x000D_
  border: 2px solid green;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
a:target {_x000D_
  font-size: 18px;_x000D_
  border: 2px solid red;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<a id="btn" href="#btn">Demo</a>
_x000D_
_x000D_
_x000D_

Notice the use of :target; this will be the style applied when the element is targeted via the hash. Which also means your HTML will need to be this: <a id="btn" href="#btn">Demo</a> a link targeting itself. and the demo http://jsfiddle.net/rlemon/Awdq5/4/

Thanks to @BenjaminGruenbaum here is a better demo: http://jsfiddle.net/agzVt/

Also, as a footnote: this should really be done with JavaScript and applying / removing CSS classes from the element. It would be much less convoluted.

nodemon not working: -bash: nodemon: command not found

Put --exec arg in single quotation.

e.g. I changed "nodemon --exec yarn build-langs" to "nodemon --exec 'yarn build-langs'" and worked.

How can I create a blank/hardcoded column in a sql query?

Thank you, in PostgreSQL this works for boolean

SELECT
hat,
shoe,
boat,
false as placeholder
FROM
objects

How can you get the first digit in an int (C#)?

Try this

public int GetFirstDigit(int number) {
  if ( number < 10 ) {
    return number;
  }
  return GetFirstDigit ( (number - (number % 10)) / 10);
}

EDIT

Several people have requested the loop version

public static int GetFirstDigitLoop(int number)
{
    while (number >= 10)
    {
        number = (number - (number % 10)) / 10;
    }
    return number;
}

How to generate a random string of 20 characters

Here you go. Just specify the chars you want to allow on the first line.

char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 20; i++) {
    char c = chars[random.nextInt(chars.length)];
    sb.append(c);
}
String output = sb.toString();
System.out.println(output);

If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use java.security.SecureRandom instead. Values produced by java.util.Random and java.util.concurrent.ThreadLocalRandom are mathematically predictable.

How to get absolute path to file in /resources folder of your project

There are two problems on our way to the absolute path:

  1. The placement found will be not where the source files lie, but where the class is saved. And the resource folder almost surely will lie somewhere in the source folder of the project.
  2. The same functions for retrieving the resource work differently if the class runs in a plugin or in a package directly in the workspace.

The following code will give us all useful paths:

    URL localPackage = this.getClass().getResource("");
    URL urlLoader = YourClassName.class.getProtectionDomain().getCodeSource().getLocation();
    String localDir = localPackage.getPath();
    String loaderDir = urlLoader.getPath();
    System.out.printf("loaderDir = %s\n localDir = %s\n", loaderDir, localDir);

Here both functions that can be used for localization of the resource folder are researched. As for class, it can be got in either way, statically or dynamically.


If the project is not in the plugin, the code if run in JUnit, will print:

loaderDir = /C:.../ws/source.dir/target/test-classes/
 localDir = /C:.../ws/source.dir/target/test-classes/package/

So, to get to src/rest/resources we should go up and down the file tree. Both methods can be used. Notice, we can't use getResource(resourceFolderName), for that folder is not in the target folder. Nobody puts resources in the created folders, I hope.


If the class is in the package that is in the plugin, the output of the same test will be:

loaderDir = /C:.../ws/plugin/bin/
 localDir = /C:.../ws/plugin/bin/package/

So, again we should go up and down the folder tree.


The most interesting is the case when the package is launched in the plugin. As JUnit plugin test, for our example. The output is:

loaderDir = /C:.../ws/plugin/
 localDir = /package/

Here we can get the absolute path only combining the results of both functions. And it is not enough. Between them we should put the local path of the place where the classes packages are, relatively to the plugin folder. Probably, you will have to insert something as src or src/test/resource here.

You can insert the code into yours and see the paths that you have.

React - Display loading screen while DOM is rendering?

I'm also using React in my app. For requests I'm using axios interceptors, so great way to make loader screen (fullpage as you showed an example) is to add class or id to for example body inside interceptors (here code from official documentation with some custom code):

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
     document.body.classList.add('custom-loader');
     return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
       document.body.classList.remove('custom-loader');
       return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  }); 

And then just implement in CSS your loader with pseudo-elements (or add class or id to different element, not body as you like) - you can set color of background to opaque or transparent, etc... Example:

custom-loader:before {
    background: #000000;
    content: "";
    position: fixed;
    ...
}

custom-loader:after {
    background: #000000;
    content: "Loading content...";
    position: fixed;
    color: white;
    ...
}

How do I load an HTML page in a <div> using JavaScript?

showhide.html

<!DOCTYPE html>
<html>
    <head>
      <script type="text/javascript">
        function showHide(switchTextDiv, showHideDiv)
        {
          var std = document.getElementById(switchTextDiv);
          var shd = document.getElementById(showHideDiv);
          if (shd.style.display == "block")
          {
            shd.style.display = "none";
            std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>"; 
          }
          else
          {
            if (shd.innerHTML.length <= 0)
            {
              shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
            }
            shd.style.display = "block";
            std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
          }
        }
      </script>
    </head>
    <body>
      <a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
        <span style="display: block; background-color: yellow">Show</span>
      </a>
      <div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
    </body>
</html>

showhide_embedded.html

<!DOCTYPE html>
<html>
    <head>
      <script type="text/javascript"> 
        function load()
        {
          var ts = document.getElementById("theString");
          ts.scrollIntoView(true);
        }
      </script>
    </head>
    <body onload="load()">
      <pre>
        some text 1
        some text 2
        some text 3
        some text 4
        some text 5
        <span id="theString" style="background-color: yellow">some text 6 highlight</span>
        some text 7
        some text 8
        some text 9
      </pre>
    </body>
</html>

Move an array element from one array position to another

Array.move.js

Summary

Moves elements within an array, returning an array containing the moved elements.

Syntax

array.move(index, howMany, toIndex);

Parameters

index: Index at which to move elements. If negative, index will start from the end.

howMany: Number of elements to move from index.

toIndex: Index of the array at which to place the moved elements. If negative, toIndex will start from the end.

Usage

array = ["a", "b", "c", "d", "e", "f", "g"];

array.move(3, 2, 1); // returns ["d","e"]

array; // returns ["a", "d", "e", "b", "c", "f", "g"]

Polyfill

Array.prototype.move || Object.defineProperty(Array.prototype, "move", {
    value: function (index, howMany, toIndex) {
        var
        array = this,
        index = parseInt(index) || 0,
        index = index < 0 ? array.length + index : index,
        toIndex = parseInt(toIndex) || 0,
        toIndex = toIndex < 0 ? array.length + toIndex : toIndex,
        toIndex = toIndex <= index ? toIndex : toIndex <= index + howMany ? index : toIndex - howMany,
        moved;

        array.splice.apply(array, [toIndex, 0].concat(moved = array.splice(index, howMany)));

        return moved;
    }
});

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

Replacing backslashes with forward slashes with str_replace() in php

Single quoted php string variable works.

$str = 'http://www.domain.com/data/images\flags/en.gif';
$str = str_replace('\\', '/', $str);

Use virtualenv with Python with Visual Studio Code in Ubuntu

As of September 2016 (according to the GitHub repository documentation of the extension) you can just execute a command from within Visual Studio Code that will let you select the interpreter from an automatically generated list of known interpreters (including the one in your project's virtual environment).

How can I use this feature?

  • Select the command Python: Select Workspace Interpreter(*) from the command palette (F1).
  • Upon selecting the above command a list of discovered interpreters will be displayed in a quick pick list.
  • Selecting an interpreter from this list will update the settings.json file automatically.

(*) This command has been updated to Python: Select Interpreter in the latest release of Visual Studio Code (thanks @nngeek).

Also, notice that your selected interpreter will be shown at the left side of the statusbar, e.g., Python 3.6 64-bit. This is a button you can click to trigger the Select Interpreter feature.

Oracle JDBC intermittent Connection Issue

Other thing that was causing me this problem was having the HOSTNAME settings wrong. My connection attempt was hanged at:

"main" prio=10 tid=0x00007f7cc8009000 nid=0x2f3a runnable [0x00007f7cce69e000]
   java.lang.Thread.State: RUNNABLE
        at java.net.Inet4AddressImpl.getLocalHostName(Native Method)
        at java.net.InetAddress.getLocalHost(InetAddress.java:1444)
        at sun.security.provider.SeedGenerator$1.run(SeedGenerator.java:176)
        at sun.security.provider.SeedGenerator$1.run(SeedGenerator.java:162)
        at java.security.AccessController.doPrivileged(Native Method)

So make sure you have an entry for your hostname in /etc/hosts/.

If you issue a hostname command like this:

$ hostname
my.server.com

You need a line in your /etc/hosts:

127.0.0.1 my my.server.com

How to check if a DateTime field is not null or empty?

DateTime is not standard nullable type. If you want assign null to DateTime type of variable, you have to use DateTime? type which supports null value.

If you only want test your variable to be set (e.g. variable holds other than default value), you can use keyword "default" like in following code:

if (dateTimeVariable == default(DateTime))
{
    //do work for dateTimeVariable == null situation
}

How to break out of multiple loops?

Introduce a new variable that you'll use as a 'loop breaker'. First assign something to it(False,0, etc.), and then, inside the outer loop, before you break from it, change the value to something else(True,1,...). Once the loop exits make the 'parent' loop check for that value. Let me demonstrate:

breaker = False #our mighty loop exiter!
while True:
    while True:
        if conditionMet:
            #insert code here...
            breaker = True 
            break
    if breaker: # the interesting part!
        break   # <--- !

If you have an infinite loop, this is the only way out; for other loops execution is really a lot faster. This also works if you have many nested loops. You can exit all, or just a few. Endless possibilities! Hope this helped!

Change div height on button click

Just remove the "px" in the style.height assignation, like:

<button type="button" onClick = "document.getElementById('chartdiv').style.height = 200px"> </button>

Should be

<button type="button" onClick = "document.getElementById('chartdiv').style.height = 200">Click Me!</button>

Open new popup window without address bars in firefox & IE

Firefox 3.0 and higher have disabled setting location by default. resizable and status are also disabled by default. You can verify this by typing `about:config' in your address bar and filtering by "dom". The items of interest are:

  • dom.disable_window_open_feature.location
  • dom.disable_window_open_feature.resizable
  • dom.disable_window_open_feature.status

You can get further information at the Mozilla Developer site. What this basically means, though, is that you won't be able to do what you want to do.

One thing you might want to do (though it won't solve your problem), is put quotes around your window feature parameters, like so:

window.open('/pageaddress.html','winname','directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=350');

Delete with "Join" in Oracle sql Query

Use a subquery in the where clause. For a delete query requirig a join, this example will delete rows that are unmatched in the joined table "docx_document" and that have a create date > 120 days in the "docs_documents" table.

delete from docs_documents d
where d.id in (
    select a.id from docs_documents a
    left join docx_document b on b.id = a.document_id
    where b.id is null
        and floor(sysdate - a.create_date) > 120
 );

Internal vs. Private Access Modifiers

internal members are visible to all code in the assembly they are declared in.
(And to other assemblies referenced using the [InternalsVisibleTo] attribute)

private members are visible only to the declaring class. (including nested classes)

An outer (non-nested) class cannot be declared private, as there is no containing scope to make it private to.

To answer the question you forgot to ask, protected members are like private members, but are also visible in all classes that inherit the declaring type. (But only on an expression of at least the type of the current class)

Showing all errors and warnings

I was able to get all errors via the below code:

ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);

MySQL connection not working: 2002 No such file or directory

If you use Linux: the path to the mysql.sock file is wrong. This is usually because you are using (LAMPP) XAMPP and it isn't in /tmp/mysql.sock

Open the php.ini file and find this line:

mysql.default_socket

And make it

mysql.default_socket = /path/to/mysql.sock

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

It is important that the Main method is placed in the class that is properly configured in Visual Studio as a start-up object:

  • Right-click your project in project explorer; choose "Properties..."
  • In the properties dialog, choose "Application" tab
  • In the application tab, choose SimpleAIMLEditor.Program from the drop-down for your start-up object

Now run your application again. The error will disappear.

C++ - Hold the console window open?

hey first of all to include c++ functions you should use

include<iostream.h> instead of stdio .h

and to hold the output screen there is a simple command getch();
here, is an example:
   #include<iostream.h>
   #include<conio.h>
   void main()  \\or int main(); if you want
  {
    cout<<"c# is more advanced than c++";
    getch();
  }

thank you

How to set transparent background for Image Button in code?

Do it in your xml

<ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButtonSettings"
        android:layout_gravity="right|bottom"
        android:src="@drawable/tabbar_settings_icon"
        android:background="@android:color/transparent"/>

Bash Templating: How to build configuration files from templates with Bash?

Here is another solution: generate a bash script with all the variables and the contents of the template file, that script would look like this:

word=dog           
i=1                
cat << EOF         
the number is ${i} 
the word is ${word}

EOF                

If we feed this script into bash it would produce the desired output:

the number is 1
the word is dog

Here is how to generate that script and feed that script into bash:

(
    # Variables
    echo word=dog
    echo i=1

    # add the template
    echo "cat << EOF"
    cat template.txt
    echo EOF
) | bash

Discussion

  • The parentheses opens a sub shell, its purpose is to group together all the output generated
  • Within the sub shell, we generate all the variable declarations
  • Also in the sub shell, we generate the cat command with HEREDOC
  • Finally, we feed the sub shell output to bash and produce the desired output
  • If you want to redirect this output into a file, replace the last line with:

    ) | bash > output.txt
    

How to convert string to long

Do this:

long l = Long.parseLong(str);

However, always check that str contains digits to prevent throwing exceptions. For instance:

String str="ABCDE";
long l = Long.parseLong(str);

would throw an exception but this

String str="1234567";
long l = Long.parseLong(str);

won't.

Group By Eloquent ORM

Laravel 5

This is working for me (i use laravel 5.6).

$collection = MyModel::all()->groupBy('column');

If you want to convert the collection to plain php array, you can use toArray()

$array = MyModel::all()->groupBy('column')->toArray();

How do I make a Docker container start automatically on system boot?

If you want the container to be started even if no user has performed a login (like the VirtualBox VM that I only start and don't want to login each time). Here are the steps I performed to for Ubuntu 16.04 LTS. As an example, I installed a oracle db container:

$ docker pull alexeiled/docker-oracle-xe-11g
$ docker run -d --name=MYPROJECT_oracle_db --shm-size=2g -p 1521:1521 -p 8080:8080 alexeiled/docker-oracle-xe-11g
$ vim /etc/systemd/system/docker-MYPROJECT-oracle_db.service

and add the following content:

[Unit]
Description=Redis container
Requires=docker.service
After=docker.service

[Service]
Restart=always
ExecStart=/usr/bin/docker start -a MYPROJECT_oracle_db
ExecStop=/usr/bin/docker stop -t 2 MYPROJECT_oracle_db

[Install]
WantedBy=default.target

and enable the service at startup

sudo systemctl enable docker-MYPROJECT-oracle_db.service

For more informations https://docs.docker.com/engine/admin/host_integration/

How do I make a relative reference to another workbook in Excel?

The only solutions that I've seen to organize the external files into sub-folders has required the use of VBA to resolve a full path to the external file in the formulas. Here is a link to a site with several examples others have used:

http://www.teachexcel.com/excel-help/excel-how-to.php?i=415651

Alternatively, if you can place all of the files in the same folder instead of dividing them into sub-folders, then Excel will resolve the external references without requiring the use of VBA even if you move the files to a network location. Your formulas then become simply ='[ComponentsC.xlsx]Sheet1'!A1 with no folder names to traverse.