Programs & Examples On #Database caching

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

select to_char(to_date('1/21/2000','mm/dd/yyyy'),'dd-mm-yyyy') from dual

Find all files with a filename beginning with a specified string?

Use find with a wildcard:

find . -name 'mystring*'

Sorting dropdown alphabetically in AngularJS

var module = angular.module("example", []);

module.controller("orderByController", function ($scope) {
    $scope.orderByValue = function (value) {
        return value;
    };

    $scope.items = ["c", "b", "a"];
    $scope.objList = [
        {
            "name": "c"
        }, {
            "name": "b"
        }, {
            "name": "a"
        }];
        $scope.item = "b";
    });

http://jsfiddle.net/Nfv42/65/

Reducing video size with same format and reducing frame size

ffmpeg -i <input.mp4> -b:v 2048k -s 1000x600 -fs 2048k -vcodec mpeg4 -acodec copy <output.mp4>
  • -i input file

  • -b:v videobitrate of output video in kilobytes (you have to try)

  • -s dimensions of output video

  • -fs FILESIZE of output video in kilobytes

  • -vcodec videocodec (use ffmpeg -codecs to list all available codecs)

  • -acodec audio codec for output video (only copy the audiostream, don't temper)

How to retrieve checkboxes values in jQuery

Try this one..

var listCheck = [];
console.log($("input[name='YourCheckBokName[]']"));
$("input[name='YourCheckBokName[]']:checked").each(function() {
     console.log($(this).val());
     listCheck .push($(this).val());
});
console.log(listCheck);

How to set placeholder value using CSS?

Some type of input hasn't got the :after or :before pseudo-element, so you can use a background-image with an SVG text element:

    input {
       background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='50px' width='120px'><text x='0' y='15' fill='gray' font-size='15'>Type Something...</text></svg>");
       background-repeat: no-repeat;
    }

    input:focus {
       background-image: none;
    }

My codepen: https://codepen.io/Scario/pen/BaagbeZ

What is a file with extension .a?

.a files are created with the ar utility, and they are libraries. To use it with gcc, collect all .a files in a lib/ folder and then link with -L lib/ and -l<name of specific library>.

Collection of all .a files into lib/ is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.

how to sort order of LEFT JOIN in SQL query?

Try using MAX with a GROUP BY.

SELECT u.userName, MAX(c.carPrice)
FROM users u
    LEFT JOIN cars c ON u.id = c.belongsToUser
WHERE u.id = 4;
GROUP BY u.userName;

Further information on GROUP BY

The group by clause is used to split the selected records into groups based on unique combinations of the group by columns. This then allows us to use aggregate functions (eg. MAX, MIN, SUM, AVG, ...) that will be applied to each group of records in turn. The database will return a single result record for each grouping.

For example, if we have a set of records representing temperatures over time and location in a table like this:

Location   Time    Temperature
--------   ----    -----------
London     12:00          10.0
Bristol    12:00          12.0
Glasgow    12:00           5.0
London     13:00          14.0
Bristol    13:00          13.0
Glasgow    13:00           7.0
...

Then if we want to find the maximum temperature by location, then we need to split the temperature records into groupings, where each record in a particular group has the same location. We then want to find the maximum temperature of each group. The query to do this would be as follows:

SELECT Location, MAX(Temperature)
FROM Temperatures
GROUP BY Location;

ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

I can't see that you're adding these controls to the control hierarchy. Try:

Controls.Add ( ddlCountries );
Controls.Add ( ddlStates );

Events won't be invoked unless the control is part of the control hierarchy.

Is there a naming convention for MySQL?

as @fabrizio-valencia said use lower case. in windows if you export mysql database (phpmyadmin) the tables name will converted to lower case and this lead to all sort of problems. see Are table names in MySQL case sensitive?

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

Oracle SQL Developer spool output?

I was trying things to duplicate the spools you get from sqlplus. I found the following and hope it helps:

Create your sql script file ie:

Please note the echo and serveroutput.

Test_Spool.SQL

Spool 'c:\temp\Test1.txt';
set echo on;
set serveroutput on;
declare
sqlresult varchar2(60);

begin
  select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') into sqlresult from dual;
  dbms_output.put_line('The date is ' || sqlresult);
end;

/

Spool off;
set serveroutput off;
set echo off;

Run the script from another worksheet:

@TEST_Spool.SQL

My output from the Test1.txt

set serveroutput on
declare
sqlresult varchar2(60);

begin
  select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') into sqlresult from dual;
  dbms_output.put_line('The date is ' || sqlresult);
end;

anonymous block completed

The date is 2016-04-07 09:21:32

Spool of

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

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


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


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

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

Guid is all 0's (zeros)?

In the spirit of being complete, the answers that instruct you to use Guid.NewGuid() are correct.

In addressing your subsequent edit, you'll need to post the code for your RequestObject class. I'm suspecting that your guid property is not marked as a DataMember, and thus is not being serialized over the wire. Since default(Guid) is the same as new Guid() (i.e. all 0's), this would explain the behavior you're seeing.

How to read from input until newline is found using scanf()?

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

int main(void)
{
  int i = 0;
  char *a = (char *) malloc(sizeof(char) * 1024);
  while (1) {
    scanf("%c", &a[i]);
    if (a[i] == '\n') {
      break;
    }
    else {
      i++;
    }
  }
  a[i] = '\0';
  i = 0;
  printf("\n");
  while (a[i] != '\0') {
    printf("%c", a[i]);
    i++;
  }
  free(a);
  getch();
  return 0;
}

How can I label points in this scatterplot?

Your call to text() doesn't output anything because you inverted your x and your y:

plot(abs_losses, percent_losses, 
     main= "Absolute Losses vs. Relative Losses(in%)",
     xlab= "Losses (absolute, in miles of millions)",
     ylab= "Losses relative (in % of January´2007 value)",
     col= "blue", pch = 19, cex = 1, lty = "solid", lwd = 2)

text(abs_losses, percent_losses, labels=namebank, cex= 0.7)

Now if you want to move your labels down, left, up or right you can add argument pos= with values, respectively, 1, 2, 3 or 4. For instance, to place your labels up:

 text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=3)

enter image description here

You can of course gives a vector of value to pos if you want some of the labels in other directions (for instance for Goldman_Sachs, UBS and Société_Generale since they are overlapping with other labels):

 pos_vector <- rep(3, length(namebank))
 pos_vector[namebank %in% c("Goldman_Sachs", "Societé_Generale", "UBS")] <- 4
 text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=pos_vector)

enter image description here

How to ensure that there is a delay before a service is started in systemd?

The systemd way to do this is to have the process "talk back" when it's setup somehow, like by opening a socket or sending a notification (or a parent script exiting). Which is of course not always straight-forward especially with third party stuff :|

You might be able to do something inline like

ExecStart=/bin/bash -c '/bin/start_cassandra &; do_bash_loop_waiting_for_it_to_come_up_here'

or a script that does the same. Or put do_bash_loop_waiting_for_it_to_come_up_here in an ExecStartPost

Or create a helper .service that waits for it to come up, so the helper service depends on cassandra, and waits for it to come up, then your other process can depend on the helper service.

(May want to increase TimeoutStartSec from the default 90s as well)

How to detect when keyboard is shown and hidden

Swift 4:

  NotificationCenter.default.addObserver( self, selector: #selector(ControllerClassName.keyboardWillShow(_:)),
  name: Notification.Name.UIKeyboardWillShow,
  object: nil)
  NotificationCenter.default.addObserver(self, selector: #selector(ControllerClassName.keyboardWillHide(_:)),
  name: Notification.Name.UIKeyboardWillHide,
  object: nil)

Next, adding method to stop listening for notifications when the object’s life ends:-

Then add the promised methods from above to the view controller:
deinit {
  NotificationCenter.default.removeObserver(self)
}
func adjustKeyboardShow(_ open: Bool, notification: Notification) {
  let userInfo = notification.userInfo ?? [:]
  let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
  let height = (keyboardFrame.height + 20) * (open ? 1 : -1)
  scrollView.contentInset.bottom += height
  scrollView.scrollIndicatorInsets.bottom += height
}

@objc func keyboardWillShow(_ notification: Notification) {
  adjustKeyboardShow(true, notification: notification)
}
@objc func keyboardWillHide(_ notification: Notification) {
  adjustKeyboardShow(false, notification: notification)
}

Doctrine query builder using inner join with conditions

I'm going to answer my own question.

  1. innerJoin should use the keyword "WITH" instead of "ON" (Doctrine's documentation [13.2.6. Helper methods] is inaccurate; [13.2.5. The Expr class] is correct)
  2. no need to link foreign keys in join condition as they're already specified in the entity mapping.

Therefore, the following works for me

$qb->select('c')
    ->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
    ->where('c.username = :username');

or

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
    ->where('c.username = :username');

generate random double numbers in c++

This solution requires C++11 (or TR1).

#include <random>

int main()
{
   double lower_bound = 0;
   double upper_bound = 10000;
   std::uniform_real_distribution<double> unif(lower_bound,upper_bound);
   std::default_random_engine re;
   double a_random_double = unif(re);

   return 0;
}

For more details see John D. Cook's "Random number generation using C++ TR1".

See also Stroustrup's "Random number generation".

How to pass the password to su/sudo/ssh without overriding the TTY?

I wrote some Applescript which prompts for a password via a dialog box and then builds a custom bash command, like this:

echo <password> | sudo -S <command>

I'm not sure if this helps.

It'd be nice if sudo accepted a pre-encrypted password, so I could encrypt it within my script and not worry about echoing clear text passwords around. However this works for me and my situation.

How to easily import multiple sql files into a MySQL database?

just type:

cat *.sql |mysql -uroot -p

and mysql will import all the sql file in sequence

Clear back stack using fragments

Reading the documentation and studying what the fragment id is, it appears to simply be the stack index, so this works:

fragmentManager.popBackStackImmediate(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);

Zero (0) is the the bottom of the stack, so popping up to it inclusive clears the stack.

CAVEAT: Although the above works in my program, I hesitate a bit because the FragmentManager documentation never actually states that the id is the stack index. It makes sense that it would be, and all my debug logs bare out that it is, but perhaps in some special circumstance it would not? Can any one confirm this one way or the other? If it is, then the above is the best solution. If not, this is the alternative:

while(fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStackImmediate(); }

How do I remove whitespace from the end of a string in Python?

You can use strip() or split() to control the spaces values as in the following:

words = "   first  second   "

# Remove end spaces
def remove_end_spaces(string):
    return "".join(string.rstrip())


# Remove the first and end spaces
def remove_first_end_spaces(string):
    return "".join(string.rstrip().lstrip())


# Remove all spaces
def remove_all_spaces(string):
    return "".join(string.split())


# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))

Is it possible to cherry-pick a commit from another git repository?

Assuming A is the repo you want to cherry-pick from, and B is the one you want to cherry-pick to, you can do this by adding </path/to/repo/A/>/.git/objects to </path/to/repo/B>/.git/objects/info/alternates. Create this alternates files if it does not exist.

This will make repo B access all git objects from repo A, and will make cherry-pick work for you.

How to check if a variable is empty in python?

See section 5.1:

http://docs.python.org/library/stdtypes.html

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

None

False

zero of any numeric type, for example, 0, 0L, 0.0, 0j.

any empty sequence, for example, '', (), [].

any empty mapping, for example, {}.

instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False. [1]

All other values are considered true — so objects of many types are always true.

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

posting hidden value

You should never assume register_global_variables is turned on. Even if it is, it's deprecated and you should never use it that way.

Refer directly to the $_POST or $_GET variables. Most likely your form is POSTing, so you'd want your code to look something along the lines of this:

<input type="hidden" name="date" id="hiddenField" value="<?php echo $_POST['date'] ?>" />

If this doesn't work for you right away, print out the $_POST or $_GET variable on the page that would have the hidden form field and determine exactly what you want and refer to it.

echo "<pre>";
print_r($_POST);
echo "</pre>";

turn typescript object into json string

Just use JSON.stringify(object). It's built into Javascript and can therefore also be used within Typescript.

Android - Share on Facebook, Twitter, Mail, ecc

sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"your subject" );
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "your text");
startActivity(Intent.createChooser(sharingIntent, ""));

How to position a div scrollbar on the left hand side?

I have the same problem. but when i add direction: rtl; in tabs and accordion combo but it crashes my structure.

The way to do it is add div with direction: rtl; as parent element, and for child div set direction: ltr;.

I use this first https://api.jquery.com/wrap/

$( ".your selector of child element" ).wrap( "<div class='scroll'></div>" );

then just simply work with css :)

In children div add to css

 .your_class {
            direction: ltr;    
        }

And to parent div added by jQuery with class .scroll

.scroll {
            unicode-bidi:bidi-override;
            direction: rtl;
            overflow: scroll;
            overflow-x: hidden!important;
        }

Works prefect for me

http://jsfiddle.net/jw3jsz08/1/

How do I list all tables in all databases in SQL Server in a single result set?

I posted an answer a while back here that you could use here. The outline is:

  • Create a temp table
  • Call sp_msForEachDb
  • The query run against each DB stores the data in the temp table
  • When done, query the temp table

How to know the git username and email saved during configuration?

Sometimes above solutions doesn't work in macbook to get username n password.

IDK why?, here i got another solution.

$ git credential-osxkeychain get
host=github.com
protocol=https

this will revert username and password

Order Bars in ggplot2 bar graph

