Programs & Examples On #Window.location

window.location is a property in JavaScript for getting the current page's location.

Detect HTTP or HTTPS then force HTTPS in JavaScript

Hi i used this solution works perfectly.No Need to check, just use https.

<script language="javascript" type="text/javascript">
document.location="https:" + window.location.href.substring(window.location.protocol.length, window.location.href.length);
</script>

window.location.href not working

if anyone faced problem even after using return false; . then use the below.

setTimeout(function(){document.location.href = "index.php"},500);

JavaScript hard refresh of current page

Try to use:

location.reload(true);

When this method receives a true value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.

More info:

What's the difference between window.location and document.location in JavaScript?

According to the W3C, they are the same. In reality, for cross browser safety, you should use window.location rather than document.location.

See: http://www.w3.org/TR/html/browsers.html#dom-location

Change hash without reload in jQuery

You can simply assign it a new value as follows,

window.location.hash

window.location.href doesn't redirect

From this answer,

window.location.href not working

you just need to add

return false;

at the bottom of your function

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

JavaScript: location.href to open in new window/tab?

For example:

    $(document).on('click','span.external-link',function(){
        var t               = $(this), 
            URL             = t.attr('data-href');        
        $('<a href="'+ URL +'" target="_blank">External Link</a>')[0].click();

    });

Working example.

How to remove the hash from window.location (URL) with JavaScript without page refresh?

