Programs & Examples On #Library design

How do I read a string entered by the user in C?

I found an easy and nice solution:

char*string_acquire(char*s,int size,FILE*stream){
    int i;
    fgets(s,size,stream);
    i=strlen(s)-1;
    if(s[i]!='\n') while(getchar()!='\n');
    if(s[i]=='\n') s[i]='\0';
    return s;
}

it's based on fgets but free from '\n' and stdin extra characters (to replace fflush(stdin) that doesn't works on all OS, useful if you have to acquire strings after this).

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

Here's a free tool that will do it on Windows. I prefer it to a script as it's easy to set up. It runs as a fast native app, works on XP and up, has configuration settings that allow to remap copy/paste/selection keys for command windows:

enter image description here

Plus I know the developers.

iOS: set font size of UILabel Programmatically

Try [UIFont systemFontOfSize:36] or [UIFont fontWithName:@"HelveticaNeue" size:36] i.e. [[self titleLabel] setFont:[UIFont systemFontOfSize:36]];

Git diff between current branch and master but not including unmerged master commits

According to Documentation

git diff Shows changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, changes resulting from a merge, changes between two blob objects, or changes between two files on disk.

In git diff - There's a significant difference between two dots .. and 3 dots ... in the way we compare branches or pull requests in our repository. I'll give you an easy example which demonstrates it easily.

Example: Let's assume we're checking out new branch from master and pushing some code in.

  G---H---I feature (Branch)
 /
A---B---C---D master (Branch)
  • Two dots - If we want to show the diffs between all changes happened in the current time on both sides, We would use the git diff origin/master..feature or just git diff origin/master
    ,output: ( H, I against A, B, C, D )

  • Three dots - If we want to show the diffs between the last common ancestor (A), aka the check point we started our new branch ,we use git diff origin/master...feature,output: (H, I against A ).

  • I'd rather use the 3 dots in most circumstances.

Format an Integer using Java String Format

If you are using a third party library called apache commons-lang, the following solution can be useful:

Use StringUtils class of apache commons-lang :

int i = 5;
StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"

As StringUtils.leftPad() is faster than String.format()

How do you stop tracking a remote branch in Git?

git branch --unset-upstream stops tracking all the local branches, which is not desirable.

Remove the [branch "branch-name"] section from the .git/config file followed by

git branch -D 'branch-name' && git branch -D -r 'origin/branch-name'

works out the best for me.

SMTP connect() failed PHPmailer - PHP

You need to add the Host parameter

$mail->Host = "ssl://smtp.gmail.com"; 

Also, check if you have open_ssl enabled.

<?php
echo !extension_loaded('openssl')?"Not Available":"Available";

Why can't I use a list as a dict key in python?

dict keys need to be hashable. Lists are Mutable and they do not provide a valid hash method.

failed to lazily initialize a collection of role

Lazy exceptions occur when you fetch an object typically containing a collection which is lazily loaded, and try to access that collection.

You can avoid this problem by

  • accessing the lazy collection within a transaction.
  • Initalizing the collection using Hibernate.initialize(obj);
  • Fetch the collection in another transaction
  • Use Fetch profiles to select lazy/non-lazy fetching runtime
  • Set fetch to non-lazy (which is generally not recommended)

Further I would recommend looking at the related links to your right where this question has been answered many times before. Also see Hibernate lazy-load application design.

angularjs: ng-src equivalent for background-image:url(...)

Since you mentioned ng-src and it seems as though you want the page to finish rendering before loading your image, you may modify jaime's answer to run the native directive after the browser finishes rendering.

This blog post explains this pretty well; essentially, you insert the $timeout wrapper for window.setTimeout before the callback function wherein you make those modifications to the CSS.

Change url query string value using jQuery

purls $.params() used without a parameter will give you a key-value object of the parameters.

jQuerys $.param() will build a querystring from the supplied object/array.

var params = parsedUrl.param();
delete params["page"];

var newUrl = "?page=" + $(this).val() + "&" + $.param(params);

Update
I've no idea why I used delete here...

var params = parsedUrl.param();
params["page"] = $(this).val();

var newUrl = "?" + $.param(params);

Copy files from one directory into an existing directory

If you want to copy something from one directory into the current directory, do this:

cp dir1/* .

This assumes you're not trying to copy hidden files.

MySQL error 1449: The user specified as a definer does not exist

i came here for the same problem, i couldn't find anywhere in my code where a certain user was making the action. apparently it was from a trigger that was using a user which was long deleted (db was restored from an older version) so in case you are puzzled as i were, take a look at your db events/triggers/routines. hope this will help someone.

How can we stop a running java process through Windows cmd?

The answer which suggests something like taskkill /f /im java.exe will probably work, but if you want to kill only one java process instead of all, I can suggest doing it with the help of window titles. Expample:

Start

start "MyProgram" "C:/Program Files/Java/jre1.8.0_201/bin/java.exe" -jar MyProgram.jar

Stop

taskkill /F /FI "WINDOWTITLE eq MyProgram" /T

Is it possible to Turn page programmatically in UIPageViewController?

For single page, I just edited the answer of @Jack Humphries

-(void)viewDidLoad
{
  counter = 0;
}
-(IBAction)buttonClick:(id)sender
{
  counter++;
  DataViewController *secondVC = [self.modelController viewControllerAtIndex:counter storyboard:self.storyboard];
  NSArray *viewControllers = nil;          
  viewControllers = [NSArray arrayWithObjects:secondVC, nil];          
  [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];
}

jQuery issue - #<an Object> has no method

This problem can also arise if you include jQuery more than once.

Swift days between two NSDates

Here is the answer for Swift 3 (tested for IOS 10 Beta)

func daysBetweenDates(startDate: Date, endDate: Date) -> Int
{
    let calendar = Calendar.current
    let components = calendar.components([.day], from: startDate, to: endDate, options: [])
    return components.day!
}

Then you can call it like this

let pickedDate: Date = sender.date
let NumOfDays: Int = daysBetweenDates(startDate: pickedDate, endDate: Date())
    print("Num of Days: \(NumOfDays)")

Case-insensitive search

ES6+:

let string="Stackoverflow is the BEST";
let searchstring="best";


let found = string.toLowerCase()
                  .includes(searchstring.toLowerCase());

includes() returns true if searchString appears at one or more positions or false otherwise.

How to change color of Toolbar back button in Android?

If you want white back button (?) and white toolbar title, follow this:

<android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    </android.support.design.widget.AppBarLayout>

Change theme from Dark to Light if you want black back button (?) and black toolbar title.

ToString() function in Go

Attach a String() string method to any named type and enjoy any custom "ToString" functionality:

package main

import "fmt"

type bin int

func (b bin) String() string {
        return fmt.Sprintf("%b", b)
}

func main() {
        fmt.Println(bin(42))
}

Playground: http://play.golang.org/p/Azql7_pDAA


Output

101010

How to set scope property with ng-init?

I had some trouble with $scope.$watch but after a lot of testing I found out that my data-ng-model="User.UserName" was badly named and after I changed it to data-ng-model="UserName" everything worked fine. I expect it to be the . in the name causing the issue.

Android Webview gives net::ERR_CACHE_MISS message

Answers assembled! I wanted to just combine all the answers into one comprehensive one.

1. Check if <uses-permission android:name="android.permission.INTERNET" /> is present in manifest.xml. Make sure that it is nested under <manifest> and not <application>. Thanks to sajid45 and Liyanis Velazquez

2. Ensure that you are using <uses-permission android:name="android.permission.INTERNET"/> instead of the deprecated <uses-permission android:name="android.permission.internet"/>. Much thanks to alan_shi and creos.

3. If minimum version is below KK, check that you have

if (18 < Build.VERSION.SDK_INT ){
    //18 = JellyBean MR2, KITKAT=19
    mWeb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
}

or

if (Build.VERSION.SDK_INT >= 19) {
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}

because proper webview is only added in KK (SDK 19). Thanks to Devavrata, Mike ChanSeong Kim and Liyanis Velazquez

4. Ensure that you don't have webView.getSettings().setBlockNetworkLoads (false);. Thanks to TechNikh for pointing this out.

5. If all else fails, make sure that your Android Studio, Android SDK and the emulator image (if you are using one) is updated. And if you are still meeting the problem, just open a new question and make a comment below to your URL.

Check if an element is a child of a parent

In addition to the other answers, you can use this less-known method to grab elements of a certain parent like so,

$('child', 'parent');

In your case, that would be

if ($(event.target, 'div#hello')[0]) console.log(`${event.target.tagName} is an offspring of div#hello`);

Note the use of commas between the child and parent and their separate quotation marks. If they were surrounded by the same quotes

$('child, parent');

you'd have an object containing both objects, regardless of whether they exist in their document trees.

How to make a machine trust a self-signed Java application

Just Go To *Startmenu >>Java >>Configure Java >> Security >> Edit site list >> copy and paste your Link with problem >> OK Problem fixed :)*

Remove blank lines with grep

egrep -v "^\s\s+"

egrep already do regex, and the \s is white space.

The + duplicates current pattern.

The ^ is for the start

How to read a text file directly from Internet using Java?

What really worked to me: (source: oracle documentation "reading url")

 import java.net.*;
 import java.io.*;

 public class UrlTextfile {
public static void main(String[] args) throws Exception {

    URL oracle = new URL("http://yoursite.com/yourfile.txt");
    BufferedReader in = new BufferedReader(
    new InputStreamReader(oracle.openStream()));

    String inputLine;
    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();
}
 }

TypeError: 'NoneType' object has no attribute '__getitem__'

move.CompleteMove() does not return a value (perhaps it just prints something). Any method that does not return a value returns None, and you have assigned None to self.values.

Here is an example of this:

>>> def hello(x):
...    print x*2
...
>>> hello('world')
worldworld
>>> y = hello('world')
worldworld
>>> y
>>>

You'll note y doesn't print anything, because its None (the only value that doesn't print anything on the interactive prompt).

how to make a jquery "$.post" request synchronous

If you want an synchronous request set the async property to false for the request. Check out the jQuery AJAX Doc

How do I pipe or redirect the output of curl -v?

The following worked for me:

Put your curl statement in a script named abc.sh

Now run:

sh abc.sh 1>stdout_output 2>stderr_output

You will get your curl's results in stdout_output and the progress info in stderr_output.

What does a lazy val do?

Also lazy is useful without cyclic dependencies, as in the following code:

abstract class X {
  val x: String
  println ("x is "+x.length)
}

object Y extends X { val x = "Hello" }
Y

Accessing Y will now throw null pointer exception, because x is not yet initialized. The following, however, works fine:

abstract class X {
  val x: String
  println ("x is "+x.length)
}

object Y extends X { lazy val x = "Hello" }
Y

EDIT: the following will also work:

object Y extends { val x = "Hello" } with X 

This is called an "early initializer". See this SO question for more details.

Inserting a text where cursor is using Javascript/jquery

The approved answer from George Claghorn worked great for simply inserting text at the cursor position. If the user had selected text though, and you want that text to be replaced (the default experience with most text), you need to make a small change when setting the 'back' variable.

Also, if you don't need to support older versions of IE, modern versions support textarea.selectionStart, so you can take out all of the browser detection, and IE-specific code.

Here is a simplified version that works for Chrome and IE11 at least, and handles replacing selected text.

function insertAtCaret(areaId, text) {
    var txtarea = document.getElementById(areaId);
    var scrollPos = txtarea.scrollTop;
    var caretPos = txtarea.selectionStart;

    var front = (txtarea.value).substring(0, caretPos);
    var back = (txtarea.value).substring(txtarea.selectionEnd, txtarea.value.length);
    txtarea.value = front + text + back;
    caretPos = caretPos + text.length;
    txtarea.selectionStart = caretPos;
    txtarea.selectionEnd = caretPos;
    txtarea.focus();
    txtarea.scrollTop = scrollPos;
}

Lazy Loading vs Eager Loading

I think it is good to categorize relations like this

When to use eager loading

  1. In "one side" of one-to-many relations that you sure are used every where with main entity. like User property of an Article. Category property of a Product.
  2. Generally When relations are not too much and eager loading will be good practice to reduce further queries on server.

When to use lazy loading

  1. Almost on every "collection side" of one-to-many relations. like Articles of User or Products of a Category
  2. You exactly know that you will not need a property instantly.

Note: like Transcendent said there may be disposal problem with lazy loading.

How to perform a sum of an int[] array

Your syntax and logic are incorrect in a number of ways. You need to create an index variable and use it to access the array's elements, like so:

int i = 0;        // Create a separate integer to serve as your array indexer.
while(i < 10) {   // The indexer needs to be less than 10, not A itself.
   sum += A[i];   // either sum = sum + ... or sum += ..., but not both
   i++;           // You need to increment the index at the end of the loop.
}

The above example uses a while loop, since that's the approach you took. A more appropriate construct would be a for loop, as in Bogdan's answer.

Correct Semantic tag for copyright info - html5

Put it inside your <footer> by all means, but the most fitting element is the small element.

The HTML5 spec for this says:

Small print typically features disclaimers, caveats, legal restrictions, or copyrights. Small print is also sometimes used for attribution, or for satisfying licensing requirements.

What is special about /dev/tty?

The 'c' means it's a character device. tty is a special file representing the 'controlling terminal' for the current process.

Character Devices

Unix supports 'device files', which aren't really files at all, but file-like access points to hardware devices. A 'character' device is one which is interfaced byte-by-byte (as opposed to buffered IO).

TTY

/dev/tty is a special file, representing the terminal for the current process. So, when you echo 1 > /dev/tty, your message ('1') will appear on your screen. Likewise, when you cat /dev/tty, your subsequent input gets duplicated (until you press Ctrl-C).

/dev/tty doesn't 'contain' anything as such, but you can read from it and write to it (for what it's worth). I can't think of a good use for it, but there are similar files which are very useful for simple IO operations (e.g. /dev/ttyS0 is normally your serial port)

This quote is from http://tldp.org/HOWTO/Text-Terminal-HOWTO-7.html#ss7.3 :

/dev/tty stands for the controlling terminal (if any) for the current process. To find out which tty's are attached to which processes use the "ps -a" command at the shell prompt (command line). Look at the "tty" column. For the shell process you're in, /dev/tty is the terminal you are now using. Type "tty" at the shell prompt to see what it is (see manual pg. tty(1)). /dev/tty is something like a link to the actually terminal device name with some additional features for C-programmers: see the manual page tty(4).

Here is the man page: http://linux.die.net/man/4/tty

How to remove leading and trailing zeros in a string? Python

Did you try with strip() :

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
print [item.strip('0') for item in listOfNum]

>>> ['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric']

How to read a large file line by line?

Two memory efficient ways in ranked order (first is best) -

  1. use of with - supported from python 2.5 and above
  2. use of yield if you really want to have control over how much to read

1. use of with

with is the nice and efficient pythonic way to read large files. advantages - 1) file object is automatically closed after exiting from with execution block. 2) exception handling inside the with block. 3) memory for loop iterates through the f file object line by line. internally it does buffered IO (to optimized on costly IO operations) and memory management.

with open("x.txt") as f:
    for line in f:
        do something with data

2. use of yield

Sometimes one might want more fine-grained control over how much to read in each iteration. In that case use iter & yield. Note with this method one explicitly needs close the file at the end.

def readInChunks(fileObj, chunkSize=2048):
    """
    Lazy function to read a file piece by piece.
    Default chunk size: 2kB.

    """
    while True:
        data = fileObj.read(chunkSize)
        if not data:
            break
        yield data

f = open('bigFile')
for chunk in readInChunks(f):
    do_something(chunk)
f.close()

Pitfalls and for the sake of completeness - below methods are not as good or not as elegant for reading large files but please read to get rounded understanding.

In Python, the most common way to read lines from a file is to do the following:

for line in open('myfile','r').readlines():
    do_something(line)

When this is done, however, the readlines() function (same applies for read() function) loads the entire file into memory, then iterates over it. A slightly better approach (the first mentioned two methods above are the best) for large files is to use the fileinput module, as follows:

import fileinput

for line in fileinput.input(['myfile']):
    do_something(line)

the fileinput.input() call reads lines sequentially, but doesn't keep them in memory after they've been read or even simply so this, since file in python is iterable.

References

  1. Python with statement

How do I remove a library from the arduino environment?

I had to look for them in C:\Users\Dell\AppData\Local\Arduino15\

I had to take help from the "date created" and "date modified" attributes to identify which libraries to delete.

But the names still show in the IDE... But it is something I can live with for now.

Get all mysql selected rows into an array

You could try:

$rows = array();
while($row = mysql_fetch_array($result)){
  array_push($rows, $row);
}
echo json_encode($rows);

How to get a single value from FormGroup

for Angular 6+ and >=RC.6

.html

<form [formGroup]="formGroup">
  <input type="text" formControlName="myName">
</form>

.ts

public formGroup: FormGroup;
this.formGroup.value.myName

should also work.

The apk must be signed with the same certificates as the previous version

Here i get the answer for that question . After searching for too long finally i get to crack the key and password for this . I forget my key and alias also the jks file but fortunately i know the bunch of password what i had put in it . but finding correct combinations for that was toughest task for me .

Solution - Download this - Keytool IUI version 2.4.1 plugin enter image description here

the window will pop up now it show the alias name ..if you jks file is correct .. right click on alias and hit "view certificates chain ".. it will show the SHA1 Key .. match this key with tha key you get while you was uploading the apk in google app store ...

if it match then you are with the right jks file and alias ..

now lucky i have bunch of password to match .. enter image description here

now go to this scrren put the same jks path .. and password(among the password you have ) put any path in "Certificate file"

if the screen shows any error then password is not matching .. if it doesn't show any error then it means you are with correct jks file . correct alias and password() now with that you can upload your apk in play store :)

Regex using javascript to return just numbers

For number with decimal fraction and minus sign, I use this snippet:

_x000D_
_x000D_
const NUMERIC_REGEXP = /[-]{0,1}[\d]*[.]{0,1}[\d]+/g;

const numbers = '2.2px 3.1px 4px -7.6px obj.key'.match(NUMERIC_REGEXP)

console.log(numbers); // ["2.2", "3.1", "4", "-7.6"]
_x000D_
_x000D_
_x000D_

Update: - 7/9/2018

Found a tool which allows you to edit regular expression visually: JavaScript Regular Expression Parser & Visualizer.

Update:

Here's another one with which you can even debugger regexp: Online regex tester and debugger.

Update:

Another one: RegExr.

Update:

Regexper and Regex Pal.

Android appcompat v7:23

Latest published version of the Support Library is 24.1.1, So you can use it like this,

compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:design:24.1.1'

Same as for other support components.

You can see the revisions here,
https://developer.android.com/topic/libraries/support-library/revisions.html

Single Line Nested For Loops

First of all, your first code doesn't use a for loop per se, but a list comprehension.

  1. Would be equivalent to

    for j in range(0, width): for i in range(0, height): m[i][j]

  2. Much the same way, it generally nests like for loops, right to left. But list comprehension syntax is more complex.

  3. I'm not sure what this question is asking


  1. Any iterable object that yields iterable objects that yield exactly two objects (what a mouthful - i.e [(1,2),'ab'] would be valid )

  2. The order in which the object yields upon iteration. i goes to the first yield, j the second.

  3. Yes, but not as pretty. I believe it is functionally equivalent to:

    l = list()
    for i,j in object:
        l.append(function(i,j))
    

    or even better use map:

    map(function, object)
    

    But of course function would have to get i, j itself.

  4. Isn't this the same question as 3?

Converting java.sql.Date to java.util.Date

If you really want the runtime type to be util.Date then just do this:

java.util.Date utilDate = new java.util.Date(sqlDate.getTime());

Brian.

Assign output of a program to a variable using a MS batch file

Some macros to set the output of a command to a variable/

For directly in the command prompt

c:\>doskey assign=for /f "tokens=1,2 delims=," %a in ("$*") do @for /f "tokens=* delims=" %# in ('"%a"') do @set "%b=%#"

c:\>assign WHOAMI /LOGONID,my-id

c:\>echo %my-id%

Macro with arguments

As this macro accepts arguments as a function i think it is the neatest macro to be used in a batch file:

@echo off

::::: ---- defining the assign macro ---- ::::::::
setlocal DisableDelayedExpansion
(set LF=^
%=EMPTY=%
)
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"

::set argv=Empty
set assign=for /L %%n in (1 1 2) do ( %\n%
   if %%n==2 (%\n%
      setlocal enableDelayedExpansion%\n%
      for /F "tokens=1,2 delims=," %%A in ("!argv!") do (%\n%
         for /f "tokens=* delims=" %%# in ('%%~A') do endlocal^&set "%%~B=%%#" %\n%
      ) %\n%
   ) %\n%
) ^& set argv=,

::::: -------- ::::::::


:::EXAMPLE
%assign% "WHOAMI /LOGONID",result
echo %result%

FOR /F macro

not so easy to read as the previous macro.

::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set ""                        &::
;;set "}}==%%#""                               &::
::::::::::::::::::::::::::::::::::::::::::::::::::

:: --examples

::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%


::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%

Macro using a temp file

Easier to read , it is not so slow if you have a SSD drive but still it creates a temp file.

@echo off

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1" &::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

chcp %[[%code-page%]]%
echo ~~%code-page%~~

whoami %[[%its-me%]]%
echo ##%its-me%##

The zip() function in Python 3

Unlike in Python 2, the zip function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you want to reuse your zipped object, just create a list out of it as you do in your second example, and then duplicate the list by something like

 test2 = list(zip(lis1,lis2))
 zipped_list = test2[:]
 zipped_list_2 = list(test2)

Shuffling a list of objects

from random import random
my_list = range(10)
shuffled_list = sorted(my_list, key=lambda x: random())

This alternative may be useful for some applications where you want to swap the ordering function.

IE Enable/Disable Proxy Settings via Registry

I know this is an old question, however here is a simple one-liner to switch it on or off depending on its current state:

set-itemproperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'  -name ProxyEnable -value (-not ([bool](get-itemproperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'  -name ProxyEnable).proxyenable))

Instagram API: How to get all user media?

In June 2016 Instagram made most of the functionality of their API available only to applications that have passed a review process. They still however provide JSON data through the web interface, and you can add the parameter __a=1 to a URL to only include the JSON data.

max=
while :;do
  c=$(curl -s "https://www.instagram.com/username/?__a=1&max_id=$max")
  jq -r '.user.media.nodes[]?|.display_src'<<<"$c"
  max=$(jq -r .user.media.page_info.end_cursor<<<"$c")
  jq -e .user.media.page_info.has_next_page<<<"$c">/dev/null||break
done

Edit: As mentioned in the comment by alnorth29, the max_id parameter is now ignored. Instagram also changed the format of the response, and you need to perform additional requests to get the full-size URLs of images in the new-style posts with multiple images per post. You can now do something like this to list the full-size URLs of images on the first page of results:

c=$(curl -s "https://www.instagram.com/username/?__a=1")
jq -r '.graphql.user.edge_owner_to_timeline_media.edges[]?|.node|select(.__typename!="GraphSidecar").display_url'<<<"$c"
jq -r '.graphql.user.edge_owner_to_timeline_media.edges[]?|.node|select(.__typename=="GraphSidecar")|.shortcode'<<<"$c"|while read l;do
  curl -s "https://www.instagram.com/p/$l?__a=1"|jq -r '.graphql.shortcode_media|.edge_sidecar_to_children.edges[]?.node|.display_url'
done

To make a list of the shortcodes of each post made by the user whose profile is opened in the frontmost tab in Safari, I use a script like this:

sjs(){ osascript -e'{on run{a}','tell app"safari"to do javascript a in document 1',end} -- "$1";}

while :;do
  sjs 'o="";a=document.querySelectorAll(".v1Nh3 a");for(i=0;e=a[i];i++){o+=e.href+"\n"};o'>>/tmp/a
  sjs 'window.scrollBy(0,window.innerHeight)'
  sleep 1
done

sed one-liner to convert all uppercase to lowercase?

If you are using posix sed

Selection for any case for a pattern (converting the searched pattern with this sed than use the converted pattern in you wanted command using regex:

echo "${MyOrgPattern} | sed "s/[aA]/[aA]/g;s/[bB]/[bB]/g;s/[cC]/[cC]/g;s/[dD]/[dD]/g;s/[eE]/[eE]/g;s/[fF]/[fF]/g;s/[gG]/[gG]/g;s/[hH]/[hH]/g;s/[iI]/[iI]/g;s/[jJ]/[jJ]/g;s/[kK]/[kK]/g;s/[lL]/[lL]/g;s/[mM]/[mM]/g;s/[nN]/[nN]/g;s/[oO]/[oO]/g;s/[pP]/[pP]/g;s/[qQ]/[qQ]/g;s/[rR]/[rR]/g;s/[sS]/[sS]/g;s/[tT]/[tT]/g;s/[uU]/[uU]/g;s/[vV]/[vV]/g;s/[wW]/[wW]/g;s/[xX]/[xX]/g;s/[yY]/[yY]/g;s/[zZ]/[zZ]/g" | read -c MyNewPattern
 YourInputStreamCommand | egrep "${MyNewPattern}"

convert in lower case

sed "s/[aA]/a/g;s/[bB]/b/g;s/[cC]/c/g;s/[dD]/d/g;s/[eE]/e/g;s/[fF]/f/g;s/[gG]/g/g;s/[hH]/h/g;s/[iI]/i/g;s/j/[jJ]/g;s/[kK]/k/g;s/[lL]/l/g;s/[mM]/m/g;s/[nN]/n/g;s/[oO]/o/g;s/[pP]/p/g;s/[qQ]/q/g;s/[rR]/r/g;s/[sS]/s/g;s/[tT]/t/g;s/[uU]/u/g;s/[vV]/v/g;s/[wW]/w/g;s/[xX]/x/g;s/[yY]/y/g;s/[zZ]/z/g"

same for uppercase replace lower letter between // by upper equivalent in the sed

Have fun

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

Just telling my resolution: in my case, the libraries and projects weren't being added automatically to the classpath (i don't know why), even clicking at the "add to build path" option. So I went on run -> run configurations -> classpath and added everything I needed through there.

How to set textColor of UILabel in Swift

You can use as below and also can use various color just assign

myLabel.textColor = UIColor.yourChoiceOfColor

Ex:

Swift

myLabel.textColor = UIColor.red

Objective-C

[myLabel setTextColor:[UIColor redColor]];

or you can click here to Choose the color,

https://www.ralfebert.de/ios-examples/uikit/swift-uicolor-picker/

Table 'mysql.user' doesn't exist:ERROR

You can run the following query to check for the existance of the user table.

SELECT * FROM information_schema.TABLES
WHERE TABLE_NAME LIKE '%user%'

See if you can find a row with the following values in

mysql   user    BASE TABLE  MyISAM  

If you cant find this table look at the following link to rebuild the database How to recover/recreate mysql's default 'mysql' database

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

Possible duplicate: Is there a maven 2 archetype for spring 3 MVC applications?

That said, I would encourage you to think about making your own archetype. The reason is, no matter what you end up getting from someone else's, you can do better in not that much time, and a decent sized Java project is going to end up making a lot of jar projects.

What is the difference between __init__ and __call__?

>>> class A:
...     def __init__(self):
...         print "From init ... "
... 
>>> a = A()
From init ... 
>>> a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: A instance has no __call__ method
>>> 
>>> class B:
...     def __init__(self):
...         print "From init ... "
...     def __call__(self):
...         print "From call ... "
... 
>>> b = B()
From init ... 
>>> b()
From call ... 
>>> 

Entity Framework and SQL Server View

To get a view I had to only show one primary key column I created a second view that pointed to the first and used NULLIF to make the types nullable. This worked for me to make the EF think there was just a single primary key in the view.

Not sure if this will help you though since I don't believe the EF will accept an entity with NO primary key.

Find a string within a cell using VBA

For a search routine you should look to use Find, AutoFilter or variant array approaches. Range loops are nomally too slow, worse again if they use Select

The code below will look for the strText variable in a user selected range, it then adds any matches to a range variable rng2 which you can then further process

Option Explicit

Const strText As String = "%"

Sub ColSearch_DelRows()
    Dim rng1 As Range
    Dim rng2 As Range
    Dim rng3 As Range
    Dim cel1 As Range
    Dim cel2 As Range
    Dim strFirstAddress As String
    Dim lAppCalc As Long


    'Get working range from user
    On Error Resume Next
    Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8)
    On Error GoTo 0
    If rng1 Is Nothing Then Exit Sub

    With Application
        lAppCalc = .Calculation
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
    End With

    Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False)

    'A range variable - rng2 - is used to store the range of cells that contain the string being searched for
    If Not cel1 Is Nothing Then
        Set rng2 = cel1
        strFirstAddress = cel1.Address
        Do
            Set cel1 = rng1.FindNext(cel1)
            Set rng2 = Union(rng2, cel1)
        Loop While strFirstAddress <> cel1.Address
    End If

    If Not rng2 Is Nothing Then
        For Each cel2 In rng2
            Debug.Print cel2.Address & " contained " & strText
        Next
    Else
        MsgBox "No " & strText
    End If

    With Application
        .ScreenUpdating = True
        .Calculation = lAppCalc
    End With

End Sub

Convert/cast an stdClass object to another class

BTW: Converting is highly important if you are serialized, mainly because the de-serialization breaks the type of objects and turns into stdclass, including DateTime objects.

I updated the example of @Jadrovski, now it allows objects and arrays.

example

$stdobj=new StdClass();
$stdobj->field=20;
$obj=new SomeClass();
fixCast($obj,$stdobj);

example array

$stdobjArr=array(new StdClass(),new StdClass());
$obj=array(); 
$obj[0]=new SomeClass(); // at least the first object should indicates the right class.
fixCast($obj,$stdobj);

code: (its recursive). However, i don't know if its recursive with arrays. May be its missing an extra is_array

public static function fixCast(&$destination,$source)
{
    if (is_array($source)) {
        $getClass=get_class($destination[0]);
        $array=array();
        foreach($source as $sourceItem) {
            $obj = new $getClass();
            fixCast($obj,$sourceItem);
            $array[]=$obj;
        }
        $destination=$array;
    } else {
        $sourceReflection = new \ReflectionObject($source);
        $sourceProperties = $sourceReflection->getProperties();
        foreach ($sourceProperties as $sourceProperty) {
            $name = $sourceProperty->getName();
            if (is_object(@$destination->{$name})) {
                fixCast($destination->{$name}, $source->$name);
            } else {
                $destination->{$name} = $source->$name;
            }
        }
    }
}

svn : how to create a branch from certain revision of trunk

append the revision using an "@" character:

svn copy http://src@REV http://dev

Or, use the -r [--revision] command line argument.

Calling method using JavaScript prototype

This solution uses Object.getPrototypeOf

TestA is super that has getName

TestB is a child that overrides getName but, also has getBothNames that calls the super version of getName as well as the child version

_x000D_
_x000D_
function TestA() {_x000D_
  this.count = 1;_x000D_
}_x000D_
TestA.prototype.constructor = TestA;_x000D_
TestA.prototype.getName = function ta_gn() {_x000D_
  this.count = 2;_x000D_
  return ' TestA.prototype.getName is called  **';_x000D_
};_x000D_
_x000D_
function TestB() {_x000D_
  this.idx = 30;_x000D_
  this.count = 10;_x000D_
}_x000D_
TestB.prototype = new TestA();_x000D_
TestB.prototype.constructor = TestB;_x000D_
TestB.prototype.getName = function tb_gn() {_x000D_
  return ' TestB.prototype.getName is called ** ';_x000D_
};_x000D_
_x000D_
TestB.prototype.getBothNames = function tb_gbn() {_x000D_
  return Object.getPrototypeOf(TestB.prototype).getName.call(this) + this.getName() + ' this object is : ' + JSON.stringify(this);_x000D_
};_x000D_
_x000D_
var tb = new TestB();_x000D_
console.log(tb.getBothNames());
_x000D_
_x000D_
_x000D_

Setting public class variables

class Testclass
{
  public $testvar;

  function dosomething()
  {
    echo $this->testvar;
  }
}

$Testclass = new Testclass();
$Testclass->testvar = "another value";    
$Testclass->dosomething(); ////It will print "another value"

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

This is a general rambling on Parallelism in SQL Server, it might not answer your question directly.

From Books Online, on MAXDOP:

Sets the maximum number of processors the query processor can use to execute a single index statement. Fewer processors may be used depending on the current system workload.

See Rickie Lee's blog on parallelism and CXPACKET wait type. It's quite interesting.

Generally, in an OLTP database, my opinion is that if a query is so costly it needs to be executed on several processors, the query needs to be re-written into something more efficient.

Why you get better results adding MAXDOP(1)? Hard to tell without the actual execution plans, but it might be so simple as that the execution plan is totally different that without the OPTION, for instance using a different index (or more likely) JOINing differently, using MERGE or HASH joins.

Beginner question: returning a boolean value from a function in Python

Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:

def rps():
    # Code to determine if player wins
    if player_wins:
        return True

    return False

Then, just assign a value to the variable outside this function like so:

player_wins = rps()

It will be assigned the return value (either True or False) of the function you just called.


After the comments, I decided to add that idiomatically, this would be better expressed thus:

 def rps(): 
     # Code to determine if player wins, assigning a boolean value (True or False)
     # to the variable player_wins.

     return player_wins

 pw = rps()

This assigns the boolean value of player_wins (inside the function) to the pw variable outside the function.

Exec : display stdout "live"

I have found it helpful to add a custom exec script to my utilities that do this.

utilities.js

const { exec } = require('child_process')

module.exports.exec = (command) => {
  const process = exec(command)

  process.stdout.on('data', (data) => {
    console.log('stdout: ' + data.toString())
  })

  process.stderr.on('data', (data) => {
    console.log('stderr: ' + data.toString())
  })

  process.on('exit', (code) => {
    console.log('child process exited with code ' + code.toString())
  })
}

app.js

const { exec } = require('./utilities.js')

exec('coffee -cw my_file.coffee')

How do I get the XML SOAP request of an WCF Web service request?

OperationContext.Current.RequestContext.RequestMessage 

this context is accesible server side during processing of request. This doesn`t works for one-way operations

How to get a context in a recycler view adapter

View mView;
mView.getContext();

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

How to reproduce this error with as few lines as possible:

>>> class C:
...   def f(self):
...     print "hi"
...
>>> C.f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with C instance as 
first argument (got nothing instead)

It fails because of TypeError because you didn't instantiate the class first, you have two choices: 1: either make the method static so you can run it in a static way, or 2: instantiate your class so you have an instance to grab onto, to run the method.

It looks like you want to run the method in a static way, do this:

>>> class C:
...   @staticmethod
...   def f():
...     print "hi"
...
>>> C.f()
hi

Or, what you probably meant is to use the instantiated instance like this:

>>> class C:
...   def f(self):
...     print "hi"
...
>>> c1 = C()
>>> c1.f()
hi
>>> C().f()
hi

If this confuses you, ask these questions:

  1. What is the difference between the behavior of a static method vs the behavior of a normal method?
  2. What does it mean to instantiate a class?
  3. Differences between how static methods are run vs normal methods.
  4. Differences between class and object.

How to subtract 2 hours from user's local time?

Subtract from another date object

var d = new Date();

d.setHours(d.getHours() - 2);

Failed to execute 'atob' on 'Window'

you don't need to pass the entire encoded string to atob method, you need to split the encoded string and pass the required string to atob method

_x000D_
_x000D_
const token= "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJob3NzYW0iLCJUb2tlblR5cGUiOiJCZWFyZXIiLCJyb2xlIjoiQURNSU4iLCJpc0FkbWluIjp0cnVlLCJFbXBsb3llZUlkIjoxLCJleHAiOjE2MTI5NDA2NTksImlhdCI6MTYxMjkzNzA1OX0.8f0EeYbGyxt9hjggYW1vR5hMHFVXL4ZvjTA6XgCCAUnvacx_Dhbu1OGh8v5fCsCxXQnJ8iAIZDIgOAIeE55LUw"
console.log(atob(token.split(".")[1]));
_x000D_
_x000D_
_x000D_

Failure [INSTALL_FAILED_INVALID_APK]

Navigate to Run/Debug Configurations

Click Run from the top Tab > Edit Configurations

  • Module: Select your App
  • Installation Options: Deploy Default APK
  • Ok

enter image description here

jQuery - Illegal invocation

Also this is a cause too: If you built a jQuery collection (via .map() or something similar) then you shouldn't use this collection in .ajax()'s data. Because it's still a jQuery object, not plain JavaScript Array. You should use .get() at the and to get plain js array and should use it on the data setting on .ajax().

Convert double to Int, rounded down

double myDouble = 420.5;
//Type cast double to int
int i = (int)myDouble;
System.out.println(i);

The double value is 420.5 and the application prints out the integer value of 420

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

In iOS 5, the Manifest.mbdx file was eliminated. For the purpose of this article, it was redundant anyway, because the domain and path are in Manifest.mbdb and the ID hash can be generated with SHA1.

Here is my update of galloglass's code so it works with backups of iOS 5 devices. The only changes are elimination of process_mbdx_file() and addition of a few lines in process_mbdb_file().

Tested with backups of an iPhone 4S and an iPad 1, both with plenty of apps and files.

#!/usr/bin/env python
import sys
import hashlib

mbdx = {}

def getint(data, offset, intsize):
    """Retrieve an integer (big-endian) and new offset from the current offset"""
    value = 0
    while intsize > 0:
        value = (value<<8) + ord(data[offset])
        offset = offset + 1
        intsize = intsize - 1
    return value, offset

def getstring(data, offset):
    """Retrieve a string and new offset from the current offset into the data"""
    if data[offset] == chr(0xFF) and data[offset+1] == chr(0xFF):
        return '', offset+2 # Blank string
    length, offset = getint(data, offset, 2) # 2-byte length
    value = data[offset:offset+length]
    return value, (offset + length)

def process_mbdb_file(filename):
    mbdb = {} # Map offset of info in this file => file info
    data = open(filename).read()
    if data[0:4] != "mbdb": raise Exception("This does not look like an MBDB file")
    offset = 4
    offset = offset + 2 # value x05 x00, not sure what this is
    while offset < len(data):
        fileinfo = {}
        fileinfo['start_offset'] = offset
        fileinfo['domain'], offset = getstring(data, offset)
        fileinfo['filename'], offset = getstring(data, offset)
        fileinfo['linktarget'], offset = getstring(data, offset)
        fileinfo['datahash'], offset = getstring(data, offset)
        fileinfo['unknown1'], offset = getstring(data, offset)
        fileinfo['mode'], offset = getint(data, offset, 2)
        fileinfo['unknown2'], offset = getint(data, offset, 4)
        fileinfo['unknown3'], offset = getint(data, offset, 4)
        fileinfo['userid'], offset = getint(data, offset, 4)
        fileinfo['groupid'], offset = getint(data, offset, 4)
        fileinfo['mtime'], offset = getint(data, offset, 4)
        fileinfo['atime'], offset = getint(data, offset, 4)
        fileinfo['ctime'], offset = getint(data, offset, 4)
        fileinfo['filelen'], offset = getint(data, offset, 8)
        fileinfo['flag'], offset = getint(data, offset, 1)
        fileinfo['numprops'], offset = getint(data, offset, 1)
        fileinfo['properties'] = {}
        for ii in range(fileinfo['numprops']):
            propname, offset = getstring(data, offset)
            propval, offset = getstring(data, offset)
            fileinfo['properties'][propname] = propval
        mbdb[fileinfo['start_offset']] = fileinfo
        fullpath = fileinfo['domain'] + '-' + fileinfo['filename']
        id = hashlib.sha1(fullpath)
        mbdx[fileinfo['start_offset']] = id.hexdigest()
    return mbdb

def modestr(val):
    def mode(val):
        if (val & 0x4): r = 'r'
        else: r = '-'
        if (val & 0x2): w = 'w'
        else: w = '-'
        if (val & 0x1): x = 'x'
        else: x = '-'
        return r+w+x
    return mode(val>>6) + mode((val>>3)) + mode(val)

def fileinfo_str(f, verbose=False):
    if not verbose: return "(%s)%s::%s" % (f['fileID'], f['domain'], f['filename'])
    if (f['mode'] & 0xE000) == 0xA000: type = 'l' # symlink
    elif (f['mode'] & 0xE000) == 0x8000: type = '-' # file
    elif (f['mode'] & 0xE000) == 0x4000: type = 'd' # dir
    else: 
        print >> sys.stderr, "Unknown file type %04x for %s" % (f['mode'], fileinfo_str(f, False))
        type = '?' # unknown
    info = ("%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" % 
            (type, modestr(f['mode']&0x0FFF) , f['userid'], f['groupid'], f['filelen'], 
             f['mtime'], f['atime'], f['ctime'], f['fileID'], f['domain'], f['filename']))
    if type == 'l': info = info + ' -> ' + f['linktarget'] # symlink destination
    for name, value in f['properties'].items(): # extra properties
        info = info + ' ' + name + '=' + repr(value)
    return info

verbose = True
if __name__ == '__main__':
    mbdb = process_mbdb_file("Manifest.mbdb")
    for offset, fileinfo in mbdb.items():
        if offset in mbdx:
            fileinfo['fileID'] = mbdx[offset]
        else:
            fileinfo['fileID'] = "<nofileID>"
            print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
        print fileinfo_str(fileinfo, verbose)

How do I set a checkbox in razor view?

This works for me:

<input id="AllowRating" type="checkbox" @(Model.AllowRating?"checked='checked'":"")    style="" onchange="" />

If you really wants to use HTML Helpers:

@Html.CheckBoxFor(m => m.AllowRating, new { @checked = Model.AllowRating})

multiple ways of calling parent method in php

There are three scenarios (that I can think of) where you would call a method in a subclass where the method exits in the parent class:

  1. Method is not overwritten by subclass, only exists in parent.

    This is the same as your example, and generally it's better to use $this -> get_species(); You are right that in this case the two are effectively the same, but the method has been inherited by the subclass, so there is no reason to differentiate. By using $this you stay consistent between inherited methods and locally declared methods.

  2. Method is overwritten by the subclass and has totally unique logic from the parent.

    In this case, you would obviously want to use $this -> get_species(); because you don't want the parent's version of the method executed. Again, by consistently using $this, you don't need to worry about the distinction between this case and the first.

  3. Method extends parent class, adding on to what the parent method achieves.

    In this case, you still want to use `$this -> get_species(); when calling the method from other methods of the subclass. The one place you will call the parent method would be from the method that is overwriting the parent method. Example:

    abstract class Animal {
    
        function get_species() {
    
            echo "I am an animal.";
    
        }
    
     }
    
     class Dog extends Animal {
    
         function __construct(){
    
             $this->get_species();
         }
    
         function get_species(){
    
             parent::get_species();
             echo "More specifically, I am a dog.";
         }
    }
    

The only scenario I can imagine where you would need to call the parent method directly outside of the overriding method would be if they did two different things and you knew you needed the parent's version of the method, not the local. This shouldn't be the case, but if it did present itself, the clean way to approach this would be to create a new method with a name like get_parentSpecies() where all it does is call the parent method:

function get_parentSpecies(){

     parent::get_species();
}

Again, this keeps everything nice and consistent, allowing for changes/modifications to the local method rather than relying on the parent method.

Resolve promises one after another (i.e. in sequence)?

With async/await of ES2016 (and maybe some features of ES2018), this can be reduced to this form:

function readFile(file) {
  ... // Returns a promise.
}

async function readFiles(files) {
  for (file in files) {
     await readFile(file)
  }
}

I haven't seen another answer express that simplicity. The OP said parallel execution of readFile was not desired. However, with IO like this it really makes sense to not be blocking on a single file read, while keeping the loop execution synchronous (you don't want to do the next step until all files have been read). Since I just learned about this and am a bit excited about it, I'll share that approach of parallel asynchronous execution of readFile with overall synchronous execution of readFiles.

async function readFiles(files) {
  await Promise.all(files.map(readFile))
}

Isn't that a thing of beauty?

How to open an Excel file in C#?

You need to have installed Microsoft Visual Studio Tools for Office (VSTO).

VSTO can be selected in the Visual Studio installer under Workloads > Web & Cloud > Office/SharePoint Development.

After that create common .NET project and add the reference to Microsoft.Office.Interop.Excel via 'Add Reference... > Assemblies' dialog.

Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);

Missing.Value is a special reflection struct for unnecessary parameters replacement


In newer versions, the assembly reference required is called Microsoft Excel 16.0 Object Library. If you do not have the latest version installed you might have Microsoft Excel 15.0 Object Library, or an older version, but it is the same process to include.

enter image description here

Can you pass parameters to an AngularJS controller on creation?

This question is old but I struggled for a long time trying to get an answer to this problem that would work for my needs and did not easily find it. I believe my following solution is much better than the currently accepted one, perhaps because angular has added functionality since this question was originally posed.

Short answer, using the Module.value method allows you to pass data into a controller constructor.

See my plunker here

I create a model object, then associate it with the module's controller, referencing it with the name 'model'

HTML / JS

  <html>
  <head>
    <script>
      var model = {"id": 1, "name":"foo"};

      $(document).ready(function(){
        var module = angular.module('myApp', []);
        module.value('model', model);
        module.controller('MyController', ['model', MyController]);
        angular.bootstrap(document, ['myApp']);
      });

      function confirmModelEdited() {
        alert("model name: " + model.name + "\nmodel id: " + model.id);
      }
    </script>

  </head>
  <body >
      <div ng-controller="MyController as controller">
        id: {{controller.model.id}} <br>
        name: <input ng-model="controller.model.name"/>{{controller.model.name}}
        <br><button ng-click="controller.incrementId()">increment ID</button>
        <br><button onclick="confirmModelEdited()">confirm model was edited</button>
    </div>
  </body>

</html>

The constructor in my controller then accepts a parameter with that same identifier 'model' which it can then access.

Controller

function MyController (model) {
  this.model = model;
}

MyController.prototype.incrementId = function() {
  this.model.id = this.model.id + 1;
}

Notes:

I'm using manual initialization of bootstrapping, which allows me to initialize my model before sending it over to angular. This plays much more nicely with existing code, as you can wait to set up your relevant data and only compile the angular subset of your app on demand when you want to.

In the plunker I've added a button to alert the values of the model object that was initially defined in javascript and passed to angular, just to confirm that angular is truly referencing the model object, rather than copying it and working with a copy.

On this line:

module.controller('MyController', ['model', MyController]);

I'm passing the MyController object into the Module.controller function, rather than declaring as a function inline. I think this allows us to far more clearly define our controller object, but Angular documentation tends to do it inline so I thought it bears clarification.

I'm using the "controller as" syntax and assigning values to the "this" property of MyController, rather than using the "$scope" variable. I believe this would work fine using $scope just as well, the controller assignment would then look something like this:

module.controller('MyController', ['$scope', 'model', MyController]);

and the controller constructor would have a signature like this:

function MyController ($scope, model) {

If for whatever reason you wanted to, you could also attach this model as a value of a second module, which you then attach as a dependency to your primary module.

I believe his solution is much better than the currently accepted one because

  1. The model passed to the controller is actually a javascript object, not a string that gets evaluated. It is a true reference to the object and changes to it affect other references to this model object.
  2. Angular says that the accepted answer's use of ng-init is a misuse, which this solution doesn't do.

The way Angular seems to work in most all other examples I've seen has the controller defining the data of the model, which never made sense to me, there is no separation between the model and the controller, that doesn't really seem like MVC to me. This solution allows you to really have a completely separate model object which you pass into the controller. Also of note, if you use the ng-include directive you can put all your angular html in a separate file, fully separating your model view and controller into separate modular pieces.

Fastest way to zero out a 2d array in C?

I think that the fastest way to do it by hand is following code. You can compare it's speed to memset function, but it shouldn't be slower.

(change type of ptr and ptr1 pointers if your array type is different then int)


#define SIZE_X 100
#define SIZE_Y 100

int *ptr, *ptr1;
ptr = &array[0][0];
ptr1 = ptr + SIZE_X*SIZE_Y*sizeof(array[0][0]);

while(ptr < ptr1)
{
    *ptr++ = 0;
}

Why is Ant giving me a Unsupported major.minor version error

The runtime jre was set to jre 6 instead of jre 7 in the build configuration window.

How to define servlet filter order of execution using annotations in WAR

  1. Make the servlet filter implement the spring Ordered interface.
  2. Declare the servlet filter bean manually in configuration class.
    import org.springframework.core.Ordered;
    
    public class MyFilter implements Filter, Ordered {

        @Override
        public void init(FilterConfig filterConfig) {
            // do something
        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            // do something
        }

        @Override
        public void destroy() {
            // do something
        }

        @Override
        public int getOrder() {
            return -100;
        }
    }


    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;

    @Configuration
    @ComponentScan
    public class MyAutoConfiguration {

        @Bean
        public MyFilter myFilter() {
            return new MyFilter();
        }
    }

How to run regasm.exe from command line other than Visual Studio command prompt?

I really dislike the hard coding of paths to get to regasm, when you install a new .Net or run on a machine with a different version, you need to ensure you find a version of regasm. Here's a solution to find the regasm.exe from the most current .Net installed regasm.

Within a bat file:

for /f %%a in ('dir %windir%\Microsoft.Net\Framework\regasm.exe /s /b') do set currentRegasm="%%a"
%currentRegasm% "full\path\to\your.dll" /options

Outside of a bat file (i.e. command prompt), just use %a instead of %%a

Why am I getting error for apple-touch-icon-precomposed.png

Simply create zero-sized files called the appropriate names.

The request will be satisfied with no additional data transfer nor further logging lines.

Tomcat - maxThreads vs maxConnections

From Tomcat documentation, For blocking I/O (BIO), the default value of maxConnections is the value of maxThreads unless Executor (thread pool) is used in which case, the value of 'maxThreads' from Executor will be used instead. For Non-blocking IO, it doesn't seem to be dependent on maxThreads.

How to generate range of numbers from 0 to n in ES2015 only?

Here's another variation that doesn't use Array.

let range = (n, l=[], delta=1) => {
  if (n < 0) { 
    return l 
  }
  else {
    l.unshift(n)
    return range(n - delta, l) 
  }
}

How can I get client information such as OS and browser

The browser sends this information in the HTTP header. See the snoop example of Tomcat for some code (source, online demo).

Note that this information is not reliable. Browser can and do lie about who they are and what OS they run on.

Get Selected value from Multi-Value Select Boxes by jquery-select2?

Returns the selected data in structure of object:

console.log($(".leaderMultiSelctdropdown").select2('data'));

Something like:

   [{id:"1",text:"Text",disabled:false,selected:true},{id:"2",text:"Text2",disabled:false,selected:true}]

Returns the selected val:

console.log($('.leaderMultiSelctdropdown').val());
console.log($('.leaderMultiSelctdropdown').select2("val"));

Something like:

["1", "2"]

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

Its an XML namespace. It is required when you use XHTML 1.0 or 1.1 doctypes or application/xhtml+xml mimetypes.

You should be using HTML5 doctype, then you don't need it for text/html. Better start from template like this :

<!DOCTYPE html>
<html>
    <head>
        <meta charset=utf-8 />
        <title>domcument title</title>
        <link rel="stylesheet" href="/stylesheet.css" type="text/css" />
    </head>
    <body>
            <!-- your html content -->
            <script src="/script.js"></script>
    </body>
</html>



When you have put your Doctype straight - do and validate you html and your css .
That usually will sove you layout issues.

Auto refresh page every 30 seconds

If you want refresh the page you could use like this, but refreshing the page is usually not the best method, it better to try just update the content that you need to be updated.

javascript:

<script language="javascript">
setTimeout(function(){
   window.location.reload(1);
}, 30000);
</script>

How to correctly save instance state of Fragments in back stack?

Thanks to DroidT, I made this:

I realize that if the Fragment does not execute onCreateView(), its view is not instantiated. So, if the fragment on back stack did not create its views, I save the last stored state, otherwise I build my own bundle with the data I want to save/restore.

1) Extend this class:

import android.os.Bundle;
import android.support.v4.app.Fragment;

public abstract class StatefulFragment extends Fragment {

    private Bundle savedState;
    private boolean saved;
    private static final String _FRAGMENT_STATE = "FRAGMENT_STATE";

    @Override
    public void onSaveInstanceState(Bundle state) {
        if (getView() == null) {
            state.putBundle(_FRAGMENT_STATE, savedState);
        } else {
            Bundle bundle = saved ? savedState : getStateToSave();

            state.putBundle(_FRAGMENT_STATE, bundle);
        }

        saved = false;

        super.onSaveInstanceState(state);
    }

    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);

        if (state != null) {
            savedState = state.getBundle(_FRAGMENT_STATE);
        }
    }

    @Override
    public void onDestroyView() {
        savedState = getStateToSave();
        saved = true;

        super.onDestroyView();
    }

    protected Bundle getSavedState() {
        return savedState;
    }

    protected abstract boolean hasSavedState();

    protected abstract Bundle getStateToSave();

}

2) In your Fragment, you must have this:

@Override
protected boolean hasSavedState() {
    Bundle state = getSavedState();

    if (state == null) {
        return false;
    }

    //restore your data here

    return true;
}

3) For example, you can call hasSavedState in onActivityCreated:

@Override
public void onActivityCreated(Bundle state) {
    super.onActivityCreated(state);

    if (hasSavedState()) {
        return;
    }

    //your code here
}

Include CSS and Javascript in my django template

Refer django docs on static files.

In settings.py:

import os
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))

MEDIA_ROOT = os.path.join(CURRENT_PATH, 'media')

MEDIA_URL = '/media/'

STATIC_ROOT = 'static/'

STATIC_URL = '/static/'

STATICFILES_DIRS = (
                    os.path.join(CURRENT_PATH, 'static'),
)

Then place your js and css files static folder in your project. Not in media folder.

In views.py:

from django.shortcuts import render_to_response, RequestContext

def view_name(request):
    #your stuff goes here
    return render_to_response('template.html', locals(), context_instance = RequestContext(request))

In template.html:

<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css" />
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery-1.8.3.min.js"></script>

In urls.py:

from django.conf import settings
urlpatterns += patterns('',
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)

Project file structure can be found here in imgbin.

ALTER DATABASE failed because a lock could not be placed on database

In my scenario, there was no process blocking the database under sp_who2. However, we discovered because the database is much larger than our other databases that pending processes were still running which is why the database under the availability group still displayed as red/offline after we tried to 'resume data'by right clicking the paused database.

To check if you still have processes running just execute this command: select percent complete from sys.dm_exec_requests where percent_complete > 0

Twitter Bootstrap Datepicker within modal window

Wrap your datapicker JavaScript code inside

function pageLoad() {}

jquery $(this).id return Undefined

Hiya demo http://jsfiddle.net/LYTbc/

this is a reference to the DOM element, so you can wrap it directly.

attr api: http://api.jquery.com/attr/

The .attr() method gets the attribute value for only the first element in the matched set.

have a nice one, cheers!

code

$(document).ready(function () {
    $(".inputs").click(function () {
         alert(this.id);

        alert(" or " + $(this).attr("id"));

    });

});?

Error in eval(expr, envir, enclos) : object not found

This can happen if you don't attach your dataset.

Adding three months to a date in PHP

Change it to this will give you the expected format:

$effectiveDate = date('Y-m-d', strtotime("+3 months", strtotime($effectiveDate)));

JavaFX: How to get stage from controller during initialization?

Platform.runLater works to prevent execution until initialization is complete. In this case, i want to refresh a list view every time I resize the window width.

Platform.runLater(() -> {
    ((Stage) listView.getScene().getWindow()).widthProperty().addListener((obs, oldVal, newVal) -> {
        listView.refresh();
    });
});

in your case

Platform.runLater(()->{
    ((Stage)myPane.getScene().getWindow()).setOn*whatIwant*(...);
});

How to add bootstrap to an angular-cli project

You can also watch this video by Mike Brocchi which has useful information on how to add bootstrap to your Angular-Cli generated project. https://www.youtube.com/watch?v=obbdFFbjLIU (around minutes 13:00)

Auto-indent spaces with C in vim?

I think the best answer is actually explained on the vim wikia:

http://vim.wikia.com/wiki/Indenting_source_code

Note that it advises against using "set autoindent." The best feature of all I find in this explanation is being able to set per-file settings, which is especially useful if you program in python and C++, for example, as you'd want 4 spaces for tabs in the former and 2 for spaces in the latter.

Is there a Sleep/Pause/Wait function in JavaScript?

You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout to kick off a function after a delay:

setTimeout(function(){alert("hi")}, 1000);

Depending on your needs, setInterval might be useful, too.

How to launch an EXE from Web page (asp.net)

This assumes the exe is somewhere you know on the user's computer:

<a href="javascript:LaunchApp()">Launch the executable</a>

<script>
function LaunchApp() {
if (!document.all) {
  alert ("Available only with Internet Explorer.");
  return;
}
var ws = new ActiveXObject("WScript.Shell");
ws.Exec("C:\\Windows\\notepad.exe");
}
</script>

Documentation: ActiveXObject, Exec Method (Windows Script Host).

How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame

There's a handy ntile function in package dplyr. It's flexible in the sense that you can very easily define the number of *tiles or "bins" you want to create.

Load the package (install first if you haven't) and add the quartile column:

library(dplyr)
temp$quartile <- ntile(temp$value, 4)  

Or, if you want to use dplyr syntax:

temp <- temp %>% mutate(quartile = ntile(value, 4))

Result in both cases is:

temp
#   name       value quartile
#1     a -0.56047565        1
#2     b -0.23017749        2
#3     c  1.55870831        4
#4     d  0.07050839        2
#5     e  0.12928774        3
#6     f  1.71506499        4
#7     g  0.46091621        3
#8     h -1.26506123        1
#9     i -0.68685285        1
#10    j -0.44566197        2
#11    k  1.22408180        4
#12    l  0.35981383        3

data:

Note that you don't need to create the "quartile" column in advance and use set.seed to make the randomization reproducible:

set.seed(123)
temp <- data.frame(name=letters[1:12], value=rnorm(12))

Invert colors of an image in CSS or JavaScript

Can be done in major new broswers using the code below

.img {
    -webkit-filter:invert(100%);
     filter:progid:DXImageTransform.Microsoft.BasicImage(invert='1');
}

However, if you want it to work across all browsers you need to use Javascript. Something like this gist will do the job.

Is calling destructor manually always a sign of bad design?

Found another example where you would have to call destructor(s) manually. Suppose you have implemented a variant-like class that holds one of several types of data:

struct Variant {
    union {
        std::string str;
        int num;
        bool b;
    };
    enum Type { Str, Int, Bool } type;
};

If the Variant instance was holding a std::string, and now you're assigning a different type to the union, you must destruct the std::string first. The compiler will not do that automatically.

How to change the default charset of a MySQL table?

If you want to change the table default character set and all character columns to a new character set, use a statement like this:

ALTER TABLE tbl_name CONVERT TO CHARACTER SET charset_name;

So query will be:

ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8;

Replacing spaces with underscores in JavaScript?

To answer Prasanna's question below:

How do you replace multiple spaces by single space in Javascript ?

You would use the same function replace with a different regular expression. The expression for whitespace is \s and the expression for "1 or more times" is + the plus sign, so you'd just replace Adam's answer with the following:

key=key.replace(/\s+/g,"_");

ORA-28000: the account is locked error getting frequently

Way to unlock the user :

$ sqlplus  /nolog
SQL > conn sys as sysdba
SQL > ALTER USER USER_NAME ACCOUNT UNLOCK;

and open new terminal

SQL > sqlplus / as sysdba
connected
SQL > conn username/password  //which username u gave before unlock
  • it will ask new password:password
  • it will ask re-type password:password
  • press enter u will get loggedin

how to "execute" make file

As paxdiablo said make -f pax.mk would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.

Also you can just type make if your file name is makefile/Makefile.

Suppose you have two files named makefile and Makefile in the same directory then makefile is executed if make alone is given. You can even pass arguments to makefile.

Check out more about makefile at this Tutorial : Basic understanding of Makefile

Create a custom View by inflating a layout?

Here is a simple demo to create customview (compoundview) by inflating from xml

attrs.xml

<resources>

    <declare-styleable name="CustomView">
        <attr format="string" name="text"/>
        <attr format="reference" name="image"/>
    </declare-styleable>
</resources>

CustomView.kt

class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
        ConstraintLayout(context, attrs, defStyleAttr) {

    init {
        init(attrs)
    }

    private fun init(attrs: AttributeSet?) {
        View.inflate(context, R.layout.custom_layout, this)

        val ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView)
        try {
            val text = ta.getString(R.styleable.CustomView_text)
            val drawableId = ta.getResourceId(R.styleable.CustomView_image, 0)
            if (drawableId != 0) {
                val drawable = AppCompatResources.getDrawable(context, drawableId)
                image_thumb.setImageDrawable(drawable)
            }
            text_title.text = text
        } finally {
            ta.recycle()
        }
    }
}

custom_layout.xml

We should use merge here instead of ConstraintLayout because

If we use ConstraintLayout here, layout hierarchy will be ConstraintLayout->ConstraintLayout -> ImageView + TextView => we have 1 redundant ConstraintLayout => not very good for performance

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:parentTag="android.support.constraint.ConstraintLayout">

    <ImageView
        android:id="@+id/image_thumb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:ignore="ContentDescription"
        tools:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/text_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="@id/image_thumb"
        app:layout_constraintStart_toStartOf="@id/image_thumb"
        app:layout_constraintTop_toBottomOf="@id/image_thumb"
        tools:text="Text" />

</merge>

Using activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <your_package.CustomView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#f00"
        app:image="@drawable/ic_android"
        app:text="Android" />

    <your_package.CustomView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#0f0"
        app:image="@drawable/ic_adb"
        app:text="ADB" />

</LinearLayout>

Result

enter image description here

Github demo

Can I hide/show asp:Menu items based on role?

You can remove unwanted menu items in Page_Load, like this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Roles.IsUserInRole("Admin"))
        {
            MenuItemCollection menuItems = mTopMenu.Items;
            MenuItem adminItem = new MenuItem();
            foreach (MenuItem menuItem in menuItems)
            {
                if (menuItem.Text == "Roles")
                    adminItem = menuItem;
            }
            menuItems.Remove(adminItem);
        }
    }

I'm sure there's a neater way to find the right item to remove, but this one works. You could also add all the wanted menu items in a Page_Load method, instead of adding them in the markup.

How to Remove Line Break in String

Replace(yourString, vbNewLine, "", , , vbTextCompare)

In C#, should I use string.Empty or String.Empty or "" to intitialize a string?

While difference is very, VERY little, the difference still exist.

1) "" creates object while String.Empty does not. But this object will be created once and will be referenced from the string pool later if you have another "" in the code.

2) String and string are the same, but I would recommend to use String.Empty (as well as String.Format, String.Copy etc.) since dot notation indicates class, not operator, and having class starting with capital letter conforms to C# coding standards.

add title attribute from css

As Quentin and other suggested this cannot totally be done with css(partially done with content attribute of css). Instead you should use javascript/jQuery to achieve this,

JS:

document.getElementsByClassName("mandatory")[0].title = "mandatory";

or using jQuery:

$('.mandatory').attr('title','mandatory');

_x000D_
_x000D_
document.getElementsByClassName('mandatory')[0].setAttribute('title', 'mandatory');_x000D_
_x000D_
$('.jmandatory').attr('title', 'jmandatory');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
Place the Mouse Over the following elements to see the title,_x000D_
<br/><br/>_x000D_
<b><label class="mandatory">->Javascript Mandatory</label></b>_x000D_
<br/><br/>_x000D_
<b><label class="jmandatory">->jQuery Mandatory</label></b>
_x000D_
_x000D_
_x000D_

Installing SetupTools on 64-bit Windows

I made a registry (.reg) file that will automatically change the registry for you. It works if it's installed in "C:\Python27":

Download 32-bit version HKEY_LOCAL_MACHINE|HKEY_CURRENT_USER\SOFTWARE\wow6432node\

Download 64-bit version HKEY_LOCAL_MACHINE|HKEY_CURRENT_USER\SOFTWARE\

React - uncaught TypeError: Cannot read property 'setState' of undefined

You need to bind this to the constructor and remember that changes to constructor needs restarting the server. Or else, you will end with the same error.

How to parse freeform street/postal address out of text, and into components

There are many street address parsers. They come in two basic flavors - ones that have databases of place names and street names, and ones that don't.

A regular expression street address parser can get up to about a 95% success rate without much trouble. Then you start hitting the unusual cases. The Perl one in CPAN, "Geo::StreetAddress::US", is about that good. There are Python and Javascript ports of that, all open source. I have an improved version in Python which moves the success rate up slightly by handling more cases. To get the last 3% right, though, you need databases to help with disambiguation.

A database with 3-digit ZIP codes and US state names and abbreviations is a big help. When a parser sees a consistent postal code and state name, it can start to lock on to the format. This works very well for the US and UK.

Proper street address parsing starts from the end and works backwards. That's how the USPS systems do it. Addresses are least ambiguous at the end, where country names, city names, and postal codes are relatively easy to recognize. Street names can usually be isolated. Locations on streets are the most complex to parse; there you encounter things such as "Fifth Floor" and "Staples Pavillion". That's when a database is a big help.

How can I trim beginning and ending double quotes from a string?

Using Guava you can write more elegantly CharMatcher.is('\"').trimFrom(mystring);

How to enable cURL in PHP / XAMPP

Steps for Windows 7:

  1. Ensure that the php.ini file that the PHP engine uses is the one you think it is.
  2. Ensure extension_dir in php.ini is correctly set to the ext folder
  3. Ensure extension=php_curl.dll in the php.ini is uncommented

Finally and maybe the one most people don't know: 4. Ensure that there are these two files in the Windows System32 folder: libeay32.dll ssleay32.dll If not there, you may copy these two files from the php folder.

Execute a SQL Stored Procedure and process the results

My Stored Procedure Requires 2 Parameters and I needed my function to return a datatable here is 100% working code

Please make sure that your procedure return some rows

Public Shared Function Get_BillDetails(AccountNumber As String) As DataTable
    Try
        Connection.Connect()
        debug.print("Look up account number " & AccountNumber)
        Dim DP As New SqlDataAdapter("EXEC SP_GET_ACCOUNT_PAYABLES_GROUP  '" & AccountNumber & "' , '" & 08/28/2013 &"'", connection.Con)
        Dim DST As New DataSet
        DP.Fill(DST)
        Return DST.Tables(0)      
    Catch ex As Exception
        Return Nothing
    End Try
End Function

Scala: write string to file in one statement

You can easily use Apache File Utils. Look at function writeStringToFile. We use this library in our projects.

How much does it cost to develop an iPhone application?

I hate to admit how little I've done an iPhone app for, but I can tell you I won't be doing that again. The guy who said that "simple, one function apps can be done .. [by solo developers]... for $5K" is correct; however, that is still lowball, and presumes almost no project design, graphic design or network backend work.

How to find SQL Server running port?

If you can start the Sql Server Configuration Manager > SQL Server Network Configuration > Your instance > TCP/IP > Properties

enter image description here

Search all the occurrences of a string in the entire project in Android Studio

On a mac use shift + cmmd + f

To get rid of the screen press esc

I use IntelliJ IDEA version: 2019.2.3 (Community Edition) Build #IC-192.6817.14, built on September 24, 2019 Runtime version: 11.0.4+10-b304.69 x86_64

What's the right way to pass form element state to sibling/parent elements?

So, if I'm understanding you correctly, your first solution is suggesting that you're keeping state in your root component? I can't speak for the creators of React, but generally, I find this to be a proper solution.

Maintaining state is one of the reasons (at least I think) that React was created. If you've ever implemented your own state pattern client side for dealing with a dynamic UI that has a lot of interdependent moving pieces, then you'll love React, because it alleviates a lot of this state management pain.

By keeping state further up in the hierarchy, and updating it through eventing, your data flow is still pretty much unidirectional, you're just responding to events in the Root component, you're not really getting the data there via two way binding, you're telling the Root component that "hey, something happened down here, check out the values" or you're passing the state of some data in the child component up in order to update the state. You changed the state in C1, and you want C2 to be aware of it, so, by updating the state in the Root component and re-rendering, C2's props are now in sync since the state was updated in the Root component and passed along.

class Example extends React.Component {
  constructor (props) {
    super(props)
    this.state = { data: 'test' }
  }
  render () {
    return (
      <div>
        <C1 onUpdate={this.onUpdate.bind(this)}/>
        <C2 data={this.state.data}/>
      </div>
    )
  }
  onUpdate (data) { this.setState({ data }) }
}

class C1 extends React.Component {
    render () {
      return (
        <div>
          <input type='text' ref='myInput'/>
          <input type='button' onClick={this.update.bind(this)} value='Update C2'/>
        </div>
      )
    }
    update () {
      this.props.onUpdate(this.refs.myInput.getDOMNode().value)
    }
})

class C2 extends React.Component {
    render () {
      return <div>{this.props.data}</div>
    }
})

ReactDOM.renderComponent(<Example/>, document.body)

Add a common Legend for combined ggplots

If the legend is the same for both plots, there is a simple solution using grid.arrange(assuming you want your legend to align with both plots either vertically or horizontally). Simply keep the legend for the bottom-most or right-most plot while omitting the legend for the other. Adding a legend to just one plot, however, alters the size of one plot relative to the other. To avoid this use the heights command to manually adjust and keep them the same size. You can even use grid.arrange to make common axis titles. Note that this will require library(grid) in addition to library(gridExtra). For vertical plots:

y_title <- expression(paste(italic("E. coli"), " (CFU/100mL)"))

grid.arrange(arrangeGrob(p1, theme(legend.position="none"), ncol=1), 
   arrangeGrob(p2, theme(legend.position="bottom"), ncol=1), 
   heights=c(1,1.2), left=textGrob(y_title, rot=90, gp=gpar(fontsize=20)))

Here is the result for a similar graph for a project I was working on: enter image description here

How to get the size of a range in Excel

The Range object has both width and height properties, which are measured in points.

Fatal error: Call to undefined function mb_detect_encoding()

Under Windows / WAMP there doesn't seem to be any php_mbstring.dll dependencies on the GD2 extension, the MySQL extensions, nor on external dlls/libs:

deplister.exe ext\php_mbstring.dll

php5ts.dll,OK
MSVCR110.dll,OK
KERNEL32.dll,OK

deplister.exe ext\php_gd2.dll

php5ts.dll,OK
USER32.dll,OK
GDI32.dll,OK
KERNEL32.dll,OK
MSVCR110.dll,OK

Whatever php_mbstring already needs, it's built-in (statically compiled right into the DLL).

Call to undefined function mb_detect_encoding()

This error is also very specific and deterministic...

The function mb_detect_encoding() didn't fail because php_gd, php_mysql, php_mysqli, or another extension was not loaded; it simply was NOT found.

I'm guessing that all the answers that are reported as valid (for Windows / WAMP), that say to load other extensions, to change php.ini extension_dir paths (if this one was wrong to begin with, NO extensions would load), etc, work more due to a) un-commenting the extension = php_mbstring.dll line, or b) restarting Apache or the computer (for changes to take effect).

On Windows, most of the time the problem is that php_mbstring.dll is either:

  • Blocked by Windows. Unblock it by right-clicking it, check Properties.

  • Or PHP can't load php_mbstring.dll due to another version getting loaded (e.g., from some improper PHP DLLs install into C:\Windows\system32), some version mismatch, missing run-time DLLs, etc. Check Apache's and PHP's error log files first for clues.

More in-depth answer here: Call to undefined function mb_detect_encoding

R adding days to a date

You could also use

library(lubridate)
dmy("1/1/2001") + days(45)

Access 2010 VBA query a table and iterate through results

I know some things have changed in AC 2010. However, the old-fashioned ADODB is, as far as I know, the best way to go in VBA. An Example:

Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Dim rs As ADODB.Recordset
Dim colReturn As New Collection

Dim SQL As String
SQL = _
    "SELECT c.ClientID, c.LastName, c.FirstName, c.MI, c.DOB, c.SSN, " & _
    "c.RaceID, c.EthnicityID, c.GenderID, c.Deleted, c.RecordDate " & _
    "FROM tblClient AS c " & _
    "WHERE c.ClientID = @ClientID"

Set cn = New ADODB.Connection
Set cmd = New ADODB.Command

With cn
    .Provider = DataConnection.MyADOProvider
    .ConnectionString = DataConnection.MyADOConnectionString
    .Open
End With

With cmd
    .CommandText = SQL
    .ActiveConnection = cn
    Set prm = .CreateParameter("@ClientID", adInteger, adParamInput, , mlngClientID)
    .Parameters.Append prm
End With

Set rs = cmd.Execute

With rs
    If Not .EOF Then
        Do Until .EOF
            mstrLastName = Nz(!LastName, "")
            mstrFirstName = Nz(!FirstName, "")
            mstrMI = Nz(!MI, "")
            mdDOB = !DOB
            mstrSSN = Nz(!SSN, "")
            mlngRaceID = Nz(!RaceID, -1)
            mlngEthnicityID = Nz(!EthnicityID, -1)
            mlngGenderID = Nz(!GenderID, -1)
            mbooDeleted = Deleted
            mdRecordDate = Nz(!RecordDate, "")

            .MoveNext
        Loop
    End If
    .Close
End With

cn.Close

Set rs = Nothing
Set cn = Nothing

Using SVG as background image

Try placing it on your body

body {
    height: 100%;
    background-image: url(../img/bg.svg);
    background-size:100% 100%;
    -o-background-size: 100% 100%;
    -webkit-background-size: 100% 100%;
    background-size:cover;
}

Git: Could not resolve host github.com error while cloning remote repository in git

One reason for this issue could be wrong/empty /etc/resolv.conf file.

The way I resolved this issue in my centos 7 minimal is as follows: my /etc/resolv.conf was empty and I added the following lines:

nameserver 192.168.1.1
nameserver 0.0.0.0

where 192.168.1.1 is my gateway, in your case it can be different.

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

The FailedPreconditionError comes because the session is trying to read a variable that hasn"t been initialized.

As of Tensorflow version 1.11.0, you need to take this :

init_op = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init_op)

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

PHP - get base64 img string decode and save as jpg (resulting empty image )

A minor simplification on the example by @naresh. Should deal with permission issues and offer some clarification.

$data = '<base64_encoded_string>';

$data = base64_decode($data);

$img = imagecreatefromstring($data);

header('Content-Type: image/png');

$file = '<path_to_home_or_user_directory>/decoded_images/test.png';

imagepng($img, $file);

imagedestroy($img);

Best way to log POST data in Apache?

You can install mod_security and put in /etc/modsecurity/modsecurity.conf:

SecRuleEngine On
SecAuditEngine On
SecAuditLog /var/log/apache2/modsec_audit.log
SecRequestBodyAccess on
SecAuditLogParts ABIJDFHZ

Complex JSON nesting of objects and arrays

First, choosing a data structure(xml,json,yaml) usually includes only a readability/size problem. For example

Json is very compact, but no human being can read it easily, very hard do debug,

Xml is very large, but everyone can easily read/debug it,

Yaml is in between Xml and json.

But if you want to work with Javascript heavily and/or your software makes a lot of data transfer between browser-server, you should use Json, because it is pure javascript and very compact. But don't try to write it in a string, use libraries to generate the code you needed from an object.

Hope this helps.

Getting the screen resolution using PHP

PHP works only on server side, not on user host. Use JavaScript or jQuery to get this info and send via AJAX or URL (?x=1024&y=640).

increment date by one month

I needed similar functionality, except for a monthly cycle (plus months, minus 1 day). After searching S.O. for a while, I was able to craft this plug-n-play solution:

function add_months($months, DateTime $dateObject) 
    {
        $next = new DateTime($dateObject->format('Y-m-d'));
        $next->modify('last day of +'.$months.' month');

        if($dateObject->format('d') > $next->format('d')) {
            return $dateObject->diff($next);
        } else {
            return new DateInterval('P'.$months.'M');
        }
    }

function endCycle($d1, $months)
    {
        $date = new DateTime($d1);

        // call second function to add the months
        $newDate = $date->add(add_months($months, $date));

        // goes back 1 day from date, remove if you want same day of month
        $newDate->sub(new DateInterval('P1D')); 

        //formats final date to Y-m-d form
        $dateReturned = $newDate->format('Y-m-d'); 

        return $dateReturned;
    }

Example:

$startDate = '2014-06-03'; // select date in Y-m-d format
$nMonths = 1; // choose how many months you want to move ahead
$final = endCycle($startDate, $nMonths); // output: 2014-07-02

How to print out all the elements of a List in Java?

I have faced similar problems. My code:

List<Integer> leaveDatesList = new ArrayList<>();

.....inserted value in list.......

Way 1: printing a list in a for loop

for(int i=0;i<leaveDatesList.size();i++){
    System.out.println(leaveDatesList.get(i));
}

Way 2: printing the list in a forEach, for loop

for(Integer leave : leaveDatesList){
    System.out.println(leave);
}

Way 3: printing the list in java 8

leaveDatesList.forEach(System.out::println);

How can I create download link in HTML?

To link to the file, do the same as any other page link:

<a href="...">link text</a>

To force things to download even if they have an embedded plugin (Windows + QuickTime = ugh), you can use this in your htaccess / apache2.conf:

AddType application/octet-stream EXTENSION

./xx.py: line 1: import: command not found

It's about Shebang

#!usr/bin/python

This will tell which interpreter to wake up to run the code written in file.

Mock HttpContext.Current in Test Init Method

If your application third party redirect internally, so it is better to mock HttpContext in below way :

HttpWorkerRequest initWorkerRequest = new SimpleWorkerRequest("","","","",new StringWriter(CultureInfo.InvariantCulture));
System.Web.HttpContext.Current = new HttpContext(initWorkerRequest);
System.Web.HttpContext.Current.Request.Browser = new HttpBrowserCapabilities();
System.Web.HttpContext.Current.Request.Browser.Capabilities = new Dictionary<string, string> { { "requiresPostRedirectionHandling", "false" } };

How to change TIMEZONE for a java.util.Calendar/Date

  1. The class Date/Timestamp represents a specific instant in time, with millisecond precision, since January 1, 1970, 00:00:00 GMT. So this time difference (from epoch to current time) will be same in all computers across the world with irrespective of Timezone.

  2. Date/Timestamp doesn't know about the given time is on which timezone.

  3. If we want the time based on timezone we should go for the Calendar or SimpleDateFormat classes in java.

  4. If you try to print a Date/Timestamp object using toString(), it will convert and print the time with the default timezone of your machine.

  5. So we can say (Date/Timestamp).getTime() object will always have UTC (time in milliseconds)

  6. To conclude Date.getTime() will give UTC time, but toString() is on locale specific timezone, not UTC.

Now how will I create/change time on specified timezone?

The below code gives you a date (time in milliseconds) with specified timezones. The only problem here is you have to give date in string format.

   DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
   dateFormatLocal.setTimeZone(timeZone);
   java.util.Date parsedDate = dateFormatLocal.parse(date);

Use dateFormat.format for taking input Date (which is always UTC), timezone and return date as String.

How to store UTC/GMT time in DB:

If you print the parsedDate object, the time will be in default timezone. But you can store the UTC time in DB like below.

        Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        Timestamp tsSchedStartTime = new Timestamp (parsedDate.getTime());
        if (tsSchedStartTime != null) {
            stmt.setTimestamp(11, tsSchedStartTime, calGMT );
        } else {
            stmt.setNull(11, java.sql.Types.DATE);
        }

How to programmatically send SMS on the iPhone?

Here is a tutorial which does exactly what you are looking for: the MFMessageComposeViewController.

http://blog.mugunthkumar.com/coding/iphone-tutorial-how-to-send-in-app-sms/

Essentially:

MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
    controller.body = @"SMS message here";
    controller.recipients = [NSArray arrayWithObjects:@"1(234)567-8910", nil];
    controller.messageComposeDelegate = self;
    [self presentModalViewController:controller animated:YES];
}

And a link to the docs.

https://developer.apple.com/documentation/messageui/mfmessagecomposeviewcontroller

difference between primary key and unique key

difference between Primary Key and Unique Key

Both Primary key and Unique Key are used to uniquely define of a row in a table. Primary Key creates a clustered index of the column whereas a Unique creates an unclustered index of the column.

A Primary Key doesn’t allow NULL value, however a Unique Key does allow one NULL value.

Programmatically change the src of an img tag

With the snippet you provided (and without making assumptions about the parents of the element) you could get a reference to the image with

document.querySelector('img[name="edit-save"]');

and change the src with

document.querySelector('img[name="edit-save"]').src = "..."

so you could achieve the desired effect with

var img = document.querySelector('img[name="edit-save"]');
img.onclick = function() {
    this.src = "..." // this is the reference to the image itself
};

otherwise, as other suggested, if you're in control of the code, it's better to assign an id to the image a get a reference with getElementById (since it's the fastest method to retrieve an element)

SQL Server: Null VS Empty String

NULL is a non value, like undefined. '' is a empty string with 0 characters.
The value of a string in database depends of your value in your UI, but generally, it's an empty string '' if you specify the parameter in your query or stored procedure.

How to pass parameter to a promise function

Try this:

function someFunction(username, password) {
      return new Promise((resolve, reject) => {
        // Do something with the params username and password...
        if ( /* everything turned out fine */ ) {
          resolve("Stuff worked!");
        } else {
          reject(Error("It didn't work!"));
        }
      });
    }
    
    someFunction(username, password)
      .then((result) => {
        // Do something...
      })
      .catch((err) => {
        // Handle the error...
      });