Another alternative using reorder to order the levels of a factor. In ascending (n) or descending order (-n) based on the count. Very similar to the one using fct_reorder from the forcats package:

Descending order

df %>%
  count(Position) %>%
  ggplot(aes(x = reorder(Position, -n), y = n)) +
  geom_bar(stat = 'identity') +
  xlab("Position")

enter image description here

Ascending order

df %>%
  count(Position) %>%
  ggplot(aes(x = reorder(Position, n), y = n)) +
  geom_bar(stat = 'identity') +
  xlab("Position")

enter image description here

Data frame:

df <- structure(list(Position = structure(c(3L, 3L, 1L, 1L, 1L, 2L), .Label = c("Defense", 
"Striker", "Zoalkeeper"), class = "factor"), Name = structure(c(2L, 
1L, 3L, 5L, 4L, 6L), .Label = c("Frank", "James", "Jean", "John", 
"Steve", "Tim"), class = "factor")), class = "data.frame", row.names = c(NA, 
-6L))

Div Background Image Z-Index Issue

For z-index to work, you also need to give it a position:

header {
    width: 100%;
    height: 100px;
    background: url(../img/top.png) repeat-x;
    z-index: 110;
    position: relative;
}

Determining whether an object is a member of a collection in VBA

This is an old question. I have carefully reviewed all the answers and comments, tested the solutions for performance.

I came up with the fastest option for my environment which does not fail when a collection has objects as well as primitives.

Public Function ExistsInCollection(col As Collection, key As Variant) As Boolean
    On Error GoTo err
    ExistsInCollection = True
    IsObject(col.item(key))
    Exit Function
err:
    ExistsInCollection = False
End Function

In addition, this solution does not depend on hard-coded error values. So the parameter col As Collection can be substituted by some other collection type variable, and the function must still work. E.g., on my current project, I will have it as col As ListColumns.

"No such file or directory" but it exists

As mentioned by others, this is because the loader can't be found, not your executable file. Unfortunately the message is not clear enough.

You can fix it by changing the loader that your executable uses, see my thorough answer in this other question: Multiple glibc libraries on a single host

Basically you have to find which loader it's trying to use:

$ readelf -l arm-mingw32ce-g++ | grep interpreter
  [Requesting program interpreter: /lib/ld-linux.so.2]

Then find the right path for an equivalent loader, and change your executable to use the loader from the path that it really is:

$ ./patchelf --set-interpreter /path/to/newglibc/ld-linux.so.2 arm-mingw32ce-g++

You will probably need to set the path of the includes too, you will know if you want it or not after you try to run it. See all the details in that other thread.

How do I set up Vim autoindentation properly for editing Python files?

I use this on my macbook:

" configure expanding of tabs for various file types
au BufRead,BufNewFile *.py set expandtab
au BufRead,BufNewFile *.c set expandtab
au BufRead,BufNewFile *.h set expandtab
au BufRead,BufNewFile Makefile* set noexpandtab

" --------------------------------------------------------------------------------
" configure editor with tabs and nice stuff...
" --------------------------------------------------------------------------------
set expandtab           " enter spaces when tab is pressed
set textwidth=120       " break lines when line length increases
set tabstop=4           " use 4 spaces to represent tab
set softtabstop=4
set shiftwidth=4        " number of spaces to use for auto indent
set autoindent          " copy indent from current line when starting a new line

" make backspaces more powerfull
set backspace=indent,eol,start

set ruler                           " show line and column number
syntax on               " syntax highlighting
set showcmd             " show (partial) command in status line

(edited to only show stuff related to indent / tabs)

Change background colour for Visual Studio

File-> Preferences-> Settings.

Find workbench.colorCustomizations object, change its editor.background property and save (you will see the results immediately — no need to restart vs code). Or you just can copy my current config file vs code config gist.

Compare two objects in Java with possible null values

Using Java 8:

private static Comparator<String> nullSafeStringComparator = Comparator
        .nullsFirst(String::compareToIgnoreCase); 

private static Comparator<Metadata> metadataComparator = Comparator
        .comparing(Metadata::getName, nullSafeStringComparator)
        .thenComparing(Metadata::getValue, nullSafeStringComparator);

public int compareTo(Metadata that) {
    return metadataComparator.compare(this, that);
}

How can I save application settings in a Windows Forms application?

Yes, it is possible to save the configuration - but it pretty much depends on the way you choose to do it. Let me describe the technical differences so you can understand the options you have:

First, you need to distinguish, whether you want to use applicationSettings or AppSettings in your *.exe.config(aka App.config in Visual Studio) file - there are fundamental differences, being described here.

Both provide different ways of saving changes:

  • The AppSettings allow you to read and write directly into the config file (via config.Save(ConfigurationSaveMode.Modified);, where config is defined as config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);).

  • The applicationSettings allow to read, but if you write changes (via Properties.Settings.Default.Save();) it will be written on a per-user basis, stored in a special place (e.g. C:\Documents and Settings\USERID\Local Settings\Application Data\FIRMNAME\WindowsFormsTestApplicati_Url_tdq2oylz33rzq00sxhvxucu5edw2oghw\1.0.0.0). As Hans Passant mentioned in his answer, this is because a user usually has restricted rights to Program Files and cannot write to it without invoking the UAC prompt. A disadvantage is if you're adding configuration keys in the future you need to synchronize them with every user profile.

Note: As mentioned in the question, there is a 3rd option: If you treat the configuration file as XML document, you can load, modify and save it by using the System.Xml.Linq.XDocument class. It is not required to use a custom XML file, you can read the existing config file; for querying elements, you can even use Linq queries. I have given an example here, check out the function GetApplicationSetting there in the answer.

If you require encryption to protect your values, check out this answer.

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

To pull a remote branch locally, I do the following:

git checkout -b branchname // creates a local branch with the same name and checks out on it

git pull origin branchname // pulls the remote one onto your local one

The only time I did this and it didn't work, I deleted the repo, cloned it again and repeated the above 2 steps; it worked.

How do you open an SDF file (SQL Server Compact Edition)?

You can open SQL Compact 4.0 Databases from Visual Studio 2012 directly, by going to

  1. View ->
  2. Server Explorer ->
  3. Data Connections ->
  4. Add Connection...
  5. Change... (Data Source:)
  6. Microsoft SQL Server Compact 4.0
  7. Browse...

and following the instructions there.

If you're okay with them being upgraded to 4.0, you can open older versions of SQL Compact Databases also - handy if you just want to have a look at some tables, etc for stuff like Windows Phone local database development.

(note I'm not sure if this requires a specific SKU of VS2012, if it helps I'm running Premium)

Running Node.Js on Android

You can use Node.js for Mobile Apps.

It works on Android devices and simulators, with pre-built binaries for armeabi-v7a, x86, arm64-v8a, x86_64. It also works on iOS, though that's outside the scope of this question.

Like JXcore, it is used to host a Node.js engine in the same process as the app, in a dedicated thread. Unlike JXcore, it is basically pure Node.js, built as a library, with a few portability fixes to run on Android. This means that it's much easier to keep the project up to date with mainline Node.js.

Plugins for Cordova and React Native are also available. The plugins provide a communication layer between the JavaScript side of those frameworks and the Node.js side. They also simplify development by taking care of a few things automatically, like packaging modules and cross-compiling native modules at build time.

Full disclosure: I work for the company that develops Node.js for Mobile Apps.

How to read a text file?

It depends on what you are trying to do.

file, err := os.Open("file.txt")
fmt.print(file)

The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File), not file-content. To obtain file-content, you may READ from a file-descriptor.


To read all file content(in bytes) to memory, ioutil.ReadAll

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


  b, err := ioutil.ReadAll(file)
  fmt.Print(b)
}

But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read from *os.File

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


    buf := make([]byte, 32*1024) // define your buffer size here.

    for {
        n, err := file.Read(buf)

        if n > 0 {
            fmt.Print(buf[:n]) // your read buffer.
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Printf("read %d bytes: %v", n, err)
            break
        }
    }

}

Otherwise, you could also use the standard util package: bufio, try Scanner. A Scanner reads your file in tokens: separator.

By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {             // internally, it advances token based on sperator
        fmt.Println(scanner.Text())  // token in unicode-char
        fmt.Println(scanner.Bytes()) // token in bytes

    }
}

Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.

How to use JavaScript variables in jQuery selectors?

var x = $(this).attr("name");
$("#" + x).hide();

How to change text color of simple list item

try this code...

<RelativeLayout 
         xmlns:android="http://schemas.android.com/apk/res/android" 
         android:layout_width="fill_parent" 
         android:layout_height="fill_parent" 
         android:background="#ffff00"> 

    <ListView 
            android:id="@+id/android:list" 
            android:layout_marginTop="2px" 
            android:layout_marginLeft="2px" 
            android:layout_marginRight="2px"
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:layout_weight="1" 
            android:background="@drawable/shape_1" 
            android:listSelector="@drawable/shape_3" 
            android:textColor="#ffff00" 
            android:layout_marginBottom="44px" /> 
</RelativeLayout>

How to sort with lambda in Python

Use

a = sorted(a, key=lambda x: x.modified, reverse=True)
#             ^^^^

On Python 2.x, the sorted function takes its arguments in this order:

sorted(iterable, cmp=None, key=None, reverse=False)

so without the key=, the function you pass in will be considered a cmp function which takes 2 arguments.

Check if a file exists or not in Windows PowerShell?

Use Test-Path:

if (!(Test-Path $exactadminfile) -and !(Test-Path $userfile)) {
  Write-Warning "$userFile absent from both locations"
}

Placing the above code in your ForEach loop should do what you want

Getting Access Denied when calling the PutObject operation with bucket-level permission

I had a similar issue uploading to an S3 bucket protected with KWS encryption. I have a minimal policy that allows the addition of objects under a specific s3 key.

I needed to add the following KMS permissions to my policy to allow the role to put objects in the bucket. (Might be slightly more than are strictly required)

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "kms:ListKeys",
                "kms:GenerateRandom",
                "kms:ListAliases",
                "s3:PutAccountPublicAccessBlock",
                "s3:GetAccountPublicAccessBlock",
                "s3:ListAllMyBuckets",
                "s3:HeadBucket"
            ],
            "Resource": "*"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "kms:ImportKeyMaterial",
                "kms:ListKeyPolicies",
                "kms:ListRetirableGrants",
                "kms:GetKeyPolicy",
                "kms:GenerateDataKeyWithoutPlaintext",
                "kms:ListResourceTags",
                "kms:ReEncryptFrom",
                "kms:ListGrants",
                "kms:GetParametersForImport",
                "kms:TagResource",
                "kms:Encrypt",
                "kms:GetKeyRotationStatus",
                "kms:GenerateDataKey",
                "kms:ReEncryptTo",
                "kms:DescribeKey"
            ],
            "Resource": "arn:aws:kms:<MY-REGION>:<MY-ACCOUNT>:key/<MY-KEY-GUID>"
        },
        {
            "Sid": "VisualEditor2",
            "Effect": "Allow",
            "Action": [
            <The S3 actions>
            ],
            "Resource": [
                "arn:aws:s3:::<MY-BUCKET-NAME>",
                "arn:aws:s3:::<MY-BUCKET-NAME>/<MY-BUCKET-KEY>/*"
            ]
        }
    ]
}

Display the binary representation of a number in C?

There is no direct way (i.e. using printf or another standard library function) to print it. You will have to write your own function.

/* This code has an obvious bug and another non-obvious one :) */
void printbits(unsigned char v) {
   for (; v; v >>= 1) putchar('0' + (v & 1));
}

If you're using terminal, you can use control codes to print out bytes in natural order:

void printbits(unsigned char v) {
    printf("%*s", (int)ceil(log2(v)) + 1, ""); 
    for (; v; v >>= 1) printf("\x1b[2D%c",'0' + (v & 1));
}

Gradients on UIView and UILabels On iPhone

Mirko Froehlich's answer worked for me, except when i wanted to use custom colors. The trick is to specify UI color with Hue, saturation and brightness instead of RGB.

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = myView.bounds;
UIColor *startColour = [UIColor colorWithHue:.580555 saturation:0.31 brightness:0.90 alpha:1.0];
UIColor *endColour = [UIColor colorWithHue:.58333 saturation:0.50 brightness:0.62 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)[startColour CGColor], (id)[endColour CGColor], nil];
[myView.layer insertSublayer:gradient atIndex:0];

To get the Hue, Saturation and Brightness of a color, use the in built xcode color picker and go to the HSB tab. Hue is measured in degrees in this view, so divide the value by 360 to get the value you will want to enter in code.

Fastest way to write huge data in text file Java

For those who want to improve the time for retrieval of records and dump into the file (i.e no processing on records), instead of putting them into an ArrayList, append those records into a StringBuffer. Apply toSring() function to get a single String and write it into the file at once.

For me, the retrieval time reduced from 22 seconds to 17 seconds.

Bind failed: Address already in use

The error usually means that the port you are trying to open is being already used by another application. Try using netstat to see which ports are open and then use an available port.

Also check if you are binding to the right ip address (I am assuming it would be localhost)

Create comma separated strings C#?

If you're using .Net 4 you can use the overload for string.Join that takes an IEnumerable if you have them in a List, too:

string.Join(", ", strings);

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

In the following httpd.conf file, configure the ServerName properly.

/etc/httpd/conf/httpd.conf

Like below:

ServerName 127.0.0.1:80

or

ServerName sitename

This resolved similar issue I was facing.

