Programs & Examples On #Gpc

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:

while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
    n = (3*n + 1) / 2;
    if (n % 2 == 0) {
        do n /= 2; while (n % 2 == 0);
        if (n == 1) break;
    }
}

Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:

3n+1 -> ???? 0000 0100
/ 2  -> ???? ?000 0010
/ 2  -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2  -> ???? ???0 0010
/ 2  -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2  -> ???? ???? ?010
/ 2  -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2  -> ???? ???? ???0
/ 2  -> ???? ???? ????

So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:

k = n / 256;
m = n % 256;

switch (m) {
    case 0: n = 1 * k + 0; break;
    case 1: n = 81 * k + 1; break; 
    case 2: n = 81 * k + 1; break; 
    ...
    case 155: n = 729 * k + 425; break;
    ...
}

Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.

PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like

static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }

while (n > 128) {
    size_t lastBits = n % 256;
    n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}

In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.

PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).

We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).

If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.

PHP call Class method / function

To answer your question, the current method would be to create the object then call the method:

$functions = new Functions();
$var = $functions->filter($_GET['params']);

Another way would be to make the method static since the class has no private data to rely on:

public static function filter($data){

This can then be called like so:

$var = Functions::filter($_GET['params']);

Lastly, you do not need a class and can just have a file of functions which you include. So you remove the class Functions and the public in the method. This can then be called like you tried:

$var = filter($_GET['params']);

WCF named pipe minimal example

Try this.

Here is the service part.

[ServiceContract]
public interface IService
{
    [OperationContract]
    void  HelloWorld();
}

public class Service : IService
{
    public void HelloWorld()
    {
        //Hello World
    }
}

Here is the Proxy

public class ServiceProxy : ClientBase<IService>
{
    public ServiceProxy()
        : base(new ServiceEndpoint(ContractDescription.GetContract(typeof(IService)),
            new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyAppNameThatNobodyElseWillUse/helloservice")))
    {

    }
    public void InvokeHelloWorld()
    {
        Channel.HelloWorld();
    }
}

And here is the service hosting part.

var serviceHost = new ServiceHost
        (typeof(Service), new Uri[] { new Uri("net.pipe://localhost/MyAppNameThatNobodyElseWillUse") });
    serviceHost.AddServiceEndpoint(typeof(IService), new NetNamedPipeBinding(), "helloservice");
    serviceHost.Open();

    Console.WriteLine("Service started. Available in following endpoints");
    foreach (var serviceEndpoint in serviceHost.Description.Endpoints)
    {
        Console.WriteLine(serviceEndpoint.ListenUri.AbsoluteUri);
    }

How to use sha256 in php5.3.0

First of all, sha256 is a hashing algorithm, not a type of encryption. An encryption would require having a way to decrypt the information back to its original value (collisions aside).

Looking at your code, it seems it should work if you are providing the correct parameter.

  • Try using a literal string in your code first, and verify its validity instead of using the $_POST[] variable

  • Try moving the comparison from the database query to the code (get the hash for the given user and compare to the hash you have just calculated)

But most importantly before deploying this in any kind of public fashion, please remember to sanitize your inputs. Don't allow arbitrary SQL to be insert into the queries. The best idea here would be to use parameterized queries.

What is a mixin, and why are they useful?

I think previous responses defined very well what MixIns are. However, in order to better understand them, it might be useful to compare MixIns with Abstract Classes and Interfaces from the code/implementation perspective:

1. Abstract Class

  • Class that needs to contain one or more abstract methods

  • Abstract Class can contain state (instance variables) and non-abstract methods

2. Interface

  • Interface contains abstract methods only (no non-abstract methods and no internal state)

3. MixIns

  • MixIns (like Interfaces) do not contain internal state (instance variables)
  • MixIns contain one or more non-abstract methods (they can contain non-abstract methods unlike interfaces)

In e.g. Python these are just conventions, because all of the above are defined as classes. However, the common feature of both Abstract Classes, Interfaces and MixIns is that they should not exist on their own, i.e. should not be instantiated.

How to turn off magic quotes on shared hosting?

======================== =============== MY SOLUTION ============================ (rename your php.ini to php5.ini)

and in the top (!), add these:

magic_quotes_gpc = Off
magic_quotes_runtime = Off
magic_quotes_sybase = Off
extension=pdo.so
extension=pdo_mysql.so

then in .htaccess, add this (in the top):

SetEnv PHPRC /home/your_path/to/public_html/php5.ini

p.s. change /home/your_path/to/ correctly (you can see that path by executing the <?php phpinfo(); ?> command from a typical .php file.)

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

"Case" can return single value only, but you can use complex type:

create type foo as (a int, b text);
select (case 1 when 1 then (1,'qq')::foo else (2,'ww')::foo end).*;

Delete commit on gitlab

We've had similar problem and it was not enough to only remove commit and force push to GitLab.
It was still available in GitLab interface using url:

https://gitlab.example.com/<group>/<project>/commit/<commit hash>

We've had to remove project from GitLab and recreate it to get rid of this commit in GitLab UI.

How to fix error with xml2-config not found when installing PHP from sources?

I had the same issue when I used a DockerFile. My Docker is based on the php:5.5-apache image.

I got that error when executing the command "RUN docker-php-ext-install soap"

I have solved it by adding the following command to my DockerFile

"RUN apt-get update && apt-get install -y libxml2-dev"

How to write DataFrame to postgres table?

Starting from pandas 0.14 (released end of May 2014), postgresql is supported. The sql module now uses sqlalchemy to support different database flavors. You can pass a sqlalchemy engine for a postgresql database (see docs). E.g.:

from sqlalchemy import create_engine
engine = create_engine('postgresql://username:password@localhost:5432/mydatabase')
df.to_sql('table_name', engine)

You are correct that in pandas up to version 0.13.1 postgresql was not supported. If you need to use an older version of pandas, here is a patched version of pandas.io.sql: https://gist.github.com/jorisvandenbossche/10841234.
I wrote this a time ago, so cannot fully guarantee that it always works, buth the basis should be there). If you put that file in your working directory and import it, then you should be able to do (where con is a postgresql connection):

import sql  # the patched version (file is named sql.py)
sql.write_frame(df, 'table_name', con, flavor='postgresql')

getting the index of a row in a pandas apply function

To answer the original question: yes, you can access the index value of a row in apply(). It is available under the key name and requires that you specify axis=1 (because the lambda processes the columns of a row and not the rows of a column).

Working example (pandas 0.23.4):

>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
   b  c
a      
1  2  3
4  5  6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
   b  c  index_x10
a                 
1  2  3         10
4  5  6         40

how to include js file in php?

Its more likely that the path to file.js from the page is what is wrong. as long as when you view the page, and view-source you see the tag, its working, now its time to debug whether or not your path is too relative, maybe you need a / in front of it.

Creating an R dataframe row-by-row

Dirk Eddelbuettel's answer is the best; here I just note that you can get away with not pre-specifying the dataframe dimensions or data types, which is sometimes useful if you have multiple data types and lots of columns:

row1<-list("a",1,FALSE) #use 'list', not 'c' or 'cbind'!
row2<-list("b",2,TRUE)  

df<-data.frame(row1,stringsAsFactors = F) #first row
df<-rbind(df,row2) #now this works as you'd expect.

How does JavaScript .prototype work?

Every object has an internal property, [[Prototype]], linking it to another object:

object [[Prototype]] ? anotherObject

In traditional javascript, the linked object is the prototype property of a function:

object [[Prototype]] ? aFunction.prototype

Some environments expose [[Prototype]] as __proto__:

anObject.__proto__ === anotherObject

You create the [[Prototype]] link when creating an object.

// (1) Object.create:
var object = Object.create(anotherObject)
// object.__proto__ = anotherObject

// (2) ES6 object initializer:
var object = { __proto__: anotherObject };
// object.__proto__ = anotherObject

// (3) Traditional JavaScript:
var object = new aFunction;
// object.__proto__ = aFunction.prototype

So these statements are equivalent:

var object = Object.create(Object.prototype);
var object = { __proto__: Object.prototype }; // ES6 only
var object = new Object;

You can't actually see the link target (Object.prototype) in a new statement; instead the target is implied by the constructor (Object).

Remember:

  • Every object has a link, [[Prototype]], sometimes exposed as __proto__.
  • Every function has a prototype property, initially holding an empty object.
  • Objects created with new are linked to the prototype property of their constructor.
  • If a function is never used as a constructor, its prototype property will go unused.
  • If you don't need a constructor, use Object.create instead of new.

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

Reference excel worksheet by name?

To expand on Ryan's answer, when you are declaring variables (using Dim) you can cheat a little bit by using the predictive text feature in the VBE, as in the image below. screenshot of predictive text in VBE

If it shows up in that list, then you can assign an object of that type to a variable. So not just a Worksheet, as Ryan pointed out, but also a Chart, Range, Workbook, Series and on and on.

You set that variable equal to the object you want to manipulate and then you can call methods, pass it to functions, etc, just like Ryan pointed out for this example. You might run into a couple snags when it comes to collections vs objects (Chart or Charts, Range or Ranges, etc) but with trial and error you'll get it for sure.

SQL exclude a column using SELECT * [except columnA] FROM tableA?

If you are using SQL Server Management Studio then do as follows:

  1. Type in your desired tables name and select it
  2. Press Alt+F1
  3. o/p shows the columns in table.
  4. Select the desired columns
  5. Copy & paste those in your select query
  6. Fire the query.

Enjoy.

How can I retrieve Id of inserted entity using Entity framework?

I come across a situation where i need to insert the data in the database & simultaneously require the primary id using entity framework. Solution :

long id;
IGenericQueryRepository<myentityclass, Entityname> InfoBase = null;
try
 {
    InfoBase = new GenericQueryRepository<myentityclass, Entityname>();
    InfoBase.Add(generalinfo);
    InfoBase.Context.SaveChanges();
    id = entityclassobj.ID;
    return id;
 }

How to implement the --verbose or -v option into a script?

Building and simplifying @kindall's answer, here's what I typically use:

v_print = None
def main()
    parser = argparse.ArgumentParser()
    parser.add_argument('-v', '--verbosity', action="count", 
                        help="increase output verbosity (e.g., -vv is more than -v)")

    args = parser.parse_args()

    if args.verbosity:
        def _v_print(*verb_args):
            if verb_args[0] > (3 - args.verbosity):
                print verb_args[1]  
    else:
        _v_print = lambda *a: None  # do-nothing function

    global v_print
    v_print = _v_print

if __name__ == '__main__':
    main()

This then provides the following usage throughout your script:

v_print(1, "INFO message")
v_print(2, "WARN message")
v_print(3, "ERROR message")

And your script can be called like this:

% python verbose-tester.py -v
ERROR message

% python verbose=tester.py -vv
WARN message
ERROR message

% python verbose-tester.py -vvv
INFO message
WARN message
ERROR message

A couple notes:

  1. Your first argument is your error level, and the second is your message. It has the magic number of 3 that sets the upper bound for your logging, but I accept that as a compromise for simplicity.
  2. If you want v_print to work throughout your program, you have to do the junk with the global. It's no fun, but I challenge somebody to find a better way.

How to find minimum value from vector?

#include <iostream>
#include <vector>
#include <algorithm> // std::min_element
#include <iterator>  // std::begin, std::end

int main() {
    std::vector<int> v = {5,14,2,4,6};
    auto result = std::min_element(std::begin(v), std::end(v));
    if (std::end(v)!=result)
        std::cout << *result << '\n';
}

The program you show has a few problems, the primary culprit being the for condition: i<v[n]. You initialize the array, setting the first 5 elements to various values and the rest to zero. n is set to the number of elements you explicitly initialized so v[n] is the first element that was implicitly initialized to zero. Therefore the loop condition is false the first time around and the loop does not run at all; your code simply prints out the first element.

Some minor issues:

  • avoid raw arrays; they behave strangely and inconsistently (e.g., implicit conversion to pointer to the array's first element, can't be assigned, can't be passed to/returned from functions by value)

  • avoid magic numbers. int v[100] is an invitation to a bug if you want your array to get input from somewhere and then try to handle more than 100 elements.

  • avoid using namespace std; It's not a big deal in implementation files, although IMO it's better to just get used to explicit qualification, but it can cause problems if you blindly use it everywhere because you'll put it in header files and start causing unnecessary name conflicts.

What is the difference between a "function" and a "procedure"?

A function returns a value and a procedure just executes commands.

The name function comes from math. It is used to calculate a value based on input.

A procedure is a set of commands which can be executed in order.

In most programming languages, even functions can have a set of commands. Hence the difference is only returning a value.

But if you like to keep a function clean, (just look at functional languages), you need to make sure a function does not have a side effect.

How to kill a nodejs process in Linux?

Run ps aux | grep nodejs, find the PID of the process you're looking for, then run kill starting with SIGTERM (kill -15 25239). If that doesn't work then use SIGKILL instead, replacing -15 with -9.

Why does C# XmlDocument.LoadXml(string) fail when an XML header is included?

This really saved my day.

I have written a extension method based on Zach's answer, also I have extended it to use the encoding as a parameter, allowing for different encodings beside from UTF-8 to be used, and I wrapped the MemoryStream in a 'using' statement.

public static class XmlHelperExtentions
{
    /// <summary>
    /// Loads a string through .Load() instead of .LoadXml()
    /// This prevents character encoding problems.
    /// </summary>
    /// <param name="xmlDocument"></param>
    /// <param name="xmlString"></param>
    public static void LoadString(this XmlDocument xmlDocument, string xmlString, Encoding encoding = null) {

        if (encoding == null) {
            encoding = Encoding.UTF8;
        }

        // Encode the XML string in a byte array
        byte[] encodedString = encoding.GetBytes(xmlString);

        // Put the byte array into a stream and rewind it to the beginning
        using (var ms = new MemoryStream(encodedString)) {
            ms.Flush();
            ms.Position = 0;

            // Build the XmlDocument from the MemorySteam of UTF-8 encoded bytes
            xmlDocument.Load(ms);
        }
    }
}

Difference between DOM parentNode and parentElement

In Internet Explorer, parentElement is undefined for SVG elements, whereas parentNode is defined.

Convert integer to string Jinja

The OP needed to cast as string outside the {% set ... %}. But if that not your case you can do:

{% set curYear = 2013 | string() %}

Note that you need the parenthesis on that jinja filter.

If you're concatenating 2 variables, you can also use the ~ custom operator.

Finding version of Microsoft C++ compiler from command-line (for makefiles)

Create a .c file containing just the line:

_MSC_VER

or

CompilerVersion=_MSC_VER

then pre-process with

cl /nologo /EP <filename>.c

It is easy to parse the output.

What is the difference between a field and a property?

Properties have the primary advantage of allowing you to change the way data on an object is accessed without breaking it's public interface. For example, if you need to add extra validation, or to change a stored field into a calculated you can do so easily if you initially exposed the field as a property. If you just exposed a field directly, then you would have to change the public interface of your class to add the new functionality. That change would break existing clients, requiring them to be recompiled before they could use the new version of your code.

If you write a class library designed for wide consumption (like the .NET Framework, which is used by millions of people), that can be a problem. However, if you are writing a class used internally inside a small code base (say <= 50 K lines), it's really not a big deal, because no one would be adversely affected by your changes. In that case it really just comes down to personal preference.

How do I zip two arrays in JavaScript?

Use the map method:

_x000D_
_x000D_
var a = [1, 2, 3]_x000D_
var b = ['a', 'b', 'c']_x000D_
_x000D_
var c = a.map(function(e, i) {_x000D_
  return [e, b[i]];_x000D_
});_x000D_
_x000D_
console.log(c)
_x000D_
_x000D_
_x000D_

DEMO

C++: Print out enum value as text

How about this?

    enum class ErrorCodes : int{
          InvalidInput = 0
    };

    std::cout << ((int)error == 0 ? "InvalidInput" : "") << std::endl;

etc... I know this is a highly contrived example but I think it has application where applicable and needed and is certainly shorter than writing a script for it.

Disable a textbox using CSS

You can't disable a textbox in CSS. Disabling it is not a presentational task, you will have to do this in the HTML markup using the disabled attribute.

You may be able to put something together by putting the textbox underneath an absolutely positioned transparent element with z-index... But that's just silly, plus you would need a second HTML element anyway.

You can, however, style disabled text boxes (if that's what you mean) in CSS using

input[disabled] { ... }

from IE7 upwards and in all other major browsers.

How do I revert back to an OpenWrt router configuration?

Some addition to previous comments: 'firstboot' won't be available until you run 'mount_root' command.

So here is a full recap of what needs to be done. All manipulations I did on Windows 8.1.

  • Enter Failsafe mode (hold the reset button on boot for a few seconds)
  • Assign a static IP address, 192.168.1.2, to your PC. Example of a command: netsh interface ip set address name="Ethernet" static 192.168.1.2 255.255.255.0 192.168.1.1
  • Connect to address 192.168.1.1 from telnet (I use PuTTY) and login/password isn't required).
  • Run 'mount_root' (otherwise 'firstboot' won't be available).
  • Run 'firstboot' to reset.
  • Run 'reboot -f' to reboot.

Now you can enter to the router console from a browser. Also don't forget to return your PC from static to DHCP address assignment. Example: netsh interface ip set address name="Ethernet" source=dhcp

How to configure Spring Security to allow Swagger URL to be accessed without authentication

Adding this to your WebSecurityConfiguration class should do the trick.

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v2/api-docs",
                                   "/configuration/ui",
                                   "/swagger-resources/**",
                                   "/configuration/security",
                                   "/swagger-ui.html",
                                   "/webjars/**");
    }

}

How to run console application from Windows Service?

I've done this before successfully - I have some code at home. When I get home tonight, I'll update this answer with the working code of a service launching a console app.

I thought I'd try this from scratch. Here's some code I wrote that launches a console app. I installed it as a service and ran it and it worked properly: cmd.exe launches (as seen in Task Manager) and lives for 10 seconds until I send it the exit command. I hope this helps your situation as it does work properly as expected here.

    using (System.Diagnostics.Process process = new System.Diagnostics.Process())
    {
        process.StartInfo = new System.Diagnostics.ProcessStartInfo(@"c:\windows\system32\cmd.exe");
        process.StartInfo.CreateNoWindow = true;
        process.StartInfo.ErrorDialog = false;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        process.Start();
        //// do some other things while you wait...
        System.Threading.Thread.Sleep(10000); // simulate doing other things...
        process.StandardInput.WriteLine("exit"); // tell console to exit
        if (!process.HasExited)
        {
            process.WaitForExit(120000); // give 2 minutes for process to finish
            if (!process.HasExited)
            {
                process.Kill(); // took too long, kill it off
            }
        }
    }

How to remove all CSS classes using jQuery/JavaScript?

Let's use this example. Maybe you want the user of your website to know a field is valid or it needs attention by changing the background color of the field. If the user hits reset then your code should only reset the fields that have data and not bother to loop through every other field on your page.

This jQuery filter will remove the class "highlightCriteria" only for the input or select fields that have this class.

$form.find('input,select').filter(function () {
    if((!!this.value) && (!!this.name)) {
        $("#"+this.id).removeClass("highlightCriteria");
    }
});

Firebase: how to generate a unique numeric ID for key?

As the docs say, this can be achieved just by using set instead if push.

As the docs say, it is not recommended (due to possible overwrite by other user at the "same" time).

But in some cases it's helpful to have control over the feed's content including keys.

As an example of webapp in js, 193 being your id generated elsewhere, simply:

 firebase.initializeApp(firebaseConfig);
  var data={
      "name":"Prague"
  };
  firebase.database().ref().child('areas').child("193").set(data);

This will overwrite any area labeled 193 or create one if it's not existing yet.

How to get the python.exe location programmatically?

sys.executable is not reliable if working in an embedded python environment. My suggestions is to deduce it from

import os
os.__file__

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

I got similar error (my app crashes) after I renamed something in strings.xml and forgot to modify other files (a preference xml resource file and java code).

IDE (android studio) didn't showed any errors. But, after I repaired my xml files and java code, app ran okay. So, maybe there are some small mistakes in your xml files or constants.

How to count the number of occurrences of a character in an Oracle varchar value?

Here you go:

select length('123-345-566') - length(replace('123-345-566','-',null)) 
from dual;

Technically, if the string you want to check contains only the character you want to count, the above query will return NULL; the following query will give the correct answer in all cases:

select coalesce(length('123-345-566') - length(replace('123-345-566','-',null)), length('123-345-566'), 0) 
from dual;

The final 0 in coalesce catches the case where you're counting in an empty string (i.e. NULL, because length(NULL) = NULL in ORACLE).

Angular 4 HttpClient Query Parameters

I ended up finding it through the IntelliSense on the get() function. So, I'll post it here for anyone who is looking for similar information.

Anyways, the syntax is nearly identical, but slightly different. Instead of using URLSearchParams() the parameters need to be initialized as HttpParams() and the property within the get() function is now called params instead of search.

import { HttpClient, HttpParams } from '@angular/common/http';
getLogs(logNamespace): Observable<any> {

    // Setup log namespace query parameter
    let params = new HttpParams().set('logNamespace', logNamespace);

    return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, { params: params })
}

I actually prefer this syntax as its a little more parameter agnostic. I also refactored the code to make it slightly more abbreviated.

getLogs(logNamespace): Observable<any> {

    return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, {
        params: new HttpParams().set('logNamespace', logNamespace)
    })
}