Make browser window blink in task Bar

These users do want to be distracted when a new message arrives.

It sounds like you're writing an app for an internal company project.

You might want to investigate writing a small windows app in .net which adds a notify icon and can then do fancy popups or balloon popups or whatever, when they get new messages.

This isn't overly hard and I'm sure if you ask SO 'how do I show a tray icon' and 'how do I do pop up notifications' you'll get some great answers :-)

For the record, I'm pretty sure that (other than using an alert/prompt dialog box) you can't flash the taskbar in JS, as this is heavily windows specific, and JS really doesn't work like that. You may be able to use some IE-specific windows activex controls, but then you inflict IE upon your poor users. Don't do that :-(

Max parallel http connections in a browser?

Firefox stores that number in this setting (you find it in about:config): network.http.max-connections-per-server

For the max connections, Firefox stores that in this setting: network.http.max-connections

HQL ERROR: Path expected for join

You need to name the entity that holds the association to User. For example,

... INNER JOIN ug.user u ...

That's the "path" the error message is complaining about -- path from UserGroup to User entity.

Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.

Bootstrap 4 - Glyphicons migration?

Migrating from Glyphicons to Font Awesome is quite easy.

Include a reference to Font Awesome (either locally, or use the CDN).

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

Then run a search and replace where you search for glyphicon glyphicon- and replace it with fa fa-, and also change the enclosing element from <span to <i. Most of the CSS class names are the same. Some have changed though, so you have to manually fix those.

How do I create an executable in Visual Studio 2013 w/ C++?

All executable files from Visual Studio should be located in the debug folder of your project, e.g:

Visual Studio Directory: c:\users\me\documents\visual studio

Then the project which was called 'hello world' would be in the directory:

c:\users\me\documents\visual studio\hello world

And your exe would be located in:

c:\users\me\documents\visual studio\hello world\Debug\hello world.exe

Note the exe being named the same as the project.

Otherwise, you could publish it to a specified folder of your choice which comes with an installation, which would be good if you wanted to distribute it quickly

EDIT:

Everytime you build your project in VS, the exe is updated with the new one according to the code (as long as it builds without errors). When you publish it, you can choose the location, aswell as other factors, and the setup exe will be in that location, aswell as some manifest files and other files about the project.

Opening Chrome From Command Line

open command prompt and type

cd\ (enter)

then type

start chrome "www.google.com"(any website you require)

How can I resolve "Your requirements could not be resolved to an installable set of packages" error?

Your software dependencies have an incompatible version conflict.

At the same time you want to install any Laravel 4.2.x version, and "zizaco/entrust" from its master branch. And that master branch requires at least Laravel 5.0 (roughly speaking).

The problem comes from the dependency on branches. It's likely that the package zizaco/entrust once was using Laravel 4.2 in its master branch, and that you were able to install your dependencies at that day. But the very moment this branch gets updated with an incompatible version requirement, you will never ever be able to run composer update and get updated dependencies.

Always use tagged versions! Ideally you use a relaxed version requirement that allows for compatible updates. This should be expressed as a tilde-two-number version requirement: ~1.2 would install a version 1.2.0 and up (like 1.2.99 or 1.2.100), and also 1.3 and up. If you need a certain patch release: Caret-three-number version ^1.2.10 will install 1.2.10 or up, also 1.3 and up.

Using this version requirement instead of dev-master will allow you to use released versions instead of the unstable state in the master branch, and allows you to address the most recent version that still works with Laravel 4.2. I guess that would be zizaco/entrust version 1.3.0, but version 1.2 would also qualify. Go with "zizaco/entrust": "~1.2".

How do I install soap extension?

How To for Linux Ubuntu...

sudo apt-get install php7.1-soap 

Check if file php_soap.ao exists on /usr/lib/php/20160303/

ls /usr/lib/php/20160303/ | grep -i soap
soap.so
php_soap.so
sudo vi /etc/php/7.1/cli/php.ini

Change the line :

;extension=php_soap.dll

to

extension=php_soap.so

sudo systemctl restart apache2

CHecking...

php -m | more

PHP: How do I display the contents of a textfile on my page?

For just reading file and outputting it the best one would be readfile.

If isset $_POST

If you send the form empty, $_POST['mail'] will still be sent, but the value is empty. To check if the field is empty you need to check

if(isset($_POST["mail"]) && trim($_POST["mail"]) != "") { .. }

Raise an error manually in T-SQL to jump to BEGIN CATCH block

THROW (Transact-SQL)

Raises an exception and transfers execution to a CATCH block of a TRY…CATCH construct in SQL Server 2017.

Please refer the below link

T-SQL Throw Exception

Simple and fast method to compare images for similarity

I face the same issues recently, to solve this problem(simple and fast algorithm to compare two images) once and for all, I contribute an img_hash module to opencv_contrib, you can find the details from this link.

img_hash module provide six image hash algorithms, quite easy to use.

Codes example

origin lenaorigin lena

blur lenablur lena

resize lenaresize lena

shift lenashift lena

#include <opencv2/core.hpp>
#include <opencv2/core/ocl.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/img_hash.hpp>
#include <opencv2/imgproc.hpp>

#include <iostream>

void compute(cv::Ptr<cv::img_hash::ImgHashBase> algo)
{
    auto input = cv::imread("lena.png");
    cv::Mat similar_img;

    //detect similiar image after blur attack
    cv::GaussianBlur(input, similar_img, {7,7}, 2, 2);
    cv::imwrite("lena_blur.png", similar_img);
    cv::Mat hash_input, hash_similar;
    algo->compute(input, hash_input);
    algo->compute(similar_img, hash_similar);
    std::cout<<"gaussian blur attack : "<<
               algo->compare(hash_input, hash_similar)<<std::endl;

    //detect similar image after shift attack
    similar_img.setTo(0);
    input(cv::Rect(0,10, input.cols,input.rows-10)).
            copyTo(similar_img(cv::Rect(0,0,input.cols,input.rows-10)));
    cv::imwrite("lena_shift.png", similar_img);
    algo->compute(similar_img, hash_similar);
    std::cout<<"shift attack : "<<
               algo->compare(hash_input, hash_similar)<<std::endl;

    //detect similar image after resize
    cv::resize(input, similar_img, {120, 40});
    cv::imwrite("lena_resize.png", similar_img);
    algo->compute(similar_img, hash_similar);
    std::cout<<"resize attack : "<<
               algo->compare(hash_input, hash_similar)<<std::endl;
}

int main()
{
    using namespace cv::img_hash;

    //disable opencl acceleration may(or may not) boost up speed of img_hash
    cv::ocl::setUseOpenCL(false);

    //if the value after compare <= 8, that means the images
    //very similar to each other
    compute(ColorMomentHash::create());

    //there are other algorithms you can try out
    //every algorithms have their pros and cons
    compute(AverageHash::create());
    compute(PHash::create());
    compute(MarrHildrethHash::create());
    compute(RadialVarianceHash::create());
    //BlockMeanHash support mode 0 and mode 1, they associate to
    //mode 1 and mode 2 of PHash library
    compute(BlockMeanHash::create(0));
    compute(BlockMeanHash::create(1));
}

In this case, ColorMomentHash give us best result

  • gaussian blur attack : 0.567521
  • shift attack : 0.229728
  • resize attack : 0.229358

Pros and cons of each algorithm

Performance under different attacks

The performance of img_hash is good too

Speed comparison with PHash library(100 images from ukbench) compute performance comparison performance

If you want to know the recommend thresholds for these algorithms, please check this post(http://qtandopencv.blogspot.my/2016/06/introduction-to-image-hash-module-of.html). If you are interesting about how do I measure the performance of img_hash modules(include speed and different attacks), please check this link(http://qtandopencv.blogspot.my/2016/06/speed-up-image-hashing-of-opencvimghash.html).

how to get current location in google map android

I think that better way now is:

Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

Documentation. Getting the Last Known Location

Converting HTML files to PDF

Check out iText; it is a pure Java PDF toolkit which has support for reading data from HTML. I used it recently in a project when I needed to pull content from our CMS and export as PDF files, and it was all rather straightforward. The support for CSS and style tags is pretty limited, but it does render tables without any problems (I never managed to set column width though).

Creating a PDF from HTML goes something like this:

Document doc = new Document(PageSize.A4);
PdfWriter.getInstance(doc, out);
doc.open();
HTMLWorker hw = new HTMLWorker(doc);
hw.parse(new StringReader(html));
doc.close();

How to set shape's opacity?

In general you just have to define a slightly transparent color when creating the shape.

You can achieve that by setting the colors alpha channel.

#FF000000 will get you a solid black whereas #00000000 will get you a 100% transparent black (well it isn't black anymore obviously).

The color scheme is like this #AARRGGBB there A stands for alpha channel, R stands for red, G for green and B for blue.

The same thing applies if you set the color in Java. There it will only look like 0xFF000000.

UPDATE

In your case you'd have to add a solid node. Like below.

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/shape_my">
    <stroke android:width="4dp" android:color="#636161" />
    <padding android:left="20dp"
        android:top="20dp"
        android:right="20dp"
        android:bottom="20dp" />
    <corners android:radius="24dp" />
    <solid android:color="#88000000" />
</shape>

The color here is a half transparent black.

What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

Disabled means that no data from that form element will be submitted when the form is submitted. Read-only means any data from within the element will be submitted, but it cannot be changed by the user.

For example:

<input type="text" name="yourname" value="Bob" readonly="readonly" />

This will submit the value "Bob" for the element "yourname".

<input type="text" name="yourname" value="Bob" disabled="disabled" />

This will submit nothing for the element "yourname".

How do I integrate Ajax with Django applications?

I am writing this because the accepted answer is pretty old, it needs a refresher.

So this is how I would integrate Ajax with Django in 2019 :) And lets take a real example of when we would need Ajax :-

Lets say I have a model with registered usernames and with the help of Ajax I wanna know if a given username exists.

html:

<p id="response_msg"></p> 
<form id="username_exists_form" method='GET'>
      Name: <input type="username" name="username" />
      <button type='submit'> Check </button>           
</form>   

ajax:

$('#username_exists_form').on('submit',function(e){
    e.preventDefault();
    var username = $(this).find('input').val();
    $.get('/exists/',
          {'username': username},   
          function(response){ $('#response_msg').text(response.msg); }
    );
}); 

urls.py:

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('exists/', views.username_exists, name='exists'),
]