How do I force git pull to overwrite everything on every pull?

You can change the hook to wipe everything clean.

# Danger! Wipes local data!

# Remove all local changes to tracked files
git reset --hard HEAD

# Remove all untracked files and directories
git clean -dfx

git pull ...

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

How do I start a program with arguments when debugging?

Go to Project-><Projectname> Properties. Then click on the Debug tab, and fill in your arguments in the textbox called Command line arguments.

What is jQuery Unobtrusive Validation?

jQuery Validation Unobtrusive Native is a collection of ASP.Net MVC HTML helper extensions. These make use of jQuery Validation's native support for validation driven by HTML 5 data attributes. Microsoft shipped jquery.validate.unobtrusive.js back with MVC 3. It provided a way to apply data model validations to the client side using a combination of jQuery Validation and HTML 5 data attributes (that's the "unobtrusive" part).

Foreign Key naming scheme

A note from Microsoft concerning SQL Server:

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.

so, I'll use terms describing dependency instead of the conventional primary/foreign relationship terms.

When referencing the PRIMARY KEY of the independent (parent) table by the similarly named column(s) in the dependent (child) table, I omit the column name(s):

FK_ChildTable_ParentTable

When referencing other columns, or the column names vary between the two tables, or just to be explicit:

FK_ChildTable_childColumn_ParentTable_parentColumn

Apache Spark: map vs mapPartitions?

Map:

Map transformation.

The map works on a single Row at a time.

Map returns after each input Row.

The map doesn’t hold the output result in Memory.

Map no way to figure out then to end the service.

// map example

val dfList = (1 to 100) toList

val df = dfList.toDF()

val dfInt = df.map(x => x.getInt(0)+2)

display(dfInt)

MapPartition:

MapPartition transformation.

MapPartition works on a partition at a time.

MapPartition returns after processing all the rows in the partition.

MapPartition output is retained in memory, as it can return after processing all the rows in a particular partition.

MapPartition service can be shut down before returning.

// MapPartition example

Val dfList = (1 to 100) toList

Val df = dfList.toDF()

Val df1 = df.repartition(4).rdd.mapPartition((int) => Iterator(itr.length))

Df1.collec()

//display(df1.collect())

For more details, please refer to the Spark map vs mapPartitions transformation article.

Hope this is helpful!

Laravel Eloquent limit and offset

Quick:

Laravel has a fast pagination method, paginate, which only needs to pass in the number of data displayed per page.


//use the paginate
Book::orderBy('updated_at', 'desc')->paginate(8);

how to customize paging:

you can use these method: offset,limit ,skip,take

  • offset,limit : where does the offset setting start, limiting the amount of data to be queried

  • skip,take: skip skips a few pieces of data and takes a lot of data

for example:


Model::offset(0)->limit(10)->get();

Model::skip(3)->take(3)->get();


//i use it in my project, work fine ~

class BookController extends Controller
{
    public function getList(Request $request) {

        $page = $request->has('page') ? $request->get('page') : 1;
        $limit = $request->has('limit') ? $request->get('limit') : 10;

        $books = Book::where('status', 0)->limit($limit)->offset(($page - 1) * $limit)->get()->toArray();

        return $this->getResponse($books, count($books));
    }
}


ImportError: No module named requests

I have had this issue a couple times in the past few months. I haven't seen a good solution for fedora systems posted, so here's yet another solution. I'm using RHEL7, and I discovered the following:

If you have urllib3 installed via pip, and requests installed via yum you will have issues, even if you have the correct packages installed. The same will apply if you have urllib3 installed via yum, and requests installed via pip. Here's what I did to fix the issue:

sudo pip uninstall requests
sudo pip uninstall urllib3
sudo yum remove python-urllib3
sudo yum remove python-requests

(confirm that all those libraries have been removed)

sudo yum install python-urllib3
sudo yum install python-requests

Just be aware that this will only work for systems that are running Fedora, Redhat, or CentOS.

Sources:
This very question (in the comments to this answer).
This github issue.

Javascript require() function giving ReferenceError: require is not defined

Yes, require is a Node.JS function and doesn't work in client side scripting without certain requirements. If you're getting this error while writing electronJS code, try the following:

In your BrowserWindow declaration, add the following webPreferences field: i.e, instead of plain mainWindow = new BrowserWindow(), write

mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true
        }
    });

Using Python, how can I access a shared folder on windows network?

I had the same issue as OP but none of the current answers solved my issue so to add a slightly different answer that did work for me:

Running Python 3.6.5 on a Windows Machine, I used the format

r"\DriveName\then\file\path\txt.md"

so the combination of double backslashes from reading @Johnsyweb UNC link and adding the r in front as recommended solved my similar to OP's issue.

There is already an open DataReader associated with this Command which must be closed first

In addition to Ladislav Mrnka's answer:

If you are publishing and overriding container on Settings tab, you can set MultipleActiveResultSet to True. You can find this option by clicking Advanced... and it's going to be under Advanced group.

Bypass popup blocker on window.open when JQuery event.preventDefault() is set

you can call window.open without browser blocking only if user does directly some action. Browser send some flag and determine that window opened by user action.

So, you can try this scenario:

  1. var myWindow = window.open('')
  2. draw any loading message in this window
  3. when request done, just call myWindow.location = 'http://google.com'

Pushing an existing Git repository to SVN

I needed this as well, and with the help of Bombe's answer + some fiddling around, I got it working. Here's the recipe:

Import Git -> Subversion

1. cd /path/to/git/localrepo
2. svn mkdir --parents protocol:///path/to/repo/PROJECT/trunk -m "Importing git repo"
3. git svn init protocol:///path/to/repo/PROJECT -s
4. git svn fetch
5. git rebase origin/trunk
5.1.  git status
5.2.  git add (conflicted-files)
5.3.  git rebase --continue
5.4.  (repeat 5.1.)
6. git svn dcommit

After #3 you'll get a cryptic message like this:

Using higher level of URL: protocol:///path/to/repo/PROJECT => protocol:///path/to/repo

Just ignore that.

When you run #5, you might get conflicts. Resolve these by adding files with state "unmerged" and resuming rebase. Eventually, you'll be done; then sync back to the SVN repository, using dcommit. That's all.

Keeping repositories in sync

You can now synchronise from SVN to Git, using the following commands:

git svn fetch
git rebase trunk

And to synchronise from Git to SVN, use:

git svn dcommit

Final note

You might want to try this out on a local copy, before applying to a live repository. You can make a copy of your Git repository to a temporary place; simply use cp -r, as all data is in the repository itself. You can then set up a file-based testing repository, using:

svnadmin create /home/name/tmp/test-repo

And check a working copy out, using:

svn co file:///home/name/tmp/test-repo svn-working-copy

That'll allow you to play around with things before making any lasting changes.

Addendum: If you mess up git svn init

If you accidentally run git svn init with the wrong URL, and you weren't smart enough to take a backup of your work (don't ask ...), you can't just run the same command again. You can however undo the changes by issuing:

rm -rf .git/svn
edit .git/config

And remove the section [svn-remote "svn"] section.

You can then run git svn init anew.

How to escape a single quote inside awk

This maybe what you're looking for:

awk 'BEGIN {FS=" ";} {printf "'\''%s'\'' ", $1}'

That is, with '\'' you close the opening ', then print a literal ' by escaping it and finally open the ' again.

How to loop through a checkboxlist and to find what's checked and not checked?

Use the CheckBoxList's GetItemChecked or GetItemCheckState method to find out whether an item is checked or not by its index.

PowerShell: how to grep command output?

PS> alias | Where-Object {$_.Definition -match 'alias'}

CommandType     Name                   Definition
-----------     ----                   ----------
Alias           epal                   Export-Alias
Alias           gal                    Get-Alias
Alias           ipal                   Import-Alias
Alias           nal                    New-Alias
Alias           sal                    Set-Alias

what would be contradict of match in PS then as in to get field not matching a certain value in a column

Passing parameters to a Bash function

It takes two numbers from the user, feeds them to the function called add (in the very last line of the code), and add will sum them up and print them.

#!/bin/bash

read -p "Enter the first  value: " x
read -p "Enter the second value: " y

add(){
    arg1=$1 # arg1 gets to be the first  assigned argument (note there are no spaces)
      arg2=$2 # arg2 gets to be the second assigned argument (note there are no spaces)

    echo $(($arg1 + $arg2))
}

add x y # Feeding the arguments

Convert XmlDocument to String

" is shown as \" in the debugger, but the data is correct in the string, and you don't need to replace anything. Try to dump your string to a file and you will note that the string is correct.

How to set base url for rest in spring boot?

With spring-boot 2.x you can configure in application.properties:

spring.mvc.servlet.path=/api

Java: Date from unix timestamp

Date's constructor expects the timeStamp value to be in milliseconds. Multiply your timestamp's value with 1000, then pass it to the constructor.

Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed

As of ES 7, mapping types have been removed. You can read more details here

If you are using Ruby On Rails this means that you may need to remove document_type from your model or concern.

As an alternative to mapping types one solution is to use an index per document type.

Before:

module Searchable
  extend ActiveSupport::Concern

  included do
    include Elasticsearch::Model
    include Elasticsearch::Model::Callbacks
    index_name [Rails.env, Rails.application.class.module_parent_name.underscore].join('_')
    document_type self.name.downcase
  end
end

After:

module Searchable
  extend ActiveSupport::Concern

  included do
    include Elasticsearch::Model
    include Elasticsearch::Model::Callbacks
    index_name [Rails.env, Rails.application.class.module_parent_name.underscore, self.name.downcase].join('_')
  end
end

Difference between "enqueue" and "dequeue"

A queue is a certain 2-sided data structure. You can add new elements on one side, and remove elements from the other side (as opposed to a stack that has only one side). Enqueue means to add an element, dequeue to remove an element. Please have a look here.

ServletException, HttpServletResponse and HttpServletRequest cannot be resolved to a type

Select Tomcat server in Targeted Runtime

Project->Properties->Targeted Runtimes (Select your Tomcat Server)

How to increase buffer size in Oracle SQL Developer to view all records?

Select Tools > Preferences > Database / Advanced

There is an input field for Sql Array Fetch Size but it only allows setting a max of 500 rows.

How to ignore files/directories in TFS for avoiding them to go to central source repository?

I found the perfect way to Ignore files in TFS like SVN does.
First of all, select the file that you want to ignore (e.g. the Web.config).
Now go to the menu tab and select:

File Source control > Advanced > Exclude web.config from source control

... and boom; your file is permanently excluded from source control.

How do I clone a range of array elements to a new array?

As far as cloning goes, I don't think serialization calls your constructors. This may break class invariants if you're doing interesting things in the ctor's.

It seems the safer bet is virtual clone methods calling copy constructors.

protected MyDerivedClass(MyDerivedClass myClass) 
{
  ...
}

public override MyBaseClass Clone()
{
  return new MyDerivedClass(this);
}

round value to 2 decimals javascript

If you want it visually formatted to two decimals as a string (for output) use toFixed():

var priceString = someValue.toFixed(2);

The answer by @David has two problems:

  1. It leaves the result as a floating point number, and consequently holds the possibility of displaying a particular result with many decimal places, e.g. 134.1999999999 instead of "134.20".

  2. If your value is an integer or rounds to one tenth, you will not see the additional decimal value:

    var n = 1.099;
    (Math.round( n * 100 )/100 ).toString() //-> "1.1"
    n.toFixed(2)                            //-> "1.10"
    
    var n = 3;
    (Math.round( n * 100 )/100 ).toString() //-> "3"
    n.toFixed(2)                            //-> "3.00"
    

And, as you can see above, using toFixed() is also far easier to type. ;)

Active Menu Highlight CSS

As the given tag to this question is CSS, I will provide the way I accomplished it.

  1. Create a class in the .css file.

    a.activePage{ color: green; border-bottom: solid; border-width: 3px;}

  2. Nav-bar will be like:

    • Home
    • Contact Us
    • About Us

NOTE: If you are already setting the style for all Nav-Bar elements using a class, you can cascade the special-case class we created with a white-space after the generic class in the html-tag.

Example: Here, I was already importing my style from a class called 'navList' I created for all list-items . But the special-case styling-attributes are part of class 'activePage'

.CSS file:

a.navList{text-decoration: none; color: gray;}
a.activePage{ color: green; border-bottom: solid; border-width: 3px;}

.HTML file:

<div id="sub-header">
    <ul>
        <li> <a href="index.php" class= "navList activePage" >Home</a> </li>
        <li> <a href="contact.php" class= "navList">Contact Us</a> </li>
        <li> <a href="about.php" class= "navList">About Us</a> </li>
    </ul>
</div>

Look how I've cascaded one class-name behind other.

Property [title] does not exist on this collection instance

When you're using get() you get a collection. In this case you need to iterate over it to get properties:

@foreach ($collection as $object)
    {{ $object->title }}
@endforeach

Or you could just get one of objects by it's index:

{{ $collection[0]->title }}

Or get first object from collection:

{{ $collection->first() }}

When you're using find() or first() you get an object, so you can get properties with simple:

{{ $object->title }}

How to count number of unique values of a field in a tab-delimited text file?

# COLUMN is integer column number
# INPUT_FILE is input file name

cut -f ${COLUMN} < ${INPUT_FILE} | sort -u | wc -l

Single-threaded apartment - cannot instantiate ActiveX control

Go ahead and add [STAThread] to the main entry of your application, this indicates the COM threading model is single-threaded apartment (STA)

example:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new WebBrowser());
    }
}

connect local repo with remote repo

git remote add origin <remote_repo_url>
git push --all origin

If you want to set all of your branches to automatically use this remote repo when you use git pull, add --set-upstream to the push:

git push --all --set-upstream origin

Get all rows from SQLite

public List<String> getAllData(String email)
{

    db = this.getReadableDatabase();
    String[] projection={email};

    List<String> list=new ArrayList<>();

    Cursor cursor = db.query(TABLE_USER, //Table to query
            null,    //columns to return
            "user_email=?",        //columns for the WHERE clause
            projection,        //The values for the WHERE clause
            null,       //group the rows
            null,       //filter by row groups
            null);
    //  cursor.moveToFirst();

    if (cursor.moveToFirst()) {
        do {

            list.add(cursor.getString(cursor.getColumnIndex("user_id")));
            list.add(cursor.getString(cursor.getColumnIndex("user_name")));
            list.add(cursor.getString(cursor.getColumnIndex("user_email")));
            list.add(cursor.getString(cursor.getColumnIndex("user_password")));
            // cursor.moveToNext();

        } while (cursor.moveToNext());
    }
    return list;
}

ERROR Error: No value accessor for form control with unspecified name attribute on switch

In my case the problem was that i created an @Input variable with the reserved name formControl.

Delete files older than 10 days using shell script in Unix

Just spicing up the shell script above to delete older files but with logging and calculation of elapsed time

#!/bin/bash

path="/data/backuplog/"
timestamp=$(date +%Y%m%d_%H%M%S)    
filename=log_$timestamp.txt    
log=$path$filename
days=7

START_TIME=$(date +%s)

find $path -maxdepth 1 -name "*.txt"  -type f -mtime +$days  -print -delete >> $log

echo "Backup:: Script Start -- $(date +%Y%m%d_%H%M)" >> $log


... code for backup ...or any other operation .... >> $log


END_TIME=$(date +%s)

ELAPSED_TIME=$(( $END_TIME - $START_TIME ))


echo "Backup :: Script End -- $(date +%Y%m%d_%H%M)" >> $log
echo "Elapsed Time ::  $(date -d 00:00:$ELAPSED_TIME +%Hh:%Mm:%Ss) "  >> $log

The code adds a few things.

  • log files named with a timestamp
  • log folder specified
  • find looks for *.txt files only in the log folder
  • type f ensures you only deletes files
  • maxdepth 1 ensures you dont enter subfolders
  • log files older than 7 days are deleted ( assuming this is for a backup log)
  • notes the start / end time
  • calculates the elapsed time for the backup operation...

Note: to test the code, just use -print instead of -print -delete. But do check your path carefully though.

Note: Do ensure your server time is set correctly via date - setup timezone/ntp correctly . Additionally check file times with 'stat filename'

Note: mtime can be replaced with mmin for better control as mtime discards all fractions (older than 2 days (+2 days) actually means 3 days ) when it deals with getting the timestamps of files in the context of days

-mtime +$days  --->  -mmin  +$((60*24*$days))

How to create a sticky left sidebar menu using bootstrap 3?

You can also try to use a Polyfill like Fixed-Sticky. Especially when you are using Bootstrap4 the affix component is no longer included:

Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead.

Testing if a site is vulnerable to Sql Injection

The test has to be done on a page that queries a database so yes typically that is a login page because it's the page that can do the most harm but could be an unsecure page as well.

Generally you would have your database queries behind a secure login but if you just have a listing of items or something that you don't care if the world sees a hacker could append some sql injection to the end of the querystring.

The key with SQL Injection is the person doing the injection would have to know that your querying a database so if your not querying a database then no sql inject can be done. If your form is submitting to a database then yes they could SQL Inject that. It's always good practice to use either stored procedures to select/insert/update/delete or make sure you prepare or escape out all the statements that will be hitting the database.

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

The other answers so far demonstrate pretty well why Dijkstra's algorithm cannot handle negative weights on paths.

But the question itself is maybe based on a wrong understanding of the weight of paths. If negative weights on paths would be allowed in pathfinding algorithms in general, then you would get permanent loops that would not stop.

Consider this:

A  <- 5 ->  B  <- (-1) ->  C <- 5 -> D

What is the optimal path between A and D?

Any pathfinding algorithm would have to continuously loop between B and C because doing so would reduce the weight of the total path. So allowing negative weights for a connection would render any pathfindig algorithm moot, maybe except if you limit each connection to be used only once.

So, to explain this in more detail, consider the following paths and weights:

Path               | Total weight
ABCD               | 9
ABCBCD             | 7
ABCBCBCD           | 5
ABCBCBCBCD         | 3
ABCBCBCBCBCD       | 1
ABCBCBCBCBCBCD     | -1
...

So, what's the perfect path? Any time the algorithm adds a BC step, it reduces the total weight by 2.

So the optimal path is A (BC) D with the BC part being looped forever.

Since Dijkstra's goal is to find the optimal path (not just any path), it, by definition, cannot work with negative weights, since it cannot find the optimal path.

Dijkstra will actually not loop, since it keeps a list of nodes that it has visited. But it will not find a perfect path, but instead just any path.

Checking session if empty or not

You need to check that Session["emp_num"] is not null before trying to convert it to a string otherwise you will get a null reference exception.

I'd go with your first example - but you could make it slightly more "elegant".

There are a couple of ways, but the ones that springs to mind are:

if (Session["emp_num"] is string)
{
}

or

if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
}

This will return null if the variable doesn't exist or isn't a string.

Disable time in bootstrap date time picker

In my case, the option I used was:

var from = $("input.datepicker").datetimepicker({
  format:'Y-m-d',
  timepicker:false # <- HERE
});

I'm using this plugin https://xdsoft.net/jqplugins/datetimepicker/

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

Below are three functions you can use to alter and use the MS Access 2010 Import Specification. The third sub changes the name of an existing import specification. The second sub allows you to change any xml text in the import spec. This is useful if you need to change column names, data types, add columns, change the import file location, etc.. In essence anything you want modify for an existing spec. The first Sub is a routine that allows you to call an existing import spec, modify it for a specific file you are attempting to import, importing that file, and then deleting the modified spec, keeping the import spec "template" unaltered and intact. Enjoy.

Public Sub MyExcelTransfer(myTempTable As String, myPath As String)
On Error GoTo ERR_Handler:
    Dim mySpec As ImportExportSpecification
    Dim myNewSpec As ImportExportSpecification
    Dim x As Integer

    For x = 0 To CurrentProject.ImportExportSpecifications.Count - 1
    If CurrentProject.ImportExportSpecifications.Item(x).Name = "TemporaryImport" Then
        CurrentProject.ImportExportSpecifications.Item("TemporaryImport").Delete
        x = CurrentProject.ImportExportSpecifications.Count
    End If
    Next x
    Set mySpec = CurrentProject.ImportExportSpecifications.Item(myTempTable)
    CurrentProject.ImportExportSpecifications.Add "TemporaryImport", mySpec.XML
    Set myNewSpec = CurrentProject.ImportExportSpecifications.Item("TemporaryImport")

    myNewSpec.XML = Replace(myNewSpec.XML, "\\MyComputer\ChangeThis", myPath)
    myNewSpec.Execute
    myNewSpec.Delete
    Set mySpec = Nothing
    Set myNewSpec = Nothing
    exit_ErrHandler:
    For x = 0 To CurrentProject.ImportExportSpecifications.Count - 1
    If CurrentProject.ImportExportSpecifications.Item(x).Name = "TemporaryImport" Then
        CurrentProject.ImportExportSpecifications.Item("TemporaryImport").Delete
        x = CurrentProject.ImportExportSpecifications.Count
    End If
    Next x
Exit Sub    
ERR_Handler:
    MsgBox Err.Description
    Resume exit_ErrHandler
End Sub

Public Sub fixImportSpecs(myTable As String, strFind As String, strRepl As String)
    Dim mySpec As ImportExportSpecification    
    Set mySpec = CurrentProject.ImportExportSpecifications.Item(myTable)    
    mySpec.XML = Replace(mySpec.XML, strFind, strRepl)
    Set mySpec = Nothing
End Sub


Public Sub MyExcelChangeName(OldName As String, NewName As String)
    Dim mySpec As ImportExportSpecification
    Dim myNewSpec As ImportExportSpecification
    Set mySpec = CurrentProject.ImportExportSpecifications.Item(OldName)    
    CurrentProject.ImportExportSpecifications.Add NewName, mySpec.XML
    mySpec.Delete
    Set mySpec = Nothing
    Set myNewSpec = Nothing
End Sub

rsync copy over only certain types of files using include option

Here's the important part from the man page:

As the list of files/directories to transfer is built, rsync checks each name to be transferred against the list of include/exclude patterns in turn, and the first matching pattern is acted on: if it is an exclude pattern, then that file is skipped; if it is an include pattern then that filename is not skipped; if no matching pattern is found, then the filename is not skipped.

To summarize:

  • Not matching any pattern means a file will be copied!
  • The algorithm quits once any pattern matches

Also, something ending with a slash is matching directories (like find -type d would).

Let's pull apart this answer from above.

rsync -zarv  --prune-empty-dirs --include "*/"  --include="*.sh" --exclude="*" "$from" "$to"
  1. Don't skip any directories
  2. Don't skip any .sh files
  3. Skip everything
  4. (Implicitly, don't skip anything, but the rule above prevents the default rule from ever happening.)

Finally, the --prune-empty-directories keeps the first rule from making empty directories all over the place.

How do I share a global variable between c files?

Do same as you did in file1.c In file2.c:

#include <stdio.h> 

extern int i;  /*This declare that i is an int variable which is defined in some other file*/

int main(void)
{
/* your code*/

If you use int i; in file2.c under main() then i will be treated as local auto variable not the same as defined in file1.c

How to use filesaver.js

It works in my react project:

import FileSaver from 'file-saver';
// ...
onTestSaveFile() {
    var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
    FileSaver.saveAs(blob, "hello world.txt");
}

Simple bubble sort c#

I saw someone use this example as part of a job application test. My feedback to him was that it lacks an escape from the outer loop when the array is mostly sorted.

consider what would happen in this case:

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

here's something that makes more sense:

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

int temp = 0;
int loopCount=0;
bool doBreak=true;

for (int write = 0; write < arr.Length; write++)
{
    doBreak=true;
    for (int sort = 0; sort < arr.Length - 1; sort++)
    {
        if (arr[sort] > arr[sort + 1])
        {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
            doBreak=false;
        }
        loopCount++;
    }
    if(doBreak){ break; /*early escape*/ }
}

Console.WriteLine(loopCount);
for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " ");

laravel Unable to prepare route ... for serialization. Uses Closure

If none of your routes contain closures, but you are still getting this error, please check

routes/api.php

Laravel has a default auth api route in the above file.

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

which can be commented or replaced with a call to controller method if required.

SQL to add column and comment in table in single command

Add comments for two different columns of the EMPLOYEE table :

COMMENT ON EMPLOYEE
     (WORKDEPT IS 'see DEPARTMENT table for names',
     EDLEVEL IS 'highest grade level passed in school' )

List and kill at jobs on UNIX

at -l to list jobs, which gives return like this:

age2%> at -l
11      2014-10-21 10:11 a hoppent
10      2014-10-19 13:28 a hoppent

atrm 10 kills job 10

Or so my sysadmin told me, and it

add id to dynamically created <div>

You'll have to actually USE jQuery to build the div, if you want to write maintainable or usable code.

//create a div
var $newDiv = $('<div>');

//set the id
$newDiv.attr("id","myId");

How to declare global variables in Android?

You can do this using two approaches:

  1. Using Application class
  2. Using Shared Preferences

  3. Using Application class

Example:

class SessionManager extends Application{

  String sessionKey;

  setSessionKey(String key){
    this.sessionKey=key;
  }

  String getSessisonKey(){
    return this.sessionKey;
  }
}

You can use above class to implement login in your MainActivity as below. Code will look something like this:

@override 
public void onCreate (Bundle savedInstanceState){
  // you will this key when first time login is successful.
  SessionManager session= (SessionManager)getApplicationContext();
  String key=getSessisonKey.getKey();
  //Use this key to identify whether session is alive or not.
}

This method will work for temporary storage. You really do not any idea when operating system is gonna kill the application, because of low memory. When your application is in background and user is navigating through other application which demands more memory to run, then your application will be killed since operating system given more priority to foreground processes than background. Hence your application object will be null before user logs out. Hence for this I recommend to use second method Specified above.

  1. Using shared preferences.

    String MYPREF="com.your.application.session"
    
    SharedPreferences pref= context.getSharedPreferences(MyPREF,MODE_PRIVATE);
    
    //Insert key as below:
    
    Editot editor= pref.edit();
    
    editor.putString("key","value");
    
    editor.commit();
    
    //Get key as below.
    
    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    
    String key= getResources().getString("key");
    

How to download all dependencies and packages to directory

This will download all packages and dependencies (no already installed) to a directory of your choice:

sudo apt-get install -d -o Dir::Cache=/path-to/directory/apt/cache -o Dir::State::Lists=/path-to/directory/apt/lists packages

Make sure /path-to/directory/apt/cache and /path-to/directory/apt/lists exist. If you don't set -o Dir::Cache it points to /var/cache/apt, Dir::State::Lists points to /var/lib/apt/lists (which keeps the index files of available packages)

Both -o options can be used with update and upgrade instead of install.

On different machine run the same command without '-d'

Chrome dev tools fails to show response even the content returned has header Content-Type:text/html; charset=UTF-8

I think this only happens when you have 'Preserve log' checked and you are trying to view the response data of a previous request after you have navigated away.

For example, I viewed the Response to loading this Stack Overflow question. You can see it.

Response Data

The second time, I reloaded this page but didn't look at the Headers or Response. I navigated to a different website. Now when I look at the response, it shows 'Failed to load response data'.

No Response Data

This is a known issue, that's been around for a while, and debated a lot. However, there is a workaround, in which you pause on onunload, so you can view the response before it navigates away, and thereby doesn't lose the data upon navigating away.

window.onunload = function() { debugger; }

Turning error reporting off php

Tried this yet?

error_reporting(0);
@ini_set('display_errors', 0);

What does it mean to inflate a view from an xml file?

Because we make UI into XML but view objects is what we display so we somehow need to convert xml into view objects so inflating means we are converting xml into view objects so that it can be displayed, for this we need a service called layout inflator service and give it an xml and it will be convert for you.

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

Make a link in the Android browser start up my app?

You may want to consider a library to handle the deep link to your app:

https://github.com/airbnb/DeepLinkDispatch

You can add the intent filter on an annotated Activity like people suggested above. It will handle the routing and parsing of parameters for all of your deep links. For example, your MainActivity might have something like this:

@DeepLink("somePath/{useful_info_for_anton_app}")
public class MainActivity extends Activity {
   ...
}

It can also handle query parameters as well.

Select current element in jQuery

When the jQuery click event calls your event handler, it sets "this" to the object that was clicked on. To turn it into a jQuery object, just pass it to the "$" function: $(this). So, to get, for example, the next sibling element, you would do this inside the click handler:

var nextSibling = $(this).next();

Edit: After reading Kevin's comment, I realized I might be mistaken about what you want. If you want to do what he asked, i.e. select the corresponding link in the other div, you could use $(this).index() to get the clicked link's position. Then you would select the link in the other div by its position, for example with the "eq" method.

var $clicked = $(this);
var linkIndex = $clicked.index();
$clicked.parent().next().children().eq(linkIndex);

If you want to be able to go both ways, you will need some way of determining which div you are in so you know if you need "next()" or "prev()" after "parent()"

How to declare strings in C

char *p = "String";   means pointer to a string type variable.

char p3[5] = "String"; means you are pre-defining the size of the array to consist of no more than 5 elements. Note that,for strings the null "\0" is also considered as an element.So,this statement would give an error since the number of elements is 7 so it should be:

char p3[7]= "String";

How to auto adjust the <div> height according to content in it?

Try with the following mark-up instead of directly specifying height:

_x000D_
_x000D_
.box-centerside {_x000D_
  background: url("../images/greybox-center-bg1.jpg") repeat-x scroll center top transparent;_x000D_
  float: left;_x000D_
  min-height: 100px;_x000D_
  width: 260px;_x000D_
}
_x000D_
<div class="box-centerside">_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
</div>
_x000D_
_x000D_
_x000D_

MySQL SELECT DISTINCT multiple columns

Taking a guess at the results you want so maybe this is the query you want then

SELECT DISTINCT a FROM my_table
UNION 
SELECT DISTINCT b FROM my_table
UNION
SELECT DISTINCT c FROM my_table
UNION
SELECT DISTINCT d FROM my_table

How to create two columns on a web page?

i recommend to look this article

http://www.456bereastreet.com/lab/developing_with_web_standards/csslayout/2-col/

see 4. Place the columns side by side special

To make the two columns (#main and #sidebar) display side by side we float them, one to the left and the other to the right. We also specify the widths of the columns.

    #main {
    float:left;
    width:500px;
    background:#9c9;
    }
    #sidebar {
    float:right;
    width:250px;
   background:#c9c;
   }