Multiple Parameters

The best way I have found thus far is to define a Params object with all of the parameters I want to define defined within. As @estus pointed out in the comment below, there are a lot of great answers in This Question as to how to assign multiple parameters.

getLogs(parameters) {

    // Initialize Params Object
    let params = new HttpParams();

    // Begin assigning parameters
    params = params.append('firstParameter', parameters.valueOne);
    params = params.append('secondParameter', parameters.valueTwo);

    // Make the API call using the new parameters.
    return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, { params: params })

Multiple Parameters with Conditional Logic

Another thing I often do with multiple parameters is allow the use of multiple parameters without requiring their presence in every call. Using Lodash, it's pretty simple to conditionally add/remove parameters from calls to the API. The exact functions used in Lodash or Underscores, or vanilla JS may vary depending on your application, but I have found that checking for property definition works pretty well. The function below will only pass parameters that have corresponding properties within the parameters variable passed into the function.

getLogs(parameters) {

    // Initialize Params Object
    let params = new HttpParams();

    // Begin assigning parameters
    if (!_.isUndefined(parameters)) {
        params = _.isUndefined(parameters.valueOne) ? params : params.append('firstParameter', parameters.valueOne);
        params = _.isUndefined(parameters.valueTwo) ? params : params.append('secondParameter', parameters.valueTwo);
    }

    // Make the API call using the new parameters.
    return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, { params: params })

How do I use su to execute the rest of the bash script as that user?

You need to execute all the different-user commands as their own script. If it's just one, or a few commands, then inline should work. If it's lots of commands then it's probably best to move them to their own file.

su -c "cd /home/$USERNAME/$PROJECT ; svn update" -m "$USERNAME" 

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

Rails 4 Authenticity Token

I don't think it's good to generally turn off CSRF protection as long as you don't exclusively implement an API.

When looking at the Rails 4 API documentation for ActionController I found that you can turn off forgery protection on a per controller or per method base.

For example to turn off CSRF protection for methods you can use

class FooController < ApplicationController
  protect_from_forgery except: :index

Hide Spinner in Input Number - Firefox 29

Faced the same issue post Firefox update to 29.0.1, this is also listed out here https://bugzilla.mozilla.org/show_bug.cgi?id=947728

Solutions: They(Mozilla guys) have fixed this by introducing support for "-moz-appearance" for <input type="number">. You just need to have a style associated with your input field with "-moz-appearance:textfield;".

I prefer the CSS way E.g.:-

.input-mini{
-moz-appearance:textfield;}

Or

You can do it inline as well:

<input type="number" style="-moz-appearance: textfield">

Laravel Request::all() Should Not Be Called Statically

I thought it would be useful for future visitors to provide a bit of an explanation on what is happening here.

The Illuminate\Http\Request class

Laravel's Illuminate\Http\Request class has a method named all (in fact the all method is defined in a trait that the Request class uses, called Illuminate\Http\Concerns\InteractsWithInput). The signature of the all method at the time of writing looks like this:

public function all($keys = null)

This method is not defined as static and so when you try to call the method in a static context, i.e. Illuminate\Http\Request::all() you will get the error displayed in OP's question. The all method is an instance method and deals with information that is present in an instance of the Request class, so calling it in this way makes no sense.

Facades

A facade in Laravel provides developers with a convenient way of accessing objects in the IoC container, and calling methods on those objects. A developer can call a method "statically" on a facade like Request::all(), but the actual method call on the real Illuminate\Http\Request object is not static.

A facade works like a proxy - it refers to an object in the IoC container and passes the static method call onto that object (non-statically). For instance, take the Illuminate\Support\Facades\Request facade, this is what it looks like:

class Request extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'request';
    }
}

Under the hood, the base Illuminate\Support\Facades\Facade class uses some PHP magic, namely the __callStatic method to:

  • Listen for a static method call, in this case all with no parameters
  • Grab the underlying object from the IoC container using the key returned by getFacadeAccessor, in this case a Illuminate\Http\Request object
  • Dynamically call the method that it received statically on the object it has retrieved, in this case all is called non-statically on an instance of Illuminate\Http\Request.

This is why, as @patricus pointed out in his answer above, by changing the use/import statement to refer to the facade, the error is no longer there, because as far as PHP is concerned, all has been correctly called on an instance of Illuminate\Http\Request.

Aliasing

Aliasing is another feature that Laravel provides for convenience. It works by effectively creating alias classes that point to facades in the root namespace. If you take a look at your config/app.php file, under the aliases key, you will find a long list of mappings of strings to facade classes. For example:

'aliases' => [

    'App' => Illuminate\Support\Facades\App::class,
    'Artisan' => Illuminate\Support\Facades\Artisan::class,
    'Auth' => Illuminate\Support\Facades\Auth::class,
    // ...
    'Request' => Illuminate\Support\Facades\Request::class,

Laravel creates these alias classes for you, based on your configuration and this allows you to utilise classes available in the root namespace (as referred to by the string keys of the aliases config) as if you're using the facade itself:

use Request:

class YourController extends Controller
{
    public function yourMethod()
    {
        $input = Request::all();

        // ...
    }
}

A note on dependency injection

While facades and aliasing are still provided in Laravel, it is possible and usually encouraged to go down the dependency injection route. For example, using constructor injection to achieve the same result:

use Illuminate\Http\Request;

class YourController extends Controller
{
    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function yourMethod()
    {
        $input = $this->request->all();

        // ...
    }
}

There are a number of benefits to this approach but in my personal opinion the greatest pro for dependency injection is that it makes your code way easier to test. By declaring the dependencies of your classes as constructor or method arguments, it becomes very easy to mock out those dependencies and unit test your class in isolation.

import httplib ImportError: No module named httplib

I had this issue when I was trying to make my Docker container smaller. It was because I'd installed Python 2.7 with:

apt-get install -y --no-install-recommends python

And I should not have included the --no-install-recommends flag:

apt-get install -y python

Is there a way to programmatically minimize a window

in c#.net

this.WindowState = FormWindowState.Minimized

"google is not defined" when using Google Maps V3 in Firefox remotely

Changed the

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API"> 
      function(){
            myMap()
                }
</script>

and made it

<script type="text/javascript">
      function(){
            myMap()
                }
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API"></script>

It worked :)

Why use pip over easy_install?

pip won't install binary packages and isn't well tested on Windows.

As Windows doesn't come with a compiler by default pip often can't be used there. easy_install can install binary packages for Windows.

What's the difference between ".equals" and "=="?

== is an operator. equals is a method defined in the Object class