views.py:

def username_exists(request):
    data = {'msg':''}   
    if request.method == 'GET':
        username = request.GET.get('username').lower()
        exists = Usernames.objects.filter(name=username).exists()
        if exists:
            data['msg'] = username + ' already exists.'
        else:
            data['msg'] = username + ' does not exists.'
    return JsonResponse(data)

Also render_to_response which is deprecated and has been replaced by render and from Django 1.7 onwards instead of HttpResponse we use JsonResponse for ajax response. Because it comes with a JSON encoder, so you don’t need to serialize the data before returning the response object but HttpResponse is not deprecated.

How to get the jQuery $.ajax error response text?

This will allow you to see the whole response not just the "responseText" value

error: function(xhr, status, error) {
    var acc = []
    $.each(xhr, function(index, value) {
        acc.push(index + ': ' + value);
    });
    alert(JSON.stringify(acc));
}

How to efficiently build a tree from a flat structure?

Store IDs of the objects in a hash table mapping to the specific object. Enumerate through all the objects and find their parent if it exists and update its parent pointer accordingly.

class MyObject
{ // The actual object
    public int ParentID { get; set; }
    public int ID { get; set; }
}

class Node
{
    public List<Node> Children = new List<Node>();
    public Node Parent { get; set; }
    public MyObject AssociatedObject { get; set; }
}