function removeLocationHash(){
    var noHashURL = window.location.href.replace(/#.*$/, '');
    window.history.replaceState('', document.title, noHashURL) 
}

window.addEventListener("load", function(){
    removeLocationHash();
});

How to import a module in Python with importlib.import_module

And don't forget to create a __init__.py with each folder/subfolder (even if they are empty)

Concatenate two slices in Go

Nothing against the other answers, but I found the brief explanation in the docs more easily understandable than the examples in them:

func append

func append(slice []Type, elems ...Type) []Type The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice. It is therefore necessary to store the result of append, often in the variable holding the slice itself:

slice = append(slice, elem1, elem2)
slice = append(slice, anotherSlice...)

As a special case, it is legal to append a string to a byte slice, like this:

slice = append([]byte("hello "), "world"...)

Interface type check with Typescript

Because the type is unknown at run-time, I wrote code as follows to compare the unknown object, not against a type, but against an object of known type:

  1. Create a sample object of the right type
  2. Specify which of its elements are optional
  3. Do a deep compare of your unknown object against this sample object

Here's the (interface-agnostic) code I use for the deep compare:

function assertTypeT<T>(loaded: any, wanted: T, optional?: Set<string>): T {
  // this is called recursively to compare each element
  function assertType(found: any, wanted: any, keyNames?: string): void {
    if (typeof wanted !== typeof found) {
      throw new Error(`assertType expected ${typeof wanted} but found ${typeof found}`);
    }
    switch (typeof wanted) {
      case "boolean":
      case "number":
      case "string":
        return; // primitive value type -- done checking
      case "object":
        break; // more to check
      case "undefined":
      case "symbol":
      case "function":
      default:
        throw new Error(`assertType does not support ${typeof wanted}`);
    }
    if (Array.isArray(wanted)) {
      if (!Array.isArray(found)) {
        throw new Error(`assertType expected an array but found ${found}`);
      }
      if (wanted.length === 1) {
        // assume we want a homogenous array with all elements the same type
        for (const element of found) {
          assertType(element, wanted[0]);
        }
      } else {
        // assume we want a tuple
        if (found.length !== wanted.length) {
          throw new Error(
            `assertType expected tuple length ${wanted.length} found ${found.length}`);
        }
        for (let i = 0; i < wanted.length; ++i) {
          assertType(found[i], wanted[i]);
        }
      }
      return;
    }
    for (const key in wanted) {
      const expectedKey = keyNames ? keyNames + "." + key : key;
      if (typeof found[key] === 'undefined') {
        if (!optional || !optional.has(expectedKey)) {
          throw new Error(`assertType expected key ${expectedKey}`);
        }
      } else {
        assertType(found[key], wanted[key], expectedKey);
      }
    }
  }

  assertType(loaded, wanted);
  return loaded as T;
}

Below is an example of how I use it.

In this example I expect the JSON contains an array of tuples, of which the second element is an instance of an interface called User (which has two optional elements).

TypeScript's type-checking will ensure that my sample object is correct, then the assertTypeT function checks that the unknown (loaded from JSON) object matches the sample object.

export function loadUsers(): Map<number, User> {
  const found = require("./users.json");
  const sample: [number, User] = [
    49942,
    {
      "name": "ChrisW",
      "email": "[email protected]",
      "gravatarHash": "75bfdecf63c3495489123fe9c0b833e1",
      "profile": {
        "location": "Normandy",
        "aboutMe": "I wrote this!\n\nFurther details are to be supplied ..."
      },
      "favourites": []
    }
  ];
  const optional: Set<string> = new Set<string>(["profile.aboutMe", "profile.location"]);
  const loaded: [number, User][] = assertTypeT(found, [sample], optional);
  return new Map<number, User>(loaded);
}

You could invoke a check like this in the implementation of a user-defined type guard.

import module from string variable

I developed these 3 useful functions:

def loadModule(moduleName):
    module = None
    try:
        import sys
        del sys.modules[moduleName]
    except BaseException as err:
        pass
    try:
        import importlib
        module = importlib.import_module(moduleName)
    except BaseException as err:
        serr = str(err)
        print("Error to load the module '" + moduleName + "': " + serr)
    return module

def reloadModule(moduleName):
    module = loadModule(moduleName)
    moduleName, modulePath = str(module).replace("' from '", "||").replace("<module '", '').replace("'>", '').split("||")
    if (modulePath.endswith(".pyc")):
        import os
        os.remove(modulePath)
        module = loadModule(moduleName)
    return module

def getInstance(moduleName, param1, param2, param3):
    module = reloadModule(moduleName)
    instance = eval("module." + moduleName + "(param1, param2, param3)")
    return instance

And everytime I want to reload a new instance I just have to call getInstance() like this:

myInstance = getInstance("MyModule", myParam1, myParam2, myParam3)

Finally I can call all the functions inside the new Instance:

myInstance.aFunction()

The only specificity here is to customize the params list (param1, param2, param3) of your instance.

How to make a programme continue to run after log out from ssh?

Start in the background:

./long_running_process options &

And disown the job before you log out:

disown

Is there an equivalent of 'which' on the Windows command line?

If you can find a free Pascal compiler, you can compile this. At least it works and shows the algorithm necessary.

program Whence (input, output);
  Uses Dos, my_funk;
  Const program_version = '1.00';
        program_date    = '17 March 1994';
  VAR   path_str          : string;
        command_name      : NameStr;
        command_extension : ExtStr;
        command_directory : DirStr;
        search_dir        : DirStr;
        result            : DirStr;


  procedure Check_for (file_name : string);
    { Check existence of the passed parameter. If exists, then state so   }
    { and exit.                                                           }
  begin
    if Fsearch(file_name, '') <> '' then
    begin
      WriteLn('DOS command = ', Fexpand(file_name));
      Halt(0);    { structured ? whaddayamean structured ? }
    end;
  end;

  function Get_next_dir : DirStr;
    { Returns the next directory from the path variable, truncating the   }
    { variable every time. Implicit input (but not passed as parameter)   }
    { is, therefore, path_str                                             }
    var  semic_pos : Byte;

  begin
      semic_pos := Pos(';', path_str);
      if (semic_pos = 0) then
      begin
        Get_next_dir := '';
        Exit;
      end;

      result := Copy(Path_str, 1, (semic_pos - 1));  { return result   }
      { Hmm! although *I* never reference a Root drive (my directory tree) }
      { is 1/2 way structured), some network logon software which I run    }
      { does (it adds Z:\ to the path). This means that I have to allow    }
      { path entries with & without a terminating backslash. I'll delete   }
      { anysuch here since I always add one in the main program below.     }
      if (Copy(result, (Length(result)), 1) = '\') then
         Delete(result, Length(result), 1);

      path_str := Copy(path_str,(semic_pos + 1),
                       (length(path_str) - semic_pos));
      Get_next_dir := result;
  end;  { Of function get_next_dir }

begin
  { The following is a kludge which makes the function Get_next_dir easier  }
  { to implement. By appending a semi-colon to the end of the path         }
  { Get_next_dir doesn't need to handle the special case of the last entry }
  { which normally doesn't have a semic afterwards. It may be a kludge,    }
  { but it's a documented kludge (you might even call it a refinement).    }
  path_str := GetEnv('Path') + ';';

  if (paramCount = 0) then
  begin
    WriteLn('Whence: V', program_version, ' from ', program_date);
    Writeln;
    WriteLn('Usage: WHENCE command[.extension]');
    WriteLn;
    WriteLn('Whence is a ''find file''type utility witha difference');
    Writeln('There are are already more than enough of those :-)');
    Write  ('Use Whence when you''re not sure where a command which you ');
    WriteLn('want to invoke');
    WriteLn('actually resides.');
    Write  ('If you intend to invoke the command with an extension e.g ');
    Writeln('"my_cmd.exe param"');
    Write  ('then invoke Whence with the same extension e.g ');
    WriteLn('"Whence my_cmd.exe"');
    Write  ('otherwise a simple "Whence my_cmd" will suffice; Whence will ');
    Write  ('then search the current directory and each directory in the ');
    Write  ('for My_cmd.com, then My_cmd.exe and lastly for my_cmd.bat, ');
    Write  ('just as DOS does');
    Halt(0);
  end;

  Fsplit(paramStr(1), command_directory, command_name, command_extension);
  if (command_directory <> '') then
  begin
WriteLn('directory detected *', command_directory, '*');
    Halt(0);
  end;

  if (command_extension <> '') then
  begin
    path_str := Fsearch(paramstr(1), '');    { Current directory }
    if   (path_str <> '') then WriteLn('Dos command = "', Fexpand(path_str), '"')
    else
    begin
      path_str := Fsearch(paramstr(1), GetEnv('path'));
      if (path_str <> '') then WriteLn('Dos command = "', Fexpand(path_str), '"')
                          else Writeln('command not found in path.');
    end;
  end
  else
  begin
    { O.K, the way it works, DOS looks for a command firstly in the current  }
    { directory, then in each directory in the Path. If no extension is      }
    { given and several commands of the same name exist, then .COM has       }
    { priority over .EXE, has priority over .BAT                             }

    Check_for(paramstr(1) + '.com');     { won't return if file is found }
    Check_for(paramstr(1) + '.exe');
    Check_for(paramstr(1) + '.bat');

    { Not in current directory, search through path ... }

    search_dir := Get_next_dir;

    while (search_dir <> '') do
    begin
       Check_for(search_dir + '\' + paramstr(1) + '.com');
       Check_for(search_dir + '\' + paramstr(1) + '.exe');
       Check_for(search_dir + '\' + paramstr(1) + '.bat');
       search_dir := Get_next_dir;
    end;

    WriteLn('DOS command not found: ', paramstr(1));
  end;
end.

Java method to swap primitives

AFAIS, no one mentions of atomic reference.

Integer

public void swap(AtomicInteger a, AtomicInteger b){
    a.set(b.getAndSet(a.get()));
}

String

public void swap(AtomicReference<String> a, AtomicReference<String> b){
    a.set(b.getAndSet(a.get()));
}

How to set standard encoding in Visual Studio

I work with Windows7.

Control Panel - Region and Language - Administrative - Language for non-Unicode programs.

After I set "Change system locale" to English(United States). My default encoding of vs2010 change to Windows-1252. It was gb2312 before.

I created a new .cpp file for a C++ project, after checking in the new file to TFS the encoding show Windows-1252 from the properties page of the file.

Java JTable getting the data of the selected row

if you want to get the data in the entire row, you can use this combination below

tableModel.getDataVector().elementAt(jTable.getSelectedRow());

Where "tableModel" is the model for the table that can be accessed like so

(DefaultTableModel) jTable.getModel();

this will return the entire row data.

I hope this helps somebody

How can I insert vertical blank space into an html document?

While the above answers are probably best for this situation, if you just want to do a one-off and don't want to bother with modifying other files, you can in-line the CSS.

<p style="margin-bottom:3cm;">This is the first question?</p>

Function passed as template argument

Yes, it is valid.

As for making it work with functors as well, the usual solution is something like this instead:

template <typename F>
void doOperation(F f)
{
  int temp=0;
  f(temp);
  std::cout << "Result is " << temp << std::endl;
}

which can now be called as either:

doOperation(add2);
doOperation(add3());

See it live

The problem with this is that if it makes it tricky for the compiler to inline the call to add2, since all the compiler knows is that a function pointer type void (*)(int &) is being passed to doOperation. (But add3, being a functor, can be inlined easily. Here, the compiler knows that an object of type add3 is passed to the function, which means that the function to call is add3::operator(), and not just some unknown function pointer.)

HTML <input type='file'> File Selection Event

Though it is an old question, it is still a valid one.

Expected behavior:

  • Show selected file name after upload.
  • Do not do anything if the user clicks Cancel.
  • Show the file name even when the user selects the same file.

Code with a demonstration:

_x000D_
_x000D_
<!DOCTYPE html>
<html>

<head>
  <title>File upload event</title>
</head>

<body>
  <form action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="userFile" id="userFile"><br>
    <input type="submit" name="upload_btn" value="upload">
  </form>
  <script type="text/javascript">
    document.getElementById("userFile").onchange = function(e) {
      alert(this.value);
      this.value = null;
    }
  </script>
</body>

</html>
_x000D_
_x000D_
_x000D_

Explanation:

  • The onchange event handler is used to handle any change in file selection event.
  • The onchange event is triggered only when the value of an element is changed. So, when we select the same file using the input field the event will not be triggered. To overcome this, I set this.value = null; at the end of the onchange event function. It sets the file path of the selected file to null. Thus, the onchange event is triggered even at the time of the same file selection.

Embed Youtube video inside an Android app

It works like this:

String item = "http://www.youtube.com/embed/";

String ss = "your url";
ss = ss.substring(ss.indexOf("v=") + 2);
item += ss;
DisplayMetrics metrics = getResources().getDisplayMetrics();
int w1 = (int) (metrics.widthPixels / metrics.density), h1 = w1 * 3 / 5;
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebChromeClient(chromeClient);
wv.getSettings().setPluginsEnabled(true);

try {
    wv.loadData(
    "<html><body><iframe class=\"youtube-player\" type=\"text/html5\" width=\""
    + (w1 - 20)
    + "\" height=\""
    + h1
    + "\" src=\""
    + item
    + "\" frameborder=\"0\"\"allowfullscreen\"></iframe></body></html>",
                            "text/html5", "utf-8");
} catch (Exception e) {
    e.printStackTrace();
}

private WebChromeClient chromeClient = new WebChromeClient() {

    @Override
    public void onShowCustomView(View view, CustomViewCallback callback) {
        super.onShowCustomView(view, callback);
        if (view instanceof FrameLayout) {
            FrameLayout frame = (FrameLayout) view;
            if (frame.getFocusedChild() instanceof VideoView) {
                VideoView video = (VideoView) frame.getFocusedChild();
                frame.removeView(video);
                video.start();
            }
        }

    }
};

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

Intent emailIntent = new Intent(Intent.ACTION_SENDTO, 
    Uri.fromParts("mailto", "[email protected]", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, text);
startActivity(Intent.createChooser(emailIntent, "Send email..."));

How do I combine two data-frames based on two columns?

You can also use the join command (dplyr).

For example:

new_dataset <- dataset1 %>% right_join(dataset2, by=c("column1","column2"))

How to Make A Chevron Arrow Using CSS?

Left Right Arrow with hover effect using Roko C. Buljan box-shadow trick

_x000D_
_x000D_
.arr {_x000D_
  display: inline-block;_x000D_
  padding: 1.2em;_x000D_
  box-shadow: 8px 8px 0 2px #777 inset;_x000D_
}_x000D_
.arr.left {_x000D_
  transform: rotate(-45deg);_x000D_
}_x000D_
.arr.right {_x000D_
  transform: rotate(135deg);_x000D_
}_x000D_
.arr:hover {_x000D_
  box-shadow: 8px 8px 0 2px #000 inset_x000D_
}
_x000D_
<div class="arr left"></div>_x000D_
<div class="arr right"></div>
_x000D_
_x000D_
_x000D_

Left Join without duplicate rows from left table

You can do this using generic SQL with group by:

SELECT C.Content_ID, C.Content_Title, MAX(M.Media_Id)
FROM tbl_Contents C LEFT JOIN
     tbl_Media M
     ON M.Content_Id = C.Content_Id 
GROUP BY C.Content_ID, C.Content_Title
ORDER BY MAX(C.Content_DatePublished) ASC;

Or with a correlated subquery:

SELECT C.Content_ID, C.Contt_Title,
       (SELECT M.Media_Id
        FROM tbl_Media M
        WHERE M.Content_Id = C.Content_Id
        ORDER BY M.MEDIA_ID DESC
        LIMIT 1
       ) as Media_Id
FROM tbl_Contents C 
ORDER BY C.Content_DatePublished ASC;

Of course, the syntax for limit 1 varies between databases. Could be top. Or rownum = 1. Or fetch first 1 rows. Or something like that.

expected assignment or function call: no-unused-expressions ReactJS

In my case I have got this error, because used a call inside of the condition without a semicolon:

  private async _setActive(active: boolean) {
    if (this.isActive === active) {
      return;
    }
    this.isActive = active;

    this.isActive ? this._start() : this._stop();
  }

I changed it, and the error has gone:

  private async _setActive(active: boolean) {
    if (this.isActive === active) {
      return;
    }
    this.isActive = active;

    if (this.isActive) {
      await this._start();
    } else {
      this._stop();
    }
  }

Disabling and enabling a html input button

Stick to php...

Why not only allow the button to appear once an above criteria is met.

<?
if (whatever == something) {
    $display = '<input id="Button" type="button" value="+" style="background-color:grey" onclick="Me();"/>';
    return $display;
}
?>

How to make an "alias" for a long path?

Another option would be to use a symbolic link. ie:

ln -s ~/Files/Scripts/Main ~/myFold

After that you can perform operations to ~/myFold, such as:

cp some_file.txt ~/myFold

which will put the file in ~/Files/Scripts/Main. You can remove the symbolic link at any time with rm ~/myFold, which will keep the original directory.

npm install won't install devDependencies

Check if npm config production value is set to true. If this value is true, it will skip over the dev dependencies.

Run npm config get production

To set it: npm config set -g production false

The system cannot find the file specified. in Visual Studio

This is because you have not compiled it. Click 'Project > compile'. Then, either click 'start debugging', or 'start without debugging'.

How do I make a request using HTTP basic authentication with PHP curl?

You want this:

curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  

Zend has a REST client and zend_http_client and I'm sure PEAR has some sort of wrapper. But its easy enough to do on your own.

So the entire request might look something like this:

$ch = curl_init($host);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', $additionalHeaders));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payloadName);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($ch);
curl_close($ch);

How to round down to nearest integer in MySQL?

Use FLOOR(), if you want to round your decimal to the lower integer. Examples:

FLOOR(1.9) => 1
FLOOR(1.1) => 1

Use ROUND(), if you want to round your decimal to the nearest integer. Examples:

ROUND(1.9) => 2
ROUND(1.1) => 1

Use CEIL(), if you want to round your decimal to the upper integer. Examples:

CEIL(1.9) => 2
CEIL(1.1) => 2

Validate form field only on submit or user input

If you want to show error messages on form submission, you can use condition form.$submitted to check if an attempt was made to submit the form. Check following example.

<form name="myForm" novalidate ng-submit="myForm.$valid && createUser()">
  <input type="text" name="name" ng-model="user.name" placeholder="Enter name of user" required>
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user name.</div>
  </div>

  <input type="text" name="address" ng-model="user.address" placeholder="Enter Address" required ng-maxlength="30">
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user address.</div>
    <div ng-message="maxlength">Should be less than 30 chars</div>
  </div>

  <button type="submit">
    Create user
  </button>
</form>

.htaccess not working on localhost with XAMPP

Without seeing your system it's hard to tell what's wrong but try the following (comment answer if these didn't work WITH log error messages)

[STOP your Apache server instance. Ensure it's not running!]

1) move apache server/install to a folder that has no long file names and spaces

2) check httpd.conf in install\conf folder and look for AccessFileName. If it's .htaccess change it to a file name windows accepts (e.g. conf.htaccess)

3) double-check that your htaccess file gets read: add some uninterpretable garbage to it and start server: you should get an Error 500. If you don't, file is not getting read, re-visit httpd.conf file (if that looks OK, check if this is the only file which defines htaccess and it's location and it does at one place -within the file- only; also check if both httpd.conf and htaccess files are accessible: not encrypted, file access rights are not limited, drive/path available -and no long folder path and file names-)
STOP Apache again, then go on:
4) If you have IIS too on your system, stop it (uninstall it too if you can) from services.msc

5) Add the following to the top of your valid htaccess file:
RewriteEngine On
RewriteLog "/path/logs/rewrite.log" #make sure path is there!
RewriteLogLevel 9

6) Empty your [apache]\logs folder (if you use another folder, then that one :)

7) Check the following entries are set and correct:
Action application/x-httpd-php "c:/your-php5-path/php-cgi.exe"
LoadModule php5_module "c:/your-php5-path/php5apache2.dll"
LoadModule rewrite_module modules/mod_rewrite.so
Avoid long path names and spaces in folder names for phpX install too!

8) START apache server

You can do all the steps above or go one-by-one, your call. But at the end of the day make sure you tried everything above!
If system still blows up and you can't fix it, copy&paste error message(s) from log folder for further assistance

Loading DLLs at runtime in C#

It's not so difficult.

You can inspect the available functions of the loaded object, and if you find the one you're looking for by name, then snoop its expected parms, if any. If it's the call you're trying to find, then call it using the MethodInfo object's Invoke method.

Another option is to simply build your external objects to an interface, and cast the loaded object to that interface. If successful, call the function natively.

This is pretty simple stuff.

How do you decrease navbar height in Bootstrap 3?

 .navbar-nav > li > a {padding-top:7px !important; padding-bottom:7px !important;}
.navbar {min-height:32px !important;} 
.navbar-brand{padding-top:7px !important; max-height: 24px;  }
.navbar .navbar-toggle {  margin-top: 0px; margin-bottom: 0px; padding: 8px 9px; }

ImportError: No module named model_selection

do you have sklearn? if not, do the following:

sudo pip install sklearn

After installing sklearn

from sklearn.model_selection import train_test_split

works fine

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available

For future Oracle Linux users trying to solve this, below is what worked for me. First install missing libs:

yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel 
readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel

Then cd to your Python3.X library and run:

make
make install 

How to store a dataframe using Pandas

Another quite fresh test with to_pickle().

I have 25 .csv files in total to process and the final dataframe consists of roughly 2M items.

(Note: Besides loading the .csv files, I also manipulate some data and extend the data frame by new columns.)

Going through all 25 .csv files and create the dataframe takes around 14 sec.

Loading the whole dataframe from a pkl file takes less than 1 sec

How to pass table value parameters to stored procedure from .net code

The cleanest way to work with it. Assuming your table is a list of integers called "dbo.tvp_Int" (Customize for your own table type)

Create this extension method...

public static void AddWithValue_Tvp_Int(this SqlParameterCollection paramCollection, string parameterName, List<int> data)
{
   if(paramCollection != null)
   {
       var p = paramCollection.Add(parameterName, SqlDbType.Structured);
       p.TypeName = "dbo.tvp_Int";
       DataTable _dt = new DataTable() {Columns = {"Value"}};
       data.ForEach(value => _dt.Rows.Add(value));
       p.Value = _dt;
   }
}

Now you can add a table valued parameter in one line anywhere simply by doing this:

cmd.Parameters.AddWithValueFor_Tvp_Int("@IDValues", listOfIds);

fatal: could not create work tree dir 'kivy'

You should do the command in a directory where you have write permission. So:

cd ~/
mkdir code
cd code
git clone https://github.com/kivy/kivy

For example.

Reset local repository branch to be just like remote repository HEAD

I did:

git branch -D master
git checkout master

to totally reset branch


note, you should checkout to another branch to be able to delete required branch

Dynamic instantiation from string name of a class in dynamically imported module?

If you want this sentence from foo.bar import foo2 to be loaded dynamically, you should do this

foo = __import__("foo")
bar = getattr(foo,"bar")
foo2 = getattr(bar,"foo2")

instance = foo2()

What is the difference between sed and awk?

Both tools are meant to work with text and there are tasks both tools can be used for.

For me the rule to separate them is: Use sed to automate tasks you would do otherwise in a text editor manually. That's why it is called stream editor. (You can use the same commands to edit text in vim). Use awk if you want to analyze text, meaning counting fields, calculate totals, extract and reorganize structures etc.

Also you should not forget about grep. Use grep if you only want to search/extract something in a text (file)

How to convert a Django QuerySet to a list

Why not just call list() on the Queryset?

answers_list = list(answers)

This will also evaluate the QuerySet/run the query. You can then remove/add from that list.

How to convert int to NSString?

If this string is for presentation to the end user, you should use NSNumberFormatter. This will add thousands separators, and will honor the localization settings for the user:

NSInteger n = 10000;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:@(n)];

In the US, for example, that would create a string 10,000, but in Germany, that would be 10.000.

SQL Server ON DELETE Trigger

Better to use:

DELETE tbl FROM tbl INNER JOIN deleted ON tbl.key=deleted.key

Resize an Array while keeping current elements in Java?

Standard class java.util.ArrayList is resizable array, growing when new elements added.

Put Excel-VBA code in module or sheet?

I would suggest separating your code based on the functionality and purpose specific to each sheet or module. In this manner, you would only put code relative to a sheet's UI inside the sheet's module and only put code related to modules in respective modules. Also, use separate modules to encapsulate code that is shared or reused among several different sheets.

For example, let's say you multiple sheets that are responsible for displaying data from a database in a special way. What kinds of functionality do we have in this situation? We have functionality related to each specific sheet, tasks related to getting data from the database, and tasks related to populating a sheet with data. In this case, I might start with a module for the data access, a module for populating a sheet with data, and within each sheet I'd have code for accessing code in those modules.

It might be laid out like this.

Module: DataAccess:

Function GetData(strTableName As String, strCondition1 As String) As Recordset
    'Code Related to getting data from the database'
End Function

Module: PopulateSheet:

Sub PopulateASheet(wsSheet As Worksheet, rs As Recordset)
    'Code to populate a worksheet '
End Function

Sheet: Sheet1 Code:

Sub GetDataAndPopulate()
    'Sample Code'
     Dim rs As New Recordset
     Dim ws As Worksheet
     Dim strParam As String
     Set ws = ActiveSheet
     strParam = ws.Range("A1").Value

     Set rs = GetData("Orders",strParam)

     PopulateASheet ws, rs
End Sub

Sub Button1_Click()
    Call GetDataAndPopulate
End Sub

How can I change the value of the elements in a vector?

Just use:

for (int i = 0; i < v.size(); i++)
{
    v[i] -= valueToSubstract;
}

Or its equivalent (and more readable?):

for (int i = 0; i < v.size(); i++)
    v[i] = v[i] - valueToSubstract;

How to pass credentials to the Send-MailMessage command for sending emails

in addition to UseSsl, you have to include smtp port 587 to make it work.

Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -Credential $credential -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'

Is there any way to delete local commits in Mercurial?

As everyone else is pointing out you should probably just pull and then merge the heads, but if you really want to get rid of your commits without any of the EditingHistory tools then you can just hg clone -r your repo to get all but those changes.

This doesn't delete them from the original repository, but it creates a new clone that doesn't have them. Then you can delete the repo you modified (if you'd like).

How to Migrate to WKWebView?

Step : 1 Import webkit in ViewController.swift

import WebKit

Step : 2 Declare variable of webView.

var webView : WKWebView!

Step : 3 Adding Delegate of WKNavigationDelegate

class ViewController: UIViewController , WKNavigationDelegate{

Step : 4 Adding code in ViewDidLoad.

let myBlog = "https://iosdevcenters.blogspot.com/"
let url = NSURL(string: myBlog)
let request = NSURLRequest(URL: url!)

// init and load request in webview.
webView = WKWebView(frame: self.view.frame)
webView.navigationDelegate = self
webView.loadRequest(request)
self.view.addSubview(webView)
self.view.sendSubviewToBack(webView)

Step : 5 Edit the info.plist adding

<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>google.com</key>
<dict>
    <key>NSExceptionAllowsInsecureHTTPLoads</key>
    <true/>
    <key>NSIncludesSubdomains</key>
    <true/>
</dict>
</dict>

How to enable zoom controls and pinch zoom in a WebView?

Use these:

webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setDisplayZoomControls(false);

Where does Internet Explorer store saved passwords?

No guarantee, but I suspect IE uses the older Protected Storage API.

How to call a JavaScript function from PHP?

try like this

<?php
 if(your condition){
     echo "<script> window.onload = function() {
     yourJavascriptFunction(param1, param2);
 }; </script>";
?>

Add directives from directive in AngularJS

Here's a solution that moves the directives that need to be added dynamically, into the view and also adds some optional (basic) conditional-logic. This keeps the directive clean with no hard-coded logic.

The directive takes an array of objects, each object contains the name of the directive to be added and the value to pass to it (if any).

I was struggling to think of a use-case for a directive like this until I thought that it might be useful to add some conditional logic that only adds a directive based on some condition (though the answer below is still contrived). I added an optional if property that should contain a bool value, expression or function (e.g. defined in your controller) that determines if the directive should be added or not.

I'm also using attrs.$attr.dynamicDirectives to get the exact attribute declaration used to add the directive (e.g. data-dynamic-directive, dynamic-directive) without hard-coding string values to check for.

Plunker Demo

_x000D_
_x000D_
angular.module('plunker', ['ui.bootstrap'])_x000D_
    .controller('DatepickerDemoCtrl', ['$scope',_x000D_
        function($scope) {_x000D_
            $scope.dt = function() {_x000D_
                return new Date();_x000D_
            };_x000D_
            $scope.selects = [1, 2, 3, 4];_x000D_
            $scope.el = 2;_x000D_
_x000D_
            // For use with our dynamic-directive_x000D_
            $scope.selectIsRequired = true;_x000D_
            $scope.addTooltip = function() {_x000D_
                return true;_x000D_
            };_x000D_
        }_x000D_
    ])_x000D_
    .directive('dynamicDirectives', ['$compile',_x000D_
        function($compile) {_x000D_
            _x000D_
             var addDirectiveToElement = function(scope, element, dir) {_x000D_
                var propName;_x000D_
                if (dir.if) {_x000D_
                    propName = Object.keys(dir)[1];_x000D_
                    var addDirective = scope.$eval(dir.if);_x000D_
                    if (addDirective) {_x000D_
                        element.attr(propName, dir[propName]);_x000D_
                    }_x000D_
                } else { // No condition, just add directive_x000D_
                    propName = Object.keys(dir)[0];_x000D_
                    element.attr(propName, dir[propName]);_x000D_
                }_x000D_
            };_x000D_
            _x000D_
            var linker = function(scope, element, attrs) {_x000D_
                var directives = scope.$eval(attrs.dynamicDirectives);_x000D_
        _x000D_
                if (!directives || !angular.isArray(directives)) {_x000D_
                    return $compile(element)(scope);_x000D_
                }_x000D_
               _x000D_
                // Add all directives in the array_x000D_
                angular.forEach(directives, function(dir){_x000D_
                    addDirectiveToElement(scope, element, dir);_x000D_
                });_x000D_
                _x000D_
                // Remove attribute used to add this directive_x000D_
                element.removeAttr(attrs.$attr.dynamicDirectives);_x000D_
                // Compile element to run other directives_x000D_
                $compile(element)(scope);_x000D_
            };_x000D_
        _x000D_
            return {_x000D_
                priority: 1001, // Run before other directives e.g.  ng-repeat_x000D_
                terminal: true, // Stop other directives running_x000D_
                link: linker_x000D_
            };_x000D_
        }_x000D_
    ]);
_x000D_
<!doctype html>_x000D_
<html ng-app="plunker">_x000D_
_x000D_
<head>_x000D_
    <script src="//code.angularjs.org/1.2.20/angular.js"></script>_x000D_
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js"></script>_x000D_
    <script src="example.js"></script>_x000D_
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
    <div data-ng-controller="DatepickerDemoCtrl">_x000D_
_x000D_
        <select data-ng-options="s for s in selects" data-ng-model="el" _x000D_
            data-dynamic-directives="[_x000D_
                { 'if' : 'selectIsRequired', 'ng-required' : '{{selectIsRequired}}' },_x000D_
                { 'tooltip-placement' : 'bottom' },_x000D_
                { 'if' : 'addTooltip()', 'tooltip' : '{{ dt() }}' }_x000D_
            ]">_x000D_
            <option value=""></option>_x000D_
        </select>_x000D_
_x000D_
    </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

What is the difference between C and embedded C?

c cant access physical address, embedded c can access physical address embedded c variable address is stored in stack, in embedded c variable should be declaired at the begining of the block embedded c input output port are used but in c printf and scanf used

Can I access constants in settings.py from templates in Django?

If it's a value you'd like to have for every request & template, using a context processor is more appropriate.

Here's how:

  1. Make a context_processors.py file in your app directory. Let's say I want to have the ADMIN_PREFIX_VALUE value in every context:

    from django.conf import settings # import the settings file
    
    def admin_media(request):
        # return the value you want as a dictionnary. you may add multiple values in there.
        return {'ADMIN_MEDIA_URL': settings.ADMIN_MEDIA_PREFIX}
    
  2. add your context processor to your settings.py file:

    TEMPLATES = [{
        # whatever comes before
        'OPTIONS': {
            'context_processors': [
                # whatever comes before
                "your_app.context_processors.admin_media",
            ],
        }
    }]
    
  3. Use RequestContext in your view to add your context processors in your template. The render shortcut does this automatically:

    from django.shortcuts import render
    
    def my_view(request):
        return render(request, "index.html")
    
  4. and finally, in your template:

    ...
    <a href="{{ ADMIN_MEDIA_URL }}">path to admin media</a>
    ...
    

Set transparent background of an imageview on Android

In xml

@android:color/transparent

In code

mComponentName.setBackgroundResource(android.R.color.transparent);

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

In case you are using Eclipse you might try http4e

How to use external ".js" files

Code like this

 <html>
    <head>
          <script type="text/javascript" src="path/to/script.js"></script>
          <!--other script and also external css included over here-->
    </head>
    <body>
        <form>
            <select name="users" onChange="showUser(this.value)">
               <option value="1">Tom</option>
               <option value="2">Bob</option>
               <option value="3">Joe</option>
            </select>
        </form>
    </body>
    </html>

I hope it will help you.... thanks

Page unload event in asp.net

Refer to the ASP.NET page lifecycle to help find the right event to override. It really depends what you want to do. But yes, there is an unload event.

    protected override void OnUnload(EventArgs e)
    {
        base.OnUnload(e);

        // your code
    }

But just remember (from the above link): During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

Detecting a redirect in ajax request?

You can now use fetch API/ It returns redirected: *boolean*

How to set up datasource with Spring for HikariCP?

my test java config (for MySql)

@Bean(destroyMethod = "close")
public DataSource dataSource(){
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setDriverClassName("com.mysql.jdbc.Driver");
    hikariConfig.setJdbcUrl("jdbc:mysql://localhost:3306/spring-test"); 
    hikariConfig.setUsername("root");
    hikariConfig.setPassword("admin");

    hikariConfig.setMaximumPoolSize(5);
    hikariConfig.setConnectionTestQuery("SELECT 1");
    hikariConfig.setPoolName("springHikariCP");

    hikariConfig.addDataSourceProperty("dataSource.cachePrepStmts", "true");
    hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSize", "250");
    hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSqlLimit", "2048");
    hikariConfig.addDataSourceProperty("dataSource.useServerPrepStmts", "true");

    HikariDataSource dataSource = new HikariDataSource(hikariConfig);

    return dataSource;
}

What is causing ERROR: there is no unique constraint matching given keys for referenced table?

You should have name column as a unique constraint. here is a 3 lines of code to change your issues

  1. First find out the primary key constraints by typing this code

    \d table_name
    

    you are shown like this at bottom "some_constraint" PRIMARY KEY, btree (column)

  2. Drop the constraint:

    ALTER TABLE table_name DROP CONSTRAINT some_constraint
    
  3. Add a new primary key column with existing one:

    ALTER TABLE table_name ADD CONSTRAINT some_constraint PRIMARY KEY(COLUMN_NAME1,COLUMN_NAME2);
    

That's All.

How to change option menu icon in the action bar?

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
            android:id="@+id/logout"
            android:icon="@drawable/logout"
            android:title="Log Out"
            app:showAsAction="always"
        />
</menu>

This did the trick for me!

R Markdown - changing font size and font type in html output

To change the font size, you don't need to know a lot of html for this. Open the html output with notepad ++. Control F search for "font-size". You should see a section with font sizes for the headers (h1, h2, h3,...).

Add the following somewhere in this section.

body {
  font-size: 16px;
}

The font size above is 16 pt font. You can change the number to whatever you want.

Compiling with g++ using multiple cores

I'm not sure about g++, but if you're using GNU Make then "make -j N" (where N is the number of threads make can create) will allow make to run multple g++ jobs at the same time (so long as the files do not depend on each other).

Why should I use a pointer rather than the object itself?

In C++, objects allocated on the stack (using Object object; statement within a block) will only live within the scope they are declared in. When the block of code finishes execution, the object declared are destroyed. Whereas if you allocate memory on heap, using Object* obj = new Object(), they continue to live in heap until you call delete obj.

I would create an object on heap when I like to use the object not only in the block of code which declared/allocated it.

How to bind multiple values to a single WPF TextBlock?

You can use a MultiBinding combined with the StringFormat property. Usage would resemble the following:

<TextBlock>
    <TextBlock.Text>    
        <MultiBinding StringFormat="{}{0} + {1}">
            <Binding Path="Name" />
            <Binding Path="ID" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Giving Name a value of Foo and ID a value of 1, your output in the TextBlock would then be Foo + 1.

Note: that this is only supported in .NET 3.5 SP1 and 3.0 SP2 or later.

Byte array to image conversion

First Install This Package:

Install-Package SixLabors.ImageSharp -Version 1.0.0-beta0007

[SixLabors.ImageSharp][1] [1]: https://www.nuget.org/packages/SixLabors.ImageSharp

Then use Below Code For Cast Byte Array To Image :

Image<Rgba32> image = Image.Load(byteArray); 

For Get ImageFormat Use Below Code:

IImageFormat format = Image.DetectFormat(byteArray);

For Mutate Image Use Below Code:

image.Mutate(x => x.Resize(new Size(1280, 960)));

Finding the position of the max element

In the STL, std::max_element provides the iterator (which can be used to get index with std::distance, if you really want it).

int main(int argc, char** argv) {
  int A[4] = {0, 2, 3, 1};
  const int N = sizeof(A) / sizeof(int);

  cout << "Index of max element: "
       << distance(A, max_element(A, A + N))
       << endl;

  return 0;
}

Failed to serialize the response in Web API with Json

public class UserController : ApiController
{

   Database db = new Database();

   // construction
   public UserController()
   {
      // Add the following code
      // problem will be solved
      db.Configuration.ProxyCreationEnabled = false;
   }

   public IEnumerable<User> GetAll()
    {
            return db.Users.ToList();
    }
}

How do I define a method which takes a lambda as a parameter in Java 8?

Here's roughly how C# handles this problem (but expressed as Java code). Something like this could handle almost all your needs:

import static org.util.function.Functions.*;

public class Test {

    public static void main(String[] args)
    {
        Test.invoke((a, b) -> a + b);       
    }

    public static void invoke(Func2<Integer, Integer, Integer> func)
    {
        System.out.println(func.apply(5, 6));
    }
}

package org.util.function;

public interface Functions {

    //Actions:
    public interface Action {
        public void apply();
    }

    public interface Action1<T1> {
        public void apply(T1 arg1);
    }

    public interface Action2<T1, T2> {
        public void apply(T1 arg1, T2 arg2);
    }

    public interface Action3<T1, T2, T3> {
        public void apply(T1 arg1, T2 arg2, T3 arg3);
    }

    public interface Action4<T1, T2, T3, T4> {
        public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
    }

    public interface Action5<T1, T2, T3, T4, T5> {
        public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
    }

    public interface Action6<T1, T2, T3, T4, T5, T6> {
        public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
    }

    public interface Action7<T1, T2, T3, T4, T5, T6, T7> {
        public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
    }

    public interface Action8<T1, T2, T3, T4, T5, T6, T7, T8> {
        public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
    }

    //Functions:
    public interface Func<TResult> {
        public TResult apply();
    }

    public interface Func1<T1, TResult> {
        public TResult apply(T1 arg1);
    }

    public interface Func2<T1, T2, TResult> {
        public TResult apply(T1 arg1, T2 arg2);
    }

    public interface Func3<T1, T2, T3, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3);
    }

    public interface Func4<T1, T2, T3, T4, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
    }

    public interface Func5<T1, T2, T3, T4, T5, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
    }

    public interface Func6<T1, T2, T3, T4, T5, T6, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
    }

    public interface Func7<T1, T2, T3, T4, T5, T6, T7, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
    }

    public interface Func8<T1, T2, T3, T4, T5, T6, T7, T8, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
    }
}