== checks if two objects have the same address in the memory and for primitive it checks if they have the same value.equals method on the other hand checks if the two objects which are being compared have an equal value(depending on how ofcourse the equals method has been implemented for the objects. equals method cannot be applied on primitives(which means that if a is a primitive a.equals(someobject) is not allowed, however someobject.equals(a) is allowed).

Priority queue in .Net

AlgoKit

I wrote an open source library called AlgoKit, available via NuGet. It contains:

  • Implicit d-ary heaps (ArrayHeap),
  • Binomial heaps,
  • Pairing heaps.

The code has been extensively tested. I definitely recommend you to give it a try.

Example

var comparer = Comparer<int>.Default;
var heap = new PairingHeap<int, string>(comparer);

heap.Add(3, "your");
heap.Add(5, "of");
heap.Add(7, "disturbing.");
heap.Add(2, "find");
heap.Add(1, "I");
heap.Add(6, "faith");
heap.Add(4, "lack");

while (!heap.IsEmpty)
    Console.WriteLine(heap.Pop().Value);

Why those three heaps?

The optimal choice of implementation is strongly input-dependent — as Larkin, Sen, and Tarjan show in A back-to-basics empirical study of priority queues, arXiv:1403.0252v1 [cs.DS]. They tested implicit d-ary heaps, pairing heaps, Fibonacci heaps, binomial heaps, explicit d-ary heaps, rank-pairing heaps, quake heaps, violation heaps, rank-relaxed weak heaps, and strict Fibonacci heaps.

AlgoKit features three types of heaps that appeared to be most efficient among those tested.

Hint on choice

For a relatively small number of elements, you would likely be interested in using implicit heaps, especially quaternary heaps (implicit 4-ary). In case of operating on larger heap sizes, amortized structures like binomial heaps and pairing heaps should perform better.

How can I tell when a MySQL table was last updated?

Cache the query in a global variable when it is not available.

Create a webpage to force the cache to be reloaded when you update it.

Add a call to the reloading page into your deployment scripts.

Write to Windows Application Event Log

try

   System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
   appLog.Source = "This Application's Name";
   appLog.WriteEntry("An entry to the Application event log.");

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

Besides checking the right minSdkVersion in build.gradle, make sure you have installed all necessary tools and correct SDK Platform for your preferred Android Version in SDK Manager. In Android Studio klick on Tools -> Android -> SDK Manager. Then install at minimum (for Android 2.2 without emulator):

  • Android SDK Tools
  • Android SDK Platform-tools
  • Android SDK Build-tools (latest)
  • Android 2.2 (API 8)
    • SDK Platform
    • Google APIs

This is what worked for me.

Truncate Two decimal places without rounding

I will leave the solution for decimal numbers.

Some of the solutions for decimals here are prone to overflow (if we pass a very large decimal number and the method will try to multiply it).

Tim Lloyd's solution is protected from overflow but it's not too fast.

The following solution is about 2 times faster and doesn't have an overflow problem:

public static class DecimalExtensions
{
    public static decimal TruncateEx(this decimal value, int decimalPlaces)
    {
        if (decimalPlaces < 0)
            throw new ArgumentException("decimalPlaces must be greater than or equal to 0.");

        var modifier = Convert.ToDecimal(0.5 / Math.Pow(10, decimalPlaces));
        return Math.Round(value >= 0 ? value - modifier : value + modifier, decimalPlaces);
    }
}

[Test]
public void FastDecimalTruncateTest()
{
    Assert.AreEqual(-1.12m, -1.129m. TruncateEx(2));
    Assert.AreEqual(-1.12m, -1.120m. TruncateEx(2));
    Assert.AreEqual(-1.12m, -1.125m. TruncateEx(2));
    Assert.AreEqual(-1.12m, -1.1255m.TruncateEx(2));
    Assert.AreEqual(-1.12m, -1.1254m.TruncateEx(2));
    Assert.AreEqual(0m,      0.0001m.TruncateEx(3));
    Assert.AreEqual(0m,     -0.0001m.TruncateEx(3));
    Assert.AreEqual(0m,     -0.0000m.TruncateEx(3));
    Assert.AreEqual(0m,      0.0000m.TruncateEx(3));
    Assert.AreEqual(1.1m,    1.12m.  TruncateEx(1));
    Assert.AreEqual(1.1m,    1.15m.  TruncateEx(1));
    Assert.AreEqual(1.1m,    1.19m.  TruncateEx(1));
    Assert.AreEqual(1.1m,    1.111m. TruncateEx(1));
    Assert.AreEqual(1.1m,    1.199m. TruncateEx(1));
    Assert.AreEqual(1.2m,    1.2m.   TruncateEx(1));
    Assert.AreEqual(0.1m,    0.14m.  TruncateEx(1));
    Assert.AreEqual(0,      -0.05m.  TruncateEx(1));
    Assert.AreEqual(0,      -0.049m. TruncateEx(1));
    Assert.AreEqual(0,      -0.051m. TruncateEx(1));
    Assert.AreEqual(-0.1m,  -0.14m.  TruncateEx(1));
    Assert.AreEqual(-0.1m,  -0.15m.  TruncateEx(1));
    Assert.AreEqual(-0.1m,  -0.16m.  TruncateEx(1));
    Assert.AreEqual(-0.1m,  -0.19m.  TruncateEx(1));
    Assert.AreEqual(-0.1m,  -0.199m. TruncateEx(1));
    Assert.AreEqual(-0.1m,  -0.101m. TruncateEx(1));
    Assert.AreEqual(0m,     -0.099m. TruncateEx(1));
    Assert.AreEqual(0m,     -0.001m. TruncateEx(1));
    Assert.AreEqual(1m,      1.99m.  TruncateEx(0));
    Assert.AreEqual(1m,      1.01m.  TruncateEx(0));
    Assert.AreEqual(-1m,    -1.99m.  TruncateEx(0));
    Assert.AreEqual(-1m,    -1.01m.  TruncateEx(0));
}

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

MySql Error: 1364 Field 'display_name' doesn't have default value

I got this error when I forgot to add new form fields/database columns to the $fillable array in the Laravel model - the model was stripping them out.

python mpl_toolkits installation issue

It is not on PyPI and you should not be installing it via pip. If you have matplotlib installed, you should be able to import mpl_toolkits directly:

$ pip install --upgrade matplotlib
...

$ python
>>> import mpl_toolkits
>>> 

Create a function with optional call variables

Not sure I understand the question correctly.

From what I gather, you want to be able to assign a value to Domain if it is null and also what to check if $args2 is supplied and according to the value, execute a certain code?

I changed the code to reassemble the assumptions made above.

Function DoStuff($computername, $arg2, $domain)
{
    if($domain -ne $null)
    {
        $domain = "Domain1"
    }

    if($arg2 -eq $null)
    {
    }
    else
    {
    }
}

DoStuff -computername "Test" -arg2 "" -domain "Domain2"
DoStuff -computername "Test" -arg2 "Test"  -domain ""
DoStuff -computername "Test" -domain "Domain2"
DoStuff -computername "Test" -arg2 "Domain2"

Did that help?

HTML text input allow only numeric input

You can use pattern for this:

<input id="numbers" pattern="[0-9.]+" type="number">

Here you can see the complete mobile website interface tips.

Using Bootstrap Modal window as PartialView

I use AJAX to do this. You have your partial with your typical twitter modal template html:

<div class="container">
  <!-- Modal -->
  <div class="modal fade" id="LocationNumberModal" role="dialog">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">
            &times;
          </button>
          <h4 class="modal-title">
            Serial Numbers
          </h4>
        </div>
        <div class="modal-body">
          <span id="test"></span>
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">
            Close
          </button>
        </div>
      </div>
    </div>
  </div>
</div>

Then you have your controller method, I use JSON and have a custom class that rendors the view to a string. I do this so I can perform multiple ajax updates on the screen with one ajax call. Reference here: Example but you can use an PartialViewResult/ActionResult on return if you are just doing the one call. I will show it using JSON..

And the JSON Method in Controller:

public JsonResult LocationNumberModal(string partNumber = "")
{
  //Business Layer/DAL to get information
  return Json(new {
      LocationModal = ViewUtility.RenderRazorViewToString(this.ControllerContext, "LocationNumberModal.cshtml", new SomeModelObject())
    },
    JsonRequestBehavior.AllowGet
  );
}

And then, in the view using your modal: You can package the AJAX in your partial and call @{Html.RenderPartial... Or you can have a placeholder with a div:

<div id="LocationNumberModalContainer"></div>

then your ajax:

function LocationNumberModal() {
  var partNumber = "1234";

  var src = '@Url.Action("LocationNumberModal", "Home", new { area = "Part" })'
    + '?partNumber='' + partNumber; 

  $.ajax({
    type: "GET",
    url: src,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (data) {
      $("#LocationNumberModalContainer").html(data.LocationModal);
      $('#LocationNumberModal').modal('show');
    }
  });
};

Then the button to your modal:

<button type="button" id="GetLocBtn" class="btn btn-default" onclick="LocationNumberModal()">Get</button>

Add ... if string is too long PHP

$string = "Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don't know how long maybe around 1000 characters. Anyway this should be over 50 characters know...";

if(strlen($string) >= 50)
{
    echo substr($string, 50); //prints everything after 50th character
    echo substr($string, 0, 50); //prints everything before 50th character
}

GDB: Listing all mapped memory regions for a crashed process

You can also use info files to list all the sections of all the binaries loaded in process binary.

IN Clause with NULL or IS NULL

An in statement will be parsed identically to field=val1 or field=val2 or field=val3. Putting a null in there will boil down to field=null which won't work.

(Comment by Marc B)

I would do this for clairity

SELECT *
FROM tbl_name
WHERE 
(id_field IN ('value1', 'value2', 'value3') OR id_field IS NULL)

Capture HTML Canvas as gif/jpg/png/pdf?

I would use "wkhtmltopdf". It just work great. It uses webkit engine (used in Chrome, Safari, etc.), and it is very easy to use:

wkhtmltopdf stackoverflow.com/questions/923885/ this_question.pdf

That's it!

Try it

SQLDataReader Row Count

SQLDataReaders are forward-only. You're essentially doing this:

count++;  // initially 1
.DataBind(); //consuming all the records

//next iteration on
.Read()
//we've now come to end of resultset, thanks to the DataBind()
//count is still 1 

You could do this instead:

if (reader.HasRows)
{
    rep.DataSource = reader;
    rep.DataBind();
}
int count = rep.Items.Count; //somehow count the num rows/items `rep` has.

How to properly set the 100% DIV height to match document/window height?

You could make it absolute and put zeros to top and bottom that is:

#fullHeightDiv {
    position: absolute;
    top: 0;
    bottom: 0;
}

Change user-agent for Selenium web-driver

To build on Louis's helpful answer...

Setting the User Agent in PhantomJS

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
...
caps = DesiredCapabilities.PHANTOMJS
caps["phantomjs.page.settings.userAgent"] = "whatever you want"
driver = webdriver.PhantomJS(desired_capabilities=caps)

The only minor issue is that, unlike for Firefox and Chrome, this does not return your custom setting:

driver.execute_script("return navigator.userAgent")

So, if anyone figures out how to do that in PhantomJS, please edit my answer or add a comment below! Cheers.

Is it possible to deserialize XML into List<T>?

Yes, it does deserialize to List<>. No need to keep it in an array and wrap/encapsulate it in a list.

public class UserHolder
{
    private List<User> users = null;

    public UserHolder()
    {
    }

    [XmlElement("user")]
    public List<User> Users
    {
        get { return users; }
        set { users = value; }
    }
}

Deserializing code,

XmlSerializer xs = new XmlSerializer(typeof(UserHolder));
UserHolder uh = (UserHolder)xs.Deserialize(new StringReader(str));

How to allow only a number (digits and decimal point) to be typed in an input?

I wanted a directive that could be limited in range by min and max attributes like so:

<input type="text" integer min="1" max="10" />

so I wrote the following:

.directive('integer', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, elem, attr, ngModel) {
            if (!ngModel)
                return;

            function isValid(val) {
                if (val === "")
                    return true;

                var asInt = parseInt(val, 10);
                if (asInt === NaN || asInt.toString() !== val) {
                    return false;
                }

                var min = parseInt(attr.min);
                if (min !== NaN && asInt < min) {
                    return false;
                }

                var max = parseInt(attr.max);
                if (max !== NaN && max < asInt) {
                    return false;
                }

                return true;
            }

            var prev = scope.$eval(attr.ngModel);
            ngModel.$parsers.push(function (val) {
                // short-circuit infinite loop
                if (val === prev)
                    return val;

                if (!isValid(val)) {
                    ngModel.$setViewValue(prev);
                    ngModel.$render();
                    return prev;
                }

                prev = val;
                return val;
            });
        }
    };
});

How can I regenerate ios folder in React Native project?

? react-native eject

error Unrecognized command "eject". info Run "react-native --help" to see a list of all available commands.

? react-native upgrade --legacy true