Note that the sum of the widths should be equal to the width given to #wrap in Step 3.

How to set time zone in codeigniter?

Add this line inside the main index.php of codeigniter folder

date_default_timezone_set('Asia/Kolkata');

Android: adbd cannot run as root in production builds

The problem is that, even though your phone is rooted, the 'adbd' server on the phone does not use root permissions. You can try to bypass these checks or install a different adbd on your phone or install a custom kernel/distribution that includes a patched adbd.

Or, a much easier solution is to use 'adbd insecure' from chainfire which will patch your adbd on the fly. It's not permanent, so you have to run it before starting up the adb server (or else set it to run every boot). You can get the app from the google play store for a couple bucks:

https://play.google.com/store/apps/details?id=eu.chainfire.adbd&hl=en

Or you can get it for free, the author has posted a free version on xda-developers:

http://forum.xda-developers.com/showthread.php?t=1687590

Install it to your device (copy it to the device and open the apk file with a file manager), run adb insecure on the device, and finally kill the adb server on your computer:

% adb kill-server

And then restart the server and it should already be root.

How to break/exit from a each() function in JQuery?

if (condition){ // where condition evaluates to true 
    return false
}

see similar question asked 3 days ago.

How can I query a value in SQL Server XML column

declare @T table(Roles xml)

insert into @T values
('<root>
   <role>Alpha</role>
   <role>Beta</role>
   <role>Gamma</role>
</root>')

declare @Role varchar(10)

set @Role = 'Beta'

select Roles
from @T
where Roles.exist('/root/role/text()[. = sql:variable("@Role")]') = 1

If you want the query to work as where col like '%Beta%' you can use contains

declare @T table(Roles xml)

insert into @T values
('<root>
   <role>Alpha</role>
   <role>Beta</role>
   <role>Gamma</role>
</root>')

declare @Role varchar(10)

set @Role = 'et'

select Roles
from @T
where Roles.exist('/root/role/text()[contains(., sql:variable("@Role"))]') = 1

Exclude subpackages from Spring autowiring?

One thing that seems to work for me is this:

@ComponentScan(basePackageClasses = {SomeTypeInYourPackage.class}, resourcePattern = "*.class")

Or in XML:

<context:component-scan base-package="com.example" resource-pattern="*.class"/>

This overrides the default resourcePattern which is "**/*.class".

This would seem like the most type-safe way to ONLY include your base package since that resourcePattern would always be the same and relative to your base package.

What is the meaning of single and double underscore before an object name?

In the case of methods, you can use the double underscore to hide away private 'methods' with the following pattern:

# Private methods of MyClass
def _MyClass__do_something(obj:'MyClass'):
    print('_MyClass__do_something() called. type(obj) = {}'.format(type(obj)))

class MyClass():
    def __init__(self):
        __do_something(self)

mc = MyClass()

Output:

_MyClass__do_something() called. type(obj) = <class '__main__.MyClass'>

I stumbled across this today when I tried using double underscore for class methods and got the NameError: name '_<class><method>' is not defined error.

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

The minimal-ui viewport property is no longer supported in iOS 8. However, the minimal-ui itself is not gone. User can enter the minimal-ui with a "touch-drag down" gesture.

There are several pre-conditions and obstacles to manage the view state, e.g. for minimal-ui to work, there has to be enough content to enable user to scroll; for minimal-ui to persist, window scroll must be offset on page load and after orientation change. However, there is no way of calculating the dimensions of the minimal-ui using the screen variable, and thus no way of telling when user is in the minimal-ui in advance.

These observations is a result of research as part of developing Brim – view manager for iOS 8. The end implementation works in the following way:

When page is loaded, Brim will create a treadmill element. Treadmill element is used to give user space to scroll. Presence of the treadmill element ensures that user can enter the minimal-ui view and that it continues to persist if user reloads the page or changes device orientation. It is invisible to the user the entire time. This element has ID brim-treadmill.

Upon loading the page or after changing the orientation, Brim is using Scream to detect if page is in the minimal-ui view (page that has been previously in minimal-ui and has been reloaded will remain in the minimal-ui if content height is greater than the viewport height).

When page is in the minimal-ui, Brim will disable scrolling of the document (it does this in a safe way that does not affect the contents of the main element). Disabling document scrolling prevents accidentally leaving the minimal-ui when scrolling upwards. As per the original iOS 7.1 spec, tapping the top bar brings back the rest of the chrome.

The end result looks like this:

Brim in iOS simulator.

For the sake of documentation, and in case you prefer to write your own implementation, it is worth noting that you cannot use Scream to detect if device is in minimal-ui straight after the orientationchange event because window dimensions do not reflect the new orientation until the rotation animation has ended. You have to attach a listener to the orientationchangeend event.

Scream and orientationchangeend have been developed as part of this project.

Error:Unable to locate adb within SDK in Android Studio

I get the error message, but adb.exe runs anyway (and debugging works fine), so its not a problem (apart from the error message being annoying). My best guess is that more than one process is trying to start the program at the same time.

What does it mean to have an index to scalar variable error? python

IndexError: invalid index to scalar variable happens when you try to index a numpy scalar such as numpy.int64 or numpy.float64. It is very similar to TypeError: 'int' object has no attribute '__getitem__' when you try to index an int.

>>> a = np.int64(5)
>>> type(a)
<type 'numpy.int64'>
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: invalid index to scalar variable.
>>> a = 5
>>> type(a)
<type 'int'>
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'

How to represent multiple conditions in a shell if statement?

In Bash:

if [[ ( $g == 1 && $c == 123 ) || ( $g == 2 && $c == 456 ) ]]

data.frame Group By column

Using dplyr:

require(dplyr)    
df <- data.frame(A = c(1, 1, 2, 3, 3), B = c(2, 3, 3, 5, 6))
df %>% group_by(A) %>% summarise(B = sum(B))

## Source: local data frame [3 x 2]
## 
##   A  B
## 1 1  5
## 2 2  3
## 3 3 11

With sqldf:

library(sqldf)
sqldf('SELECT A, SUM(B) AS B FROM df GROUP BY A')

subtract two times in python

datetime.time can not do it - But you could use datetime.datetime.now()

start = datetime.datetime.now()
sleep(10)
end = datetime.datetime.now()
duration = end - start

fork() child and parent processes

Start by reading the fork man page as well as the getppid / getpid man pages.

From fork's

On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set appropriately.

So this should be something down the lines of

if ((pid=fork())==0){
    printf("yada yada %u and yada yada %u",getpid(),getppid());
}
else{ /* avoids error checking*/
    printf("Dont yada yada me, im your parent with pid %u ", getpid());
}

As to your question:

This is the child process. My pid is 22163 and my parent's id is 0.

This is the child process. My pid is 22162 and my parent's id is 22163.

fork() executes before the printf. So when its done, you have two processes with the same instructions to execute. Therefore, printf will execute twice. The call to fork() will return 0 to the child process, and the pid of the child process to the parent process.

You get two running processes, each one will execute this instruction statement:

printf ("... My pid is %d and my parent's id is %d",getpid(),0); 

and

printf ("... My pid is %d and my parent's id is %d",getpid(),22163);  

~

To wrap it up, the above line is the child, specifying its pid. The second line is the parent process, specifying its id (22162) and its child's (22163).

Absolute and Flexbox in React Native

Ok, solved my problem, if anyone is passing by here is the answer:

Just had to add left: 0, and top: 0, to the styles, and yes, I'm tired.

position: 'absolute',
left:     0,
top:      0,

How to hide form code from view code/inspect element browser?

While I don't think there is a way to fully do this you can take a few measures to stop almost everyone from viewing the HTML.

You can first of all try and stop the inspect menu by doing the following:

<body oncontextmenu="return false" onkeydown="return false;" onmousedown="return false;">

I would also suggest using the method that Jonas gave of using his javascript and putting what you don't want people to see in a div with id="element-to-hide" and his given js script to furthermore stop people from inspecting.

I'm pretty sure that it's quite hard to get past that. But then someone can just type view-source:www.exapmle.com and that will show them the source. So you will then probably want to encrypt the HTML(I would advise using a website that gives you an extended security option). There are plenty of good websites that do this for free (eg:http://www.smartgb.com/free_encrypthtml.php) and use extended security which you can't usually unencrypt through HTML un encryptors.

This will basically encrypt your HTML so if you view the source using the method I showed above you will just get encrypted HTML(that is also extremely difficult to unencrypt if you used the extended security option). But you can view the unencrypted HTML through inspecting but we have already blocked that(to a very reasonable extent)

Ok so you can't fully hide the HTML but you can do an extremely good job at stopping people seeing it.(If you think about it most people don't care about looking at a page's HTML, some people don't even know about inspecting and viewing the source and the people who do probably won't be bothered or won't be able to get past theses implications! So probably no one will see you HTML)

(Hope this helps!)

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

This answer seems quite outdated and not adapt for nowadays single page applications. In my case I found the solution thank to this aricle where a simple but effective solution is proposed:

_x000D_
_x000D_
html,
body {
  position: fixed;
  overflow: hidden;
}
_x000D_
_x000D_
_x000D_

This solution it's not applicable if your body is your scroll container.

Useful example of a shutdown hook in Java?

You could do the following:

  • Let the shutdown hook set some AtomicBoolean (or volatile boolean) "keepRunning" to false
  • (Optionally, .interrupt the working threads if they wait for data in some blocking call)
  • Wait for the working threads (executing writeBatch in your case) to finish, by calling the Thread.join() method on the working threads.
  • Terminate the program

Some sketchy code:

  • Add a static volatile boolean keepRunning = true;
  • In run() you change to

    for (int i = 0; i < N && keepRunning; ++i)
        writeBatch(pw, i);
    
  • In main() you add:

    final Thread mainThread = Thread.currentThread();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            keepRunning = false;
            mainThread.join();
        }
    });
    