How to schedule a periodic task in Java?

If your application is already using Spring framework, you have Scheduling built in

How to use wget in php?

This method is only one class and doesn't require importing other libraries or reusing code.

Personally I use this script that I made a while ago. Located here but for those who don't want to click on that link you can view it below. It lets the developer use the static method HTTP::GET($url, $options) to use the get method in curl while being able to pass through custom curl options. You can also use HTTP::POST($url, $options) but I hardly use that method.

/**
  *  echo HTTP::POST('http://accounts.kbcomp.co',
  *      array(
  *            'user_name'=>'[email protected]',
  *            'user_password'=>'demo1234'
  *      )
  *  );
  *  OR
  *  echo HTTP::GET('http://api.austinkregel.com/colors/E64B3B/1');
  *                  
  */

class HTTP{
   public static function GET($url,Array $options=array()){
    $ch = curl_init();
    if(count($options>0)){
       curl_setopt_array($ch, $options);
       curl_setopt($ch, CURLOPT_URL, $url);
       $json = curl_exec($ch);
       curl_close($ch);
       return $json;
     }
   }
   public static function POST($url, $postfields, $options = null){
       $ch = curl_init();
       $options = array(
          CURLOPT_URL=>$url,
          CURLOPT_RETURNTRANSFER => TRUE,
          CURLOPT_POSTFIELDS => $postfields,
          CURLOPT_HEADER => true
          //CURLOPT_HTTPHEADER, array('Content-Type:application/json')
          ); 
       if(count($options>0)){
           curl_setopt_array($ch, $options);
       }
       $json = curl_exec($ch);
       curl_close($ch);
       return $json;
   }
}