IEnumerable<Node> BuildTreeAndGetRoots(List<MyObject> actualObjects)
{
    Dictionary<int, Node> lookup = new Dictionary<int, Node>();
    actualObjects.ForEach(x => lookup.Add(x.ID, new Node { AssociatedObject = x }));
    foreach (var item in lookup.Values) {
        Node proposedParent;
        if (lookup.TryGetValue(item.AssociatedObject.ParentID, out proposedParent)) {
            item.Parent = proposedParent;
            proposedParent.Children.Add(item);
        }
    }
    return lookup.Values.Where(x => x.Parent == null);
}

How do I set up cron to run a file just once at a specific time?

Your comment suggests you're trying to call this from a programming language. If that's the case, can your program fork a child process that calls sleep then does the work?

What about having your program calculate the number of seconds until the desired runtime, and have it call shell_exec("sleep ${secondsToWait) ; myCommandToRun");

Eclipse error: indirectly referenced from required .class files?

If you still can not find anything wrong with your setup, you can try Project -> Clean and clean all the projects in the workspace.

EDIT: Sorry, did not see the suggestion of verbose_mode ... same thing

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

What is the difference between range and xrange functions in Python 2.X?

xrange only stores the range params and generates the numbers on demand. However the C implementation of Python currently restricts its args to C longs:

xrange(2**32-1, 2**32+1)  # When long is 32 bits, OverflowError: Python int too large to convert to C long
range(2**32-1, 2**32+1)   # OK --> [4294967295L, 4294967296L]

Note that in Python 3.0 there is only range and it behaves like the 2.x xrange but without the limitations on minimum and maximum end points.

How to: Add/Remove Class on mouseOver/mouseOut - JQuery .hover?

You could just use: {in and out function callback}

$(".result").hover(function () {
    $(this).toggleClass("result_hover");
 });

For your example, better will be to use CSS pseudo class :hover: {no js/jquery needed}

.result {
    height: 72px;
    width: 100%;
    border: 1px solid #000;
  }
  .result:hover {
    background-color: #000;
  }

How to get names of enum entries?

Though the answer is already provided, Almost no one pointed to the docs

Here's a snippet

enum Enum {
    A
}
let nameOfA = Enum[Enum.A]; // "A"

Keep in mind that string enum members do not get a reverse mapping generated at all.

HTTP Request in Kotlin

Using only the standard library with minimal code!

thread {
    val jsonStr = try { URL(url).readText() } catch (ex: Exception) { return@thread }
    runOnUiThread { displayOrWhatever(jsonStr) }
}

This starts a GET request on a new thread, leaving the UI thread to respond to user input. However, we can only modify UI elements from the main/UI thread, so we actually need a runOnUiThread block to show the result to our user. This enqueues our display code to be run on the UI thread soon.