error: unknown option `--legacy'

You can init a new project that's named the same in another folder and copy ios dir over:

inside YourProjectName directory

npx react-native init YourProjectName
mv YourProjectName/ios ios
rm -rf YourProjectName

Make sure you have clean git history before doing so, in case you need to revert

How to get a value from a cell of a dataframe?

It doesn't need to be complicated:

val = df.loc[df.wd==1, 'col_name'].values[0]

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

I was importing also some projects from VS2010 to VS 2012. I had the same errors. The errors disappeared when I set back Properties > Config. Properties > General > Platform Toolset to v100 (VS2010). That might not be the correct approach, however.

Android: I lost my android key store, what should I do?

You can create a new keystore, but the Android Market wont allow you to upload the apk as an update - worse still, if you try uploading the apk as a new app it will not allow it either as it knows there is a 'different' version of the same apk already in the market even if you delete your previous version from the market

Do your absolute best to find that keystore!!

When you find it, email it to yourself so you have a copy on your gmail that you can go and get in the case you loose it from your hard drive!

How could I put a border on my grid control in WPF?

If nesting your grid in a border control

<Border>
    <Grid>
    </Grid>
</Border>

does not do what you want, then you are going to have to make your own control template for the grid (or border) that DOES do what you want.

How to uninstall Anaconda completely from macOS

To uninstall Anaconda open a terminal window:

  1. Remove the entire anaconda installation directory:
rm -rf ~/anaconda
  1. Edit ~/.bash_profile and remove the anaconda directory from your PATH environment variable.

Note: You may need to edit .bashrc and/or .profile files instead of .bash_profile

  1. Remove the following hidden files and directories, which may have been created in the home directory:

    • .condarc
    • .conda
    • .continuum

Use:

rm -rf ~/.condarc ~/.conda ~/.continuum

What is the alternative for ~ (user's home directory) on Windows command prompt?

Simply

First Define Path

doskey ~=cd %homepath%

Then Access

~

How can I inspect the file system of a failed `docker build`?

What I would do is comment out the Dockerfile below and including the offending line. Then you can run the container and run the docker commands by hand, and look at the logs in the usual way. E.g. if the Dockerfile is

RUN foo
RUN bar
RUN baz

and it's dying at bar I would do

RUN foo
# RUN bar
# RUN baz

Then

$ docker build -t foo .
$ docker run -it foo bash
container# bar
...grep logs...

JavaScript check if value is only undefined, null or false

The best way to do it I think is:

if(val != true){
//do something
} 

This will be true if val is false, NaN, or undefined.

How to determine if a decimal/double is an integer?

You can use String formatting for the double type. Here is an example:

double val = 58.6547;
String.Format("{0:0.##}", val);      
//Output: "58.65"

double val = 58.6;
String.Format("{0:0.##}", val);      
//Output: "58.6"

double val = 58.0;
String.Format("{0:0.##}", val);      
//Output: "58"

Let me know if this doesn't help.

How to set tint for an image view programmatically in android?

Adding to ADev's answer (which in my opinion is the most correct), since the widespread adoption of Kotlin, and its useful extension functions:

fun ImageView.setTint(context: Context, @ColorRes colorId: Int) {
    val color = ContextCompat.getColor(context, colorId)
    val colorStateList = ColorStateList.valueOf(color)
    ImageViewCompat.setImageTintList(this, colorStateList)
}

I think this is a function which could be useful to have in any Android project!

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

No prompt use:

dir /x

Procure o nome reduzido do diretório na linha do "Program Files (x86)"

27/08/2018  15:07    <DIR>          PROGRA~2     Program Files (x86)

Coloque a seguinte configuração em php.ini para a opção:

extension_dir="C:\PROGRA~2\path\to\php\ext"

Acredito que isso resolverá seu problema.

Zorro

How can I style even and odd elements?

_x000D_
_x000D_
li:nth-child(1n) { color:green; }_x000D_
li:nth-child(2n) { color:red; }
_x000D_
<ul>_x000D_
  <li>list element 1</li>_x000D_
  <li>list element 2</li>_x000D_
  <li>list element 3</li>_x000D_
  <li>list element 4</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

See browser support here : CSS3 :nth-child() Selector

How should I copy Strings in Java?

Since strings are immutable, both versions are safe. The latter, however, is less efficient (it creates an extra object and in some cases copies the character data).

With this in mind, the first version should be preferred.

Two onClick actions one button

<input type="button" value="..." onClick="fbLikeDump(); WriteCookie();" />

jQuery lose focus event

If the 'Cool Options' are hidden from the view before the field is focused then you would want to create this in JQuery instead of having it in the DOM so anyone using a screen reader wouldn't see unnecessary information. Why should they have to listen to it when we don't have to see it?

So you can setup variables like so:

var $coolOptions= $("<div id='options'></div>").text("Some cool options");

and then append (or prepend) on focus

$("input[name='input_name']").focus(function() {
    $(this).append($coolOptions);
});

and then remove when the focus ends

$("input[name='input_name']").focusout(function() {
    $('#options').remove();
});

DateTimePicker time picker in 24 hour but displaying in 12hr?

this will display current ate & time. Working on my side perfectly

$("#datePicker").datetimepicker({
    format: 'DD-MM-YYYY HH:mm A',
    defaultDate: new Date(),
});

List all devices, partitions and volumes in Powershell

Firstly, on Unix you use mount, not ls /mnt: many things are not mounted in /mnt.

Anyhow, there's the mountvol DOS command, which continues to work in Powershell, and there's the Powershell-specific Get-PSDrive.

How to remove anaconda from windows completely?

It looks that some files are still left and some registry keys are left. So you can run revocleaner tool to remove those entries as well. Do a reboot and install again it should be doing it now. I also faced issue and by complete cleaning I got Rid of it.

How to generate a random string of 20 characters

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

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

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

Conversion from List<T> to array T[]

Use ToArray() on List<T>.

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

With PowerShell 5.1 in Windows 10 you can use:

Get-SmbMapping | Remove-SmbMapping -Confirm:$false

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

You can either:

1) Pass raw arguments and use the {0} syntax. E.g:

DbContext.Database.SqlQuery("StoredProcedureName {0}", paramName);

2) Pass DbParameter subclass arguments and use @ParamName syntax.

DbContext.Database.SqlQuery("StoredProcedureName @ParamName", 
                                   new SqlParameter("@ParamName", paramValue);

If you use the first syntax, EF will actually wrap your arguments with DbParamater classes, assign them names, and replace {0} with the generated parameter name.

The first syntax if preferred because you don't need to use a factory or know what type of DbParamaters to create (SqlParameter, OracleParamter, etc.).

Android Pop-up message

If you want a Popup that closes automatically, you should look for Toasts. But if you want a dialog that the user has to close first before proceeding, you should look for a Dialog.

For both approaches it is possible to read a text file with the text you want to display. But you could also hardcode the text or use R.String to set the text.

How to connect to LocalDB in Visual Studio Server Explorer?

OK, answering to my own question.

Steps to connect LocalDB to Visual Studio Server Explorer

  1. Open command prompt
  2. Run SqlLocalDB.exe start v11.0
  3. Run SqlLocalDB.exe info v11.0
  4. Copy the Instance pipe name that starts with np:\...
  5. In Visual Studio select TOOLS > Connect to Database...
  6. For Server Name enter (localdb)\v11.0. If it didn't work, use the Instance pipe name that you copied earlier. You can also use this to connect with SQL Management Studio.
  7. Select the database on next dropdown list
  8. Click OK

enter image description here

What is the difference between AF_INET and PF_INET in socket programming?

AF_INET = Address Format, Internet = IP Addresses

PF_INET = Packet Format, Internet = IP, TCP/IP or UDP/IP

AF_INET is the address family that is used for the socket you're creating (in this case an Internet Protocol address). The Linux kernel, for example, supports 29 other address families such as UNIX sockets and IPX, and also communications with IRDA and Bluetooth (AF_IRDA and AF_BLUETOOTH, but it is doubtful you'll use these at such a low level).

For the most part sticking with AF_INET for socket programming over a network is the safest option.

Meaning, AF_INET refers to addresses from the internet, IP addresses specifically.

PF_INET refers to anything in the protocol, usually sockets/ports.

"Instantiating" a List in Java?

Use List<Integer> list = new ArrayList<Integer>();

How do I copy directories recursively with gulp?

If you want to copy the entire contents of a folder recursively into another folder, you can execute the following windows command from gulp:

xcopy /path/to/srcfolder /path/to/destfolder /s /e /y

The /y option at the end is to suppress the overwrite confirmation message.

In Linux, you can execute the following command from gulp:

cp -R /path/to/srcfolder /path/to/destfolder

you can use gulp-exec or gulp-run plugin to execute system commands from gulp.

Related Links:

  1. xcopy usage

  2. gulp-exec and gulp-run

HTML tag <a> want to add both href and onclick working

Use ng-click in place of onclick. and its as simple as that:

<a href="www.mysite.com" ng-click="return theFunction();">Item</a>

<script type="text/javascript">
function theFunction () {
    // return true or false, depending on whether you want to allow 
    // the`href` property to follow through or not
 }
</script>

Download a file with Android, and showing the progress in a ProgressDialog

You can observer the progress of the download manager using LiveData and coroutines, see the gist below

https://gist.github.com/FhdAlotaibi/678eb1f4fa94475daf74ac491874fc0e

data class DownloadItem(val bytesDownloadedSoFar: Long = -1, val totalSizeBytes: Long = -1, val status: Int)

class DownloadProgressLiveData(private val application: Application, private val requestId: Long) : LiveData<DownloadItem>(), CoroutineScope {

    private val downloadManager by lazy {
        application.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
    }

    private val job = Job()

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.IO + job

    override fun onActive() {
        super.onActive()
        launch {
            while (isActive) {
                val query = DownloadManager.Query().setFilterById(requestId)
                val cursor = downloadManager.query(query)
                if (cursor.moveToFirst()) {
                    val status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
                    Timber.d("Status $status")
                    when (status) {
                        DownloadManager.STATUS_SUCCESSFUL,
                        DownloadManager.STATUS_PENDING,
                        DownloadManager.STATUS_FAILED,
                        DownloadManager.STATUS_PAUSED -> postValue(DownloadItem(status = status))
                        else -> {
                            val bytesDownloadedSoFar = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
                            val totalSizeBytes = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
                            postValue(DownloadItem(bytesDownloadedSoFar.toLong(), totalSizeBytes.toLong(), status))
                        }
                    }
                    if (status == DownloadManager.STATUS_SUCCESSFUL || status == DownloadManager.STATUS_FAILED)
                        cancel()
                } else {
                    postValue(DownloadItem(status = DownloadManager.STATUS_FAILED))
                    cancel()
                }
                cursor.close()
                delay(300)
            }
        }
    }

    override fun onInactive() {
        super.onInactive()
        job.cancel()
    }

}

How to order citations by appearance using BibTeX?

Just a brief note - I'm using a modified version of plain.bst sitting in the directory with my Latex files; it turns out having sorting by order of appearance is a relatively easy change; just find the piece of code:

...
ITERATE {presort}

SORT
...

... and comment it - I turned it to:

...
%% % avoid sort:
%% ITERATE {presort}
%%
%% SORT
...

... and then, after running bibtex, pdflatex, pdflatex - the citations will be sorted by order of appearance (that is, they will be unsorted :) ).

Cheers!

EDIT: just realized that what I wrote is actually in the comment by @ChrisN: "can you edit it to remove the SORT command" ;)

Where can I find my Facebook application id and secret key?

Dashboard -> [your app] -> [View Details] -> Settings -> Basic

source

What is the Simplest Way to Reverse an ArrayList?

We can also do the same using java 8.

public static<T> List<T> reverseList(List<T> list) {
        List<T> reverse = new ArrayList<>(list.size());

        list.stream()
                .collect(Collectors.toCollection(LinkedList::new))
                .descendingIterator()
                .forEachRemaining(reverse::add);

        return reverse;
    }

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

I prefer to use the FindItem method and use the value path for locating the item. Make sure your PathSeparator property on the menu matches what you're using in FindItem parameter.

    protected void Page_Load(object sender, EventArgs e)
    {

        // remove manage user accounts menu item for non-admin users.
        if (!Page.User.IsInRole("Admin"))
        {
            MenuItem item = NavigationMenu.FindItem("Users/Manage Accounts");
            item.Parent.ChildItems.Remove(item);  
        }

    }

Is it possible to set a custom font for entire of application?

Yes, its possible to set the font to the entire application.

The easiest way to accomplish this is to package the desired font(s) with your application.

To do this, simply create an assets/ folder in the project root, and put your fonts (in TrueType, or TTF, form) in the assets.

You might, for example, create assets/fonts/ and put your TTF files in there.

public class FontSampler extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TextView tv=(TextView)findViewById(R.id.custom);

Typeface face=Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");
tv.setTypeface(face);
}
}

Implementing Singleton with an Enum (in Java)

In this Java best practices book by Joshua Bloch, you can find explained why you should enforce the Singleton property with a private constructor or an Enum type. The chapter is quite long, so keeping it summarized:

Making a class a Singleton can make it difficult to test its clients, as it’s impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type. Recommended approach is implement Singletons by simply make an enum type with one element:

// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}

This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks.

While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

Reorder / reset auto increment primary key

SELECT * from `user` ORDER BY `user_id`; 

SET @count = 0;

UPDATE `user`  SET `user_id` = @count:= @count + 1;

ALTER TABLE `user_id` AUTO_INCREMENT = 1;

if you want to order by

How to select count with Laravel's fluent query builder?

You can use an array in the select() to define more columns and you can use the DB::raw() there with aliasing it to followers. Should look like this:

$query = DB::table('category_issue')
    ->select(array('issues.*', DB::raw('COUNT(issue_subscriptions.issue_id) as followers')))
    ->where('category_id', '=', 1)
    ->join('issues', 'category_issue.issue_id', '=', 'issues.id')
    ->left_join('issue_subscriptions', 'issues.id', '=', 'issue_subscriptions.issue_id')
    ->group_by('issues.id')
    ->order_by('followers', 'desc')
    ->get();

rails bundle clean

I assume you install gems into vendor/bundle? If so, why not just delete all the gems and do a clean bundle install?

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

How to get the pure text without HTML element using JavaScript?

Depending on what you need, you can use either element.innerText or element.textContent. They differ in many ways. innerText tries to approximate what would happen if you would select what you see (rendered html) and copy it to the clipboard, while textContent sort of just strips the html tags and gives you what's left.

innerText is not just used for IE anymore, and it is supported in all major browsers. Of course, unlike textContent, it has compatability with old IE browsers (since they came up with it).

Complete example (from Gabi's answer):

var element = document.getElementById('txt');
var text = element.innerText || element.textContent; // or element.textContent || element.innerText
element.innerHTML = text;

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Session.Abandon() destroys the session and the Session_OnEnd event is triggered.

Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.

So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.

Use Session.Clear(), if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.

What's the difference between equal?, eql?, ===, and ==?

I wrote a simple test for all the above.

def eq(a, b)
  puts "#{[a, '==',  b]} : #{a == b}"
  puts "#{[a, '===', b]} : #{a === b}"
  puts "#{[a, '.eql?', b]} : #{a.eql?(b)}"
  puts "#{[a, '.equal?', b]} : #{a.equal?(b)}"
end

eq("all", "all")
eq(:all, :all)
eq(Object.new, Object.new)
eq(3, 3)
eq(1, 1.0)

Create a new txt file using VB.NET

You can try writing into the Documents folder. Here is a "debug" function I did for the debugging needs of my project:

Private Sub writeDebug(ByVal x As String)
    Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
    Dim FILE_NAME As String = path & "\mydebug.txt"
    MsgBox(FILE_NAME)
    If System.IO.File.Exists(FILE_NAME) = False Then
        System.IO.File.Create(FILE_NAME).Dispose()
    End If
    Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
    objWriter.WriteLine(x)
    objWriter.Close()
End Sub

There are more standard folders you can access through the "SpecialFolder" object.

DataGridView.Clear()

I don't like messing with the DataSource personally so after discussing the issue with an IT friend I was able to discover this way which is simple and doesn't effect the DataSource. Hope this helps!

foreach (DataGridViewRow row in dataGridView1.Rows) 
{
    foreach (DataGridViewCell cell in row.Cells)
    {
        cell.Value = "";
    }
}

What's the difference between SoftReference and WeakReference in Java?

From Understanding Weak References, by Ethan Nicholas:

Weak references

A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself. You create a weak reference like this:

WeakReference weakWidget = new WeakReference(widget);

and then elsewhere in the code you can use weakWidget.get() to get the actual Widget object. Of course the weak reference isn't strong enough to prevent garbage collection, so you may find (if there are no strong references to the widget) that weakWidget.get() suddenly starts returning null.

...

Soft references

A soft reference is exactly like a weak reference, except that it is less eager to throw away the object to which it refers. An object which is only weakly reachable (the strongest references to it are WeakReferences) will be discarded at the next garbage collection cycle, but an object which is softly reachable will generally stick around for a while.

SoftReferences aren't required to behave any differently than WeakReferences, but in practice softly reachable objects are generally retained as long as memory is in plentiful supply. This makes them an excellent foundation for a cache, such as the image cache described above, since you can let the garbage collector worry about both how reachable the objects are (a strongly reachable object will never be removed from the cache) and how badly it needs the memory they are consuming.

And Peter Kessler added in a comment:

The Sun JRE does treat SoftReferences differently from WeakReferences. We attempt to hold on to object referenced by a SoftReference if there isn't pressure on the available memory. One detail: the policy for the "-client" and "-server" JRE's are different: the -client JRE tries to keep your footprint small by preferring to clear SoftReferences rather than expand the heap, whereas the -server JRE tries to keep your performance high by preferring to expand the heap (if possible) rather than clear SoftReferences. One size does not fit all.

How to get last N records with activerecord?

Let's say N = 5 and your model is Message, you can do something like this:

Message.order(id: :asc).from(Message.all.order(id: :desc).limit(5), :messages)

Look at the sql:

SELECT "messages".* FROM (
  SELECT  "messages".* FROM "messages"  ORDER BY "messages"."created_at" DESC LIMIT 5
) messages  ORDER BY "messages"."created_at" ASC

The key is the subselect. First we need to define what are the last messages we want and then we have to order them in ascending order.

Resolve build errors due to circular dependency amongst classes

I've written a post about this once: Resolving circular dependencies in c++

The basic technique is to decouple the classes using interfaces. So in your case:

//Printer.h
class Printer {
public:
    virtual Print() = 0;
}

//A.h
#include "Printer.h"
class A: public Printer
{
    int _val;
    Printer *_b;
public:

    A(int val)
        :_val(val)
    {
    }

    void SetB(Printer *b)
    {
        _b = b;
        _b->Print();
    }

    void Print()
    {
        cout<<"Type:A val="<<_val<<endl;
    }
};

//B.h
#include "Printer.h"
class B: public Printer
{
    double _val;
    Printer* _a;
public:

    B(double val)
        :_val(val)
    {
    }

    void SetA(Printer *a)
    {
        _a = a;
        _a->Print();
    }

    void Print()
    {
        cout<<"Type:B val="<<_val<<endl;
    }
};

//main.cpp
#include <iostream>
#include "A.h"
#include "B.h"

int main(int argc, char* argv[])
{
    A a(10);
    B b(3.14);
    a.Print();
    a.SetB(&b);
    b.Print();
    b.SetA(&a);
    return 0;
}

Python TypeError: not enough arguments for format string

You need to put the format arguments into a tuple (add parentheses):

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)

What you currently have is equivalent to the following:

intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl

Example:

>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'

Difference between private, public, and protected inheritance

I found an easy answer and so thought of posting it for my future reference too.

Its from the links http://www.learncpp.com/cpp-tutorial/115-inheritance-and-access-specifiers/

class Base
{
public:
    int m_nPublic; // can be accessed by anybody
private:
    int m_nPrivate; // can only be accessed by Base member functions (but not derived classes)
protected:
    int m_nProtected; // can be accessed by Base member functions, or derived classes.
};

class Derived: public Base
{
public:
    Derived()
    {
        // Derived's access to Base members is not influenced by the type of inheritance used,
        // so the following is always true:

        m_nPublic = 1; // allowed: can access public base members from derived class
        m_nPrivate = 2; // not allowed: can not access private base members from derived class
        m_nProtected = 3; // allowed: can access protected base members from derived class
    }
};

int main()
{
    Base cBase;
    cBase.m_nPublic = 1; // allowed: can access public members from outside class
    cBase.m_nPrivate = 2; // not allowed: can not access private members from outside class
    cBase.m_nProtected = 3; // not allowed: can not access protected members from outside class
}

JavaScript Promises - reject vs. throw

There is no advantage of using one vs the other, but, there is a specific case where throw won't work. However, those cases can be fixed.

Any time you are inside of a promise callback, you can use throw. However, if you're in any other asynchronous callback, you must use reject.

For example, this won't trigger the catch:

_x000D_
_x000D_
new Promise(function() {
  setTimeout(function() {
    throw 'or nah';
    // return Promise.reject('or nah'); also won't work
  }, 1000);
}).catch(function(e) {
  console.log(e); // doesn't happen
});
_x000D_
_x000D_
_x000D_

Instead you're left with an unresolved promise and an uncaught exception. That is a case where you would want to instead use reject. However, you could fix this in two ways.

  1. by using the original Promise's reject function inside the timeout:

_x000D_
_x000D_
new Promise(function(resolve, reject) {
  setTimeout(function() {
    reject('or nah');
  }, 1000);
}).catch(function(e) {
  console.log(e); // works!
});
_x000D_
_x000D_
_x000D_

  1. by promisifying the timeout:

_x000D_
_x000D_
function timeout(duration) { // Thanks joews
  return new Promise(function(resolve) {
    setTimeout(resolve, duration);
  });
}

timeout(1000).then(function() {
  throw 'worky!';
  // return Promise.reject('worky'); also works
}).catch(function(e) {
  console.log(e); // 'worky!'
});
_x000D_
_x000D_
_x000D_

Inheritance with base class constructor with parameters

I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.

public bar(int a, int b) : base(a, b)
{
     c = a * b;
}

This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.

How to convert an int value to string in Go?

Use the strconv package's Itoa function.

For example:

package main

import (
    "strconv"
    "fmt"
)

func main() {
    t := strconv.Itoa(123)
    fmt.Println(t)
}

You can concat strings simply by +'ing them, or by using the Join function of the strings package.

Call a method of a controller from another controller using 'scope' in AngularJS

The best approach for you to communicate between the two controllers is to use events.

Scope Documentation

In this check out $on, $broadcast and $emit.

In general use case the usage of angular.element(catapp).scope() was designed for use outside the angular controllers, like within jquery events.

Ideally in your usage you would write an event in controller 1 as:

$scope.$on("myEvent", function (event, args) {
   $scope.rest_id = args.username;
   $scope.getMainCategories();
});

And in the second controller you'd just do

$scope.initRestId = function(){
   $scope.$broadcast("myEvent", {username: $scope.user.username });
};

Edit: Realised it was communication between two modules

Can you try including the firstApp module as a dependency to the secondApp where you declare the angular.module. That way you can communicate to the other app.

Send FormData and String Data Together Through JQuery AJAX?

For multiple files in ajax try this

        var url = "your_url";
        var data = $('#form').serialize();
        var form_data = new FormData(); 
        //get the length of file inputs   
        var length = $('input[type="file"]').length; 

        for(var i = 0;i<length;i++){
           file_data = $('input[type="file"]')[i].files;

            form_data.append("file_"+i, file_data[0]);
        }

            // for other data
            form_data.append("data",data);


        $.ajax({
                url: url,
                type: "POST",
                data: form_data,
                cache: false,
                contentType: false, //important
                processData: false, //important
                success: function (data) {
                  //do something
                }
        })

In php

        parse_str($_POST['data'], $_POST); 
        for($i=0;$i<count($_FILES);$i++){
              if(isset($_FILES['file_'.$i])){
                   $file = $_FILES['file_'.$i];
                   $file_name = $file['name'];
                   $file_type = $file ['type'];
                   $file_size = $file ['size'];
                   $file_path = $file ['tmp_name'];
              }
        }

If statement within Where clause

You can't use IF like that. You can do what you want with AND and OR:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE ((status_flag = STATUS_ACTIVE   AND t.status = 'A')
     OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
     OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
     OR (source_flag = SOURCE_USER     AND t.business_unit = 'users'))
   AND t.first_name LIKE firstname
   AND t.last_name  LIKE lastname
   AND t.employid   LIKE employeeid;

Turn off display errors using file "php.ini"

Turn if off:

You can use error_reporting(); or put an @ in front of your fileopen().

json: cannot unmarshal object into Go value of type

You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.

Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.

FB OpenGraph og:image not pulling images (possibly https?)

I don't know, if it's only with me but for me og:image does not work and it picks my site logo, even though facebook debugger shows the correct image.

But changing og:image to og:image:url worked for me. Hope this helps anybody else facing similar issue.

Pandas "Can only compare identically-labeled DataFrame objects" error

You can also try dropping the index column if it is not needed to compare:

print(df1.reset_index(drop=True) == df2.reset_index(drop=True))

I have used this same technique in a unit test like so:

from pandas.util.testing import assert_frame_equal

assert_frame_equal(actual.reset_index(drop=True), expected.reset_index(drop=True))

How to change navigation bar color in iOS 7 or 6?

In iOS7, if your navigation controller is contained in tab bar, splitview or some other container, then for globally changing navigationbar appearance use following method ::

[[UINavigationBar appearanceWhenContainedIn:[UITabBarController class],nil] setBarTintColor:[UIColor blueColor]];

MINGW64 "make build" error: "bash: make: command not found"

Try using cmake itself. In the build directory, run:

cmake --build .

getting error while updating Composer

In php7.2 Ubuntu 18.04 LTS and ubuntu 19.04

sudo apt-get install php-gd php-xml php7.2-mbstring

Works like a Charm

Algorithm to randomly generate an aesthetically-pleasing color palette

Here is quick and dirty color generator in C# (using 'RYB approach' described in this article). It's a rewrite from JavaScript.

Use:

List<Color> ColorPalette = ColorGenerator.Generate(30).ToList();

First two colors tend to be white and a shade of black. I often skip them like this (using Linq):

List<Color> ColorsPalette = ColorGenerator
            .Generate(30)
            .Skip(2) // skip white and black
            .ToList(); 

Implementation:

public static class ColorGenerator
{

    // RYB color space
    private static class RYB
    {
        private static readonly double[] White = { 1, 1, 1 };
        private static readonly double[] Red = { 1, 0, 0 };
        private static readonly double[] Yellow = { 1, 1, 0 };
        private static readonly double[] Blue = { 0.163, 0.373, 0.6 };
        private static readonly double[] Violet = { 0.5, 0, 0.5 };
        private static readonly double[] Green = { 0, 0.66, 0.2 };
        private static readonly double[] Orange = { 1, 0.5, 0 };
        private static readonly double[] Black = { 0.2, 0.094, 0.0 };

        public static double[] ToRgb(double r, double y, double b)
        {
            var rgb = new double[3];
            for (int i = 0; i < 3; i++)
            {
                rgb[i] = White[i]  * (1.0 - r) * (1.0 - b) * (1.0 - y) +
                         Red[i]    * r         * (1.0 - b) * (1.0 - y) +
                         Blue[i]   * (1.0 - r) * b         * (1.0 - y) +
                         Violet[i] * r         * b         * (1.0 - y) +
                         Yellow[i] * (1.0 - r) * (1.0 - b) *        y +
                         Orange[i] * r         * (1.0 - b) *        y +
                         Green[i]  * (1.0 - r) * b         *        y +
                         Black[i]  * r         * b         *        y;
            }

            return rgb;
        }
    }

    private class Points : IEnumerable<double[]>
    {
        private readonly int pointsCount;
        private double[] picked;
        private int pickedCount;

        private readonly List<double[]> points = new List<double[]>();

        public Points(int count)
        {
            pointsCount = count;
        }

        private void Generate()
        {
            points.Clear();
            var numBase = (int)Math.Ceiling(Math.Pow(pointsCount, 1.0 / 3.0));
            var ceil = (int)Math.Pow(numBase, 3.0);
            for (int i = 0; i < ceil; i++)
            {
                points.Add(new[]
                {
                    Math.Floor(i/(double)(numBase*numBase))/ (numBase - 1.0),
                    Math.Floor((i/(double)numBase) % numBase)/ (numBase - 1.0),
                    Math.Floor((double)(i % numBase))/ (numBase - 1.0),
                });
            }
        }

        private double Distance(double[] p1)
        {
            double distance = 0;
            for (int i = 0; i < 3; i++)
            {
                distance += Math.Pow(p1[i] - picked[i], 2.0);
            }

            return distance;
        }

        private double[] Pick()
        {
            if (picked == null)
            {
                picked = points[0];
                points.RemoveAt(0);
                pickedCount = 1;
                return picked;
            }

            var d1 = Distance(points[0]);
            int i1 = 0, i2 = 0;
            foreach (var point in points)
            {
                var d2 = Distance(point);
                if (d1 < d2)
                {
                    i1 = i2;
                    d1 = d2;
                }

                i2 += 1;
            }

            var pick = points[i1];
            points.RemoveAt(i1);

            for (int i = 0; i < 3; i++)
            {
                picked[i] = (pickedCount * picked[i] + pick[i]) / (pickedCount + 1.0);
            }

            pickedCount += 1;
            return pick;
        }

        public IEnumerator<double[]> GetEnumerator()
        {
            Generate();
            for (int i = 0; i < pointsCount; i++)
            {
                yield return Pick();
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    public static IEnumerable<Color> Generate(int numOfColors)
    {
        var points = new Points(numOfColors);

        foreach (var point in points)
        {
            var rgb = RYB.ToRgb(point[0], point[1], point[2]);
            yield return Color.FromArgb(
                (int)Math.Floor(255 * rgb[0]),
                (int)Math.Floor(255 * rgb[1]),
                (int)Math.Floor(255 * rgb[2]));
        }
    }
}

Difference between DTO, VO, POJO, JavaBeans?

First Talk About

Normal Class - that's mean any class define that's a normally in java it's means you create different type of method properties etc.
Bean - Bean is nothing it's only a object of that particular class using this bean you can access your java class same as object..

and after that talk about last one POJO

POJO - POJO is that class which have no any services it's have only a default constructor and private property and those property for setting a value corresponding setter and getter methods. It's short form of Plain Java Object.

How to remove a Gitlab project?

It is hidden in Setting menu, section general (not repository!) at https://gitlab.com/$USER_NAME/$PROJECT_NAME/editand it again hidden in a section "Advance settings"- you need to click a "expand" button.

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

Tks Ramon Gil Moreno. Pasting in Terminal and then restarting R Studio did the trick:
write org.rstudio.RStudio force.LANG en_US.UTF-8

Environment: MAC OS High Sierra 10.13.1 // RStudio version 3.4.2 (2017-09-28) -- "Short Summer"

Ennio De Leon

Use of Finalize/Dispose method in C#

Dispose pattern:

public abstract class DisposableObject : IDisposable
{
    public bool Disposed { get; private set;}      

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~DisposableObject()
    {
        Dispose(false);
    }

    private void Dispose(bool disposing)
    {
        if (!Disposed)
        {
            if (disposing)
            {
                DisposeManagedResources();
            }

            DisposeUnmanagedResources();
            Disposed = true;
        }
    }

    protected virtual void DisposeManagedResources() { }
    protected virtual void DisposeUnmanagedResources() { }
}

Example of inheritance:

public class A : DisposableObject
{
    public Component components_a { get; set; }
    private IntPtr handle_a;

    protected override void DisposeManagedResources()
    {
        try
        {
          Console.WriteLine("A_DisposeManagedResources");
          components_a.Dispose();
          components_a = null;
        }
        finally
        { 
          base.DisposeManagedResources();
        }
    }

    protected override void DisposeUnmanagedResources()
    {
        try
        {
          Console.WriteLine("A_DisposeUnmanagedResources");
          CloseHandle(handle_a);
          handle_a = IntPtr.Zero;
        }
        finally
        { 
          base.DisposeUnmanagedResources();
        }
    }
}

public class B : A
{
    public Component components_b { get; set; }
    private IntPtr handle_b;

    protected override void DisposeManagedResources()
    {
        try
        {
          Console.WriteLine("B_DisposeManagedResources");
          components_b.Dispose();
          components_b = null;
        }
        finally
        { 
          base.DisposeManagedResources();
        }
    }

    protected override void DisposeUnmanagedResources()
    {
        try
        {
          Console.WriteLine("B_DisposeUnmanagedResources");
          CloseHandle(handle_b);
          handle_b = IntPtr.Zero;
        }
        finally
        { 
          base.DisposeUnmanagedResources();
        }
    }
}

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

Use build job plugin for that task in order to trigger other jobs from jenkins file. You can add variety of logic to your execution such as parallel ,node and agents options and steps for triggering external jobs. I gave some easy-to-read cookbook example for that.

1.example for triggering external job from jenkins file with conditional example:

if (env.BRANCH_NAME == 'master') {
  build job:'exactJobName' , parameters:[
    string(name: 'keyNameOfParam1',value: 'valueOfParam1')
    booleanParam(name: 'keyNameOfParam2',value:'valueOfParam2')
 ]
}

2.example triggering multiple jobs from jenkins file with conditionals example:

 def jobs =[
    'job1Title'{
    if (env.BRANCH_NAME == 'master') {
      build job:'exactJobName' , parameters:[
        string(name: 'keyNameOfParam1',value: 'valueNameOfParam1')
        booleanParam(name: 'keyNameOfParam2',value:'valueNameOfParam2')
     ]
    }
},
    'job2Title'{
    if (env.GIT_COMMIT == 'someCommitHashToPerformAdditionalTest') {
      build job:'exactJobName' , parameters:[
        string(name: 'keyNameOfParam3',value: 'valueOfParam3')
        booleanParam(name: 'keyNameOfParam4',value:'valueNameOfParam4')
        booleanParam(name: 'keyNameOfParam5',value:'valueNameOfParam5')
     ]
    }
}

What are the differences between virtual memory and physical memory?

Softwares run on the OS on a very simple premise - they require memory. The device OS provides it in the form of RAM. The amount of memory required may vary - some softwares need huge memory, some require paltry memory. Most (if not all) users run multiple applications on the OS simultaneously, and given that memory is expensive (and device size is finite), the amount of memory available is always limited. So given that all softwares require a certain amount of RAM, and all of them can be made to run at the same time, OS has to take care of two things:

  1. That the software always runs until user aborts it, i.e. it should not auto-abort because OS has run out of memory.
  2. The above activity, while maintaining a respectable performance for the softwares running.

Now the main question boils down to how the memory is being managed. What exactly governs where in the memory will the data belonging to a given software reside?

Possible solution 1: Let individual softwares specify explicitly the memory address they will use in the device. Suppose Photoshop declares that it will always use memory addresses ranging from 0 to 1023 (imagine the memory as a linear array of bytes, so first byte is at location 0, 1024th byte is at location 1023) - i.e. occupying 1 GB memory. Similarly, VLC declares that it will occupy memory range 1244 to 1876, etc.

Advantages:

  1. Every application is pre-assigned a memory slot, so when it is installed and executed, it just stores its data in that memory area, and everything works fine.

Disadvantages:

  1. This does not scale. Theoretically, an app may require a huge amount of memory when it is doing something really heavy-duty. So to ensure that it never runs out of memory, the memory area allocated to it must always be more than or equal to that amount of memory. What if a software, whose maximal theoretical memory usage is 2 GB (hence requiring 2 GB memory allocation from RAM), is installed in a machine with only 1 GB memory? Should the software just abort on startup, saying that the available RAM is less than 2 GB? Or should it continue, and the moment the memory required exceeds 2 GB, just abort and bail out with the message that not enough memory is available?

  2. It is not possible to prevent memory mangling. There are millions of softwares out there, even if each of them was allotted just 1 kB memory, the total memory required would exceed 16 GB, which is more than most devices offer. How can, then, different softwares be allotted memory slots that do not encroach upon each other's areas? Firstly, there is no centralized software market which can regulate that when a new software is being released, it must assign itself this much memory from this yet unoccupied area, and secondly, even if there were, it is not possible to do it because the no. of softwares is practically infinite (thus requiring infinite memory to accommodate all of them), and the total RAM available on any device is not sufficient to accommodate even a fraction of what is required, thus making inevitable the encroaching of the memory bounds of one software upon that of another. So what happens when Photoshop is assigned memory locations 1 to 1023 and VLC is assigned 1000 to 1676? What if Photoshop stores some data at location 1008, then VLC overwrites that with its own data, and later Photoshop accesses it thinking that it is the same data is had stored there previously? As you can imagine, bad things will happen.

So clearly, as you can see, this idea is rather naive.

Possible solution 2: Let's try another scheme - where OS will do majority of the memory management. Softwares, whenever they require any memory, will just request the OS, and the OS will accommodate accordingly. Say OS ensures that whenever a new process is requesting for memory, it will allocate the memory from the lowest byte address possible (as said earlier, RAM can be imagined as a linear array of bytes, so for a 4 GB RAM, the addresses range for a byte from 0 to 2^32-1) if the process is starting, else if it is a running process requesting the memory, it will allocate from the last memory location where that process still resides. Since the softwares will be emitting addresses without considering what the actual memory address is going to be where that data is stored, OS will have to maintain a mapping, per software, of the address emitted by the software to the actual physical address (Note: that is one of the two reasons we call this concept Virtual Memory. Softwares are not caring about the real memory address where their data are getting stored, they just spit out addresses on the fly, and the OS finds the right place to fit it and find it later if required).

Say the device has just been turned on, OS has just launched, right now there is no other process running (ignoring the OS, which is also a process!), and you decide to launch VLC. So VLC is allocated a part of the RAM from the lowest byte addresses. Good. Now while the video is running, you need to start your browser to view some webpage. Then you need to launch Notepad to scribble some text. And then Eclipse to do some coding.. Pretty soon your memory of 4 GB is all used up, and the RAM looks like this:

                                   enter image description here

Problem 1: Now you cannot start any other process, for all RAM is used up. Thus programs have to be written keeping the maximum memory available in mind (practically even less will be available, as other softwares will be running parallelly as well!). In other words, you cannot run a high-memory consuming app in your ramshackle 1 GB PC.

Okay, so now you decide that you no longer need to keep Eclipse and Chrome open, you close them to free up some memory. The space occupied in RAM by those processes is reclaimed by OS, and it looks like this now:

                                    enter image description here

Suppose that closing these two frees up 700 MB space - (400 + 300) MB. Now you need to launch Opera, which will take up 450 MB space. Well, you do have more than 450 MB space available in total, but...it is not contiguous, it is divided into individual chunks, none of which is big enough to fit 450 MB. So you hit upon a brilliant idea, let's move all the processes below to as much above as possible, which will leave the 700 MB empty space in one chunk at the bottom. This is called compaction. Great, except that...all the processes which are there are running. Moving them will mean moving the address of all their contents (remember, OS maintains a mapping of the memory spat out by the software to the actual memory address. Imagine software had spat out an address of 45 with data 123, and OS had stored it in location 2012 and created an entry in the map, mapping 45 to 2012. If the software is now moved in memory, what used to be at location 2012 will no longer be at 2012, but in a new location, and OS has to update the map accordingly to map 45 to the new address, so that the software can get the expected data (123) when it queries for memory location 45. As far as the software is concerned, all it knows is that address 45 contains the data 123!)! Imagine a process that is referencing a local variable i. By the time it is accessed again, its address has changed, and it won't be able to find it any more. The same will hold for all functions, objects, variables, basically everything has an address, and moving a process will mean changing the address of all of them. Which leads us to:

Problem 2: You cannot move a process. The values of all variables, functions and objects within that process have hardcoded values as spat out by the compiler during compilation, the process depends on them being at the same location during its lifetime, and changing them is expensive. As a result, processes leave behind big "holes" when they exit. This is called External Fragmentation.

Fine. Suppose somehow, by some miraculous manner, you do manage to move the processes up. Now there is 700 MB of free space at the bottom:

                        enter image description here

Opera smoothly fits in at the bottom. Now your RAM looks like this:

                                    enter image description here

Good. Everything is looking fine. However, there is not much space left, and now you need to launch Chrome again, a known memory-hog! It needs lots of memory to start, and you have hardly any left...Except.. you now notice that some of the processes, which were initially occupying large space, now is not needing much space. May be you have stopped your video in VLC, hence it is still occupying some space, but not as much as it required while running a high resolution video. Similarly for Notepad and Photos. Your RAM now looks like this:

                                        enter image description here

Holes, once again! Back to square one! Except, previously, the holes occurred due to processes terminating, now it is due to processes requiring less space than before! And you again have the same problem, the holes combined yield more space than required, but they are scattered around, not much of use in isolation. So you have to move those processes again, an expensive operation, and a very frequent one at that, since processes will frequently reduce in size over their lifetime.

Problem 3: Processes, over their lifetime, may reduce in size, leaving behind unused space, which if needed to be used, will require the expensive operation of moving many processes. This is called Internal Fragmentation.

Fine, so now, your OS does the required thing, moves processes around and start Chrome and after some time, your RAM looks like this:

enter image description here

Cool. Now suppose you again resume watching Avatar in VLC. Its memory requirement will shoot up! But...there is no space left for it to grow, as Notepad is snuggled at its bottom. So, again, all processes has to move below until VLC has found sufficient space!

Problem 4: If processes needs to grow, it will be a very expensive operation

Fine. Now suppose, Photos is being used to load some photos from an external hard disk. Accessing hard-disk takes you from the realm of caches and RAM to that of disk, which is slower by orders of magnitudes. Painfully, irrevocably, transcendentally slower. It is an I/O operation, which means it is not CPU bound (it is rather the exact opposite), which means it does not need to occupy RAM right now. However, it still occupies RAM stubbornly. If you want to launch Firefox in the meantime, you can't, because there is not much memory available, whereas if Photos was taken out of memory for the duration of its I/O bound activity, it would have freed lot of memory, followed by (expensive) compaction, followed by Firefox fitting in.

Problem 5: I/O bound jobs keep on occupying RAM, leading to under-utilization of RAM, which could have been used by CPU bound jobs in the meantime.

So, as we can see, we have so many problems even with the approach of virtual memory.


There are two approaches to tackle these problems - paging and segmentation. Let us discuss paging. In this approach, the virtual address space of a process is mapped to the physical memory in chunks - called pages. A typical page size is 4 kB. The mapping is maintained by something called a page table, given a virtual address, all now we have to do is find out which page the address belong to, then from the page table, find the corresponding location for that page in actual physical memory (known as frame), and given that the offset of the virtual address within the page is same for the page as well as the frame, find out the actual address by adding that offset to the address returned by the page table. For example:

enter image description here

On the left is the virtual address space of a process. Say the virtual address space requires 40 units of memory. If the physical address space (on the right) had 40 units of memory as well, it would have been possible to map all location from the left to a location on the right, and we would have been so happy. But as ill luck would have it, not only does the physical memory have less (24 here) memory units available, it has to be shared between multiple processes as well! Fine, let's see how we make do with it.

When the process starts, say a memory access request for location 35 is made. Here the page size is 8 (each page contains 8 locations, the entire virtual address space of 40 locations thus contains 5 pages). So this location belongs to page no. 4 (35/8). Within this page, this location has an offset of 3 (35%8). So this location can be specified by the tuple (pageIndex, offset) = (4,3). This is just the starting, so no part of the process is stored in the actual physical memory yet. So the page table, which maintains a mapping of the pages on the left to the actual pages on the right (where they are called frames) is currently empty. So OS relinquishes the CPU, lets a device driver access the disk and fetch the page no. 4 for this process (basically a memory chunk from the program on the disk whose addresses range from 32 to 39). When it arrives, OS allocates the page somewhere in the RAM, say first frame itself, and the page table for this process takes note that page 4 maps to frame 0 in the RAM. Now the data is finally there in the physical memory. OS again queries the page table for the tuple (4,3), and this time, page table says that page 4 is already mapped to frame 0 in the RAM. So OS simply goes to the 0th frame in RAM, accesses the data at offset 3 in that frame (Take a moment to understand this. The entire page, which was fetched from disk, is moved to frame. So whatever the offset of an individual memory location in a page was, it will be the same in the frame as well, since within the page/frame, the memory unit still resides at the same place relatively!), and returns the data! Because the data was not found in memory at first query itself, but rather had to be fetched from disk to be loaded into memory, it constitutes a miss.

Fine. Now suppose, a memory access for location 28 is made. It boils down to (3,4). Page table right now has only one entry, mapping page 4 to frame 0. So this is again a miss, the process relinquishes the CPU, device driver fetches the page from disk, process regains control of CPU again, and its page table is updated. Say now the page 3 is mapped to frame 1 in the RAM. So (3,4) becomes (1,4), and the data at that location in RAM is returned. Good. In this way, suppose the next memory access is for location 8, which translates to (1,0). Page 1 is not in memory yet, the same procedure is repeated, and the page is allocated at frame 2 in RAM. Now the RAM-process mapping looks like the picture above. At this point in time, the RAM, which had only 24 units of memory available, is filled up. Suppose the next memory access request for this process is from address 30. It maps to (3,6), and page table says that page 3 is in RAM, and it maps to frame 1. Yay! So the data is fetched from RAM location (1,6), and returned. This constitutes a hit, as data required can be obtained directly from RAM, thus being very fast. Similarly, the next few access requests, say for locations 11, 32, 26, 27 all are hits, i.e. data requested by the process is found directly in the RAM without needing to look elsewhere.

Now suppose a memory access request for location 3 comes. It translates to (0,3), and page table for this process, which currently has 3 entries, for pages 1, 3 and 4 says that this page is not in memory. Like previous cases, it is fetched from disk, however, unlike previous cases, RAM is filled up! So what to do now? Here lies the beauty of virtual memory, a frame from the RAM is evicted! (Various factors govern which frame is to be evicted. It may be LRU based, where the frame which was least recently accessed for a process is to be evicted. It may be first-come-first-evicted basis, where the frame which allocated longest time ago, is evicted, etc.) So some frame is evicted. Say frame 1 (just randomly choosing it). However, that frame is mapped to some page! (Currently, it is mapped by the page table to page 3 of our one and only one process). So that process has to be told this tragic news, that one frame, which unfortunate belongs to you, is to be evicted from RAM to make room for another pages. The process has to ensure that it updates its page table with this information, that is, removing the entry for that page-frame duo, so that the next time a request is made for that page, it right tells the process that this page is no longer in memory, and has to be fetched from disk. Good. So frame 1 is evicted, page 0 is brought in and placed there in the RAM, and the entry for page 3 is removed, and replaced by page 0 mapping to the same frame 1. So now our mapping looks like this (note the colour change in the second frame on the right side):

enter image description here

Saw what just happened? The process had to grow, it needed more space than the available RAM, but unlike our earlier scenario where every process in the RAM had to move to accommodate a growing process, here it happened by just one page replacement! This was made possible by the fact that the memory for a process no longer needs to be contiguous, it can reside at different places in chunks, OS maintains the information as to where they are, and when required, they are appropriately queried. Note: you might be thinking, huh, what if most of the times it is a miss, and the data has to be constantly loaded from disk into memory? Yes, theoretically, it is possible, but most compilers are designed in such a manner that follows locality of reference, i.e. if data from some memory location is used, the next data needed will be located somewhere very close, perhaps from the same page, the page which was just loaded into memory. As a result, the next miss will happen after quite some time, most of the upcoming memory requirements will be met by the page just brought in, or the pages already in memory which were recently used. The exact same principle allows us to evict the least recently used page as well, with the logic that what has not been used in a while, is not likely to be used in a while as well. However, it is not always so, and in exceptional cases, yes, performance may suffer. More about it later.

Solution to Problem 4: Processes can now grow easily, if space problem is faced, all it requires is to do a simple page replacement, without moving any other process.


Solution to Problem 1: A process can access unlimited memory. When more memory than available is needed, the disk is used as backup, the new data required is loaded into memory from the disk, and the least recently used data frame (or page) is moved to disk. This can go on infinitely, and since disk space is cheap and virtually unlimited, it gives an illusion of unlimited memory. Another reason for the name Virtual Memory, it gives you illusion of memory which is not really available!

Cool. Earlier we were facing a problem where even though a process reduces in size, the empty space is difficult to be reclaimed by other processes (because it would require costly compaction). Now it is easy, when a process becomes smaller in size, many of its pages are no longer used, so when other processes need more memory, a simple LRU based eviction automatically evicts those less-used pages from RAM, and replaces them with the new pages from the other processes (and of course updating the page tables of all those processes as well as the original process which now requires less space), all these without any costly compaction operation!

Solution to Problem 3: Whenever processes reduce in size, its frames in RAM will be less used, so a simple LRU based eviction can evict those pages out and replace them with pages required by new processes, thus avoiding Internal Fragmentation without need for compaction.

As for problem 2, take a moment to understand this, the scenario itself is completely removed! There is no need to move a process to accommodate a new process, because now the entire process never needs to fit at once, only certain pages of it need to fit ad hoc, that happens by evicting frames from RAM. Everything happens in units of pages, thus there is no concept of hole now, and hence no question of anything moving! May be 10 pages had to be moved because of this new requirement, there are thousands of pages which are left untouched. Whereas, earlier, all processes (every bit of them) had to be moved!

Solution to Problem 2: To accommodate a new process, data from only less recently used parts of other processes have to be evicted as required, and this happens in fixed size units called pages. Thus there is no possibility of hole or External Fragmentation with this system.

Now when the process needs to do some I/O operation, it can relinquish CPU easily! OS simply evicts all its pages from the RAM (perhaps store it in some cache) while new processes occupy the RAM in the meantime. When the I/O operation is done, OS simply restores those pages to the RAM (of course by replacing the pages from some other processes, may be from the ones which replaced the original process, or may be from some which themselves need to do I/O now, and hence can relinquish the memory!)

Solution to Problem 5: When a process is doing I/O operations, it can easily give up RAM usage, which can be utilized by other processes. This leads to proper utilization of RAM.

And of course, now no process is accessing the RAM directly. Each process is accessing a virtual memory location, which is mapped to a physical RAM address and maintained by the page-table of that process. The mapping is OS-backed, OS lets the process know which frame is empty so that a new page for a process can be fitted there. Since this memory allocation is overseen by the OS itself, it can easily ensure that no process encroaches upon the contents of another process by allocating only empty frames from RAM, or upon encroaching upon the contents of another process in the RAM, communicate to the process to update it page-table.

Solution to Original Problem: There is no possibility of a process accessing the contents of another process, since the entire allocation is managed by the OS itself, and every process runs in its own sandboxed virtual address space.

So paging (among other techniques), in conjunction with virtual memory, is what powers today's softwares running on OS-es! This frees the software developer from worrying about how much memory is available on the user's device, where to store the data, how to prevent other processes from corrupting their software's data, etc. However, it is of course, not full-proof. There are flaws:

  1. Paging is, ultimately, giving user the illusion of infinite memory by using disk as secondary backup. Retrieving data from secondary storage to fit into memory (called page swap, and the event of not finding the desired page in RAM is called page fault) is expensive as it is an IO operation. This slows down the process. Several such page swaps happen in succession, and the process becomes painfully slow. Ever seen your software running fine and dandy, and suddenly it becomes so slow that it nearly hangs, or leaves you with no option that to restart it? Possibly too many page swaps were happening, making it slow (called thrashing).

So coming back to OP,

Why do we need the virtual memory for executing a process? - As the answer explains at length, to give softwares the illusion of the device/OS having infinite memory, so that any software, big or small, can be run, without worrying about memory allocation, or other processes corrupting its data, even when running in parallel. It is a concept, implemented in practice through various techniques, one of which, as described here, is Paging. It may also be Segmentation.

Where does this virtual memory stand when the process (program) from the external hard drive is brought to the main memory (physical memory) for the execution? - Virtual memory doesn't stand anywhere per se, it is an abstraction, always present, when the software/process/program is booted, a new page table is created for it, and it contains the mapping from the addresses spat out by that process to the actual physical address in RAM. Since the addresses spat out by the process are not real addresses, in one sense, they are, actually, what you can say, the virtual memory.

Who takes care of the virtual memory and what is the size of the virtual memory? - It is taken care of by, in tandem, the OS and the software. Imagine a function in your code (which eventually compiled and made into the executable that spawned the process) which contains a local variable - an int i. When the code executes, i gets a memory address within the stack of the function. That function is itself stored as an object somewhere else. These addresses are compiler generated (the compiler which compiled your code into the executable) - virtual addresses. When executed, i has to reside somewhere in actual physical address for duration of that function at least (unless it is a static variable!), so OS maps the compiler generated virtual address of i into an actual physical address, so that whenever, within that function, some code requires the value of i, that process can query the OS for that virtual address, and OS in turn can query the physical a

How to create a custom scrollbar on a div (Facebook style)

If you're looking for a Facebook like scroll bar, then I'd highly recommend you take a look at this one:

http://rocha.la/jQuery-slimScroll

How do I download NLTK data?

you should add python to your PATH during installation of python...after installation.. open cmd prompt type command-pip install nltk then go to IDLE and open a new file..save it as file.py..then open file.py type the following: import nltk

nltk.download()

ORA-01950: no privileges on tablespace 'USERS'

You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run

ALTER USER <user> quota unlimited on <tablespace name>;

or

ALTER USER <user> quota 100M on <tablespace name>;

as a DBA user (depending on how much space you need / want to grant).

$date + 1 year?

just had the same problem, however this was the simplest solution:

<?php (date('Y')+1).date('-m-d'); ?>

tsc throws `TS2307: Cannot find module` for a local file

In some cases you just need to update the include array.

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "outDir": "dist",
    "sourceMap": false,
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*.ts", "tests/**/*.ts"],
  "exclude": ["node_modules", ".vscode"]
}

'const int' vs. 'int const' as function parameters in C++ and C

They are the same, but in C++ there's a good reason to always use const on the right. You'll be consistent everywhere because const member functions must be declared this way:

int getInt() const;

It changes the this pointer in the function from Foo * const to Foo const * const. See here.

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

Here is some SQL that actually make sense:

SELECT m.id FROM match m LEFT JOIN email e ON e.id = m.id WHERE e.id IS NULL

Simple is always better.

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

go to c->users->[Your user account]-> remove android 1.2 and restart the android studio when it ask to import select first radio button which is import setting from previous config

there you go fixed

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;
}?

An error when I add a variable to a string

You have empty $entry_database variable. As you see in error: ListEmail, Title FROM WHERE ID bewteen FROM and WHERE should be name of table. Proper syntax of SELECT:

SELECT columns FROM table [optional things as WHERE/ORDER/GROUP/JOIN etc]

which in your way should become:

SELECT ID, ListStID, ListEmail, Title FROM some_table_you_got WHERE ID = '4'

How do I get the XML root node with C#?

Agree with Jewes, XmlReader is the better way to go, especially if working with a larger XML document or processing multiple in a loop - no need to parse the entire document if you only need the document root.

Here's a simplified version, using XmlReader and MoveToContent().

http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.movetocontent.aspx

using (XmlReader xmlReader = XmlReader.Create(p_fileName))
{
  if (xmlReader.MoveToContent() == XmlNodeType.Element)
    rootNodeName = xmlReader.Name;
}

Checking for empty or null JToken in a JObject

As of C# 7 you could also use this:

if (clientsParsed["objects"] is JArray clients) 
{
    foreach (JObject item in clients.Children())
    {
        if (item["thisParameter"] as JToken itemToken) 
        {
            command.Parameters["@MyParameter"].Value = JTokenToSql(itemToken);
        }
    }
}

The is Operator checks the Type and if its corrects the Value is inside the clients variable.

Ant is using wrong java version

According to the ant manual, setting JAVA_HOME should work - are you sure the changed setting is visible to ant?

Alternatively, you could use the JAVACMD variable.

how to convert long date value to mm/dd/yyyy format

Refer below code for formatting date

long strDate1 = 1346524199000;
Date date=new Date(strDate1);

try {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        date = df2.format(format.parse("yourdate");
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Open fancybox from function

You don't have to add you own click event handler at all. Just initialize the element with fancybox:

$(function() {
    $('a[href="#modalMine"]').fancybox({
        'autoScale': true,
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'speedIn': 500,
        'speedOut': 300,
        'autoDimensions': true,
        'centerOnScroll': true  // as MattBall already said, remove the comma
    });
});

Done. Fancybox already binds a click handler that opens the box. Have a look at the HowTo section.


Later if you want to open the box programmatically, raise the click event on that element:

$('a[href="#modalMine"]').click();

log4j: Log output of a specific class to a specific appender

An example:

log4j.rootLogger=ERROR, logfile

log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.datePattern='-'dd'.log'
log4j.appender.logfile.File=log/radius-prod.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n

log4j.logger.foo.bar.Baz=DEBUG, myappender
log4j.additivity.foo.bar.Baz=false

log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myappender.datePattern='-'dd'.log'
log4j.appender.myappender.File=log/access-ext-dmz-prod.log
log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n

dplyr mutate with conditional values

Try this:

myfile %>% mutate(V5 = (V1 == 1 & V2 != 4) + 2 * (V2 == 4 & V3 != 1))

giving:

  V1 V2 V3 V4 V5
1  1  2  3  5  1
2  2  4  4  1  2
3  1  4  1  1  0
4  4  5  1  3  0
5  5  5  5  4  0

or this:

myfile %>% mutate(V5 = ifelse(V1 == 1 & V2 != 4, 1, ifelse(V2 == 4 & V3 != 1, 2, 0)))

giving:

  V1 V2 V3 V4 V5
1  1  2  3  5  1
2  2  4  4  1  2
3  1  4  1  1  0
4  4  5  1  3  0
5  5  5  5  4  0

Note

Suggest you get a better name for your data frame. myfile makes it seem as if it holds a file name.

Above used this input:

myfile <- 
structure(list(V1 = c(1L, 2L, 1L, 4L, 5L), V2 = c(2L, 4L, 4L, 
5L, 5L), V3 = c(3L, 4L, 1L, 1L, 5L), V4 = c(5L, 1L, 1L, 3L, 4L
)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5"))

Update 1 Since originally posted dplyr has changed %.% to %>% so have modified answer accordingly.

Update 2 dplyr now has case_when which provides another solution:

myfile %>% 
       mutate(V5 = case_when(V1 == 1 & V2 != 4 ~ 1, 
                             V2 == 4 & V3 != 1 ~ 2,
                             TRUE ~ 0))

Failed to connect to mysql at 127.0.0.1:3306 with user root access denied for user 'root'@'localhost'(using password:YES)

  1. sudo mysql -u root -p
  2. mysql > ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'abc@123';
  3. sudo mysql-workbench

Loop through an array of strings in Bash?

This is also easy to read:

FilePath=(
    "/tmp/path1/"    #FilePath[0]
    "/tmp/path2/"    #FilePath[1]
)

#Loop
for Path in "${FilePath[@]}"
do
    echo "$Path"
done

Import Python Script Into Another?

Following worked for me and it seems very simple as well:

Let's assume that we want to import a script ./data/get_my_file.py and want to access get_set1() function in it.

import sys
sys.path.insert(0, './data/')
import get_my_file as db

print (db.get_set1())

Add views below toolbar in CoordinatorLayout

As of Android studio 3.4, You need to put this line in your Layout which holds the RecyclerView.

app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior"

Base64: java.lang.IllegalArgumentException: Illegal character

I got this error for my Linux Jenkins slave. I fixed it by changing from the node from "Known hosts file Verification Strategy" to "Non verifying Verification Strategy".

How to change line color in EditText

Use this method.. and modify it according to ur view names. This code works great.

 private boolean validateMobilenumber() {
            if (mobilenumber.getText().toString().trim().isEmpty() || mobilenumber.getText().toString().length() < 10) {
                input_layout_mobilenumber.setErrorEnabled(true);
                input_layout_mobilenumber.setError(getString(R.string.err_msg_mobilenumber));
               // requestFocus(mobilenumber);
                return false;
            } else {
                input_layout_mobilenumber.setError(null);
                input_layout_mobilenumber.setErrorEnabled(false);
                mobilenumber.setBackground(mobilenumber.getBackground().getConstantState().newDrawable());
            }

How can a divider line be added in an Android RecyclerView?

yqritc's RecyclerView-FlexibleDivider makes this a one liner. First add this to your build.gradle:

compile 'com.yqritc:recyclerview-flexibledivider:1.4.0' // requires jcenter()

Now you can configure and add a divder where you set your recyclerView's adapter:

recyclerView.setAdapter(myAdapter);
recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).color(Color.RED).sizeResId(R.dimen.divider).marginResId(R.dimen.leftmargin, R.dimen.rightmargin).build());

Calculate logarithm in python

From the documentation:

With one argument, return the natural logarithm of x (to base e).

With two arguments, return the logarithm of x to the given base, calculated as log(x)/log(base).

But the log10 is made available as math.log10(), which does not resort to log division if possible.

How to combine multiple inline style objects?

Actually, there is a formal way to combine and it is like below:

<View style={[style01, style02]} />

But, there is a small issue, if one of them is passed by the parent component and it was created by a combined formal way we have a big problem:

// The passing style02 from props: [parentStyle01, parentStyle02]

// Now:
<View style={[style01, [parentStyle01, parentStyle02]]} />

And this last line causes to have UI bug, surly, React Native cannot deal with a deep array inside an array. So I create my helper function:

import { StyleSheet } from 'react-native';

const styleJoiner = (...arg) => StyleSheet.flatten(arg);

By using my styleJoiner anywhere you can combine any type of style and combine styles. even undefined or other useless types don't cause to break the styling.

Non-resolvable parent POM using Maven 3.0.3 and relativePath notation

You need to check your relative path, based on depth of your modules from parent if module is just below parent then in module put relative path as: ../pom.xml

if its 2 level down then ../../pom.xml

Add empty columns to a dataframe with specified names from a vector

The problem with your code is in the line:

for(i in length(namevector))

You need to ask yourself: what is length(namevector)? It's one number. So essentially you're saying:

for(i in 11)
df[,i] <- NA

Or more simply:

df[,11] <- NA

That's why you're getting an error. What you want is:

for(i in namevector)
    df[,i] <- NA

Or more simply:

df[,namevector] <- NA

What are the retransmission rules for TCP?

There's no fixed time for retransmission. Simple implementations estimate the RTT (round-trip-time) and if no ACK to send data has been received in 2x that time then they re-send.

They then double the wait-time and re-send once more if again there is no reply. Rinse. Repeat.

More sophisticated systems make better estimates of how long it should take for the ACK as well as guesses about exactly which data has been lost.

The bottom-line is that there is no hard-and-fast rule about exactly when to retransmit. It's up to the implementation. All retransmissions are triggered solely by the sender based on lack of response from the receiver.

TCP never drops data so no, there is no way to indicate a server should forget about some segment.

Replace characters from a column of a data frame R

If your variable data1$c is a factor, it's more efficient to change the labels of the factor levels than to create a new vector of characters:

levels(data1$c) <- sub("_", "-", levels(data1$c))


            a b   c
1  0.73945260 a A-B
2  0.75998815 b A-B
3  0.19576725 c A-B
4  0.85932140 d A-B
5  0.80717115 e A-C
6  0.09101492 f A-C
7  0.10183586 g A-C
8  0.97742424 h A-C
9  0.21364521 i A-C
10 0.02389782 j A-C

Segmentation fault on large array sizes

You array is being allocated on the stack in this case attempt to allocate an array of the same size using alloc.

Is it possible to change javascript variable values while debugging in Google Chrome?

It looks like not.

Put a breakpoint, when it stops switch to the console, try to set the variable. It does not error when you assign it a different value, but if you read it after the assignment, it's unmodified. :-/

Two-way SSL clarification

What you call "Two-Way SSL" is usually called TLS/SSL with client certificate authentication.

In a "normal" TLS connection to example.com only the client verifies that it is indeed communicating with the server for example.com. The server doesn't know who the client is. If the server wants to authenticate the client the usual thing is to use passwords, so a client needs to send a user name and password to the server, but this happens inside the TLS connection as part of an inner protocol (e.g. HTTP) it's not part of the TLS protocol itself. The disadvantage is that you need a separate password for every site because you send the password to the server. So if you use the same password on for example PayPal and MyPonyForum then every time you log into MyPonyForum you send this password to the server of MyPonyForum so the operator of this server could intercept it and try it on PayPal and can issue payments in your name.

Client certificate authentication offers another way to authenticate the client in a TLS connection. In contrast to password login, client certificate authentication is specified as part of the TLS protocol. It works analogous to the way the client authenticates the server: The client generates a public private key pair and submits the public key to a trusted CA for signing. The CA returns a client certificate that can be used to authenticate the client. The client can now use the same certificate to authenticate to different servers (i.e. you could use the same certificate for PayPal and MyPonyForum without risking that it can be abused). The way it works is that after the server has sent its certificate it asks the client to provide a certificate too. Then some public key magic happens (if you want to know the details read RFC 5246) and now the client knows it communicates with the right server, the server knows it communicates with the right client and both have some common key material to encrypt and verify the connection.

SSRS custom number format

am assuming that you want to know how to format numbers in SSRS

Just right click the TextBox on which you want to apply formatting, go to its expression.

suppose its expression is something like below

=Fields!myField.Value

then do this

=Format(Fields!myField.Value,"##.##") 

or

=Format(Fields!myFields.Value,"00.00")

difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00

this should give you an idea.

also: you might have to convert your field into a numerical one. i.e.

  =Format(CDbl(Fields!myFields.Value),"00.00")

so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present ie. 45.6567 would be 45.65 for both of them:

UPDATE :

if you want to apply variable formatting on the same column based on row values i.e. you want myField to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)

Go to the appropriate textbox and go to its expression and do this:

=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) > 0, 
    Format(Fields!myField.Value, "##.##"),Fields!myField.Value)

so basically you are using IIF(condition, true,false) operator of SSRS, ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.

this should give you an idea, how to handle variable formatting.

How to use zIndex in react-native

I finally solved this by creating a second object that imitates B.

My schema now looks like this:

enter image description here

I now have B1 (within parent of A) and B2 outside of it.

B1 and B2 are right next to one another, so to the naked eye it looks as if it's just 1 object.

Meaning of @classmethod and @staticmethod for beginner?

In short, @classmethod turns a normal method to a factory method.

Let's explore it with an example:

class PythonBook:
    def __init__(self, name, author):
        self.name = name
        self.author = author
    def __repr__(self):
        return f'Book: {self.name}, Author: {self.author}'

Without a @classmethod,you should labor to create instances one by one and they are scattered.

book1 = PythonBook('Learning Python', 'Mark Lutz')
In [20]: book1
Out[20]: Book: Learning Python, Author: Mark Lutz
book2 = PythonBook('Python Think', 'Allen B Dowey')
In [22]: book2
Out[22]: Book: Python Think, Author: Allen B Dowey

As for example with @classmethod

class PythonBook:
    def __init__(self, name, author):
        self.name = name
        self.author = author
    def __repr__(self):
        return f'Book: {self.name}, Author: {self.author}'
    @classmethod
    def book1(cls):
        return cls('Learning Python', 'Mark Lutz')
    @classmethod
    def book2(cls):
        return cls('Python Think', 'Allen B Dowey')

Test it:

In [31]: PythonBook.book1()
Out[31]: Book: Learning Python, Author: Mark Lutz
In [32]: PythonBook.book2()
Out[32]: Book: Python Think, Author: Allen B Dowey

See? Instances are successfully created inside a class definition and they are collected together.

In conclusion, @classmethod decorator convert a conventional method to a factory method,Using classmethods makes it possible to add as many alternative constructors as necessary.

How do I link to Google Maps with a particular longitude and latitude?

To open the google maps app in android:-

geo:<lat>,<lng>?z=<zoom>

open app with marker for give location:-

geo:<lat>,<lng>?q=<lat>,<lng>(Label,Name)

open google map in ios:-

comgooglemaps://?q=<lat>,<lng>

open google maps in browser with following parameters:-

http://maps.google.com/maps?z=12&t=m&q=<lat>,<lng>
  • z is the zoom level (1-21)
  • t is the map type ("m" map, "k" satellite, "h" hybrid, "p" terrain, "e" GoogleEarth)
  • q is the search query

What does O(log n) mean exactly?

O(log N) basically means time goes up linearly while the n goes up exponentially. So if it takes 1 second to compute 10 elements, it will take 2 seconds to compute 100 elements, 3 seconds to compute 1000 elements, and so on.

?It is O(log n) when we do divide and conquer type of algorithms e.g binary search. Another example is quick sort where each time we divide the array into two parts and each time it takes O(N) time to find a pivot element. Hence it N O(log N)

Is it possible to use global variables in Rust?

It's possible but no heap allocation allowed directly. Heap allocation is performed at runtime. Here are a few examples:

static SOME_INT: i32 = 5;
static SOME_STR: &'static str = "A static string";
static SOME_STRUCT: MyStruct = MyStruct {
    number: 10,
    string: "Some string",
};
static mut db: Option<sqlite::Connection> = None;

fn main() {
    println!("{}", SOME_INT);
    println!("{}", SOME_STR);
    println!("{}", SOME_STRUCT.number);
    println!("{}", SOME_STRUCT.string);

    unsafe {
        db = Some(open_database());
    }
}

struct MyStruct {
    number: i32,
    string: &'static str,
}

Forward declaration of a typedef in C++

Like @BillKotsias, I used inheritance, and it worked for me.

I changed this mess (which required all the boost headers in my declaration *.h)

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/moment.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/max.hpp>

typedef boost::accumulators::accumulator_set<float,
 boost::accumulators::features<
  boost::accumulators::tag::median,
  boost::accumulators::tag::mean,
  boost::accumulators::tag::min,
  boost::accumulators::tag::max
 >> VanillaAccumulator_t ;
std::unique_ptr<VanillaAccumulator_t> acc;

into this declaration (*.h)

class VanillaAccumulator;
std::unique_ptr<VanillaAccumulator> acc;

and the implementation (*.cpp) was

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/moment.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/max.hpp>

class VanillaAccumulator : public
  boost::accumulators::accumulator_set<float,
    boost::accumulators::features<
      boost::accumulators::tag::median,
      boost::accumulators::tag::mean,
      boost::accumulators::tag::min,
      boost::accumulators::tag::max
>>
{
};

How can I get the file name from request.FILES?

NOTE if you are using python 3.x:

request.FILES is a multivalue dictionary like object that keeps the files uploaded through an upload file button. Say in your html code the name of the button (type="file") is "myfile" so "myfile" will be the key in this dictionary. If you uploaded one file, then the value for this key will be only one and if you uploaded multiple files, then you will have multiple values for that specific key. If you use request.FILES['myfile'] you will get the first or last value (I cannot say for sure). This is fine if you only uploaded one file, but if you want to get all files you should do this:

list=[] #myfile is the key of a multi value dictionary, values are the uploaded files
for f in request.FILES.getlist('myfile'): #myfile is the name of your html file button
    filename = f.name
    list.append(filename)

of course one can squeeze the whole thing in one line, but this is easy to understand

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

One way is to setup a chroot environment. Debian has a number of tools for that, for example debootstrap

jquery get all input from specific form

Use HTML Form "elements" attribute:

$.each($("form").elements, function(){ 
    console.log($(this));
    });

Now it's not necessary to provide such names as "input, textarea, select ..." etc.

The remote server returned an error: (403) Forbidden

    private class GoogleShortenedURLResponse
    {
        public string id { get; set; }
        public string kind { get; set; }
        public string longUrl { get; set; }
    }

    private class GoogleShortenedURLRequest
    {
        public string longUrl { get; set; }
    }

    public ActionResult Index1()
    {
        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult ShortenURL(string longurl)
    {
        string googReturnedJson = string.Empty;
        JavaScriptSerializer javascriptSerializer = new JavaScriptSerializer();

        GoogleShortenedURLRequest googSentJson = new GoogleShortenedURLRequest();
        googSentJson.longUrl = longurl;
        string jsonData = javascriptSerializer.Serialize(googSentJson);

        byte[] bytebuffer = Encoding.UTF8.GetBytes(jsonData);

        WebRequest webreq = WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url");
        webreq.Method = WebRequestMethods.Http.Post;
        webreq.ContentLength = bytebuffer.Length;
        webreq.ContentType = "application/json";

        using (Stream stream = webreq.GetRequestStream())
        {
            stream.Write(bytebuffer, 0, bytebuffer.Length);
            stream.Close();
        }

        using (HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse())
        {
            using (Stream dataStream = webresp.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(dataStream))
                {
                    googReturnedJson = reader.ReadToEnd();
                }
            }
        }

        //GoogleShortenedURLResponse googUrl = javascriptSerializer.Deserialize<googleshortenedurlresponse>(googReturnedJson);

        //ViewBag.ShortenedUrl = googUrl.id;
        return View();
    }

JavaScript: How to get parent element by selector?

Using leech's answer with indexOf (to support IE)

This is using what leech talked about, but making it work for IE (IE doesn't support matches):

function closest(el, selector, stopSelector) {
  var retval = null;
  while (el) {
    if (el.className.indexOf(selector) > -1) {
      retval = el;
      break
    } else if (stopSelector && el.className.indexOf(stopSelector) > -1) {
      break
    }
    el = el.parentElement;
  }
  return retval;
}

It's not perfect, but it works if the selector is unique enough so it won't accidentally match the incorrect element.

Force IE10 to run in IE10 Compatibility View?

I had the same problem. The problem is a bug in MSIE 10, so telling people to fix their issues isn't helpful. Neither is telling visitors to your site to add your site to compatibility view, bleh. In my case, the problem was that the following code displayed no text:

document.write ('<P>'); 
document.write ('Blah, blah, blah... ');
document.write ('</P>');

After much trial and error, I determined that removing the <P> and </P> tags caused the text to appear properly on the page (thus, the problem IS with document mode rather than browser mode, at least in my case). Removing the <P> tags when userAgent is MSIE is not a "fix" I want to put into my pages.

The solution, as others have said, is:

<!DOCTYPE HTML whatever doctype you're using....> 
<HTML>
 <HEAD>
  <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8">
  <TITLE>Blah...

Yes, the meta tag has to be the FIRST tag after HEAD.

What special characters must be escaped in regular expressions?

Unfortunately, the meaning of things like ( and \( are swapped between Emacs style regular expressions and most other styles. So if you try to escape these you may be doing the opposite of what you want.

So you really have to know what style you are trying to quote.

How to start Spyder IDE on Windows

As stated in the documentation of Spyder, you need to install PyQt5 first.

Open a Command Prompt as Administrator, then run:

pip install pyqt5
pip install spyder

Then you can find the spyder3.exe in the Python3.6/Scripts folder. You can also make a shortcut to it. No need for Anaconda.

How can I reference a dll in the GAC from Visual Studio?

The relevant files and references can be found here:

http://msdn.microsoft.com/en-us/library/cc283981.aspx

Note the links off it about implementation/etc.

Spring @Transactional read-only propagation

By default transaction propagation is REQUIRED, meaning that the same transaction will propagate from a transactional caller to transactional callee. In this case also the read-only status will propagate. E.g. if a read-only transaction will call a read-write transaction, the whole transaction will be read-only.

Could you use the Open Session in View pattern to allow lazy loading? That way your handle method does not need to be transactional at all.

Refresh/reload the content in Div using jquery/ajax

You need to add the source from where you're loading the data.

For Example:

$("#step1Content").load("yourpage.html");

Hope It will help you.

How to reset Django admin password?

Just type this command in your command line:

python manage.py changepassword yourusername

Install apps silently, with granted INSTALL_PACKAGES permission

you can use this in terminal or shell

adb shell install -g MyApp.apk

see more in develope google

Match all elements having class name starting with a specific string

You can easily add multiple classes to divs... So:

<div class="myclass myclass-one"></div>
<div class="myclass myclass-two"></div>
<div class="myclass myclass-three"></div>

Then in the CSS call to the share class to apply the same styles:

.myclass {...}

And you can still use your other classes like this:

.myclass-three {...}

Or if you want to be more specific in the CSS like this:

.myclass.myclass-three {...}

How to have an auto incrementing version number (Visual Studio)?

Here's the quote on AssemblyInfo.cs from MSDN:

You can specify all the values or you can accept the default build number, revision number, or both by using an asterisk (). For example, [assembly:AssemblyVersion("2.3.25.1")] indicates 2 as the major version, 3 as the minor version, 25 as the build number, and 1 as the revision number. A version number such as [assembly:AssemblyVersion("1.2.")] specifies 1 as the major version, 2 as the minor version, and accepts the default build and revision numbers. A version number such as [assembly:AssemblyVersion("1.2.15.*")] specifies 1 as the major version, 2 as the minor version, 15 as the build number, and accepts the default revision number. The default build number increments daily. The default revision number is random

This effectively says, if you put a 1.1.* into assembly info, only build number will autoincrement, and it will happen not after every build, but daily. Revision number will change every build, but randomly, rather than in an incrementing fashion.

This is probably enough for most use cases. If that's not what you're looking for, you're stuck with having to write a script which will autoincrement version # on pre-build step

Could not load NIB in bundle

Using a custom Swift view in an Objective-C view controller (yes, even after importing the <<PROJECT NAME>>-Swift.h file), I'd tried to load the nib using:

MyCustomView *customView = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([MyCustomView class]) owner:self options:nil] objectAtIndex:0];

...but NSStringFromClass([MyCustomView class]) returns <<PROJECT NAME>>.MyCustomViewand the load fails. TL;DR All worked well loading the nib using a string literal:

MyCustomView *customView = [[[NSBundle mainBundle] loadNibNamed:@"MyCustomView" owner:self options:nil] objectAtIndex:0];

How to get cookie's expire time

When you create a cookie via PHP die Default Value is 0, from the manual:

If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes)

Otherwise you can set the cookies lifetime in seconds as the third parameter:

http://www.php.net/manual/en/function.setcookie.php

But if you mean to get the remaining lifetime of an already existing cookie, i fear that, is not possible (at least not in a direct way).

What is the "assert" function?

C++11 N3337 standard draft

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf

19.3 Assertions

1 The header <cassert>, described in (Table 42), provides a macro for documenting C ++ program assertions and a mechanism for disabling the assertion checks.

2 The contents are the same as the Standard C library header <assert.h>.

C99 N1256 standard draft

http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf

7.2 Diagnostics <assert.h>

1 The header <assert.h> defines the assert macro and refers to another macro, NDEBUG which is not defined by <assert.h>. If NDEBUG is defined as a macro name at the point in the source file where <assert.h> is included, the assert macro is defined simply as

 #define assert(ignore) ((void)0)

The assert macro is redefined according to the current state of NDEBUG each time that <assert.h> is included.

2. The assert macro shall be implemented as a macro, not as an actual function. If the macro definition is suppressed in order to access an actual function, the behavior is undefined.

7.2.1 Program diagnostics

7.2.1.1 The assert macro

Synopsis

1.

#include <assert.h>
void assert(scalar expression);

Description

2 The assert macro puts diagnostic tests into programs; it expands to a void expression. When it is executed, if expression (which shall have a scalar type) is false (that is, compares equal to 0), the assert macro writes information about the particular call that failed (including the text of the argument, the name of the source file, the source line number, and the name of the enclosing function — the latter are respectively the values of the preprocessing macros __FILE__ and __LINE__ and of the identifier __func__) on the standard error stream in an implementation-defined format. 165) It then calls the abort function.

Returns

3 The assert macro returns no value.

How to bind Close command to a button

All it takes is a bit of XAML...

<Window x:Class="WCSamples.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.CommandBindings>
        <CommandBinding Command="ApplicationCommands.Close"
                        Executed="CloseCommandHandler"/>
    </Window.CommandBindings>
    <StackPanel Name="MainStackPanel">
        <Button Command="ApplicationCommands.Close" 
                Content="Close Window" />
    </StackPanel>
</Window>

And a bit of C#...

private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
    this.Close();
}

(adapted from this MSDN article)

How can I make a list of lists in R?

The example creates a list of named lists in a loop.

  MyList <- list()
  for (aName in c("name1", "name2")){
    MyList[[aName]] <- list(aName)
  }
  MyList[["name1"]]
  MyList[["name2"]]

To add another list named "name3" do write:

  MyList$name3 <- list(1, 2, 3)

How do I insert datetime value into a SQLite database?

The format you need is:

'2007-01-01 10:00:00'

i.e. yyyy-MM-dd HH:mm:ss

If possible, however, use a parameterised query as this frees you from worrying about the formatting details.

What is the purpose of "&&" in a shell command?

&& lets you do something based on whether the previous command completed successfully - that's why you tend to see it chained as do_something && do_something_else_that_depended_on_something.

Get the decimal part from a double

There is a cleaner and ways faster solution than the 'Math.Truncate' approach:

double frac = value % 1;

MySQL error - #1932 - Table 'phpmyadmin.pma user config' doesn't exist in engine

If all the solutions above don't work, try to :

Add $i = 1; after /* Servers configuration */

in place of $i = 0 in your phpmyadmin config.inc.php file

Running XAMPP on local windows server, my mysql data files are not under the usual install path (C:\Xampp), but on another disk.

So now I have the phpmyadmin tables with the double __ like pma__table... and $i = 1;

How do you add Boost libraries in CMakeLists.txt?

I agree with the answers 1 and 2. However, I prefer to specify each library separately. This makes the depencencies clearer in big projects. Yet, there is the danger of mistyping the (case-sensitive) variable names. In that case there is no direct cmake error but some undefined references linker issues later on, which may take some time to resolve. Therefore I use the following cmake function:

function(VerifyVarDefined)
  foreach(lib ${ARGV}) 
    if(DEFINED ${lib})
    else(DEFINED ${lib})
      message(SEND_ERROR "Variable ${lib} is not defined")
    endif(DEFINED ${lib})
  endforeach()
endfunction(VerifyVarDefined)

For the example mentioned above, this looks like:

VerifyVarDefined(Boost_PROGRAM_OPTIONS_LIBRARY Boost_REGEX_LIBRARY)
target_link_libraries( run ${Boost_PROGRAM_OPTIONS_LIBRARY} ${Boost_REGEX_LIBRARY} )

If I had written "BOOST_PROGRAM_OPTIONS_LIBRARY" there would have been an error triggered by cmake and not much later triggered by the linker.

assignment operator overloading in c++

#include<iostream>

using namespace std;

class employee
{
    int idnum;
    double salary;
    public:
        employee(){}

        employee(int a,int b)
        {
            idnum=a;
            salary=b;
        }

        void dis()
        {
            cout<<"1st emp:"<<endl<<"idnum="<<idnum<<endl<<"salary="<<salary<<endl<<endl;
        }

        void operator=(employee &emp)
        {
            idnum=emp.idnum;
            salary=emp.salary;
        }

        void show()
        {
            cout<<"2nd emp:"<<endl<<"idnum="<<idnum<<endl<<"salary="<<salary<<endl;
        }
};

main()
{
    int a;
    double b;

    cout<<"enter id num and salary"<<endl;
    cin>>a>>b;
    employee e1(a,b);
    e1.dis();
    employee e2;
    e2=e1;
    e2.show();  
}

Scroll event listener javascript

I was looking a lot to find a solution for sticy menue with old school JS (without JQuery). So I build small test to play with it. I think it can be helpfull to those looking for solution in js. It needs improvments of unsticking the menue back, and making it more smooth. Also I find a nice solution with JQuery that clones the original div instead of position fixed, its better since the rest of page element dont need to be replaced after fixing. Anyone know how to that with JS ? Please remark, correct and improve.

<!DOCTYPE html>
<html>

<head>
<script>

// addEvent function by John Resig:
// http://ejohn.org/projects/flexible-javascript-events/

function addEvent( obj, type, fn ) {

    if ( obj.attachEvent ) {

        obj['e'+type+fn] = fn;
        obj[type+fn] = function(){obj['e'+type+fn]( window.event );};
        obj.attachEvent( 'on'+type, obj[type+fn] );
    } else {
        obj.addEventListener( type, fn, false );
    }
}
function getScrollY() {
    var  scrOfY = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
        scrOfY = window.pageYOffset;

    } else if( document.body && document.body.scrollTop )  {
        //DOM compliant
        scrOfY = document.body.scrollTop;
    } 
    return scrOfY;
}
</script>
<style>
#mydiv {
    height:100px;
    width:100%;
}
#fdiv {
    height:100px;
    width:100%;
}
</style>
</head>

<body>

<!-- HTML for example event goes here -->

<div id="fdiv" style="background-color:red;position:fix">
</div>
<div id="mydiv" style="background-color:yellow">
</div>
<div id="fdiv" style="background-color:green">
</div>

<script>

// Script for example event goes here

addEvent(window, 'scroll', function(event) {

    var x = document.getElementById("mydiv");

    var y = getScrollY();      
    if (y >= 100) {
        x.style.position = "fixed"; 
        x.style.top= "0";
    } 
});

</script>
</body>
</html>