That's roughly how I do a graceful "reject all clients upon hitting Control-C" in terminal.


From the docs:

When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the run()-method.

Vue - Deep watching an array of objects and calculating the change?

This is what I use to deep watch an object. My requirement was watching the child fields of the object.

new Vue({
    el: "#myElement",
    data:{
        entity: {
            properties: []
        }
    },
    watch:{
        'entity.properties': {
            handler: function (after, before) {
                // Changes detected.    
            },
            deep: true
        }
    }
});

Google.com and clients1.google.com/generate_204

Google is using this to detect whether the device is online or in captive portal.

Shill, the connection manager for Chromium OS, attempts to detect services that are within a captive portal whenever a service transitions to the ready state. This determination of being in a captive portal or being online is done by attempting to retrieve the webpage http://clients3.google.com/generate_204. This well known URL is known to return an empty page with an HTTP status 204. If for any reason the web page is not returned, or an HTTP response other than 204 is received, then shill marks the service as being in the portal state.

Here is the relevant explanation from the Google Chrome Privacy Whitepaper:

In the event that Chrome detects SSL connection timeouts, certificate errors, or other network issues that might be caused by a captive portal (a hotel's WiFi network, for instance), Chrome will make a cookieless request to http://www.gstatic.com/generate_204 and check the response code. If that request is redirected, Chrome will open the redirect target in a new tab on the assumption that it's a login page. Requests to the captive portal detection page are not logged.

More info: http://www.chromium.org/chromium-os/chromiumos-design-docs/network-portal-detection

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

TF2 runs Eager Execution by default, thus removing the need for Sessions. If you want to run static graphs, the more proper way is to use tf.function() in TF2. While Session can still be accessed via tf.compat.v1.Session() in TF2, I would discourage using it. It may be helpful to demonstrate this difference by comparing the difference in hello worlds:

TF1.x hello world:

import tensorflow as tf
msg = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(msg))

TF2.x hello world:

import tensorflow as tf
msg = tf.constant('Hello, TensorFlow!')
tf.print(msg)

For more info, see Effective TensorFlow 2

How to split one text file into multiple *.txt files?

If each part have the same lines number, for example 22, here my solution:
split --numeric-suffixes=2 --additional-suffix=.txt -l 22 file.txt file
and you obtain file2.txt with the first 22 lines, file3.txt the 22 next line…

Thank @hamruta-takawale, @dror-s and @stackoverflowuser2010

Difference between DOM parentNode and parentElement

Just like with nextSibling and nextElementSibling, just remember that, properties with "element" in their name always returns Element or null. Properties without can return any other kind of node.

console.log(document.body.parentNode, "is body's parent node");    // returns <html>
console.log(document.body.parentElement, "is body's parent element"); // returns <html>

var html = document.body.parentElement;
console.log(html.parentNode, "is html's parent node"); // returns document
console.log(html.parentElement, "is html's parent element"); // returns null

How to efficiently build a tree from a flat structure?

I can do this in 4 lines of code and O(n log n) time, assuming that Dictionary is something like a TreeMap.

dict := Dictionary new.
ary do: [:each | dict at: each id put: each].
ary do: [:each | (dict at: each parent) addChild: each].
root := dict at: nil.

EDIT: Ok, and now I read that some parentIDs are fake, so forget the above, and do this:

dict := Dictionary new.
dict at: nil put: OrderedCollection new.
ary do: [:each | dict at: each id put: each].
ary do: [:each | 
    (dict at: each parent ifAbsent: [dict at: nil]) 
          add: each].
roots := dict at: nil.

How do I compare two Integers?

I would go with x.equals(y) because that's consistent way to check equality for all classes.

As far as performance goes, equals is actually more expensive because it ends up calling intValue().

EDIT: You should avoid autoboxing in most cases. It can get really confusing, especially the author doesn't know what he was doing. You can try this code and you will be surprised by the result;

Integer a = 128;
Integer b = 128;

System.out.println(a==b);

Is there a way to SELECT and UPDATE rows at the same time?

Edit: my bad, you wanted the select to show results after the update, not update from a select.

Have you tried a sub-select?

update mytable set mydate = sysdate 
where mydate in (select mydate from mytable where mydate is null);

What is difference between sleep() method and yield() method of multi threading?

One way to request the current thread to relinquish CPU so that other threads can get a chance to execute is to use yield in Java.

yield is a static method. It doesn't say which other thread will get the CPU. It is possible for the same thread to get back the CPU and start its execution again.

public class Solution9  {

public static void main(String[] args) {
        yclass yy = new yclass ();
        Thread t1= new Thread(yy);
        t1.start();
        for (int i = 0; i <3; i++) {
            Thread.yield();
            System.out.println("during yield control => " + Thread.currentThread().getName());
        }
    }
}

class yclass implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println("control => " + Thread.currentThread().getName());
        }
    }
}

Extreme wait-time when taking a SQL Server database offline

Do you have any open SQL Server Management Studio windows that are connected to this DB?

Put it in single user mode, and then try again.

Is there a way to cast float as a decimal without rounding and preserving its precision?

cast (field1 as decimal(53,8)
) field 1

The default is: decimal(18,0)

Inserting records into a MySQL table using Java

This should work for any table, instead of hard-coding the columns.

_x000D_
_x000D_
//Source details_x000D_
    String sourceUrl = "jdbc:oracle:thin:@//server:1521/db";_x000D_
    String sourceUserName = "src";_x000D_
    String sourcePassword = "***";_x000D_
_x000D_
    // Destination details_x000D_
    String destinationUserName = "dest";_x000D_
    String destinationPassword = "***";_x000D_
    String destinationUrl = "jdbc:mysql://server:3306/db";_x000D_
_x000D_
    Connection srcConnection = getSourceConnection(sourceUrl, sourceUserName, sourcePassword);_x000D_
    Connection destConnection = getDestinationConnection(destinationUrl, destinationUserName, destinationPassword);_x000D_
_x000D_
    PreparedStatement sourceStatement = srcConnection.prepareStatement("SELECT *  FROM src_table ");_x000D_
    ResultSet rs = sourceStatement.executeQuery();_x000D_
    rs.setFetchSize(1000); // not needed_x000D_
_x000D_
_x000D_
    ResultSetMetaData meta = rs.getMetaData();_x000D_
_x000D_
_x000D_
_x000D_
    List<String> columns = new ArrayList<>();_x000D_
    for (int i = 1; i <= meta.getColumnCount(); i++)_x000D_
        columns.add(meta.getColumnName(i));_x000D_
_x000D_
    try (PreparedStatement destStatement = destConnection.prepareStatement(_x000D_
            "INSERT INTO dest_table ("_x000D_
                    + columns.stream().collect(Collectors.joining(", "))_x000D_
                    + ") VALUES ("_x000D_
                    + columns.stream().map(c -> "?").collect(Collectors.joining(", "))_x000D_
                    + ")"_x000D_
            )_x000D_
    )_x000D_
    {_x000D_
        int count = 0;_x000D_
        while (rs.next()) {_x000D_
            for (int i = 1; i <= meta.getColumnCount(); i++) {_x000D_
                destStatement.setObject(i, rs.getObject(i));_x000D_
            }_x000D_
            _x000D_
            destStatement.addBatch();_x000D_
            count++;_x000D_
        }_x000D_
        destStatement.executeBatch(); // you will see all the rows in dest once this statement is executed_x000D_
        System.out.println("done " + count);_x000D_
_x000D_
    }
_x000D_
_x000D_
_x000D_

jQuery UI " $("#datepicker").datepicker is not a function"

Go for the obvious first: Are you referencing well the jquery-ui.js file?

Try using the network tab of firebug to find if it is loaded, or the Information\View javascript code of the Web Developer Toolbar.

Empty an array in Java / processing

array = new String[array.length];

jQuery - Uncaught RangeError: Maximum call stack size exceeded

Your calls are made recursively which pushes functions on to the stack infinitely that causes max call stack exceeded error due to recursive behavior. Instead try using setTimeout which is a callback.

Also based on your markup your selector is wrong. it should be #advisersDiv

Demo

function fadeIn() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
    setTimeout(fadeOut,1); //<-- Provide any delay here
};

function fadeOut() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
    setTimeout(fadeIn,1);//<-- Provide any delay here
};
fadeIn();

How to get a Color from hexadecimal Color String

Try Color class method:

public static int parseColor (String colorString)

From Android documentation:

Supported formats are: #RRGGBB #AARRGGBB 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray'

AndroidX: String.toColorInt()

Serialize object to query string in JavaScript/jQuery

Another option might be node-querystring.

It's available in both npm and bower, which is why I have been using it.

How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

I believe there is a maximum number of concurrent http requests that browsers will make to the same domain, which is in the order of 4-8 requests depending on the user's settings and browser.

You could set up your requests to go to different domains, which may or may not be feasible. The Yahoo guys did a lot of research in this area, which you can read about (here). Remember that every new domain you add also requires a DNS lookup. The YSlow guys recommend between 2 and 4 domains to achieve a good compromise between parallel requests and DNS lookups, although this is focusing on the page's loading time, not subsequent AJAX requests.

Can I ask why you want to make so many requests? There is good reasons for the browsers limiting the number of requests to the same domain. You will be better off bundling requests if possible.

How to extract text from the PDF document?

I know that this topic is quite old, but this need is still alive. I read many documents, forum and script and build a new advanced one which supports compressed and uncompressed pdf :

https://gist.github.com/smalot/6183152

Hope it helps everone

Insert Unicode character into JavaScript

Although @ruakh gave a good answer, I will add some alternatives for completeness:

You could in fact use even var Omega = '&#937;' in JavaScript, but only if your JavaScript code is:

  • inside an event attribute, as in onclick="var Omega = '&#937'; alert(Omega)" or
  • in a script element inside an XHTML (or XHTML + XML) document served with an XML content type.

In these cases, the code will be first (before getting passed to the JavaScript interpreter) be parsed by an HTML parser so that character references like &#937; are recognized. The restrictions make this an impractical approach in most cases.

You can also enter the O character as such, as in var Omega = 'O', but then the character encoding must allow that, the encoding must be properly declared, and you need software that let you enter such characters. This is a clean solution and quite feasible if you use UTF-8 encoding for everything and are prepared to deal with the issues created by it. Source code will be readable, and reading it, you immediately see the character itself, instead of code notations. On the other hand, it may cause surprises if other people start working with your code.

Using the \u notation, as in var Omega = '\u03A9', works independently of character encoding, and it is in practice almost universal. It can however be as such used only up to U+FFFF, i.e. up to \uffff, but most characters that most people ever heard of fall into that area. (If you need “higher” characters, you need to use either surrogate pairs or one of the two approaches above.)

You can also construct a character using the String.fromCharCode() method, passing as a parameter the Unicode number, in decimal as in var Omega = String.fromCharCode(937) or in hexadecimal as in var Omega = String.fromCharCode(0x3A9). This works up to U+FFFF. This approach can be used even when you have the Unicode number in a variable.

Correct way to use StringBuilder in SQL

When you already have all the "pieces" you wish to append, there is no point in using StringBuilder at all. Using StringBuilder and string concatenation in the same call as per your sample code is even worse.

This would be better:

return "select id1, " + " id2 " + " from " + " table";

In this case, the string concatenation is actually happening at compile-time anyway, so it's equivalent to the even-simpler:

return "select id1, id2 from table";

Using new StringBuilder().append("select id1, ").append(" id2 ")....toString() will actually hinder performance in this case, because it forces the concatenation to be performed at execution time, instead of at compile time. Oops.

If the real code is building a SQL query by including values in the query, then that's another separate issue, which is that you should be using parameterized queries, specifying the values in the parameters rather than in the SQL.

I have an article on String / StringBuffer which I wrote a while ago - before StringBuilder came along. The principles apply to StringBuilder in the same way though.

Rebase array keys after unsetting elements

Use array_splice rather than unset:

$array = array(1,2,3,4,5);
foreach($array as $i => $info)
{
  if($info == 1 || $info == 2)
  {
    array_splice($array, $i, 1);
  }
}

print_r($array);

Working sample here.

Build unsigned APK file with Android Studio

I solve it!

First off all, you should add these:

defaultConfig { 
 multiDexEnabled true
}

dependencies {
 implementation 'com.android.support:multidex:1.0.3'
}

After, you should click Build in top bar of Android Studio:

Build > Build Bundle(s) / APK(s) > Build APK(s)

Finally, you have an app-debug.apk file in:

app > build > outputs > apk > debug > app-debug.apk

Note: apk, debug, app-debug.apk files created automatically in outputs file by Android Studio.

How can I check if a directory exists?

The best way is probably trying to open it, using just opendir() for instance.

Note that it's always best to try to use a filesystem resource, and handling any errors occuring because it doesn't exist, rather than just checking and then later trying. There is an obvious race condition in the latter approach.

jquery .live('click') vs .click()

.live() is used if elements are being added after the initial page load. Say you have a button which gets added by an AJAX call after the page gets loaded. This new button will not be accessible using .click(), so you'll have to use .live('click')

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

CR has changed the Version No of Assemblies. The Old Version is 13.0.2000.0 (this is a incompatible version problem). The New Version is 13.0.3500.0 or 13.0.4000.0 - this is for my test case of Visual Studio 2019 and .net 4.7.2 and Window Server 2019. You need to open all your projects, Remove the old dll reference and add the new references. Then build the application again.