The try/catch is there so your app won't crash if you make a request with your phone's internet off. Add your own error handling (e.g. showing a Toast) as you please.

.readText() is not part of the java.net.URL class but a Kotlin extension method, Kotlin "glues" this method onto URL. This is enough for plain GET requests, but for more control and POST requests you need something like the Fuel library.

Difference between readFile() and readFileSync()

readFileSync() is synchronous and blocks execution until finished. These return their results as return values. readFile() are asynchronous and return immediately while they function in the background. You pass a callback function which gets called when they finish. let's take an example for non-blocking.

following method read a file as a non-blocking way

var fs = require('fs');
fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        console.log(data);
});

following is read a file as blocking or synchronous way.

var data = fs.readFileSync(filename);

LOL...If you don't want readFileSync() as blocking way then take reference from the following code. (Native)

var fs = require('fs');
function readFileAsSync(){
    new Promise((resolve, reject)=>{
        fs.readFile(filename, "utf8", function(err, data) {
                if (err) throw err;
                resolve(data);
        });
    });
}

async function callRead(){
    let data = await readFileAsSync();
    console.log(data);
}

callRead();

it's mean behind scenes readFileSync() work same as above(promise) base.

How do I find the version of Apache running without access to the command line?

In the default installation, call a page that doesn't exist and you get an error with the version at the end:

Object not found!

The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
10/03/08 14:41:45
Apache/2.2.8 (Win32) DAV/2 mod_ssl/2.2.8 OpenSSL/0.9.8g mod_autoindex_color PHP/5.2.5

Java "lambda expressions not supported at this language level"

Possible Cause #1 (same as the first 3 answers for this question): Project Structure Settings

  1. File > Project Structure > Under Project Settings, go to Project > set Project SDK to 1.8 (with version 65 or above, latest is 112) and set Project Language Level to 8.

  2. File > Project Structure > Under Platform Settings, go to Project > ensure that your JDK home path is set to 1.8 (with version 65 or above, latest is 112).

If the above does not work, check the target bytecode version of your compiler and move on to Possible Cause #2.

Possible Cause #2: Compiler

  1. File > Settings > Build, Execution, Deployment > Under Compiler, go to Java Compiler > set your Project Bytecode Version to 1.8, as well as all the Target Bytecode Version for your modules. Click Apply and hit OK. Restart your IntelliJ IDE. Lambda expression was accepted in my IDE at this point.

Best wishes :)

get keys of json-object in JavaScript

The working code

_x000D_
_x000D_
var jsonData = [{person:"me", age :"30"},{person:"you",age:"25"}];_x000D_
_x000D_
for(var obj in jsonData){_x000D_
    if(jsonData.hasOwnProperty(obj)){_x000D_
    for(var prop in jsonData[obj]){_x000D_
        if(jsonData[obj].hasOwnProperty(prop)){_x000D_
           alert(prop + ':' + jsonData[obj][prop]);_x000D_
        }_x000D_
    }_x000D_
}_x000D_
}
_x000D_
_x000D_
_x000D_

Using "like" wildcard in prepared statement

PreparedStatement ps = cn.prepareStatement("Select * from Users where User_FirstName LIKE ?");
ps.setString(1, name + '%');

Try this out.

Markdown `native` text alignment

I found pretty useful to use latex syntax on jupyter notebooks cells, like:

![good-boy](https://i.imgur.com/xtoLyW2.jpg  "Good boy on boat")

$$\text{This is some centered text}$$

How to Add Incremental Numbers to a New Column Using Pandas

You can also simply set your pandas column as list of id values with length same as of dataframe.

df['New_ID'] = range(880, 880+len(df))

Reference docs : https://pandas.pydata.org/pandas-docs/stable/missing_data.html

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

Similar issue with the PHP SDK, this works:

$s3Client = S3Client::factory(array('key'=>YOUR_AWS_KEY, 'secret'=>YOUR_AWS_SECRET, 'signature' => 'v4', 'region'=>'eu-central-1'));

The important bit is the signature and the region

How to center horizontal table-cell

Just add this class in your css

.column p{
   text-align:center;
}

How can I check if string contains characters & whitespace, not just whitespace?

I've used the following method to detect if a string contains only whitespace. It also matches empty strings.

if (/^\s*$/.test(myStr)) {
  // the string contains only whitespace
}

What is the significance of load factor in HashMap?

I would pick a table size of n * 1.5 or n + (n >> 1), this would give a load factor of .66666~ without division, which is slow on most systems, especially on portable systems where there is no division in the hardware.

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

Boundary Control Entity pattern have two versions:
- old structural, described at 127 (entity as an data model elements, control as an functions, boundary as an application interface)
- new object pattern


As an object pattern:
- Boundary is an interface for "other world"
- Control in an any internal logic (like a service in DDD pattern)
- Entity is an an persistence serwis for objects (like a repository in DDD pattern).
All classes have operations (see Fowler anemic domain model anti-pattern)
All of them is an Model component in MVC pattern. The rules:
- Only Boundary provide services for the "other world"
- Boundary can call only to Controll
- Control can call anybody
- Entity can't call anybody (!), only be called.

jz

Why doesn't indexOf work on an array IE8?

Please careful with $.inArray if you want to use it. I just found out that the $.inArray is only works with "Array", not with String. That's why this function will not working in IE8!

The jQuery API make confusion

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0

--> They shouldn't say it "Similar". Since indexOf support "String" also!

How to parse a date?

You cannot expect to parse a date with a SimpleDateFormat that is set up with a different format.

To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly):

SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");

Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.

        String input = "Thu Jun 18 20:56:02 EDT 2009";
        SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
        Date date = parser.parse(input);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = formatter.format(date);

        ...

JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

implement addClass and removeClass functionality in angular2

If you want to due this in component.ts

HTML:

<button class="class1 class2" (click)="clicked($event)">Click me</button>

Component:

clicked(event) {
  event.target.classList.add('class3'); // To ADD
  event.target.classList.remove('class1'); // To Remove
  event.target.classList.contains('class2'); // To check
  event.target.classList.toggle('class4'); // To toggle
}

For more options, examples and browser compatibility visit this link.

Finding all possible combinations of numbers to reach a given sum

I thought I'd use an answer from this question but I couldn't, so here is my answer. It is using a modified version of an answer in Structure and Interpretation of Computer Programs. I think this is a better recursive solution and should please the purists more.

My answer is in Scala (and apologies if my Scala sucks, I've just started learning it). The findSumCombinations craziness is to sort and unique the original list for the recursion to prevent dupes.

def findSumCombinations(target: Int, numbers: List[Int]): Int = {
  cc(target, numbers.distinct.sortWith(_ < _), List())
}

def cc(target: Int, numbers: List[Int], solution: List[Int]): Int = {
  if (target == 0) {println(solution); 1 }
  else if (target < 0 || numbers.length == 0) 0
  else 
    cc(target, numbers.tail, solution) 
    + cc(target - numbers.head, numbers, numbers.head :: solution)
}

To use it:

 > findSumCombinations(12345, List(1,5,22,15,0,..))
 * Prints a whole heap of lists that will sum to the target *

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

One of the best solutions is to add the following in your application.properties file: spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

How to set fake GPS location on IOS real device

I had a similar issue, but with no source code to run on Xcode.

So if you want to test an application on a real device with a fake location you should use a VPN application.

There are plenty in the App Store to choose from - free ones without the option to choose a specific country/city and free ones which assign you a random location or asks you to choose from a limited set of default options.

Exception: Can't bind to 'ngFor' since it isn't a known native property

Another typo leading to the OP's error could be using in:

<div *ngFor="let talk in talks">

You should use of instead:

<div *ngFor="let talk of talks">

bootstrap 3 - how do I place the brand in the center of the navbar?

If you have no other links, then there is no use for navbar-header....

HTML:

<nav class="navbar navbar-inverse navbar-static-top">
    <div class="container">
     <a class="navbar-brand text-center center-block" href="#">Navbar Brand</a>
  .....
</nav>

CSS:

.navbar-brand {
  float: none;
}


However, if you do want other links here's a very effective approach that allows that: https://stackoverflow.com/a/34149840/3123861

window.onload vs $(document).ready()

window.onload is the built-in JavaScript event, but as its implementation had subtle quirks across browsers (Firefox, Internet Explorer 6, Internet Explorer 8, and Opera), jQuery provides document.ready, which abstracts those away, and fires as soon as the page's DOM is ready (doesn't wait for images, etc.).

$(document).ready (note that it's not document.ready, which is undefined) is a jQuery function, wrapping and providing consistency to the following events:

  • document.ondomcontentready / document.ondomcontentloaded - a newish event which fires when the document's DOM is loaded (which may be some time before the images, etc. are loaded); again, slightly different in Internet Explorer and in rest of the world
  • and window.onload (which is implemented even in old browsers), which fires when the entire page loads (images, styles, etc.)

Codeigniter : calling a method of one controller from other

Controller to be extended

require_once(PHYSICAL_BASE_URL . 'system/application/controllers/abc.php');

        $report= new onlineAssessmentReport();
        echo ($report->detailView());