Example: Communication between Activity and Service using Messaging

This is how I implemeted Activity->Service Communication: on my Activity i had

private static class MyResultReciever extends ResultReceiver {
     /**
     * Create a new ResultReceive to receive results.  Your
     * {@link #onReceiveResult} method will be called from the thread running
     * <var>handler</var> if given, or from an arbitrary thread if null.
     *
     * @param handler
     */
     public MyResultReciever(Handler handler) {
         super(handler);
     }

     @Override
     protected void onReceiveResult(int resultCode, Bundle resultData) {
         if (resultCode == 100) {
             //dostuff
         }
     }

And then I used this to start my Service

protected void onCreate(Bundle savedInstanceState) {
MyResultReciever resultReciever = new MyResultReciever(handler);
        service = new Intent(this, MyService.class);
        service.putExtra("receiver", resultReciever);
        startService(service);
}

In my Service i had

public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null)
        resultReceiver = intent.getParcelableExtra("receiver");
    return Service.START_STICKY;
}

Hope this Helps

How to dynamically change the color of the selected menu item of a web page?

I use PHP to find the URL and match the page name (without the extension of .php, also I can add multiple pages that all have the same word in common like contact, contactform, etc. All will have that class added) and add a class with PHP to change the color, etc. For that you would have to save your pages with file extension .php.

Here is a demo. Change your links and pages as required. The CSS class for all the links is .tab and for the active link there is also another class of .currentpage (as is the PHP function) so that is where you will overwrite your CSS rules. You could name them whatever you like.

<?php # Using REQUEST_URI
    $currentpage = $_SERVER['REQUEST_URI'];?>
    <div class="nav">
        <div class="tab
             <?php
                 if(preg_match("/index/i", $currentpage)||($currentpage=="/"))
                     echo " currentpage";
             ?>"><a href="index.php">Home</a>
         </div>
         <div class="tab
             <?php
                 if(preg_match("/services/i", $currentpage))
                     echo " currentpage";
             ?>"><a href="services.php">Services</a>
         </div>
         <div class="tab
             <?php
                 if(preg_match("/about/i", $currentpage))
                     echo " currentpage";
             ?>"><a href="about.php">About</a>
         </div>
         <div class="tab
             <?php
                 if(preg_match("/contact/i", $currentpage))
                     echo " currentpage";
             ?>"><a href="contact.php">Contact</a>
         </div>
     </div> <!--nav-->

How to avoid 'undefined index' errors?

You could try using a nice little function that will return the value if it exists or an empty string if not. This is what I use:

function arrayValueForKey($arrayName, $key) {
   if (isset($GLOBALS[$arrayName]) && isset($GLOBALS[$arrayName][$key])) {
      return $GLOBALS[$variable][$key];
   } else {
      return '';
   }
}

Then you can use it like this:

echo ' Values: ' . arrayValueForKey('output', 'admin_link') 
                 . arrayValueForKey('output', 'update_frequency');

And it won't throw up any errors!

Hope this helps!

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

I was getting the same error on a restored database when I tried to insert a new record using the EntityFramework. It turned out that the Indentity/Seed was screwing things up.

Using a reseed command fixed it.

DBCC CHECKIDENT ('[Prices]', RESEED, 4747030);GO

Is there a JavaScript strcmp()?

var strcmp = new Intl.Collator(undefined, {numeric:true, sensitivity:'base'}).compare;

Usage: strcmp(string1, string2)

Result: 1 means string1 is bigger, 0 means equal, -1 means string2 is bigger.

This has higher performance than String.prototype.localeCompare

Also, numeric:true makes it do logical number comparison

How to measure time taken by a function to execute

With performance

NodeJs: It is required to import the performance class

var time0 = performance.now(); // Store the time at this point into time0

yourFunction();   // The function you're measuring time for 

var time1 = performance.now(); // Store the time at this point into time1

console.log("youFunction took " + (time1 - time0) + " milliseconds to execute");

Using console.time

console.time('someFunction');

someFunction(); // Whatever is timed goes between the two "console.time"

console.timeEnd('someFunction');

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

If it's reasonable to alter the original Map data structure to be serialized to better represent the actual value wanted to be serialized, that's probably a decent approach, which would possibly reduce the amount of Jackson configuration necessary. For example, just remove the null key entries, if possible, before calling Jackson. That said...


To suppress serializing Map entries with null values:

Before Jackson 2.9

you can still make use of WRITE_NULL_MAP_VALUES, but note that it's moved to SerializationFeature:

mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);

Since Jackson 2.9

The WRITE_NULL_MAP_VALUES is deprecated, you can use the below equivalent:

mapper.setDefaultPropertyInclusion(
   JsonInclude.Value.construct(Include.ALWAYS, Include.NON_NULL))

To suppress serializing properties with null values, you can configure the ObjectMapper directly, or make use of the @JsonInclude annotation:

mapper.setSerializationInclusion(Include.NON_NULL);

or:

@JsonInclude(Include.NON_NULL)
class Foo
{
  public String bar;

  Foo(String bar)
  {
    this.bar = bar;
  }
}

To handle null Map keys, some custom serialization is necessary, as best I understand.

A simple approach to serialize null keys as empty strings (including complete examples of the two previously mentioned configurations):

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    Map<String, Foo> foos = new HashMap<String, Foo>();
    foos.put("foo1", new Foo("foo1"));
    foos.put("foo2", new Foo(null));
    foos.put("foo3", null);
    foos.put(null, new Foo("foo4"));

    // System.out.println(new ObjectMapper().writeValueAsString(foos));
    // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?)

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer());
    System.out.println(mapper.writeValueAsString(foos));
    // output: 
    // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}}
  }
}

class MyNullKeySerializer extends JsonSerializer<Object>
{
  @Override
  public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) 
      throws IOException, JsonProcessingException
  {
    jsonGenerator.writeFieldName("");
  }
}

class Foo
{
  public String bar;

  Foo(String bar)
  {
    this.bar = bar;
  }
}

To suppress serializing Map entries with null keys, further custom serialization processing would be necessary.

How to check if a json key exists?

You can check this way where 'HAS' - Returns true if this object has a mapping for name. The mapping may be NULL.

if (json.has("status")) {
   String status = json.getString("status"));
}

if (json.has("club")) {
   String club = json.getString("club"));
}

You can also check using 'isNull' - Returns true if this object has no mapping for name or if it has a mapping whose value is NULL.

if (!json.isNull("club"))
    String club = json.getString("club"));

lambda expression join multiple tables with select and where clause

I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.

    var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
    .Select (m => new 
    {
        UserName = u.UserProfile.UserName,
        RoleName = u.Roles.RoleName
    });

Optimal number of threads per core

I thought I'd add another perspective here. The answer depends on whether the question is assuming weak scaling or strong scaling.

From Wikipedia:

Weak scaling: how the solution time varies with the number of processors for a fixed problem size per processor.

Strong scaling: how the solution time varies with the number of processors for a fixed total problem size.

If the question is assuming weak scaling then @Gonzalo's answer suffices. However if the question is assuming strong scaling, there's something more to add. In strong scaling you're assuming a fixed workload size so if you increase the number of threads, the size of the data that each thread needs to work on decreases. On modern CPUs memory accesses are expensive and would be preferable to maintain locality by keeping the data in caches. Therefore, the likely optimal number of threads can be found when the dataset of each thread fits in each core's cache (I'm not going into the details of discussing whether it's L1/L2/L3 cache(s) of the system).

This holds true even when the number of threads exceeds the number of cores. For example assume there's 8 arbitrary unit (or AU) of work in the program which will be executed on a 4 core machine.

Case 1: run with four threads where each thread needs to complete 2AU. Each thread takes 10s to complete (with a lot of cache misses). With four cores the total amount of time will be 10s (10s * 4 threads / 4 cores).

Case 2: run with eight threads where each thread needs to complete 1AU. Each thread takes only 2s (instead of 5s because of the reduced amount of cache misses). With four cores the total amount of time will be 4s (2s * 8 threads / 4 cores).

I've simplified the problem and ignored overheads mentioned in other answers (e.g., context switches) but hope you get the point that it might be beneficial to have more number of threads than the available number of cores, depending on the data size you're dealing with.

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

You can also make sure you are the sudo user and you have READ/WRITE access on the directory you are working. I had a similar problem on OS X, and I got it fixed just by entering in sudo mode.

unable to start mongodb local server

Try a different port if you can't find any current running processes or killing them doesn't work. For example, try 27018 because the default is 27017.

mongod  --port 27018

I found this out with the command, mongod --help

How do I get the result of a command in a variable in windows?

Just use the result from the FOR command. For example (inside a batch file):

for /F "delims=" %%I in ('dir /b /a-d /od FILESA*') do (echo %%I)

You can use the %%I as the value you want. Just like this: %%I.

And in advance the %%I does not have any spaces or CR characters and can be used for comparisons!!

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

I think you need OpenSessionInViewFilter to keep your session open during view rendering (but it is not too good practice).

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

No need for cut or magic, in bash you can cut a string like so:

  ORGSTRING="123456"
  CUTSTRING=${ORGSTRING:0:-3}
  echo "The original string: $ORGSTRING"
  echo "The new, shorter and faster string: $CUTSTRING"

See http://tldp.org/LDP/abs/html/string-manipulation.html

What is .Net Framework 4 extended?

Got this from Bing. Seems Microsoft has removed some features from the core framework and added it to a separate optional(?) framework component.

To quote from MSDN (http://msdn.microsoft.com/en-us/library/cc656912.aspx)

The .NET Framework 4 Client Profile does not include the following features. You must install the .NET Framework 4 to use these features in your application:

* ASP.NET
* Advanced Windows Communication Foundation (WCF) functionality
* .NET Framework Data Provider for Oracle
* MSBuild for compiling

What is String pool in Java?

Let's start with a quote from the virtual machine spec:

Loading of a class or interface that contains a String literal may create a new String object (§2.4.8) to represent that literal. This may not occur if the a String object has already been created to represent a previous occurrence of that literal, or if the String.intern method has been invoked on a String object representing the same string as the literal.

This may not occur - This is a hint, that there's something special about String objects. Usually, invoking a constructor will always create a new instance of the class. This is not the case with Strings, especially when String objects are 'created' with literals. Those Strings are stored in a global store (pool) - or at least the references are kept in a pool, and whenever a new instance of an already known Strings is needed, the vm returns a reference to the object from the pool. In pseudo code, it may go like that:

1: a := "one" 
   --> if(pool[hash("one")] == null)  // true
           pool[hash("one") --> "one"]
       return pool[hash("one")]

2: b := "one" 
  --> if(pool[hash("one")] == null)   // false, "one" already in pool
        pool[hash("one") --> "one"]
      return pool[hash("one")] 

So in this case, variables a and b hold references to the same object. IN this case, we have (a == b) && (a.equals(b)) == true.

This is not the case if we use the constructor:

1: a := "one"
2: b := new String("one")

Again, "one" is created on the pool but then we create a new instance from the same literal, and in this case, it leads to (a == b) && (a.equals(b)) == false

So why do we have a String pool? Strings and especially String literals are widely used in typical Java code. And they are immutable. And being immutable allowed to cache String to save memory and increase performance (less effort for creation, less garbage to be collected).

As programmers we don't have to care much about the String pool, as long as we keep in mind:

  • (a == b) && (a.equals(b)) may be true or false (always use equals to compare Strings)
  • Don't use reflection to change the backing char[] of a String (as you don't know who is actualling using that String)

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

IF EXISTS in T-SQL

There's no need for "else" in this case:

IF EXISTS(SELECT *  FROM  table1  WHERE Name='John' ) return 1
return 0

How do I get the max ID with Linq to Entity?

The best way to get the id of the entity you added is like this:

public int InsertEntity(Entity factor)
{
    Db.Entities.Add(factor);
    Db.SaveChanges();
    var id = factor.id;
    return id;
}

How do you auto format code in Visual Studio?

On mac : Shift + Option + F

On ubuntu : Ctrl + Shift + I

"import datetime" v.s. "from datetime import datetime"

You cannot use both statements; the datetime module contains a datetime type. The local name datetime in your own module can only refer to one or the other.

Use only import datetime, then make sure that you always use datetime.datetime to refer to the contained type:

import datetime

today_date = datetime.date.today()
date_time = datetime.datetime.strptime(date_time_string, '%Y-%m-%d %H:%M')

Now datetime is the module, and you refer to the contained types via that.

Alternatively, import all types you need from the module:

from datetime import date, datetime

today_date = date.today()
date_time = datetime.strptime(date_time_string, '%Y-%m-%d %H:%M')

Here datetime is the type from the module. date is another type, from the same module.

Updating user data - ASP.NET Identity

I am using .Net Core 3.1 or higher version.Please follow the solution:

  public class UpdateAssignUserRole
    {
        public string username { get; set; }
        public string rolename { get; set; }
        public bool IsEdit { get; set; }

    }

 private async Task UpdateSeedUsers(UserManager<IdentityUser> userManager, UpdateAssignUserRole updateassignUsername)
        {
            IList<Users> Users = await FindByUserName(updateassignUsername.username);

            if (await userManager.FindByNameAsync(updateassignUsername.username) != null)
            {
                var user = new IdentityUser
                {
                    UserName = updateassignUsername.username,
                    Email = Users[0].Email,
 
                };
                var result = await userManager.FindByNameAsync(updateassignUsername.username);
                if (result != null)
                {
                    IdentityResult deletionResult = await userManager.RemoveFromRolesAsync(result, await userManager.GetRolesAsync(result));
                    if (deletionResult != null)
                    {
                        await userManager.AddToRoleAsync(result, updateassignUsername.rolename);
                    }
                }
            }

        }

SQL: Alias Column Name for Use in CASE Statement

make it so easy.