I learnt from source:

enter image description here

TO remove: Right click on an assembly under references to remove it.

enter image description here

This is where the error comes from - it is exactly what the error message outputs:

error message:

Could not load file or assembly ... The located assembly's manifest definition does not match the assembly reference ...

location error message referring to:

"C:\Visual-Studio-2019-Proj\Proj Windows Inventory\Proj Windows Inventory\obj\x86\Debug\Press HDL Windows Inventory.exe.manifest"

And it looks like this:

-The older version of .net 3.5 and CReports version="13.0.2000.0" and VS2012:

<dependentAssembly dependencyType="install" allowDelayedBinding="true" codebase="CrystalDecisions.CrystalReports.Engine.dll" size="372736">
      <assemblyIdentity name="CrystalDecisions.CrystalReports.Engine" version="13.0.2000.0" publicKeyToken="692FBEA5521E1304" language="neutral" processorArchitecture="msil" />

-The newer version of .net 4.7.2 and CReport version="13.0.4000.0" and VS2019:

<dependentAssembly dependencyType="install" allowDelayedBinding="true" codebase="CrystalDecisions.CrystalReports.Engine.dll" size="373248">
      <assemblyIdentity name="CrystalDecisions.CrystalReports.Engine" version="13.0.4000.0" publicKeyToken="692FBEA5521E1304" language="neutral" processorArchitecture="msil" />

How to set opacity in parent div and not affect in child div?

You can't. Css today simply doesn't allow that.

The logical rendering model is this one :

If the object is a container element, then the effect is as if the contents of the container element were blended against the current background using a mask where the value of each pixel of the mask is .

Reference : css transparency

The solution is to use a different element composition, usually using fixed or computed positions for what is today defined as a child : it may appear logically and visualy for the user as a child but the element doesn't need to be really a child in your code.

A solution using css : fiddle

.parent {
    width:500px;
    height:200px;    
    background-image:url('http://canop.org/blog/wp-content/uploads/2011/11/cropped-bandeau-cr%C3%AAte-011.jpg');
    opacity: 0.2;
}
.child {
    position: fixed;
    top:0;
}

Another solution with javascript : fiddle

How to set up a cron job to run an executable every hour?

0 * * * * cd folder_containing_exe && ./exe_name

should work unless there is something else that needs to be setup for the program to run.

How to change Windows 10 interface language on Single Language version

1) Upgrade using windows update or using "media creation tool" http://windows.microsoft.com/en-us/windows-10/media-creation-tool-install

  • if you are using "media creation tool" select "Upgrade this PC now"

When Windows 10 installed check that it is activated.

2) Now as you have activated Windows 10 using "media creation tool" http://windows.microsoft.com/en-us/windows-10/media-creation-tool-install select second option "Create installation media for another PC" here you can select Windows version and its language. Make sure that Windows version is also "Single Language"

3) Boot from you device, USB in my case and install clean Windows in English or any other language you selected.

reference http://bit.ly/1RKmPBs

How to use a parameter in ExecStart command line?

Although systemd indeed does not provide way to pass command-line arguments for unit files, there are possibilities to write instances: http://0pointer.de/blog/projects/instances.html

For example: /lib/systemd/system/[email protected] looks something like this:

[Unit]
Description=Serial Getty on %I
BindTo=dev-%i.device
After=dev-%i.device systemd-user-sessions.service

[Service]
ExecStart=-/sbin/agetty -s %I 115200,38400,9600
Restart=always
RestartSec=0

So, you may start it like:

$ systemctl start [email protected]
$ systemctl start [email protected]

For systemd it will different instances:

$ systemctl status [email protected]
[email protected] - Getty on ttyUSB0
      Loaded: loaded (/lib/systemd/system/[email protected]; static)
      Active: active (running) since Mon, 26 Sep 2011 04:20:44 +0200; 2s ago
    Main PID: 5443 (agetty)
      CGroup: name=systemd:/system/[email protected]/ttyUSB0
          + 5443 /sbin/agetty -s ttyUSB0 115200,38400,9600

It also mean great possibility enable and disable it separately.

Off course it lack much power of command line parsing, but in common way it is used as some sort of config files selection. For example you may look at Fedora [email protected]: http://pkgs.fedoraproject.org/cgit/openvpn.git/tree/[email protected]

Is there a way to style a TextView to uppercase all of its letters?

It seems like there is permission on mobile keypad setting, so the easiest way to do this is:

editText.setFilters(new InputFilter[]{new InputFilter.AllCaps()});

hope this will work

How to get the current loop index when using Iterator?

I had the same question and found using a ListIterator worked. Similar to the test above:

List<String> list = Arrays.asList("zero", "one", "two");

ListIterator iter = list.listIterator();
    
while (iter.hasNext()) {
    System.out.println("index: " + iter.nextIndex() + " value: " + iter.next());
}

Make sure you call the nextIndex() before you actually get the next().

Generate full SQL script from EF 5 Code First Migrations

The API appears to have changed (or at least, it doesn't work for me).

Running the following in the Package Manager Console works as expected:

Update-Database -Script -SourceMigration:0

Extract filename and extension in Bash

That doesn't seem to work if the file has no extension, or no filename. Here is what I'm using; it only uses builtins and handles more (but not all) pathological filenames.

#!/bin/bash
for fullpath in "$@"
do
    filename="${fullpath##*/}"                      # Strip longest match of */ from start
    dir="${fullpath:0:${#fullpath} - ${#filename}}" # Substring from 0 thru pos of filename
    base="${filename%.[^.]*}"                       # Strip shortest match of . plus at least one non-dot char from end
    ext="${filename:${#base} + 1}"                  # Substring from len of base thru end
    if [[ -z "$base" && -n "$ext" ]]; then          # If we have an extension and no base, it's really the base
        base=".$ext"
        ext=""
    fi

    echo -e "$fullpath:\n\tdir  = \"$dir\"\n\tbase = \"$base\"\n\text  = \"$ext\""
done

And here are some testcases:

$ basename-and-extension.sh / /home/me/ /home/me/file /home/me/file.tar /home/me/file.tar.gz /home/me/.hidden /home/me/.hidden.tar /home/me/.. .
/:
    dir  = "/"
    base = ""
    ext  = ""
/home/me/:
    dir  = "/home/me/"
    base = ""
    ext  = ""
/home/me/file:
    dir  = "/home/me/"
    base = "file"
    ext  = ""
/home/me/file.tar:
    dir  = "/home/me/"
    base = "file"
    ext  = "tar"
/home/me/file.tar.gz:
    dir  = "/home/me/"
    base = "file.tar"
    ext  = "gz"
/home/me/.hidden:
    dir  = "/home/me/"
    base = ".hidden"
    ext  = ""
/home/me/.hidden.tar:
    dir  = "/home/me/"
    base = ".hidden"
    ext  = "tar"
/home/me/..:
    dir  = "/home/me/"
    base = ".."
    ext  = ""
.:
    dir  = ""
    base = "."
    ext  = ""

"Conversion to Dalvik format failed with error 1" on external JAR

Just clean the project

If this does not work try the other solutions

How do I do a case-insensitive string comparison?

Assuming ASCII strings:

string1 = 'Hello'
string2 = 'hello'

if string1.lower() == string2.lower():
    print("The strings are the same (case insensitive)")
else:
    print("The strings are NOT the same (case insensitive)")

Get the ID of a drawable in ImageView

Even easier: just store the R.drawable id in the view's id: use v.setId(). Then get it back with v.getId().

How To Auto-Format / Indent XML/HTML in Notepad++

Not exactly a solution but a workaround.

Notepad ++ doesn't provide any such feature by default. But you can use some online tools to autoformat text like https://www.freeformatter.com/xml-formatter.html.

It helps. :)

Get fragment (value after hash '#') from a URL in php

You need to parse the url first, so it goes like this:

$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'

If you need to parse the actual url of the current browser, you need to request to call the server.

$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

Dec 10th 2019, Xcode Version 11.2.1, MacOS X 10.15.1

I was facing exactly same issue yesterday and I thought it might be network issues, at least it looks like so. But this morning I had tried couple different networks and several VPN connections, none of them is working!

The highest voted answer here asks me to reset a cache folder named .itmstransporter under my home dir, the run a program iTMSTransporter under a specific folder, but I can't find both of them.

But soon I figured that it is the cache folder for the people who uses the legacy uploader program: Application Loader, which is deprecated by Apple and can be no longer found in Xcode 11. Then I found that the latest Xcode has located iTMSTransporter here:

/Applications/Xcode.app/Contents/SharedFrameworks/ContentDeliveryServices.framework/itms/bin/iTMSTransporter

And its cache folder is here:

/Users/your_user_name/Library/Caches/com.apple.amp.itmstransporter/

I removed my existed cache folder, and run iTMSTransporter without any parameter, it soon started to output logs and download a bunch of files, and finished in 2 or 3 minutes. Then I tried again to upload my ipa file, it works!!!

CONCLUTION:

  1. Either the old Application Loader, or the latest Xcode, uses a Java program iTMSTransporter to process the ipa file uploading.
  2. To function correctly, iTMSTransporter requires a set of jar files downloaded from Internet and cached in your local folder.
  3. If your cache is somehow broken, or doesn't exist at all, directly invoking iTMSTransporter with functional parameters such as --upload-app in our case, iTMSTransporter DOES NOT WARN YOU, NOR FIX CACHE BY ITSELF, it just gets stuck there, SAYS NOTHING AT ALL! (Whoever wrote this iTMSTransporter, you seriously need to improve your programming sense).
  4. Invoking iTMSTransporter without any parameter fixes the cache.
  5. A functional cache is about 65MB, at Dec 10th 2019 with Xcode Version 11.2.1 (11B500)

Correct way to synchronize ArrayList in java

Let's take a normal list (implemented by the ArrayList class) and make it synchronized. This is shown in the SynchronizedListExample class. We pass the Collections.synchronizedList method a new ArrayList of Strings. The method returns a synchronized List of Strings. //Here is SynchronizedArrayList class

package com.mnas.technology.automation.utility;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
/**
* 
* @author manoj.kumar
* @email [email protected]
* 
*/
public class SynchronizedArrayList {
    static Logger log = Logger.getLogger(SynchronizedArrayList.class.getName());
    public static void main(String[] args) {    
        List<String> synchronizedList = Collections.synchronizedList(new ArrayList<String>());
        synchronizedList.add("Aditya");
        synchronizedList.add("Siddharth");
        synchronizedList.add("Manoj");
        // when iterating over a synchronized list, we need to synchronize access to the synchronized list
        synchronized (synchronizedList) {
            Iterator<String> iterator = synchronizedList.iterator();
            while (iterator.hasNext()) {
                log.info("Synchronized Array List Items: " + iterator.next());
            }
        }    
    }
}

Notice that when iterating over the list, this access is still done using a synchronized block that locks on the synchronizedList object. In general, iterating over a synchronized collection should be done in a synchronized block

Right way to write JSON deserializer in Spring or extend it

I've searched a lot and the best way I've found so far is on this article:

Class to serialize

package net.sghill.example;

import net.sghill.example.UserDeserializer
import net.sghill.example.UserSerializer
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonDeserialize(using = UserDeserializer.class)
public class User {
    private ObjectId id;
    private String   username;
    private String   password;

    public User(ObjectId id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public ObjectId getId()       { return id; }
    public String   getUsername() { return username; }
    public String   getPassword() { return password; }
}

Deserializer class

package net.sghill.example;

import net.sghill.example.User;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

import java.io.IOException;

public class UserDeserializer extends JsonDeserializer<User> {

    @Override
    public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
        return new User(null, node.get("username").getTextValue(), node.get("password").getTextValue());
    }
}

Edit: Alternatively you can look at this article which uses new versions of com.fasterxml.jackson.databind.JsonDeserializer.

ERROR 1064 (42000) in MySQL

Check your dump file. Looks like a stray character at the beginning. SQL isn't standard the world around, and the MySQL importer expects MySQL-friendly SQL. I'm willing to bet that your exporter did something funky.

You may have to massage the file a bit to get it to work with MySQL.

Hash string in c#

The shortest and fastest way ever. Only 1 line!

    public static string StringSha256Hash(string text) =>
        string.IsNullOrEmpty(text) ? string.Empty : BitConverter.ToString(new System.Security.Cryptography.SHA256Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(text))).Replace("-", string.Empty);

What to do on TransactionTooLargeException

This is not a definitive answer, but it may shed some light on the causes of a TransactionTooLargeException and help pinpoint the problem.

Although most answers refer to large amounts of data transferred, I see this exception being thrown incidentally after heavy scrolling and zooming and repeatedly opening an ActionBar spinner menu. The crash happens on tapping the action bar. (this is a custom mapping app)

The only data being passed around seem to be touches from the "Input Dispatcher" to the app. I think this cannot reasonably amount to anywhere near 1 mb in the "Transaction Buffer".

My app is running on a quad core 1.6 GHz device and uses 3 threads for heavylifting, keeping one core free for the UI thread. Furthermore, the app uses android:largeHeap, has 10 mb of unused heap left and has 100 mb of room left to grow the heap. So I wouldn't say it is a resource issue.

The crash is always immediately preceded by these lines:

W/InputDispatcher( 2271): channel ~ Consumer closed input channel or an error occurred.  events=0x9
E/InputDispatcher( 2271): channel ~ Channel is unrecoverably broken and will be disposed!
E/JavaBinder(28182): !!! FAILED BINDER TRANSACTION !!!