select columnnameshow = (CASE tipoventa
when 'CONTADO' then 'contadito'
when 'CREDITO' then 'cred'
else 'no result'
end) from Promocion.Promocion 

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

In the relevant page which makes a mixed content https to http call which is not accessible we can add the following entry in the relevant and get rid of the mixed content error.

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

.mp4 file not playing in chrome

This started out as an attempt to cast video from my pc to a tv (with subtitles) eventually using Chromecast. And I ended up in this "does not play mp4" situation. However I seemed to have proved that Chrome will play (exactly the same) mp4 as long as it isn't wrapped in html(5) So here is what I have constructed. I have made a webpage under localhost and in there is a default.htm which contains:-

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video  controls >
 <source src="sample.mp4" type="video/mp4">
 <track kind="subtitles" src="sample.vtt" label="gcsubs" srclang="eng">
</video>
</body>
</html>

the video and subtitle files are stored in the same folder as default.htm

I have the very latest version of Chrome (just updated this morning)

When I type the appropriate localhost... into my Chrome browser a black square appears with a "GO" arrow and an elapsed time bar, a mute button and an icon which says "CC". If I hit the go arrow, nothing happens (it doesn't change to "pause", the elapsed time doesn't move, and the timer sticks at 0:00. There are no error messages - nothing!

(note that if I input localhost.. to IE11 the video plays!!!!

In Chrome if I enter the disc address of sample.mp4 (i.e. C:\webstore\sample.mp4 then Chrome will play the video fine?.

This last bit is probably a working solution for Chromecast except that I cannot see any subtitles. I really want a solution with working subtitles. I just don't understand what is different in Chrome between the two methods of playing mp4

Swift: Reload a View Controller

In Swift 4:

self.view.layoutIfNeeded()

How to make an alert dialog fill 90% of screen size?

My answer is based on the koma's but it doesn't require to override onStart but only onCreateView which is almost always overridden by default when you create new fragments.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.your_fragment_layout, container);

    Rect displayRectangle = new Rect();
    Window window = getDialog().getWindow();
    window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);

    v.setMinimumWidth((int)(displayRectangle.width() * 0.9f));
    v.setMinimumHeight((int)(displayRectangle.height() * 0.9f));

    return v;
}

I've tested it on Android 5.0.1.

Qt - reading from a text file

You have to replace string line

QString line = in.readLine();

into while:

QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0, "error", file.errorString());
}

QTextStream in(&file);

while(!in.atEnd()) {
    QString line = in.readLine();    
    QStringList fields = line.split(",");    
    model->appendRow(fields);    
}

file.close();

JavaFX - create custom button with image

You just need to create your own class inherited from parent. Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.

public class ImageButton extends Parent {

    private static final Image NORMAL_IMAGE = ...;
    private static final Image PRESSED_IMAGE = ...;

    private final ImageView iv;

    public ImageButton() {
        this.iv = new ImageView(NORMAL_IMAGE);
        this.getChildren().add(this.iv);

        this.iv.setOnMousePressed(new EventHandler<MouseEvent>() {

            public void handle(MouseEvent evt) {
                iv.setImage(PRESSED_IMAGE);
            }

        });

        // TODO other event handlers like mouse up

    } 

}

What's the difference between "app.render" and "res.render" in express.js?

along with these two variants, there is also jade.renderFile which generates html that need not be passed to the client.

usage-

var jade = require('jade');

exports.getJson = getJson;

function getJson(req, res) {
    var html = jade.renderFile('views/test.jade', {some:'json'});
    res.send({message: 'i sent json'});
}

getJson() is available as a route in app.js.

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

It should be CascadeType.Merge, in that case it will update if the record already exists.

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

I know it's already an old question, but i had the same error today. For me setting the connection variable on model did the work.

/**
 * Table properties
 */
protected $connection = 'mysql-utf8';
protected $table = 'notification';
protected $primaryKey = 'id';

I don't know if the issue was with the database (probably), but the texts fields with special chars (like ~, ´ e etc) were all messed up.

---- Editing

That $connection var is used to select wich db connection your model will use. Sometimes it happens that in database.php (under /config folder) you have multiples connections and the default one is not using UTF-8 charset.

In any case, be sure to properly use charset and collation into your connection.

'connections' => [

    'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'your_database'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', 'database_password'),
        'unix_socket' => env('DB_SOCKET', ''),
        'prefix' => '',
        'strict' => false,
        'engine' => null
    ],

    'mysql-utf8' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'your_database'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', 'database_password'),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => false,
        'engine' => null
    ],

Twitter Bootstrap modal on mobile devices

OK this does fix it I tried it today Sept 5-2012 but you have to be sure to check out the demo

The solution by niftylettuce in issue 2130 seems to fix modals in all mobile platforms...

9/1/12 UPDATE: The fix has been updated here: twitter bootstrap jquery plugins

here is the link to the Demo It works great heres the code I used

            title_dialog.modal();
            title_dialog.modalResponsiveFix({})
            title_dialog.touchScroll();

How to add image that is on my computer to a site in css or html?

No, Not if your website is on a remote server, i.e not on localhost.

Rounding a double value to x number of decimal places in swift

round a double value to x number of decimal
NO. of digits after decimal

var x = 1.5657676754
var y = (x*10000).rounded()/10000
print(y)  // 1.5658 

var x = 1.5657676754 
var y = (x*100).rounded()/100
print(y)  // 1.57 

var x = 1.5657676754
var y = (x*10).rounded()/10
print(y)  // 1.6

how to create a logfile in php?

Agree with the @jon answer. Just added modified the path to create the log directory inside the root

 function wh_log($log_msg) {
    $log_filename = $_SERVER['DOCUMENT_ROOT']."/log";
    if (!file_exists($log_filename))
    {
        // create directory/folder uploads.
        mkdir($log_filename, 0777, true);
    }
    $log_file_data = $log_filename.'/log_' . date('d-M-Y') . '.log';
    file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
}

just added $_SERVER['DOCUMENT_ROOT']

what is the use of fflush(stdin) in c programming

It's an unportable way to remove all data from the input buffer till the next newline. I've seen it used in cases like that:

char c;
char s[32];
puts("Type a char");
c=getchar();
fflush(stdin);
puts("Type a string");
fgets(s,32,stdin);

Without the fflush(), if you type a character, say "a", and the hit enter, the input buffer contains "a\n", the getchar() peeks the "a", but the "\n" remains in the buffer, so the next fgets() will find it and return an empty string without even waiting for user input.

However, note that this use of fflush() is unportable. I've tested right now on a Linux machine, and it does not work, for example.

How to create a private class method?

Ruby seems to provide a poor solution. To explain, start with a simple C++ example that shows access to private class methods:

#include <iostream>

class C
{
    public:
        void instance_method(void)
        {
            std::cout << "instance method\n";
            class_method();  // !!! LOOK !!! no 'send' required. We can access it
                             // because 'private' allows access within the class
        }
    private:
        void static class_method(void) { std::cout << "class method\n"; }
};

int main()
{
    C c;

    c.instance_method(); // works
    // C::class_method() does not compile - it's properly private
    return 0;
}

Running the above

   % ./a.out
   instance method
   class method

Now Ruby does not seem to provide the equivalent. Ruby's rules, I think, are that private methods must not be accessed with a receiver. That is,

inst.pvt_method  # FAILS
pvt_method # WORKS only within the class (good)

That's OK for private instance methods, but causes problems with private class methods.

I would like Ruby to function this way:

class C
    def instance_method
        STDOUT << "instance method\n"

        # Simple access to the private class method would be nice:
        class_method   # DOES NOT WORK. RUBY WON'T FIND THE METHOD
        C.class_method # DOES NOT WORK. RUBY WON'T ALLOW IT

        # ONLY THIS WORKS. While I am happy such capability exists I think
        # the way 'send' should be used is when the coder knows he/she is
        # doing a no-no.  The semantic load on the coder for this is also
        # remarkably clumsy for an elegant language like ruby.
        self.class.send(:class_method)
    end

    private_class_method def self.class_method() STDOUT << "class method\n"; end
end

But, alas, the above does not work. Does someone know a better way?

When I see 'send' prior to a method, it's a clear sign the code is violating the intent of the API's designer, but in this case the design is specifically to have an instance method of the class call the private class method.

Return number of rows affected by UPDATE statements

This is exactly what the OUTPUT clause in SQL Server 2005 onwards is excellent for.

EXAMPLE

CREATE TABLE [dbo].[test_table](
    [LockId] [int] IDENTITY(1,1) NOT NULL,
    [StartTime] [datetime] NULL,
    [EndTime] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
    [LockId] ASC
) ON [PRIMARY]
) ON [PRIMARY]

INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 07','2009 JUL 07')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 08','2009 JUL 08')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 09','2009 JUL 09')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 10','2009 JUL 10')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 11','2009 JUL 11')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 12','2009 JUL 12')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 13','2009 JUL 13')

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* -- INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed 
WHERE
    StartTime > '2009 JUL 09'

Results in the following being returned

    LockId StartTime                EndTime
-------------------------------------------------------
4      2011-07-01 00:00:00.000  2009-07-10 00:00:00.000
5      2011-07-01 00:00:00.000  2009-07-11 00:00:00.000
6      2011-07-01 00:00:00.000  2009-07-12 00:00:00.000
7      2011-07-01 00:00:00.000  2009-07-13 00:00:00.000

In your particular case, since you cannot use aggregate functions with OUTPUT, you need to capture the output of INSERTED.* in a table variable or temporary table and count the records. For example,

DECLARE @temp TABLE (
  [LockId] [int],
  [StartTime] [datetime] NULL,
  [EndTime] [datetime] NULL 
)

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* INTO @temp
WHERE
    StartTime > '2009 JUL 09'


-- now get the count of affected records
SELECT COUNT(*) FROM @temp

A regular expression to exclude a word/string

This should do it:

^/\b([a-z0-9]+)\b(?<!ignoreme|ignoreme2|ignoreme3)

You can add as much ignored words as you like, here is a simple PHP implementation:

$ignoredWords = array('ignoreme', 'ignoreme2', 'ignoreme...');

preg_match('~^/\b([a-z0-9]+)\b(?<!' . implode('|', array_map('preg_quote', $ignoredWords)) . ')~i', $string);

"elseif" syntax in JavaScript

Just add a space:

if (...) {

} else if (...) {

} else {

}

Limit results in jQuery UI Autocomplete

Here is the proper documentation for the jQueryUI widget. There isn't a built-in parameter for limiting max results, but you can accomplish it easily:

$("#auto").autocomplete({
    source: function(request, response) {
        var results = $.ui.autocomplete.filter(myarray, request.term);

        response(results.slice(0, 10));
    }
});

You can supply a function to the source parameter and then call slice on the filtered array.

Here's a working example: http://jsfiddle.net/andrewwhitaker/vqwBP/

Docker: Container keeps on restarting again on again

Check the partition where you have installed docker. In most cases, the partition is at 100% capacity so you may need to look into that.

Escaping regex string

Use the re.escape() function for this:

4.2.3 re Module Contents

escape(string)

Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

A simplistic example, search any occurence of the provided string optionally followed by 's', and return the match object.

def simplistic_plural(word, text):
    word_or_plural = re.escape(word) + 's?'
    return re.match(word_or_plural, text)

How to add 'libs' folder in Android Studio?

also, to get the right arrow, right click and "Add as Library".enter image description here

Make sure that the controller has a parameterless public constructor error

In my case, it was because of exception inside the constructor of my injected dependency (in your example - inside DashboardRepository constructor). The exception was caught somewhere inside MVC infrastructure. I found this after I added logs in relevant places.

How to increment a number by 2 in a PHP For Loop

<?php
  for ($n = 0; $n <= 7; $n++) {
    echo '<p>'.($n + 1).'</p>';
    echo '<p>'.($n * 2 + 1).'</p>';
  }
?>

First paragraph:

1, 2, 3, 4, 5, 6, 7, 8

Second paragraph:

1, 3, 5, 7, 9, 11, 13, 15

How to output something in PowerShell

What would be the right thing to use to write to the Windows equivalent of stdout?

In effect, but very unfortunately, both Windows PowerShell and PowerShell Core as of v7.0, send all of their 6(!) output streams to stdout when called from the outside, via PowerShell's CLI.

  • See this GitHub issue for a discussion of this problematic behavior, which likely won't get fixed for the sake of backward compatibility.

  • In practice, this means that whatever PowerShell stream you send output to will be seen as stdout output by an external caller:

    • E.g., if you run the following from cmd.exe, you'll see no output, because the stdout redirection to NUL applies equally to all PowerShell streams:

      • C:\>powershell -noprofile -command "Write-Error error!" >NUL
    • However - curiously - if you redirect stderr, PowerShell does send its error stream to stderr, so that with 2> you can capture the error-stream output selectively; the following outputs just 'hi' - the success-stream output - while capturing the error-stream output in file err.txt:

      • C:\>powershell -noprofile -command "'hi'; Write-Error error!" 2>err.txt

The desirable behavior is:

  • Send PowerShell's success output stream (number 1) to stdout.
  • Send output from all other streams to stderr, which is the only option, given that between processes only 2 output streams exist - stdout (standard output) for data, and stderr (standard error) for error messages and all other types of messages - such as status information - that aren't data.

  • It's advisable to make this distinction in your code, even though it currently isn't being respected.


Inside PowerShell:

  • Write-Host is for display output, and bypasses the success output stream - as such, its output can neither be (directly) captured in a variable nor suppressed nor redirected.

    • Its original intent was simply to create user feedback and create simple, console-based user interfaces (colored output).

    • Due to the prior inability to be captured or redirected, PowerShell version 5 made Write-Host to the newly introduced information stream (number 6), so since then it is possible to capture and redirect Write-Host output.

  • Write-Error is meant for writing non-terminating errors to the error stream (number 2); conceptually, the error stream is the equivalent of stderr.

  • Write-Output writes to the success [output] stream (number 1), which is conceptually equivalent to stdout; it is the stream to write data (results) to.

    • However, explicit use of Write-Output is rarely needed due to PowerShell's implicit output feature:
      • Output from any command or expression that isn't explicitly captured, suppressed or redirected is automatically sent to the success stream; e.g., Write-Output "Honey, I'm $HOME" and "Honey, I'm $HOME" are equivalent, with the latter not only being more concise, but also faster.

Disable activity slide-in animation when launching new activity?

I had a similar problem of getting a black screen appear on sliding transition from one activity to another using overridependingtransition. and I followed the way below and it worked

1) created a noanim.xml in anim folder

<?xml version="1.0" encoding="utf-8"?>
<translate 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_longAnimTime"
    android:fromYDelta="0%p"
    android:toYDelta="0%p" />

and used

overridePendingTransition(R.drawable.lefttorightanim, R.anim.noanim);

The first parameter as my original animation and second parameter which is the exit animation as my dummy animation

Nginx -- static file serving confusion with root & alias

In your case, you can use root directive, because $uri part of the location directive is the same with last root directive part.

Nginx documentation advices it as well:
When location matches the last part of the directive’s value:

location /images/ {
    alias /data/w3/images/;
}

it is better to use the root directive instead:

location /images/ {
    root /data/w3;
}

and root directive will append $uri to the path.

Multiprocessing vs Threading Python

Other answers have focused more on the multithreading vs multiprocessing aspect, but in python Global Interpreter Lock (GIL) has to be taken into account. When more number (say k) of threads are created, generally they will not increase the performance by k times, as it will still be running as a single threaded application. GIL is a global lock which locks everything out and allows only single thread execution utilizing only a single core. The performance does increase in places where C extensions like numpy, Network, I/O are being used, where a lot of background work is done and GIL is released.
So when threading is used, there is only a single operating system level thread while python creates pseudo-threads which are completely managed by threading itself but are essentially running as a single process. Preemption takes place between these pseudo threads. If the CPU runs at maximum capacity, you may want to switch to multiprocessing.
Now in case of self-contained instances of execution, you can instead opt for pool. But in case of overlapping data, where you may want processes communicating you should use multiprocessing.Process.

Interface vs Base class

Well, Josh Bloch said himself in Effective Java 2d:

Prefer interfaces over abstract classes

Some main points:

  • Existing classes can be easily retrofitted to implement a new interface. All you have to do is add the required methods if they don’t yet exist and add an implements clause to the class declaration.

  • Interfaces are ideal for defining mixins. Loosely speaking, a mixin is a type that a class can implement in addition to its “primary type” to declare that it provides some optional behavior. For example, Comparable is a mixin interface that allows a class to declare that its instances are ordered with respect to other mutually comparable objects.

  • Interfaces allow the construction of nonhierarchical type frameworks. Type hierarchies are great for organizing some things, but other things don’t fall neatly into a rigid hierarchy.

  • Interfaces enable safe, powerful functionality enhancements via the wrap- per class idiom. If you use abstract classes to define types, you leave the programmer who wants to add functionality with no alternative but to use inheritance.

Moreover, you can combine the virtues of interfaces and abstract classes by providing an abstract skeletal implementation class to go with each nontrivial interface that you export.

On the other hand, interfaces are very hard to evolve. If you add a method to an interface it'll break all of it's implementations.

PS.: Buy the book. It's a lot more detailed.

await is only valid in async function

I had the same problem and the following block of code was giving the same error message:

repositories.forEach( repo => {
        const commits = await getCommits(repo);
        displayCommit(commits);
});

The problem is that the method getCommits() was async but I was passing it the argument repo which was also produced by a Promise. So, I had to add the word async to it like this: async(repo) and it started working:

repositories.forEach( async(repo) => {
        const commits = await getCommits(repo);
        displayCommit(commits);
});

-XX:MaxPermSize with or without -XX:PermSize

By playing with parameters as -XX:PermSize and -Xms you can tune the performance of - for example - the startup of your application. I haven't looked at it recently, but a few years back the default value of -Xms was something like 32MB (I think), if your application required a lot more than that it would trigger a number of cycles of fill memory - full garbage collect - increase memory etc until it had loaded everything it needed. This cycle can be detrimental for startup performance, so immediately assigning the number required could improve startup.

A similar cycle is applied to the permanent generation. So tuning these parameters can improve startup (amongst others).

WARNING The JVM has a lot of optimization and intelligence when it comes to allocating memory, dividing eden space and older generations etc, so don't do things like making -Xms equal to -Xmx or -XX:PermSize equal to -XX:MaxPermSize as it will remove some of the optimizations the JVM can apply to its allocation strategies and therefor reduce your application performance instead of improving it.

As always: make non-trivial measurements to prove your changes actually improve performance overall (for example improving startup time could be disastrous for performance during use of the application)

Overlaying histograms with ggplot2 in R

Using @joran's sample data,

ggplot(dat, aes(x=xx, fill=yy)) + geom_histogram(alpha=0.2, position="identity")

note that the default position of geom_histogram is "stack."

see "position adjustment" of this page:

docs.ggplot2.org/current/geom_histogram.html

Python - How to concatenate to a string in a for loop?

While "".join is more pythonic, and the correct answer for this problem, it is indeed possible to use a for loop.