Which are not neccesarily printed in that order, but (as far as I checked) happen on the same millisecond.

And the stack trace itself, for clarity, is the same as in the question:

E/AndroidRuntime(28182): java.lang.RuntimeException: Adding window failed
..
E/AndroidRuntime(28182): Caused by: android.os.TransactionTooLargeException

Delving into the source code of android one finds these lines:

frameworks/base/core/jni/android_util_Binder.cpp:

case FAILED_TRANSACTION:
    ALOGE("!!! FAILED BINDER TRANSACTION !!!");
    // TransactionTooLargeException is a checked exception, only throw from certain methods.
    // FIXME: Transaction too large is the most common reason for FAILED_TRANSACTION
    //        but it is not the only one.  The Binder driver can return BR_FAILED_REPLY
    //        for other reasons also, such as if the transaction is malformed or
    //        refers to an FD that has been closed.  We should change the driver
    //        to enable us to distinguish these cases in the future.
    jniThrowException(env, canThrowRemoteException
            ? "android/os/TransactionTooLargeException"
                    : "java/lang/RuntimeException", NULL);

To me it sounds like I'm possibly hitting this undocumented feature, where the transaction fails for other reasons than a Transaction being TooLarge. They should have named it TransactionTooLargeOrAnotherReasonException.

At this time I did not solve the issue, but if I find something useful I will update this answer.

update: it turned out my code leaked some file descriptors, the number of which is maximized in linux (typically 1024), and this seems to have triggered the exception. So it was a resource issue after all. I verified this by opening /dev/zero 1024 times, which resulted in all kinds of weird exceptions in UI related actions, including the exception above, and even some SIGSEGV's. Apparently failure to open a file/socket is not something which is handled/reported very cleanly throughout Android.

Structure of a PDF file?

One way to get some clues is to create a PDF file consisting of a blank page. I have CutePDF Writer on my computer, and made a blank Wordpad document of one page. Printed to a .pdf file, and then opened the .pdf file using Notepad.

Next, use a copy of this file and eliminate lines or blocks of text that might be of interest, then reload in Acrobat Reader. You'd be surprised at how little information is needed to make a working one-page PDF document.

I'm trying to make up a spreadsheet to create a PDF form from code.

How to embed HTML into IPython output?

Some time ago Jupyter Notebooks started stripping JavaScript from HTML content [#3118]. Here are two solutions:

Serving Local HTML

If you want to embed an HTML page with JavaScript on your page now, the easiest thing to do is to save your HTML file to the directory with your notebook and then load the HTML as follows:

from IPython.display import IFrame

IFrame(src='./nice.html', width=700, height=600)

Serving Remote HTML

If you prefer a hosted solution, you can upload your HTML page to an Amazon Web Services "bucket" in S3, change the settings on that bucket so as to make the bucket host a static website, then use an Iframe component in your notebook:

from IPython.display import IFrame

IFrame(src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600)

This will render your HTML content and JavaScript in an iframe, just like you can on any other web page:

_x000D_
_x000D_
<iframe src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600></iframe>
_x000D_
_x000D_
_x000D_

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

Many times when crawling we run into problems where content that is rendered on the page is generated with Javascript and therefore scrapy is unable to crawl for it (eg. ajax requests, jQuery craziness).

However, if you use Scrapy along with the web testing framework Selenium then we are able to crawl anything displayed in a normal web browser.

Some things to note:

  • You must have the Python version of Selenium RC installed for this to work, and you must have set up Selenium properly. Also this is just a template crawler. You could get much crazier and more advanced with things but I just wanted to show the basic idea. As the code stands now you will be doing two requests for any given url. One request is made by Scrapy and the other is made by Selenium. I am sure there are ways around this so that you could possibly just make Selenium do the one and only request but I did not bother to implement that and by doing two requests you get to crawl the page with Scrapy too.

  • This is quite powerful because now you have the entire rendered DOM available for you to crawl and you can still use all the nice crawling features in Scrapy. This will make for slower crawling of course but depending on how much you need the rendered DOM it might be worth the wait.

    from scrapy.contrib.spiders import CrawlSpider, Rule
    from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
    from scrapy.selector import HtmlXPathSelector
    from scrapy.http import Request
    
    from selenium import selenium
    
    class SeleniumSpider(CrawlSpider):
        name = "SeleniumSpider"
        start_urls = ["http://www.domain.com"]
    
        rules = (
            Rule(SgmlLinkExtractor(allow=('\.html', )), callback='parse_page',follow=True),
        )
    
        def __init__(self):
            CrawlSpider.__init__(self)
            self.verificationErrors = []
            self.selenium = selenium("localhost", 4444, "*chrome", "http://www.domain.com")
            self.selenium.start()
    
        def __del__(self):
            self.selenium.stop()
            print self.verificationErrors
            CrawlSpider.__del__(self)
    
        def parse_page(self, response):
            item = Item()
    
            hxs = HtmlXPathSelector(response)
            #Do some XPath selection with Scrapy
            hxs.select('//div').extract()
    
            sel = self.selenium
            sel.open(response.url)
    
            #Wait for javscript to load in Selenium
            time.sleep(2.5)
    
            #Do some crawling of javascript created content with Selenium
            sel.get_text("//div")
            yield item
    
    # Snippet imported from snippets.scrapy.org (which no longer works)
    # author: wynbennett
    # date  : Jun 21, 2011
    

Reference: http://snipplr.com/view/66998/

Undo a merge by pull request?

To undo a github pull request with commits throughout that you do not want to delete, you have to run a:

git reset --hard --merge <commit hash>

with the commit hash being the commit PRIOR to merging the pull request. This will remove all commits from the pull request without influencing any commits within the history.

A good way to find this is to go to the now closed pull request and finding this field:

Pull Request Image Pull Request Image

After you run the git reset, run a:

git push origin --force <branch name>

This should revert the branch back before the pull request WITHOUT affecting any commits in the branch peppered into the commit history between commits from the pull request.

EDIT:

If you were to click the revert button on the pull request, this creates an additional commit on the branch. It DOES NOT uncommit or unmerge. This means that if you were to hit the revert button, you cannot open a new pull request to re-add all of this code.

When and why do I need to use cin.ignore() in C++?

It is better to use scanf(" %[^\n]",str) in c++ than cin.ignore() after cin>> statement.To do that first you have to include < cstdio > header.

Python idiom to return first item or None

Python idiom to return first item or None?

The most Pythonic approach is what the most upvoted answer demonstrated, and it was the first thing to come to my mind when I read the question. Here's how to use it, first if the possibly empty list is passed into a function:

def get_first(l): 
    return l[0] if l else None

And if the list is returned from a get_list function:

l = get_list()
return l[0] if l else None

Other ways demonstrated to do this here, with explanations

for

When I began trying to think of clever ways to do this, this is the second thing I thought of:

for item in get_list():
    return item

This presumes the function ends here, implicitly returning None if get_list returns an empty list. The below explicit code is exactly equivalent:

for item in get_list():
    return item
return None

if some_list

The following was also proposed (I corrected the incorrect variable name) which also uses the implicit None. This would be preferable to the above, as it uses the logical check instead of an iteration that may not happen. This should be easier to understand immediately what is happening. But if we're writing for readability and maintainability, we should also add the explicit return None at the end:

some_list = get_list()
if some_list:
    return some_list[0]

slice or [None] and select zeroth index

This one is also in the most up-voted answer:

return (get_list()[:1] or [None])[0]

The slice is unnecessary, and creates an extra one-item list in memory. The following should be more performant. To explain, or returns the second element if the first is False in a boolean context, so if get_list returns an empty list, the expression contained in the parentheses will return a list with 'None', which will then be accessed by the 0 index:

return (get_list() or [None])[0]

The next one uses the fact that and returns the second item if the first is True in a boolean context, and since it references my_list twice, it is no better than the ternary expression (and technically not a one-liner):

my_list = get_list() 
return (my_list and my_list[0]) or None

next

Then we have the following clever use of the builtin next and iter

return next(iter(get_list()), None)

To explain, iter returns an iterator with a .next method. (.__next__ in Python 3.) Then the builtin next calls that .next method, and if the iterator is exhausted, returns the default we give, None.

redundant ternary expression (a if b else c) and circling back

The below was proposed, but the inverse would be preferable, as logic is usually better understood in the positive instead of the negative. Since get_list is called twice, unless the result is memoized in some way, this would perform poorly:

return None if not get_list() else get_list()[0]

The better inverse:

return get_list()[0] if get_list() else None

Even better, use a local variable so that get_list is only called one time, and you have the recommended Pythonic solution first discussed:

l = get_list()
return l[0] if l else None

JavaScript listener, "keypress" doesn't detect backspace?

event.key === "Backspace"

More recent and much cleaner: use event.key. No more arbitrary number codes!

note.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace") {
        // Do something
    }
});

Mozilla Docs

Supported Browsers

Pyspark: Filter dataframe based on multiple conditions

You can also write like below (without pyspark.sql.functions):

df.filter('d<5 and (col1 <> col3 or (col1 = col3 and col2 <> col4))').show()

Result:

+----+----+----+----+---+
|col1|col2|col3|col4|  d|
+----+----+----+----+---+
|   A|  xx|   D|  vv|  4|
|   A|   x|   A|  xx|  3|
|   E| xxx|   B|  vv|  3|
|   F|xxxx|   F| vvv|  4|
|   G| xxx|   G|  xx|  4|
+----+----+----+----+---+

background-size in shorthand background property (CSS3)

You will have to use vendor prefixes to support different browsers and therefore can't use it in shorthand.

body { 
        background: url(images/bg.jpg) no-repeat center center fixed; 
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
}

How does PHP 'foreach' actually work?

PHP foreach loop can be used with Indexed arrays, Associative arrays and Object public variables.

In foreach loop, the first thing php does is that it creates a copy of the array which is to be iterated over. PHP then iterates over this new copy of the array rather than the original one. This is demonstrated in the below example:

<?php
$numbers = [1,2,3,4,5,6,7,8,9]; # initial values for our array
echo '<pre>', print_r($numbers, true), '</pre>', '<hr />';
foreach($numbers as $index => $number){
    $numbers[$index] = $number + 1; # this is making changes to the origial array
    echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # showing data from the copied array
}
echo '<hr />', '<pre>', print_r($numbers, true), '</pre>'; # shows the original values (also includes the newly added values).

Besides this, php does allow to use iterated values as a reference to the original array value as well. This is demonstrated below:

<?php
$numbers = [1,2,3,4,5,6,7,8,9];
echo '<pre>', print_r($numbers, true), '</pre>';
foreach($numbers as $index => &$number){
    ++$number; # we are incrementing the original value
    echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # this is showing the original value
}
echo '<hr />';
echo '<pre>', print_r($numbers, true), '</pre>'; # we are again showing the original value

Note: It does not allow original array indexes to be used as references.

Source: http://dwellupper.io/post/47/understanding-php-foreach-loop-with-examples

Sort Array of object by object field in Angular 6

Not tested but should work

 products.sort((a,b)=>a.title.rendered > b.title.rendered)

How do I use boolean variables in Perl?

My favourites have always been

use constant FALSE => 1==0;
use constant TRUE => not FALSE;

which is completely independent from the internal representation.

How to quietly remove a directory with content in PowerShell

This worked for me:

Remove-Item $folderPath -Force  -Recurse -ErrorAction SilentlyContinue

Thus the folder is removed with all files in there and it is not producing error if folder path doesn't exists.

What does the percentage sign mean in Python

Modulus operator; gives the remainder of the left value divided by the right value. Like:

3 % 1 would equal zero (since 3 divides evenly by 1)

3 % 2 would equal 1 (since dividing 3 by 2 results in a remainder of 1).

How to cin Space in c++?

#include <iostream>
#include <string>

int main()
{
   std::string a;
   std::getline(std::cin,a);
   for(std::string::size_type i = 0; i < a.size(); ++i)
   {
       if(a[i] == ' ')
          std::cout<<"It is a space!!!"<<std::endl;
   }
   return 0;
}

How do I set the rounded corner radius of a color drawable using xml?

Try below code

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
    android:bottomLeftRadius="30dp"
    android:bottomRightRadius="30dp"
    android:topLeftRadius="30dp"
    android:topRightRadius="30dp" />
<solid android:color="#1271BB" />

<stroke
    android:width="5dp"
    android:color="#1271BB" />

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

How to get file creation date/time in Bash/Debian?

Cited from https://unix.stackexchange.com/questions/50177/birth-is-empty-on-ext4/131347#131347 , the following shellscript would work to get creation time:

get_crtime() {
   for target in "${@}"; do
       inode=$(stat -c %i "${target}")
       fs=$(df "${target}"  | tail -1 | awk '{print $1}')
       crtime=$(sudo debugfs -R 'stat <'"${inode}"'>' "${fs}" 2>/dev/null | grep -oP 'crtime.*--\s*\K.*')
       printf "%s\t%s\n" "${target}" "${crtime}"
   done
}

Using .Select and .Where in a single LINQ statement

Did you add the Select() after the Where() or before?

You should add it after, because of the concurrency logic:

 1 Take the entire table  
 2 Filter it accordingly  
 3 Select only the ID's  
 4 Make them distinct.  

If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.

Update: For clarity, this order of operators should work:

db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();

Probably want to add a .toList() at the end but that's optional :)