If this is a homework assignment (please add a tag if this is so!), and you are required to use a for loop then what will work (although is not pythonic, and shouldn't really be done this way if you are a professional programmer writing python) is this:

endstring = ""
mylist = ['first', 'second', 'other']
for word in mylist:
  print "This is the word I am adding: " + word
  endstring = endstring + word
print "This is the answer I get: " + endstring

You don't need the 'prints', I just threw them in there so you can see what is happening.

What is the best way to connect and use a sqlite database from C#

Here I am trying to help you do the job step by step: (this may be the answer to other questions)

  1. Go to this address , down the page you can see something like "List of Release Packages". Based on your system and .net framework version choose the right one for you. for example if your want to use .NET Framework 4.6 on a 64-bit Windows, choose this version and download it.
  2. Then install the file somewhere on your hard drive, just like any other software.
  3. Open Visual studio and your project. Then in solution explorer, right-click on "References" and choose "add Reference...".
  4. Click the browse button and choose where you install the previous file and go to .../bin/System.Data.SQLite.dll and click add and then OK buttons.

that is pretty much it. now you can use SQLite in your project. to use it in your project on the code level you may use this below example code:

  1. make a connection string:

    string connectionString = @"URI=file:{the location of your sqlite database}";

  2. establish a sqlite connection:

    SQLiteConnection theConnection = new SQLiteConnection(connectionString );

  3. open the connection:

    theConnection.Open();

  4. create a sqlite command:

    SQLiteCommand cmd = new SQLiteCommand(theConnection);

  5. Make a command text, or better said your SQLite statement:

    cmd.CommandText = "INSERT INTO table_name(col1, col2) VALUES(val1, val2)";

  6. Execute the command

    cmd.ExecuteNonQuery();

that is it.

Disable/enable an input with jQuery?

Just for the sake of new conventions && making it adaptable going forward (unless things change drastically with ECMA6(????):

$(document).on('event_name', '#your_id', function() {
    $(this).removeAttr('disabled');
});

and

$(document).off('event_name', '#your_id', function() {
    $(this).attr('disabled','disabled');   
});

AngularJS : Why ng-bind is better than {{}} in angular?

ng-bind is also safer because it represents html as a string.

So for example, '<script on*=maliciousCode()></script>' will be displayed as a string and not be executed.

CSS how to make scrollable list

Another solution would be as below where the list is placed under a drop-down button.

  <button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
    >Markets<span class="caret"></span></button>

    <ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
      {{ form.markets }}
    </ul>

Python Math - TypeError: 'NoneType' object is not subscriptable

lista = list.sort(lista)

This should be

lista.sort()

The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don't call your lists list. That clobbers the builtin list type.

Aside #2: I'm not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don't know why you're calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..


The exception TypeError: 'NoneType' object is not subscriptable happens because the value of lista is actually None. You can reproduce TypeError that you get in your code if you try this at the Python command line:

None[0]

The reason that lista gets set to None is because the return value of list.sort() is None... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).

If you do not want to alter the original version you can use

other_list = sorted(lista)

Why do Twitter Bootstrap tables always have 100% width?

All tables within the bootstrap stretch according to their container, which you can easily do by placing your table inside a .span* grid element of your choice. If you wish to remove this property you can create your own table class and simply add it to the table you want to expand with the content within:

.table-nonfluid {
   width: auto !important;
}

You can add this class inside your own stylesheet and simply add it to the container of your table like so:

<table class="table table-nonfluid"> ... </table>

This way your change won't affect the bootstrap stylesheet itself (you might want to have a fluid table somewhere else in your document).

How do I set up HttpContent for my HttpClient PostAsync second parameter?

This is answered in some of the answers to Can't find how to use HttpContent as well as in this blog post.

In summary, you can't directly set up an instance of HttpContent because it is an abstract class. You need to use one the classes derived from it depending on your need. Most likely StringContent, which lets you set the string value of the response, the encoding, and the media type in the constructor. See: http://msdn.microsoft.com/en-us/library/system.net.http.stringcontent.aspx

IF... OR IF... in a windows batch file

If %x%==1 (
If %y%==1 (
:: both are equal to 1.
)
)

That's for checking if multiple variables equal value. Here's for either variable.

If %x%==1 (
:: true
)
If %x%==0 (
If %y%==1 (
:: true
)
)
If %x%==0 (
If %y%==0 (
:: False
)
)

I just thought of that off the top if my head. I could compact it more.

pip install failing with: OSError: [Errno 13] Permission denied on directory

It is due permission problem,

sudo chown -R $USER /path to your python installed directory

default it would be /usr/local/lib/python2.7/

or try,

pip install --user -r package_name

and then say, pip install -r requirements.txt this will install inside your env

dont say, sudo pip install -r requirements.txt this is will install into arbitrary python path.

Generate 'n' unique random numbers within a range

Generate the range of data first and then shuffle it like this

import random
data = range(numLow, numHigh)
random.shuffle(data)
print data

By doing this way, you will get all the numbers in the particular range but in a random order.

But you can use random.sample to get the number of elements you need, from a range of numbers like this

print random.sample(range(numLow, numHigh), 3)

How to run a PowerShell script

I have a very simple answer which works:

  1. Open PowerShell in administrator mode
  2. Run: set-executionpolicy unrestricted
  3. Open a regular PowerShell window and run your script.

I found this solution following the link that was given as part of error message: About Execution Policies

updating table rows in postgres using subquery

If there are no performance gains using a join, then I prefer Common Table Expressions (CTEs) for readability:

WITH subquery AS (
    SELECT address_id, customer, address, partn
    FROM  /* big hairy SQL */ ...
)
UPDATE dummy
SET customer = subquery.customer,
    address  = subquery.address,
    partn    = subquery.partn
FROM subquery
WHERE dummy.address_id = subquery.address_id;

IMHO a bit more modern.

XSS filtering function in PHP

All above methods don't allow to preserve some tags like <a>, <table> etc. There is an ultimate solution http://sourceforge.net/projects/kses/ Drupal uses it

Simple PHP calculator

<?php
$cal1= $_GET['cal1'];
$cal2= $_GET['cal2'];
$symbol =$_GET['symbol'];


if($symbol == '+')
{
    $add = $cal1 + $cal2;
    echo "Addition is:".$add;
}

else if($symbol == '-')
{
    $subs = $cal1 - $cal2;
    echo "Substraction is:".$subs;
}

 else if($symbol == '*')
{
    $mul = $cal1 * $cal2;
    echo "Multiply is:".$mul;
}

else if($symbol == '/')
{
    $div = $cal1 / $cal2;
    echo "Division is:".$div;
}

  else
{

    echo "Oops ,something wrong in your code son";
}


?>

Python: Continuing to next iteration in outer loop

We want to find something and then stop the inner iteration. I use a flag system.

for l in f:
    flag = True
    for e in r:
        if flag==False:continue
        if somecondition:
            do_something()
            flag=False

Java constant examples (Create a java file having only constants)

- Create a Class with public static final fields.

- And then you can access these fields from any class using the Class_Name.Field_Name.

- You can declare the class as final, so that the class can't be extended(Inherited) and modify....

DB query builder toArray() laravel 4

If you prefer to use Query Builder instead of Eloquent here is the solutions

$result = DB::table('user')->where('name',=,'Jhon')->get();

First Solution

$array = (array) $result;

Second Solution

$array = get_object_vars($result);

Third Solution

$array = json_decode(json_encode($result), true);

hope it may help

How should I tackle --secure-file-priv in MySQL?

I had all sorts of problems with this. I was changing my.cnf and all sorts of crazy things that other versions of this problem tried to show.

What worked for me:

The error I was getting

The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

I was able to fix it by opening /usr/local/mysql/support-files/mysql.server and changing the following line:

$bindir/mysqld_safe --datadir="$datadir" --pid-file="$mysqld_pid_file_path" -- $other_args >/dev/null &
  wait_for_pid created "$!" "$mysqld_pid_file_path"; return_value=$?

to

$bindir/mysqld_safe --datadir="$datadir" --pid-file="$mysqld_pid_file_path" --secure-file-priv="" $other_args >/dev/null &
  wait_for_pid created "$!" "$mysqld_pid_file_path"; return_value=$?

PHP: Split a string in to an array foreach char

Since str_split() function is not multibyte safe, an easy solution to split UTF-8 encoded string is to use preg_split() with u (PCRE_UTF8) modifier.

preg_split( '//u', $str, null, PREG_SPLIT_NO_EMPTY )

How do you select a particular option in a SELECT element in jQuery?

By value, what worked for me with jQuery 1.7 was the below code, try this:

$('#id option[value=theOptionValue]').prop('selected', 'selected').change();

angularjs ng-style: background-image isn't working

Correct syntax for background-image is:

background-image: url("path_to_image");

Correct syntax for ng-style is:

ng-style="{'background-image':'url(https://www.google.com/images/srpr/logo4w.png)'}">

How to check if a "lateinit" variable has been initialized?

kotlin.UninitializedPropertyAccessException: lateinit property clientKeypair has not been initialized

Bytecode says...blah blah..

public final static synthetic access$getClientKeypair$p(Lcom/takharsh/ecdh/MainActivity;)Ljava/security/KeyPair;

`L0
LINENUMBER 11 L0
ALOAD 0
GETFIELD com/takharsh/ecdh/MainActivity.clientKeypair : Ljava/security/KeyPair;
DUP
IFNONNULL L1
LDC "clientKeypair"
INVOKESTATIC kotlin/jvm/internal/Intrinsics.throwUninitializedPropertyAccessException (Ljava/lang/String;)V
    L1
ARETURN

L2 LOCALVARIABLE $this Lcom/takharsh/ecdh/MainActivity; L0 L2 0 MAXSTACK = 2 MAXLOCALS = 1

Kotlin creates an extra local variable of same instance and check if it null or not, if null then throws 'throwUninitializedPropertyAccessException' else return the local object. Above bytecode explained here Solution Since kotlin 1.2 it allows to check weather lateinit var has been initialized or not using .isInitialized

"echo -n" prints "-n"

bash has a "built-in" command called "echo":

$ type echo
echo is a shell builtin

Additionally, there is an "echo" command that is a proper executable (that is, the shell forks and execs /bin/echo, as opposed to interpreting echo and executing it):

$ ls -l /bin/echo
-rwxr-xr-x 1 root root 22856 Jul 21  2011 /bin/echo

The behavior of either echo's WRT to \c and -n varies. Your best bet is to use printf, which is available on four different *NIX flavors that I looked at:

$ printf "a line without trailing linefeed"
$ printf "a line with trailing linefeed\n"

How do I create a master branch in a bare Git repository?

By default there will be no branches listed and pops up only after some file is placed. You don't have to worry much about it. Just run all your commands like creating folder structures, adding/deleting files, commiting files, pushing it to server or creating branches. It works seamlessly without any issue.

https://git-scm.com/docs

Ignore 'Security Warning' running script from command line

Assume that you need to launch ps script from shared folder

copy \\\server\script.ps1 c:\tmp.ps1 /y && PowerShell.exe -ExecutionPolicy Bypass -File c:\tmp.ps1 && del /f c:\tmp.ps1

P.S. Reduce googling)

Angularjs: input[text] ngChange fires while the value is changing

In case anyone else looking for additional "enter" keypress support, here's an update to the fiddle provided by Gloppy

Code for keypress binding:

elm.bind("keydown keypress", function(event) {
    if (event.which === 13) {
        scope.$apply(function() {
            ngModelCtrl.$setViewValue(elm.val());
        });
    }
});

Proper way to return JSON using node or Express

You can just prettify it using pipe and one of many processor. Your app should always response with as small load as possible.

$ curl -i -X GET http://echo.jsontest.com/key/value/anotherKey/anotherValue | underscore print

https://github.com/ddopson/underscore-cli

Get paragraph text inside an element

HTML:

<ul>
  <li onclick="myfunction(this)">
    <span></span>
    <p>This Text</p>
  </li>
</ul>?

JavaScript:

function myfunction(foo) {
    var elem = foo.getElementsByTagName('p');
    var TextInsideLi = elem[0].innerHTML;
}?

Can I make 'git diff' only the line numbers AND changed file names?

I use grep as a naive solution.

$ git diff | grep -A2 -- '---'

an output example:

--- a/fileA.txt
+++ b/fileA.txt
@@ -0,0 +1,132 @@
--
--- a/B/fileC.txt
+++ b/B/fileC.txt
@@ -33663,3 +33663,68800 @@ word_38077.png,Latin
--
--- a/D/fileE.txt
+++ b/D/fileE.txt
@@ -17998,3 +17998,84465 @@ word_23979.png,Latin
--
--- a/F
+++ b/F
@@ -1 +1 @@

Maybe you can see a colored output. It helps you to read outputs easily.

Is there a Python Library that contains a list of all the ascii characters?

You can do this without a module:

    characters = list(map(chr, range(97,123)))

Type characters and it should print ["a","b","c", ... ,"x","y","z"]. For uppercase use:

    characters=list(map(chr,range(65,91)))

Any range (including the use of range steps) can be used for this, because it makes use of Unicode. Therefore, increase the range() to add more characters to the list.
map() calls chr() every iteration of the range().

How to lay out Views in RelativeLayout programmatically?

From what I've been able to piece together, you have to add the view using LayoutParams.

LinearLayout linearLayout = new LinearLayout(this);

RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
relativeParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);

parentView.addView(linearLayout, relativeParams);

All credit to sechastain, to relatively position your items programmatically you have to assign ids to them.

TextView tv1 = new TextView(this);
tv1.setId(1);
TextView tv2 = new TextView(this);
tv2.setId(2);

Then addRule(RelativeLayout.RIGHT_OF, tv1.getId());

JavaScript null check

I think, testing variables for values you do not expect is not a good idea in general. Because the test as your you can consider as writing a blacklist of forbidden values. But what if you forget to list all the forbidden values? Someone, even you, can crack your code with passing an unexpected value. So a more appropriate approach is something like whitelisting - testing variables only for the expected values, not unexpected. For example, if you expect the data value to be a string, instead of this:

function (data) {
  if (data != null && data !== undefined) {
    // some code here
    // but what if data === false?
    // or data === '' - empty string?
  }
}

do something like this:

function (data) {
  if (typeof data === 'string' && data.length) {
    // consume string here, it is here for sure
    // cleaner, it is obvious what type you expect
    // safer, less error prone due to implicit coercion
  } 
}

How to delete and recreate from scratch an existing EF Code First database

There re many ways to drop a database or update existing database, simply you can switched to previous migrations.

dotnet ef database update previousMigraionName    

But some databases have limitations like not allow to modify after create relationships, means you have not allow privileges to drop columns from ef core database providers but most of time in ef core drop database is allowed.so you can drop DB using drop command and then you use previous migration again.

dotnet ef database drop
PMC command 
PM> drop-database

OR you can do manually deleting database and do a migration.

Docker command can't connect to Docker daemon

Usually, the following command does the trick:

sudo service docker restart

This, instead of docker start for the cases where Docker seems to already be running.

If that works then, as suggested and in another answer and on this GitHub issue, if you haven't added yourself in the docker group do it by running:

sudo usermod -aG docker <your-username> 

And you're most likely good to go.


As for anybody else bumping into this, in some OS's docker doesn't start right after you install it and, as a result, the same can't connect to daemon message appears. In this case you can first verify that Docker is indeed not running by checking the status of your docker service by executing:

sudo service docker status

If the output looks something like: docker stop/waiting instead of docker start/running, process 15378 then it obviously means Docker is not active. In this case make sure you start it with:

sudo service docker start

And, as before, you'll most likely be good to go.

How do I make a delay in Java?

I know this is a very old post but this may help someone: You can create a method, so whenever you need to pause you can type pause(1000) or any other millisecond value:

public static void pause(int ms) {
    try {
        Thread.sleep(ms);
    } catch (InterruptedException e) {
        System.err.format("IOException: %s%n", e);
    }
}

This is inserted just above the public static void main(String[] args), inside the class. Then, to call on the method, type pause(ms) but replace ms with the number of milliseconds to pause. That way, you don't have to insert the entire try-catch statement whenever you want to pause.

Why does viewWillAppear not get called when an app comes back from the background?

Just trying to make it as easy as possible see code below:

- (void)viewDidLoad
{
   [self appWillEnterForeground]; //register For Application Will enterForeground
}


- (id)appWillEnterForeground{ //Application will enter foreground.

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(allFunctions)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
    return self;
}


-(void) allFunctions{ //call any functions that need to be run when application will enter foreground 
    NSLog(@"calling all functions...application just came back from foreground");


}

How do I find out what keystore my JVM is using?

Your keystore will be in your JAVA_HOME---> JRE -->lib---> security--> cacerts. You need to check where your JAVA_HOME is configured, possibly one of these places,

  1. Computer--->Advanced --> Environment variables---> JAVA_HOME

  2. Your server startup batch files.

In your import command -keystore cacerts (give full path to the above JRE here instead of just saying cacerts).

How to improve performance of ngRepeat over a huge dataset (angular.js)?

for large data set and multiple value drop down it is better to use ng-options rather than ng-repeat.

ng-repeat is slow because it loops over all coming values but ng-options simply display to the select option.

ng-options='state.StateCode as state.StateName for state in States'>

much much faster than

<option ng-repeat="state in States" value="{{state.StateCode}}">
    {{state.StateName }}
</option>

Multiple select statements in Single query

select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) =  ('10544175A') 
 UNION  
select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) = ('10328189B') 
 UNION  
select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) = ('103498732H')

Call Activity method from adapter

Basic and simple.

In your adapter simply use this.

((YourParentClass) context).functionToRun();

How to create many labels and textboxes dynamically depending on the value of an integer variable?

I would create a user control which holds a Label and a Text Box in it and simply create instances of that user control 'n' times. If you want to know a better way to do it and use properties to get access to the values of Label and Text Box from the user control, please let me know.

Simple way to do it would be:

int n = 4; // Or whatever value - n has to be global so that the event handler can access it

private void btnDisplay_Click(object sender, EventArgs e)
{
    TextBox[] textBoxes = new TextBox[n];
    Label[] labels = new Label[n];

    for (int i = 0; i < n; i++)
    {
        textBoxes[i] = new TextBox();
        // Here you can modify the value of the textbox which is at textBoxes[i]

        labels[i] = new Label();
        // Here you can modify the value of the label which is at labels[i]
    }

    // This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(textBoxes[i]);
        this.Controls.Add(labels[i]);
    }
}

The code above assumes that you have a button btnDisplay and it has a onClick event assigned to btnDisplay_Click event handler. You also need to know the value of n and need a way of figuring out where to place all controls. Controls should have a width and height specified as well.

To do it using a User Control simply do this.

Okay, first of all go and create a new user control and put a text box and label in it.

Lets say they are called txtSomeTextBox and lblSomeLabel. In the code behind add this code:

public string GetTextBoxValue() 
{ 
    return this.txtSomeTextBox.Text; 
} 

public string GetLabelValue() 
{ 
    return this.lblSomeLabel.Text; 
} 

public void SetTextBoxValue(string newText) 
{ 
    this.txtSomeTextBox.Text = newText; 
} 

public void SetLabelValue(string newText) 
{ 
    this.lblSomeLabel.Text = newText; 
}

Now the code to generate the user control will look like this (MyUserControl is the name you have give to your user control):

private void btnDisplay_Click(object sender, EventArgs e)
{
    MyUserControl[] controls = new MyUserControl[n];

    for (int i = 0; i < n; i++)
    {
        controls[i] = new MyUserControl();

        controls[i].setTextBoxValue("some value to display in text");
        controls[i].setLabelValue("some value to display in label");
        // Now if you write controls[i].getTextBoxValue() it will return "some value to display in text" and controls[i].getLabelValue() will return "some value to display in label". These value will also be displayed in the user control.
    }

    // This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(controls[i]);
    }
}

Of course you can create more methods in the usercontrol to access properties and set them. Or simply if you have to access a lot, just put in these two variables and you can access the textbox and label directly:

public TextBox myTextBox;
public Label myLabel;

In the constructor of the user control do this:

myTextBox = this.txtSomeTextBox;
myLabel = this.lblSomeLabel;

Then in your program if you want to modify the text value of either just do this.

control[i].myTextBox.Text = "some random text"; // Same applies to myLabel

Hope it helped :)

How to open a web page from my application?

System.Diagnostics.Process.Start("http://www.webpage.com");

One of many ways.

ERROR 1067 (42000): Invalid default value for 'created_at'

Just convert it by this line :

for the new table :

CREATE TABLE t1 (
  ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

for Existing Table:

Alter ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Source :

https://dev.mysql.com/doc/refman/5.5/en/timestamp-initialization.html

Count the number of occurrences of a string in a VARCHAR field?

try this:

 select TITLE,
        (length(DESCRIPTION )-length(replace(DESCRIPTION ,'value','')))/5 as COUNT 
  FROM <table> 


SQL Fiddle Demo

Ideal way to cancel an executing AsyncTask

The thing is that AsyncTask.cancel() call only calls the onCancel function in your task. This is where you want to handle the cancel request.

Here is a small task I use to trigger an update method

private class UpdateTask extends AsyncTask<Void, Void, Void> {

        private boolean running = true;

        @Override
        protected void onCancelled() {
            running = false;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
            onUpdate();
        }

        @Override
        protected Void doInBackground(Void... params) {
             while(running) {
                 publishProgress();
             }
             return null;
        }
     }

MAC addresses in JavaScript

No you cannot get the MAC address in JavaScript, mainly because the MAC address uniquely identifies the running computer so it would be a security vulnerability.

Now if all you need is a unique identifier, I suggest you create one yourself using some cryptographic algorithm and store it in a cookie.

If you really need to know the MAC address of the computer AND you are developing for internal applications, then I suggest you use an external component to do that: ActiveX for IE, XPCOM for Firefox (installed as an extension).

Disable Logback in SpringBoot

Find spring-boot-starter-test in your pom.xml and modify it as follows:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <exclusions>
            <exclusion>
                <artifactId>commons-logging</artifactId>
                <groupId>commons-logging</groupId>
            </exclusion>
        </exclusions>
        <scope>test</scope>
    </dependency>

It fixed error like:

_Caused by: java.lang.IllegalArgumentException:_ **LoggerFactory** is not a **Logback LoggerContext** but *Logback* is on the classpath.

Either remove **Logback** or the competing implementation

(_class org.apache.logging.slf4j.Log4jLoggerFactory_
loaded from file: 

**${M2_HOME}/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.6.2/log4j-slf4j-impl-2.6.2.jar**).

If you are using WebLogic you will need to add **'org.slf4j'** to prefer-application-packages in WEB-INF/weblogic.xml: **org.apache.logging.slf4j.Log4jLoggerFactory**

Shell script to delete directories older than n days

find supports -delete operation, so:

find /base/dir/* -ctime +10 -delete;

I think there's a catch that the files need to be 10+ days older too. Haven't tried, someone may confirm in comments.

The most voted solution here is missing -maxdepth 0 so it will call rm -rf for every subdirectory, after deleting it. That doesn't make sense, so I suggest:

find /base/dir/* -maxdepth 0  -type d -ctime +10 -exec rm -rf {} \;

The -delete solution above doesn't use -maxdepth 0 because find would complain the dir is not empty. Instead, it implies -depth and deletes from the bottom up.

python and sys.argv

In Python, you can't just embed arbitrary Python expressions into literal strings and have it substitute the value of the string. You need to either:

sys.stderr.write("Usage: " + sys.argv[0])

or

sys.stderr.write("Usage: %s" % sys.argv[0])

Also, you may want to consider using the following syntax of print (for Python earlier than 3.x):

print >>sys.stderr, "Usage:", sys.argv[0]

Using print arguably makes the code easier to read. Python automatically adds a space between arguments to the print statement, so there will be one space after the colon in the above example.

In Python 3.x, you would use the print function:

print("Usage:", sys.argv[0], file=sys.stderr)

Finally, in Python 2.6 and later you can use .format:

print >>sys.stderr, "Usage: {0}".format(sys.argv[0])

Vuejs: v-model array in multiple input

If you were asking how to do it in vue2 and make options to insert and delete it, please, have a look an js fiddle

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    finds: [] _x000D_
  },_x000D_
  methods: {_x000D_
    addFind: function () {_x000D_
      this.finds.push({ value: 'def' });_x000D_
    },_x000D_
    deleteFind: function (index) {_x000D_
      console.log(index);_x000D_
      console.log(this.finds);_x000D_
      this.finds.splice(index, 1);_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <h1>Finds</h1>_x000D_
  <div v-for="(find, index) in finds">_x000D_
    <input v-model="find.value">_x000D_
    <button @click="deleteFind(index)">_x000D_
      delete_x000D_
    </button>_x000D_
  </div>_x000D_
  _x000D_
  <button @click="addFind">_x000D_
    New Find_x000D_
  </button>_x000D_
  _x000D_
  <pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Excel - programm cells to change colour based on another cell

Use conditional formatting.

You can enter a condition using any cell you like and a format to apply if the formula is true.

How is length implemented in Java Arrays?

From the JLS:

The array's length is available as a final instance variable length

And:

Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.

And arrays are implemented in the JVM. You may want to look at the VM Spec for more info.

Ruby capitalize every word first letter

try this:

puts 'one TWO three foUR'.split.map(&:capitalize).join(' ')

#=> One Two Three Four

or

puts 'one TWO three foUR'.split.map(&:capitalize)*' '

Create a pointer to two-dimensional array

You can do it like this:

uint8_t (*matrix_ptr)[10][20] = &l_matrix;

Adding POST parameters before submit

To add that using Jquery:

$('#commentForm').submit(function(){ //listen for submit event
    $.each(params, function(i,param){
        $('<input />').attr('type', 'hidden')
            .attr('name', param.name)
            .attr('value', param.value)
            .appendTo('#commentForm');
    });

    return true;
}); 

Java: Find .txt files in specified folder

You can use the listFiles() method provided by the java.io.File class.

import java.io.File;
import java.io.FilenameFilter;

public class Filter {

    public File[] finder( String dirName){
        File dir = new File(dirName);

        return dir.listFiles(new FilenameFilter() { 
                 public boolean accept(File dir, String filename)
                      { return filename.endsWith(".txt"); }
        } );

    }

}

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

In case you might be using the Express Edition:

Add "\SQLEXPRESS" after your server name

e.g. "MY-SERVER\SQLEXPRESS"

enter image description here

Using :before CSS pseudo element to add image to modal

Content and before are both highly unreliable across browsers. I would suggest sticking with jQuery to accomplish this. I'm not sure what you're doing to figure out if this carrot needs to be added or not, but you should get the overall idea:

$(".Modal").before("<img src='blackCarrot.png' class='ModalCarrot' />");

How can I get a resource content from a static context?

The Singleton:

package com.domain.packagename;

import android.content.Context;

/**
 * Created by Versa on 10.09.15.
 */
public class ApplicationContextSingleton {
    private static PrefsContextSingleton mInstance;
    private Context context;

    public static ApplicationContextSingleton getInstance() {
        if (mInstance == null) mInstance = getSync();
        return mInstance;
    }

    private static synchronized ApplicationContextSingleton getSync() {
        if (mInstance == null) mInstance = new PrefsContextSingleton();
        return mInstance;
    }

    public void initialize(Context context) {
        this.context = context;
    }

    public Context getApplicationContext() {
        return context;
    }

}

Initialize the Singleton in your Application subclass:

package com.domain.packagename;

import android.app.Application;

/**
 * Created by Versa on 25.08.15.
 */
public class mApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        ApplicationContextSingleton.getInstance().initialize(this);
    }
}

If I´m not wrong, this gives you a hook to applicationContext everywhere, call it with ApplicationContextSingleton.getInstance.getApplicationContext(); You shouldn´t need to clear this at any point, as when application closes, this goes with it anyway.

Remember to update AndroidManifest.xml to use this Application subclass:

<?xml version="1.0" encoding="utf-8"?>

<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.domain.packagename"
    >

<application
    android:allowBackup="true"
    android:name=".mApplication" <!-- This is the important line -->
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    android:icon="@drawable/app_icon"
    >

Now you should be able to use ApplicationContextSingleton.getInstance().getApplicationContext().getResources() from anywhere, also the very few places where application subclasses can´t.

Please let me know if you see anything wrong here, thank you. :)

Ruby class instance variable vs. class variable

While it may immediately seem useful to utilize class instance variables, since class instance variable are shared among subclasses and they can be referred to within both singleton and instance methods, there is a singificant drawback. They are shared and so subclasses can change the value of the class instance variable, and the base class will also be affected by the change, which is usually undesirable behavior:

class C
  @@c = 'c'
  def self.c_val
    @@c
  end
end

C.c_val
 => "c" 

class D < C
end

D.instance_eval do 
  def change_c_val
    @@c = 'd'
  end
end
 => :change_c_val 

D.change_c_val
(irb):12: warning: class variable access from toplevel
 => "d" 

C.c_val
 => "d" 

Rails introduces a handy method called class_attribute. As the name implies, it declares a class-level attribute whose value is inheritable by subclasses. The class_attribute value can be accessed in both singleton and instance methods, as is the case with the class instance variable. However, the huge benefit with class_attribute in Rails is subclasses can change their own value and it will not impact parent class.

class C
  class_attribute :c
  self.c = 'c'
end

 C.c
 => "c" 

class D < C
end

D.c = 'd'
 => "d" 

 C.c
 => "c" 

Working with time DURATION, not time of day

The custom format hh:mm only shows the number of hours correctly up to 23:59, after that, you get the remainder, less full days. For example, 48 hours would be displayed as 00:00, even though the underlaying value is correct.

To correctly display duration in hours and seconds (below or beyond a full day), you should use the custom format [h]:mm;@ In this case, 48 hours would be displayed as 48:00.

Cheers.

INFO: No Spring WebApplicationInitializer types detected on classpath

I found the error: I have a library that it was built using jdk 1.6. The Spring main controller and components are in this library. And how I use jdk 1.7, It does not find the classes built in 1.6.

The solution was built all using "compiler compliance level: 1.7" and "Generated .class files compatibility: 1.6", "Source compatibility: 1.6".

I setup this option in Eclipse: Preferences\Java\Compiler.

Thanks everybody.

How to replace local branch with remote branch entirely in Git?

The safest and most complete way to replace the current local branch with the remote:

git stash
git merge --abort
git rebase --abort
git branch -M yourBranch replaced_yourBranch
git fetch origin yourBranch:yourBranch
git checkout yourBranch

The stash line saves the changes that you have not committed. The branch line moves your branch to a different name, freeing up the original name. The fetch line retrieves the latest copy of the remote. The checkout line recreates the original branch as a tracking branch.

Or as a bash function:

replaceWithRemote() {
    yourBranch=${1:-`git rev-parse --abbrev-ref HEAD`}
    git stash
    git merge --abort
    git rebase --abort
    git branch -M ${yourBranch} replaced_${yourBranch}_`git rev-parse --short HEAD`
    git fetch origin ${yourBranch}:${yourBranch}
    git checkout ${yourBranch}
}

which renames the current branch to something like replaced_master_98d258f.

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

Another possibility to circumvent the problem is to use a proxy script. That method is described for example here

Set left margin for a paragraph in html

<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em' as the measurement, you may want to use other units, like 'px'.

EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:

In your HTML page, containing the <p> tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:

<head>
  <style type="text/css">
    p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>

So above, all <p> elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:

<head>
  <style type="text/css">
    .container p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
  </div>
  <p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>

In the example above, only the <p> element inside the div, whose class name is 'container', will have the styles applied - and not the <p> element outside the container.

In addition to the above, you can collect your styles together and remove the style element from the <head> tag, replacing it with a <link> tag, which points to an external CSS file. This external file is where you'd now put your <p> tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.

How can I find where Python is installed on Windows?

In the sys package, you can find a lot of useful information about your installation:

import sys
print sys.executable
print sys.exec_prefix

I'm not sure what this will give on your Windows system, but on my Mac executable points to the Python binary and exec_prefix to the installation root.

You could also try this for inspecting your sys module:

import sys
for k,v in sys.__dict__.items():
    if not callable(v):
        print "%20s: %s" % (k,repr(v))

Stop and Start a service via batch or cmd file?

I am writing a windows service in C#, the stop/uninstall/build/install/start loop got too tiring. Wrote a mini script, called it reploy.bat and dropped in my Visual Studio output directory (one that has the built service executable) to automate the loop.

Just set these 3 vars

servicename : this shows up on the Windows Service control panel (services.msc)

slndir : folder (not the full path) containing your solution (.sln) file

binpath : full path (not the folder path) to the service executable from the build

NOTE: This needs to be run from the Visual Studio Developer Command Line for the msbuild command to work.

SET servicename="My Amazing Service"
SET slndir="C:dir\that\contains\sln\file"
SET binpath="C:path\to\service.exe"
SET currdir=%cd%

call net stop %servicename%
call sc delete %servicename%
cd %slndir%
call msbuild 
cd %bindir%
call sc create %servicename% binpath=%binpath%
call net start %servicename%
cd %currdir%

Maybe this helps someone :)

How to create a circle icon button in Flutter?

If you need a background image, you can use CircleAvatar with IconButton. Set the backgroundImage property.

CircleAvatar(
  backgroundImage: NetworkImage(userAvatarUrl),
)

Example with button:

        CircleAvatar(
          backgroundColor: Colors.blue,
          radius: 20,
          child: IconButton(
            padding: EdgeInsets.zero,
            icon: Icon(Icons.add),
            color: Colors.white,
            onPressed: () {},
          ),
        ),

enter image description here

How do I programmatically change file permissions?

Just to update this answer unless anyone comes across this later, since JDK 6 you can use

File file = new File('/directory/to/file');
file.setWritable(boolean);
file.setReadable(boolean);
file.setExecutable(boolean);

you can find the documentation on Oracle File(Java Platform SE 7). Bear in mind that these commands only work if the current working user has ownership or write access to that file. I am aware that OP wanted chmod type access for more intricate user configuration. these will set the option across the board for all users.

Nth max salary in Oracle

There are three methods are there...

SELECT salary,first_name,rnk 
FROM (SELECT salary,first_name,rank() over (order by salary desc nulls last) as                                                                  rnk from emp) where rnk=3;


SELECT salary,first_name,rnk 
FROM (SELECT salary,first_name,dense_rank() over (order by salary desc nulls last) as                                                                  rnk from emp) where rnk=3;


select rnk,first_name,salary 
from (select rownum as rnk ,first_name,salary 
      from (select first_name,salary 
            from emp order by salary desc nulls last)) where rnk=3

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

  • pyenv - manages different python versions,
  • all others - create virtual environment (which has isolated python version and installed "requirements"),

pipenv want combine all, in addition to previous it installs "requirements" (into the active virtual environment or create its own if none is active)

So maybe you will be happy with pipenv only.

But I use: pyenv + pyenv-virtualenvwrapper, + pipenv (pipenv for installing requirements only).

In Debian:

  1. apt install libffi-dev

  2. install pyenv based on https://www.tecmint.com/pyenv-install-and-manage-multiple-python-versions-in-linux/, but..

  3. .. but instead of pyenv-virtualenv install pyenv-virtualenvwrapper (which can be standalone library or pyenv plugin, here the 2nd option):

    pyenv install 3.9.0

    git clone https://github.com/pyenv/pyenv-virtualenvwrapper.git $(pyenv root)/plugins/pyenv-virtualenvwrapper

    into ~/.bashrc add: export $VIRTUALENVWRAPPER_PYTHON="/usr/bin/python3"

    source ~/.bashrc

    pyenv virtualenvwrapper

Then create virtual environments for your projects (workingdir must exist):

pyenv local 3.9.0  # to prevent 'interpreter not found' in mkvirtualenv
python -m pip install --upgrade pip setuptools wheel
mkvirtualenv <venvname> -p python3.9 -a <workingdir>

and switch between projects:

workon <venvname>
python -m pip install --upgrade pip setuptools wheel pipenv

Inside a project I have the file requirements.txt, without fixing the versions inside (if some version limitation is not neccessary). You have 2 possible tools to install them into the current virtual environment: pip-tools or pipenv. Lets say you will use pipenv:

pipenv install -r requirements.txt

this will create Pipfile and Pipfile.lock files, fixed versions are in the 2nd one. If you want reinstall somewhere exactly same versions then (Pipfile.lock must be present):

pipenv install

Remember that Pipfile.lock is related to some Python version and need to be recreated if you use a different one.

As you see I write requirements.txt. This has some problems: You must remove a removed package from Pipfile too. So writing Pipfile directly is probably better.

So you can see I use pipenv very poorly. Maybe if you will use it well, it can replace everything?

EDIT 2021.01: I have changed my stack to: pyenv + pyenv-virtualenvwrapper + poetry. Ie. I use no apt or pip installation of virtualenv or virtualenvwrapper, and instead I install pyenv's plugin pyenv-virtualenvwrapper. This is easier way.

Poetry is great for me:

poetry add <package>   # install single package
poetry remove <package>
poetry install   # if you remove poetry.lock poetry will re-calculate versions

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

it may caused by Property which is not populated by model.. instead it is populated by Controller.. which may cause this error.. solution to this is assign the property before applying ModelState validation. and this second Assumption is . you may have already have Data in your Database and trying to update it it but now fetching it.

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

are you using jquery and prototype on the same page by any chance?

If so, use jquery noConflict mode, otherwise you are overwriting prototypes $ function.

noConflict mode is activated by doing the following:

<script src="jquery.js"></script>
<script>jQuery.noConflict();</script>

Note: by doing this, the dollar sign variable no longer represents the jQuery object. To keep from rewriting all your jQuery code, you can use this little trick to create a dollar sign scope for jQuery:

jQuery(function ($) {
    // The dollar sign will equal jQuery in this scope
});

// Out here, the dollar sign still equals Prototype