Programs & Examples On #Obiee

Oracle Business Intelligence Enterprise Edition (OBIEE, formerly Siebel Analytics, formerly nQuire) is an integrated business intelligence suite from Oracle Corporation.

C# how to use enum with switch

Your code is fine. In case you're not sure how to use Calculate function, try

Calculate(5,5,(Operator)0); //this will add 5,5
Calculate(5,5,Operator.PLUS);// alternate

Default enum values start from 0 and increase by one for following elements, until you assign different values. Also you can do :

public enum Operator{PLUS=21,MINUS=345,MULTIPLY=98,DIVIDE=100};

Is there a function to copy an array in C/C++?

Use memcpy in C, std::copy in C++.

Hex-encoded String to Byte Array

Java SE 6 or Java EE 5 provides a method to do this now so there is no need for extra libraries.

The method is DatatypeConverter.parseHexBinary

In this case it can be used as follows:

String str = "9B7D2C34A366BF890C730641E6CECF6F";
byte[] bytes = DatatypeConverter.parseHexBinary(str);

The class also provides type conversions for many other formats that are generally used in XML.

How to auto adjust table td width from the content

Remove all widths set using CSS and set white-space to nowrap like so:

.content-loader tr td {
    white-space: nowrap;
}

I would also remove the fixed width from the container (or add overflow-x: scroll to the container) if you want the fields to display in their entirety without it looking odd...

See more here: http://www.w3schools.com/cssref/pr_text_white-space.asp

Animated GIF in IE stopping

A very easy way is to use jQuery and SimpleModal plugin. Then when I need to show my "loading" gif on submit, I do:

$('*').css('cursor','wait');
$.modal("<table style='white-space: nowrap'><tr><td style='white-space: nowrap'><b>Please wait...</b></td><td><img alt='Please wait' src='loader.gif' /></td></tr></table>", {escClose:false} );

Generate PDF from HTML using pdfMake in Angularjs

this is what it worked for me I'm using html2pdf from an Angular2 app, so I made a reference to this function in the controller

var html2pdf = (function(html2canvas, jsPDF) {

declared in html2pdf.js.

So I added just after the import declarations in my angular-controller this declaration:

declare function html2pdf(html2canvas, jsPDF): any;

then, from a method of my angular controller I'm calling this function:

generate_pdf(){
    this.someService.loadContent().subscribe(
      pdfContent => {
        html2pdf(pdfContent, {
          margin:       1,
          filename:     'myfile.pdf',
          image:        { type: 'jpeg', quality: 0.98 },
          html2canvas:  { dpi: 192, letterRendering: true },
          jsPDF:        { unit: 'in', format: 'A4', orientation: 'portrait' }
        });
      }
    );
  }

Hope it helps

Java: How to stop thread?

The recommended way will be to build this into the thread. So no you can't (or rather shouldn't) kill the thread from outside.

Have the thread check infrequently if it is required to stop. (Instead of blocking on a socket until there is data. Use a timeout and every once in a while check if the user indicated wanting to stop)

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

Old question but just had that problem /dumb jira having problems with java 10/ and didn't find a simple answer here so just gonna leave it:

$ /usr/libexec/java_home -V shows the versions installed and their locations so you can simply remove /Library/Java/JavaVirtualMachines/<the_version_you_want_to_remove>. Voila

How to get POST data in WebAPI?

Is there a way to handle form post data in a Web Api controller?

The normal approach in ASP.NET Web API is to represent the form as a model so the media type formatter deserializes it. Alternative is to define the actions's parameter as NameValueCollection:

public void Post(NameValueCollection formData)
{
  var value = formData["key"];
}

INSERT with SELECT

Correct Syntax: select spelling was wrong

INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want' 
FROM courses 
WHERE cid = $ci 

Best way to do nested case statement logic in SQL Server

Wrap all those cases into one.


SELECT
    col1,
    col2,
    col3,
    CASE
        WHEN condition1 THEN calculation1 
        WHEN condition2 THEN calculation2
        WHEN condition3 THEN calculation3
        WHEN condition4 THEN calculation4
        WHEN condition5 THEN calculation5
        ELSE NULL         
    END AS 'calculatedcol1',
    col4,
    col5 -- etc
FROM table

Getting fb.me URL

I'm not aware of any way to programmatically create these URLs, but the existing username space (www.facebook.com/something) works on fb.me also (e.g. http://fb.me/facebook )

SQL server stored procedure return a table

Consider creating a function which can return a table and be used in a query.

https://msdn.microsoft.com/en-us/library/ms186755.aspx

The main difference between a function and a procedure is that a function makes no changes to any table. It only returns a value.

In this example I'm creating a query to give me the counts of all the columns in a given table which aren't null or empty.

There are probably many ways to clean this up. But it illustrates a function well.

USE Northwind

CREATE FUNCTION usp_listFields(@schema VARCHAR(50), @table VARCHAR(50))
RETURNS @query TABLE (
    FieldName VARCHAR(255)
    )
BEGIN
    INSERT @query
    SELECT
        'SELECT ''' + @table+'~'+RTRIM(COLUMN_NAME)+'~''+CONVERT(VARCHAR, COUNT(*)) '+
    'FROM '+@schema+'.'+@table+' '+
          ' WHERE isnull("'+RTRIM(COLUMN_NAME)+'",'''')<>'''' UNION'
    FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table and TABLE_SCHEMA = @schema
    RETURN
END

Then executing the function with

SELECT * FROM usp_listFields('Employees')

produces a number of rows like:

SELECT 'Employees~EmployeeID~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees  WHERE isnull("EmployeeID",'')<>'' UNION
SELECT 'Employees~LastName~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees  WHERE isnull("LastName",'')<>'' UNION
SELECT 'Employees~FirstName~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees  WHERE isnull("FirstName",'')<>'' UNION

How do I search within an array of hashes by hash values in ruby?

this will return first match

@fathers.detect {|f| f["age"] > 35 }

How to iterate over a std::map full of strings in C++

iter->first and iter->second are variables, you are attempting to call them as methods.

How to load all the images from one of my folder into my web page, using Jquery/Javascript

Use :

var dir = "Src/themes/base/images/";
var fileextension = ".png";
$.ajax({
    //This will retrieve the contents of the folder if the folder is configured as 'browsable'
    url: dir,
    success: function (data) {
        //List all .png file names in the page
        $(data).find("a:contains(" + fileextension + ")").each(function () {
            var filename = this.href.replace(window.location.host, "").replace("http://", "");
            $("body").append("<img src='" + dir + filename + "'>");
        });
    }
});

If you have other extensions, you can make it an array and then go through that one by one using in_array().

P.s : The above source code is not tested.

This application has no explicit mapping for /error

In tutorial, the controller is annotated with @Controller which is used to to create a Map of model object and find a view but @RestController simply return the object and object data is directly written into HTTP response as JSON or XML. If you want to view response, use @RestController or use @ResponseBody as well with @Controller.

@Controller
@ResponseBody

Read more: https://javarevisited.blogspot.com/2017/08/difference-between-restcontroller-and-controller-annotations-spring-mvc-rest.html#ixzz5WtrMSJHJ

What is for Python what 'explode' is for PHP?

The alternative for explode in php is split.

The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.

>>> "Rajasekar SP".split()
['Rajasekar', 'SP']

>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']

How to use JavaScript variables in jQuery selectors?

$("input").click(function(){
        var name = $(this).attr("name");
        $('input[name="' + name + '"]').hide();    
    });   

Also works with ID:

var id = $(this).attr("id");
$('input[id="' + id + '"]').hide();

when, (sometimes)

$('input#' + id).hide();

does not work, as it should.

You can even do both:

$('input[name="' + name + '"][id="' + id + '"]').hide();

SSIS Excel Connection Manager failed to Connect to the Source

Here's the solution that works fine for me.

I just Saved the Excel file as an Excel 97-2003 Version. enter image description here

Syntax error due to using a reserved word as a table or column name in MySQL

The Problem

In MySQL, certain words like SELECT, INSERT, DELETE etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.

As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.

...

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

...

The identifier quote character is the backtick ("`"):

A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.

  • ADD
  • AND
  • BEFORE
  • BY
  • CALL
  • CASE
  • CONDITION
  • DELETE
  • DESC
  • DESCRIBE
  • FROM
  • GROUP
  • IN
  • INDEX
  • INSERT
  • INTERVAL
  • IS
  • KEY
  • LIKE
  • LIMIT
  • LONG
  • MATCH
  • NOT
  • OPTION
  • OR
  • ORDER
  • PARTITION
  • RANK
  • REFERENCES
  • SELECT
  • TABLE
  • TO
  • UPDATE
  • WHERE

The Solution

You have two options.

1. Don't use reserved words as identifiers

The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.

Doing this has a couple of advantages:

  • It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.

  • The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.

Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.

2. Use backticks

If renaming the table or column isn't possible, wrap the offending identifier in backticks (`) as described in the earlier quote from 10.2 Schema Object Names.

An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):

mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax.
near 'interval (begin INT, end INT)'

mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)

Similarly, the query from the question can be fixed by wrapping the keyword key in backticks, as shown below:

INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)";               ^   ^

How can I verify if one list is a subset of another?

Pardon me if I am late to the party. ;)

To check if one set A is subset of set B, Python has A.issubset(B) and A <= B. It works on set only and works great BUT the complexity of internal implementation is unknown. Reference: https://docs.python.org/2/library/sets.html#set-objects

I came up with an algorithm to check if list A is a subset of list B with following remarks.

  • To reduce complexity of finding subset, I find it appropriate to sort both lists first before comparing elements to qualify for subset.
  • It helped me to break the loop when value of element of second list B[j] is greater than value of element of first list A[i].
  • last_index_j is used to start loop over list B where it last left off. It helps avoid starting comparisons from the start of list B (which is, as you might guess unnecessary, to start list B from index 0 in subsequent iterations.)
  • Complexity will be O(n ln n) each for sorting both lists and O(n) for checking for subset.
    O(n ln n) + O(n ln n) + O(n) = O(n ln n).

  • Code has lots of print statements to see what's going on at each iteration of the loop. These are meant for understanding only.

Check if one list is subset of another list

is_subset = True;

A = [9, 3, 11, 1, 7, 2];
B = [11, 4, 6, 2, 15, 1, 9, 8, 5, 3];

print(A, B);

# skip checking if list A has elements more than list B
if len(A) > len(B):
    is_subset = False;
else:
    # complexity of sorting using quicksort or merge sort: O(n ln n)
    # use best sorting algorithm available to minimize complexity
    A.sort();
    B.sort();

    print(A, B);

    # complexity: O(n^2)
    # for a in A:
    #   if a not in B:
    #       is_subset = False;
    #       break;

    # complexity: O(n)
    is_found = False;
    last_index_j = 0;

    for i in range(len(A)):
        for j in range(last_index_j, len(B)):
            is_found = False;

            print("i=" + str(i) + ", j=" + str(j) + ", " + str(A[i]) + "==" + str(B[j]) + "?");

            if B[j] <= A[i]:
                if A[i] == B[j]:
                    is_found = True;
                last_index_j = j;
            else:
                is_found = False;
                break;

            if is_found:
                print("Found: " + str(A[i]));
                last_index_j = last_index_j + 1;
                break;
            else:
                print("Not found: " + str(A[i]));

        if is_found == False:
            is_subset = False;
            break;

print("subset") if is_subset else print("not subset");

Output

[9, 3, 11, 1, 7, 2] [11, 4, 6, 2, 15, 1, 9, 8, 5, 3]
[1, 2, 3, 7, 9, 11] [1, 2, 3, 4, 5, 6, 8, 9, 11, 15]
i=0, j=0, 1==1?
Found: 1
i=1, j=1, 2==1?
Not found: 2
i=1, j=2, 2==2?
Found: 2
i=2, j=3, 3==3?
Found: 3
i=3, j=4, 7==4?
Not found: 7
i=3, j=5, 7==5?
Not found: 7
i=3, j=6, 7==6?
Not found: 7
i=3, j=7, 7==8?
not subset

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine" Error in importing process of xlsx to a sql server

Excel 2010 driver is 64 bit, while the default SSMS import export wizard is 32 therefore the error message.

You can import using the Import Export Data (64 bit) tool. ("C:\Program Files\Microsoft SQL Server\110\DTS\Binn\DTSWizard.exe") notice the path is not Program Files x86.

Angular 5 Button Submit On Enter Key Press

try use keyup.enter or keydown.enter

  <button type="submit" (keyup.enter)="search(...)">Search</button>

How to use OAuth2RestTemplate?

In the answer from @mariubog (https://stackoverflow.com/a/27882337/1279002) I was using password grant types too as in the example but needed to set the client authentication scheme to form. Scopes were not supported by the endpoint for password and there was no need to set the grant type as the ResourceOwnerPasswordResourceDetails object sets this itself in the constructor.

...

public ResourceOwnerPasswordResourceDetails() {
    setGrantType("password");
}

...

The key thing for me was the client_id and client_secret were not being added to the form object to post in the body if resource.setClientAuthenticationScheme(AuthenticationScheme.form); was not set.

See the switch in: org.springframework.security.oauth2.client.token.auth.DefaultClientAuthenticationHandler.authenticateTokenRequest()

Finally, when connecting to Salesforce endpoint the password token needed to be appended to the password.

@EnableOAuth2Client
@Configuration
class MyConfig {

@Value("${security.oauth2.client.access-token-uri}")
private String tokenUrl;

@Value("${security.oauth2.client.client-id}")
private String clientId;

@Value("${security.oauth2.client.client-secret}")
private String clientSecret;

@Value("${security.oauth2.client.password-token}")
private String passwordToken;

@Value("${security.user.name}")
private String username;

@Value("${security.user.password}")
private String password;


@Bean
protected OAuth2ProtectedResourceDetails resource() {

    ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();

    resource.setAccessTokenUri(tokenUrl);
    resource.setClientId(clientId);
    resource.setClientSecret(clientSecret);
    resource.setClientAuthenticationScheme(AuthenticationScheme.form);
    resource.setUsername(username);
    resource.setPassword(password + passwordToken);

    return resource;
}

@Bean
 public OAuth2RestOperations restTemplate() {
    return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));
    }
}


@Service
@SuppressWarnings("unchecked")
class MyService {
    @Autowired
    private OAuth2RestOperations restTemplate;

    public MyService() {
        restTemplate.getAccessToken();
    }
}

How to configure WAMP (localhost) to send email using Gmail?

I've answered that here: (WAMP/XAMP) send Mail using SMTP localhost (works not only GMAIL, but for others too).

Change the URL in the browser without loading the new page using JavaScript

I would strongly suspect this is not possible, because it would be an incredible security problem if it were. For example, I could make a page which looked like a bank login page, and make the URL in the address bar look just like the real bank!

Perhaps if you explain why you want to do this, folks might be able to suggest alternative approaches...

[Edit in 2011: Since I wrote this answer in 2008, more info has come to light regarding an HTML5 technique that allows the URL to be modified as long as it is from the same origin]

warning: assignment makes integer from pointer without a cast

What Jeremiah said, plus the compiler issues the warning because the production:

*src ="anotherstring";

says: take the address of "anotherstring" -- "anotherstring" IS a char pointer -- and store that pointer indirect through src (*src = ... ) into the first char of the string "abcdef..." The warning might be baffling because there is nowhere in your code any mention of any integer: the warning seems nonsensical. But, out of sight behind the curtain, is the rule that "int" and "char" are synonymous in terms of storage: both occupy the same number of bits. The compiler doesn't differentiate when it issues the warning that you are storing into an integer. Which, BTW, is perfectly OK and legal but probably not exactly what you want in this code.

-- pete

Timeout jQuery effects

You can do something like this:

$('.notice')
    .fadeIn()
    .animate({opacity: '+=0'}, 2000)   // Does nothing for 2000ms
    .fadeOut('fast');

Sadly, you can't just do .animate({}, 2000) -- I think this is a bug, and will report it.

How to round up with excel VBA round()?

I find the following function sufficient:

'
' Round Up to the given number of digits
'
Function RoundUp(x As Double, digits As Integer) As Double

    If x = Round(x, digits) Then
        RoundUp = x
    Else
        RoundUp = Round(x + 0.5 / (10 ^ digits), digits)
    End If

End Function

How to force garbage collector to run?

System.GC.Collect() forces garbage collector to run. This is not recommended but can be used if situations arise.

Write a file in UTF-8 using FileWriter (Java)?

OK it's 2019 now, and from Java 11 you have a constructor with Charset:

FileWriter?(String fileName, Charset charset)

Unfortunately, we still cannot modify the byte buffer size, and it's set to 8192. (https://www.baeldung.com/java-filewriter)

How can I append a string to an existing field in MySQL?

You need to use the CONCAT() function in MySQL for string concatenation:

UPDATE categories SET code = CONCAT(code, '_standard') WHERE id = 1;

Merge r brings error "'by' must specify uniquely valid columns"

This is what I tried for a right outer join [as per my requirement]:

m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink, 
            by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"), 
            by.y=c("company_permalink"), all.y=TRUE)

This worked.

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

C and C++ used to be defined by an execution trace of a well formed program.

Now they are half defined by an execution trace of a program, and half a posteriori by many orderings on synchronisation objects.

Meaning that these language definitions make no sense at all as no logical method to mix these two approaches. In particular, destruction of a mutex or atomic variable is not well defined.

C++ class forward declaration

In order for new T to compile, T must be a complete type. In your case, when you say new tile_tree_apple inside the definition of tile_tree::tick, tile_tree_apple is incomplete (it has been forward declared, but its definition is later in your file). Try moving the inline definitions of your functions to a separate source file, or at least move them after the class definitions.

Something like:

class A
{
    void f1();
    void f2();
};
class B
{
   void f3();
   void f4();
};

inline void A::f1() {...}
inline void A::f2() {...}
inline void B::f3() {...}
inline void B::f4() {...}

When you write your code this way, all references to A and B in these methods are guaranteed to refer to complete types, since there are no more forward references!

How to find index of all occurrences of element in array?

Just to share another method, you can use Function Generators to achieve the result as well:

_x000D_
_x000D_
function findAllIndexOf(target, needle) {_x000D_
  return [].concat(...(function*(){_x000D_
    for (var i = 0; i < target.length; i++) if (target[i] === needle) yield [i];_x000D_
  })());_x000D_
}_x000D_
_x000D_
var target = "hellooooo";_x000D_
var target2 = ['w','o',1,3,'l','o'];_x000D_
_x000D_
console.log(findAllIndexOf(target, 'o'));_x000D_
console.log(findAllIndexOf(target2, 'o'));
_x000D_
_x000D_
_x000D_

Escape double quotes for JSON in Python

i know this question is old, but hopefully it will help someone. i found a great plugin for those who are using PyCharm IDE: string-manipulation that can easily escape double quotes (and many more...), this plugin is great for cases where you know what the string going to be. for other cases, using json.dumps(string) will be the recommended solution

str_to_escape = 'my string with "double quotes" blablabla'

after_escape = 'my string with \"double quotes\" blablabla'

What exactly does Double mean in java?

In a comment on @paxdiablo's answer, you asked:

"So basically, is it better to use Double than Float?"

That is a complicated question. I will deal with it in two parts


Deciding between double versus float

On the one hand, a double occupies 8 bytes versus 4 bytes for a float. If you have many of them, this may be significant, though it may also have no impact. (Consider the case where the values are in fields or local variables on a 64bit machine, and the JVM aligns them on 64 bit boundaries.) Additionally, floating point arithmetic with double values is typically slower than with float values ... though once again this is hardware dependent.

On the other hand, a double can represent larger (and smaller) numbers than a float and can represent them with more than twice the precision. For the details, refer to Wikipedia.

The tricky question is knowing whether you actually need the extra range and precision of a double. In some cases it is obvious that you need it. In others it is not so obvious. For instance if you are doing calculations such as inverting a matrix or calculating a standard deviation, the extra precision may be critical. On the other hand, in some cases not even double is going to give you enough precision. (And beware of the trap of expecting float and double to give you an exact representation. They won't and they can't!)

There is a branch of mathematics called Numerical Analysis that deals with the effects of rounding error, etc in practical numerical calculations. It used to be a standard part of computer science courses ... back in the 1970's.


Deciding between Double versus Float

For the Double versus Float case, the issues of precision and range are the same as for double versus float, but the relative performance measures will be slightly different.

  • A Double (on a 32 bit machine) typically takes 16 bytes + 4 bytes for the reference, compared with 12 + 4 bytes for a Float. Compare this to 8 bytes versus 4 bytes for the double versus float case. So the ratio is 5 to 4 versus 2 to 1.

  • Arithmetic involving Double and Float typically involves dereferencing the pointer and creating a new object to hold the result (depending on the circumstances). These extra overheads also affect the ratios in favor of the Double case.


Correctness

Having said all that, the most important thing is correctness, and this typically means getting the most accurate answer. And even if accuracy is not critical, it is usually not wrong to be "too accurate". So, the simple "rule of thumb" is to use double in preference to float, UNLESS there is an overriding performance requirement, AND you have solid evidence that using float will make a difference with respect to that requirement.

JavaScript - cannot set property of undefined

In javascript almost everything is an object, null and undefined are exception.

Instances of Array is an object. so you can set property of an array, for the same reason,you can't set property of a undefined, because its NOT an object

What do the terms "CPU bound" and "I/O bound" mean?

It's pretty intuitive:

A program is CPU bound if it would go faster if the CPU were faster, i.e. it spends the majority of its time simply using the CPU (doing calculations). A program that computes new digits of π will typically be CPU-bound, it's just crunching numbers.

A program is I/O bound if it would go faster if the I/O subsystem was faster. Which exact I/O system is meant can vary; I typically associate it with disk, but of course networking or communication in general is common too. A program that looks through a huge file for some data might become I/O bound, since the bottleneck is then the reading of the data from disk (actually, this example is perhaps kind of old-fashioned these days with hundreds of MB/s coming in from SSDs).

Sorting an array of objects by property values

Descending order of price:

homes.sort((x,y) => {return y.price - x.price})

Ascending order of price:

homes.sort((x,y) => {return x.price - y.price})

What is the most elegant way to check if all values in a boolean array are true?

boolean alltrue = true;
for(int i = 0; alltrue && i<booleanArray.length(); i++)
   alltrue &= booleanArray[i];

I think this looks ok and behaves well...

jQuery set radio button

Try this:

$("#" + newcol).attr("checked", "checked");

I've had issues with attr("checked", true), so I tend to use the above instead.

Also, if you have the ID then you don't need that other stuff for selection. An ID is unique.

SonarQube Exclude a directory

If you're an Azure DevOps user looking for both where and how to exclude files and folders, here ya go:

  1. Edit your pipeline
  2. Make sure you have the "Prepare analysis on SonarQube" task added. You'll need to look elsewhere if you need help configuring this. Suggestion: Use the UI pipeline editor vs the yaml editor if you are missing the manage link. At present, there is no way to convert to UI from yaml. Just recreate the pipeline. If using git, you can delete the yaml from the root of your repo.
  3. Under the 'Advanced' section of the "Prepare analysis on SonarQube" task, you can add exclusions. See advice given by others for specific exclusion formats.

Example:

# Additional properties that will be passed to the scanner, 
# Put one key=value per line, example:
# sonar.exclusions=**/*.bin
sonar.exclusions=MyProjectName/MyWebContentFolder/**

Note: If you're not sure on the path, you can go into sonarqube, view your project, look at all or new 'Code Smells' and the path you need is listed above each grouping of issues. You can grab the full path to a file or use wilds like these examples:

  • MyProjectName/MyCodeFile.cs
  • MyProjectName/**

If you don't have the 'Run Code Analysis' task added, do that and place it somewhere after the 'Build solution **/*.sln' task.

Save and Queue and then check out your sonarqube server to see if the exclusions worked.

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

aapt dump badging test.apk | grep "VersionName" | sed -e "s/.*versionName='//" -e "s/' .*//"

This answers the question by returning only the version number as a result. However......

The goal as previously stated should be to find out if the apk on the server is newer than the one installed BEFORE attempting to download or install it. The easiest way to do this is include the version number in the filename of the apk hosted on the server eg myapp_1.01.apk

You will need to establish the name and version number of the apps already installed (if it is installed) in order to make the comparison. You will need a rooted device or a means of installing the aapt binary and busybox if they are not already included in the rom.

This script will get the list of apps from your server and compare with any installed apps. The result is a list flagged for upgrade/installation.

#/system/bin/sh
SERVER_LIST=$(wget -qO- "http://demo.server.com/apk/" | grep 'href' | grep '\.apk' | sed 's/.*href="//' | \
              sed 's/".*//' | grep -v '\/' | sed -E "s/%/\\\\x/g" | sed -e "s/x20/ /g" -e "s/\\\\//g")
LOCAL_LIST=$(for APP in $(pm list packages -f | sed -e 's/package://' -e 's/=.*//' | sort -u); do \
              INFO=$(echo -n $(aapt dump badging $APP | grep -e 'package: name=' -e 'application: label=')) 2>/dev/null; \
              PACKAGE=$(echo $INFO | sed "s/.*package: name='//" | sed "s/'.*$//"); \
              LABEL=$(echo $INFO | sed "s/.*application: label='//" | sed "s/'.*$//"); if [ -z "$LABEL" ]; then LABEL="$PACKAGE"; fi; \
              VERSION=$(echo $INFO | sed -e "s/.*versionName='//" -e "s/' .*//"); \
              NAME=$LABEL"_"$VERSION".apk"; echo "$NAME"; \
              done;)
OFS=$IFS; IFS=$'\t\n'
for REMOTE in $SERVER_LIST; do
    INSTALLED=0
    REMOTE_NAME=$(echo $REMOTE | sed 's/_.*//'); REMOTE_VER=$(echo $REMOTE | sed 's/^[^_]*_//g' | sed 's/[^0-9]*//g')
    for LOCAL in $LOCAL_LIST; do
        LOCAL_NAME=$(echo $LOCAL | sed 's/_.*//'); LOCAL_VER=$(echo $LOCAL | sed 's/^[^_]*_//g' | sed 's/[^0-9]*//g')
        if [ "$REMOTE_NAME" == "$LOCAL_NAME" ]; then INSTALLED=1; fi
        if [ "$REMOTE_NAME" == "$LOCAL_NAME" ] && [ ! "$REMOTE_VER" == "$LOCAL_VER" ]; then echo remote=$REMOTE ver=$REMOTE_VER local=$LOCAL ver=$LOCAL_VER; fi
    done
    if [ "$INSTALLED" == "0" ]; then echo "$REMOTE"; fi
done
IFS=$OFS

As somebody asked how to do it without using aapt. It is also possible to extract apk info with apktool and a bit of scripting. This way is slower and not simple in android but will work on windows/mac or linux as long as you have working apktool setup.

#!/bin/sh
APK=/path/to/your.apk
TMPDIR=/tmp/apktool
rm -f -R $TMPDIR
apktool d -q -f -s --force-manifest -o $TMPDIR $APK
APK=$(basename $APK)
VERSION=$(cat $TMPDIR/apktool.yml | grep "versionName" | sed -e "s/versionName: //")
LABEL=$(cat $TMPDIR/res/values/strings.xml | grep 'string name="title"' | sed -e 's/.*">//' -e 's/<.*//')
rm -f -R $TMPDIR
echo ${LABEL}_$(echo $V).apk

Also consider a drop folder on your server. Upload apks to it and a cron task renames and moves them to your update folder.

#!/bin/sh
# Drop Folder script for renaming APKs
# Read apk file from SRC folder and move it to TGT folder while changing filename to APKLABEL_APKVERSION.apk
# If an existing version of the APK exists in the target folder then script will remove it
# Define METHOD as "aapt" or "apktool" depending upon what is available on server 

# Variables
METHOD="aapt"
SRC="/home/user/public_html/dropfolders/apk"
TGT="/home/user/public_html/apk"
if [ -d "$SRC" ];then mkdir -p $SRC
if [ -d "$TGT" ]then mkdir -p $TGT

# Functions
get_apk_filename () {
    if [ "$1" = "" ]; then return 1; fi
    local A="$1"
    case $METHOD in
        "apktool")
            local D=/tmp/apktool
            rm -f -R $D
            apktool d -q -f -s --force-manifest -o $D $A
            local A=$(basename $A)
            local V=$(cat $D/apktool.yml | grep "versionName" | sed -e "s/versionName: //")
            local T=$(cat $D/res/values/strings.xml | grep 'string name="title"' | sed -e 's/.*">//' -e 's/<.*//')
            rm -f -R $D<commands>
            ;;
        "aapt")
            local A=$(aapt dump badging $A | grep -e "application-label:" -e "VersionName")
            local V=$(echo $A | sed -e "s/.*versionName='//" -e "s/' .*//")
            local T=$(echo $A | sed -e "s/.*application-label:'//" -e "s/'.*//")
            ;;
        esac
    echo ${T}_$(echo $V).apk
}

# Begin script
for APK in $(ls "$SRC"/*.apk); do
    APKNAME=$(get_apk_filename "$APK")
    rm -f $TGT/$(echo APKNAME | sed "s/_.*//")_*.apk
    mv "$APK" "$TGT"/$APKNAME
done

Cannot access a disposed object - How to fix?

Another place you could stop the timer is the FormClosing event - this happens before the form is actually closed, so is a good place to stop things before they might access unavailable resources.

How to stop mongo DB in one command

Kindly take advantage of the Task Manager provided by your OS for a quick and easy solution. Below is the screengrab from/for Windows 10. Right-click on the highlighted process and select stop. Select start, if already stopped.

enter image description here

Please Note: Internally the commands are doing the same thing which you have to do manually using a GUI (Task Manager), provided by Windows/your OS. Though, this approach to be used for study/practice purpose to get started and you won't be blocked due to this.

What is the difference between onBlur and onChange attribute in HTML?

I think it's important to note here that onBlur() fires regardless.

This is a helpful thread but the only thing it doesn't clarify is that onBlur() will fire every single time.

onChange() will only fire when the value is changed.

What is the difference between i++ & ++i in a for loop?

The difference is that the post-increment operator i++ returns i as it was before incrementing, and the pre-increment operator ++i returns i as it is after incrementing. If you're asking about a typical for loop:

for (i = 0; i < 10; i++)

or

for (i = 0; i < 10; ++i)

They're exactly the same, since you're not using i++ or ++i as a part of a larger expression.

How do you round UP a number in Python?

I think you are confusing the working mechanisms between int() and round().

int() always truncates the decimal numbers if a floating number is given; whereas round(), in case of 2.5 where 2 and 3 are both within equal distance from 2.5, Python returns whichever that is more away from the 0 point.

round(2.5) = 3
int(2.5) = 2

Can't access Eclipse marketplace

in my case: i got a new pc and I had to download and install a brand new eclipse. by default the proxy was set to native. I was getting that error at first. I then changed it to active. And still it didn't work. And then i put it back to "native" and it worked.

bash: shortest way to get n-th column of output

To accomplish the same thing as:

svn st | awk '{print $2}' | xargs rm

using only bash you can use:

svn st | while read a b; do rm "$b"; done

Granted, it's not shorter, but it's a bit more efficient and it handles whitespace in your filenames correctly.

What is the difference between window, screen, and document in Javascript?

Briefly, with more detail below,

  • window is the execution context and global object for that context's JavaScript
  • document contains the DOM, initialized by parsing HTML
  • screen describes the physical display's full screen

See W3C and Mozilla references for details about these objects. The most basic relationship among the three is that each browser tab has its own window, and a window has window.document and window.screen properties. The browser tab's window is the global context, so document and screen refer to window.document and window.screen. More details about the three objects are below, following Flanagan's JavaScript: Definitive Guide.

window

Each browser tab has its own top-level window object. Each <iframe> (and deprecated <frame>) element has its own window object too, nested within a parent window. Each of these windows gets its own separate global object. window.window always refers to window, but window.parent and window.top might refer to enclosing windows, giving access to other execution contexts. In addition to document and screen described below, window properties include

  • setTimeout() and setInterval() binding event handlers to a timer
  • location giving the current URL
  • history with methods back() and forward() giving the tab's mutable history
  • navigator describing the browser software

document

Each window object has a document object to be rendered. These objects get confused in part because HTML elements are added to the global object when assigned a unique id. E.g., in the HTML snippet

<body>
  <p id="holyCow"> This is the first paragraph.</p>
</body>

the paragraph element can be referenced by any of the following:

  • window.holyCow or window["holyCow"]
  • document.getElementById("holyCow")
  • document.querySelector("#holyCow")
  • document.body.firstChild
  • document.body.children[0]

screen

The window object also has a screen object with properties describing the physical display:

  • screen properties width and height are the full screen

  • screen properties availWidth and availHeight omit the toolbar

The portion of a screen displaying the rendered document is the viewport in JavaScript, which is potentially confusing because we call an application's portion of the screen a window when talking about interactions with the operating system. The getBoundingClientRect() method of any document element will return an object with top, left, bottom, and right properties describing the location of the element in the viewport.

How do I redirect to the previous action in ASP.NET MVC?

Pass a returnUrl parameter (url encoded) to the change and login actions and inside redirect to this given returnUrl. Your login action might look something like this:

public ActionResult Login(string returnUrl) 
{
    // Do something...
    return Redirect(returnUrl);
}

What is the difference between min SDK version/target SDK version vs. compile SDK version?

The min sdk version is the minimum version of the Android operating system required to run your application.

The target sdk version is the version of Android that your app was created to run on.

The compile sdk version is the the version of Android that the build tools uses to compile and build the application in order to release, run, or debug.

Usually the compile sdk version and the target sdk version are the same.

How to insert element as a first child?

$(".child-div div:first").before("Your div code or some text");

What does print(... sep='', '\t' ) mean?

sep='' in the context of a function call sets the named argument sep to an empty string. See the print() function; sep is the separator used between multiple values when printing. The default is a space (sep=' '), this function call makes sure that there is no space between Property tax: $ and the formatted tax floating point value.

Compare the output of the following three print() calls to see the difference

>>> print('foo', 'bar')
foo bar
>>> print('foo', 'bar', sep='')
foobar
>>> print('foo', 'bar', sep=' -> ')
foo -> bar

All that changed is the sep argument value.

\t in a string literal is an escape sequence for tab character, horizontal whitespace, ASCII codepoint 9.

\t is easier to read and type than the actual tab character. See the table of recognized escape sequences for string literals.

Using a space or a \t tab as a print separator shows the difference:

>>> print('eggs', 'ham')
eggs ham
>>> print('eggs', 'ham', sep='\t')
eggs    ham

Running multiple commands with xargs

You can use

cat file.txt | xargs -i  sh -c 'command {} | command2 {} && command3 {}'

{} = variable for each line on the text file

How is the AND/OR operator represented as in Regular Expressions?

Not an expert in regex, but you can do ^((part1|part2)|(part1, part2))$. In words: "part 1 or part2 or both"

SVN repository backup strategies

@echo off
set hour=%time:~0,2%
if "%hour:~0,1%"==" " set hour=0%time:~1,1%
set folder=%date:~6,4%%date:~3,2%%date:~0,2%%hour%%time:~3,2%

echo Performing Backup
md "\\HOME\Development\Backups\SubVersion\%folder%"

svnadmin dump "C:\Users\Yakyb\Desktop\MainRepositary\Jake" | "C:\Program Files\7-Zip\7z.exe" a "\\HOME\Development\Backups\SubVersion\%folder%\Jake.7z" -sibackupname.svn

This is the Batch File i have running that performs my Backups

Convert datetime to Unix timestamp and convert it back in python

def datetime_to_epoch(d1):

    # create 1,1,1970 in same timezone as d1
    d2 = datetime(1970, 1, 1, tzinfo=d1.tzinfo)
    time_delta = d1 - d2
    ts = int(time_delta.total_seconds())
    return ts


def epoch_to_datetime_string(ts, tz_name="UTC"):
    x_timezone = timezone(tz_name)
    d1 = datetime.fromtimestamp(ts, x_timezone)
    x = d1.strftime("%d %B %Y %H:%M:%S")
    return x

Regular expression for a hexadecimal number?

If you're using Perl or PHP, you can replace

[0-9a-fA-F]

with:

[[:xdigit:]]

How to set a default value with Html.TextBoxFor?

The default value will be the value of your Model.Age property. That's kind of the whole point.

pip install from git repo branch

Prepend the url prefix git+ (See VCS Support):

pip install git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6

And specify the branch name without the leading /.

Flutter: RenderBox was not laid out

Reading answers here, it seems that the error "RenderBox was not laid out" is caused when somehow the ListView size is limitless and this can happen in different scenarios.

Just aiming to help who may have the same case as mine. In my case, I was getting this error because my ListView was inside a a column whose parent was a SingleChildScrollView. I remove this parent and it worked.

Here is my working code:

 List _todoList = ["AAA", "BBB"];

 ...

    body: Column(
      children: [
        Container(...),
        Expanded(
            child: ListView.builder(
                itemCount: _todoList.length,
                itemBuilder: (context, index) {
                  return ListTile(title: Text(_todoList[index]));
                }))
      ],
    ));

Here how it was when I was getting the "not laid out" error:

     List _todoList = ["AAA", "BBB"];

     ...


     body: SingleChildScrollView(child: Column(
      children: [
        Container(...),
        Expanded(
            child: ListView.builder(
                itemCount: _todoList.length,
                itemBuilder: (context, index) {
                  return ListTile(title: Text(_todoList[index]));
                }))
      ],
    )));

I hope this may be useful for someone.

How do I print bold text in Python?

In straight-up computer programming, there is no such thing as "printing bold text". Let's back up a bit and understand that your text is a string of bytes and bytes are just bundles of bits. To the computer, here's your "hello" text, in binary.

0110100001100101011011000110110001101111

Each one or zero is a bit. Every eight bits is a byte. Every byte is, in a string like that in Python 2.x, one letter/number/punctuation item (called a character). So for example:

01101000 01100101 01101100 01101100 01101111
h        e        l        l        o

The computer translates those bits into letters, but in a traditional string (called an ASCII string), there is nothing to indicate bold text. In a Unicode string, which works a little differently, the computer can support international language characters, like Chinese ones, but again, there's nothing to say that some text is bold and some text is not. There's also no explicit font, text size, etc.

In the case of printing HTML, you're still outputting a string. But the computer program reading that string (a web browser) is programmed to interpret text like this is <b>bold</b> as "this is bold" when it converts your string of letters into pixels on the screen. If all text were WYSIWYG, the need for HTML itself would be mitigated -- you would just select text in your editor and bold it instead of typing out the HTML.

Other programs use different systems -- a lot of answers explained a completely different system for printing bold text on terminals. I'm glad you found out how to do what you want to do, but at some point, you'll want to understand how strings and memory work.

Closing Twitter Bootstrap Modal From Angular Controller

You can do it with a simple jquery code.

$('#Mymodal').modal('hide');

Find the IP address of the client in an SSH session

I'm getting the following output from who -m --ips on Debian 10:

root pts/0 Dec 4 06:45 123.123.123.123

Looks like a new column was added, so {print $5} or "take 5th column" attempts don't work anymore.

Try this:

who -m --ips | egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}'

Source:

How big can a MySQL database get before performance starts to degrade

Also watch out for complex joins. Transaction complexity can be a big factor in addition to transaction volume.

Refactoring heavy queries sometimes offers a big performance boost.

Select last row in MySQL

You can combine two queries suggested by @spacepille into single query that looks like this:

SELECT * FROM `table_name` WHERE id=(SELECT MAX(id) FROM `table_name`);

It should work blazing fast, but on INNODB tables it's fraction of milisecond slower than ORDER+LIMIT.

Check if a string is palindrome

Reverse the string and check if original string and reverse are same or not

Check if Internet Connection Exists with jQuery?

I wrote a jQuery plugin for doing this. By default it checks the current URL (because that's already loaded once from the Web) or you can specify a URL to use as an argument. Always doing a request to Google isn't the best idea because it's blocked in different countries at different times. Also you might be at the mercy of what the connection across a particular ocean/weather front/political climate might be like that day.

http://tomriley.net/blog/archives/111

Is it possible to disable the network in iOS Simulator?

You can throttle the internet connection with a 3rd party app such as

Charles: http://www.charlesproxy.com/

Hit command + shift + T on a Mac to setup the throttling.

How to add border around linear layout except at the bottom?

Here is a Github link to a lightweight and very easy to integrate library that enables you to play with borders as you want for any widget you want, simply based on a FrameLayout widget.

Here is a quick sample code for you to see how easy it is, but you will find more information on the link.

<com.khandelwal.library.view.BorderFrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:leftBorderColor="#00F0F0"
            app:leftBorderWidth="10dp"
            app:topBorderColor="#F0F000"
            app:topBorderWidth="15dp"
            app:rightBorderColor="#F000F0"
            app:rightBorderWidth="20dp"
            app:bottomBorderColor="#000000"
            app:bottomBorderWidth="25dp" >
    </com.khandelwal.library.view.BorderFrameLayout>

So, if you don't want borders on bottom, delete the two lines about bottom in this custom widget, and that's done.

And no, I'm neither the author of this library nor one of his friend ;-)

REST API - Use the "Accept: application/json" HTTP Header

You guessed right, HTTP Headers are not part of the URL.

And when you type a URL in the browser the request will be issued with standard headers. Anyway REST Apis are not meant to be consumed by typing the endpoint in the address bar of a browser.

The most common scenario is that your server consumes a third party REST Api.

To do so your server-side code forges a proper GET (/PUT/POST/DELETE) request pointing to a given endpoint (URL) setting (when needed, like your case) some headers and finally (maybe) sending some data (as typically occurrs in a POST request for example).

The code to forge the request, send it and finally get the response back depends on your server side language.

If you want to test a REST Api you may use curl tool from the command line.

curl makes a request and outputs the response to stdout (unless otherwise instructed).

In your case the test request would be issued like this:

$curl -H "Accept: application/json" 'http://localhost:8080/otp/routers/default/plan?fromPlace=52.5895,13.2836&toPlace=52.5461,13.3588&date=2017/04/04&time=12:00:00'

The H or --header directive sets a header and its value.

Does it matter what extension is used for SQLite database files?

SQLite doesn't define any particular extension for this, it's your own choice. Personally, I name them with the .sqlite extension, just so there isn't any ambiguity when I'm looking at my files later.

DNS problem, nslookup works, ping doesn't

I had this problem occasionally when using a multi-label name ie test.internal

The solution for me was to stop/start the dnscache on my windows 7 machine. Open a console as administrator and type

net stop dnscache
net start dnscache

then sigh and look for a way to get a Mac as your principal desktop.

How to convert answer into two decimal point

Try using the Format function:

Private Sub btncalc_Click(ByVal sender As System.Object,
                          ByVal e As System.EventArgs) Handles btncalc.Click
  txtA.Text = Format(Val(txtD.Text) / Val(txtC.Text) * 
                     Val(txtF.Text) / Val(txtE.Text), "0.00")
  txtB.Text = Format(Val(txtA.Text) * 1000 / Val(txtG.Text), "0.00")
End Sub

how to use a like with a join in sql?

Using conditional criteria in a join is definitely different than the Where clause. The cardinality between the tables can create differences between Joins and Where clauses.

For example, using a Like condition in an Outer Join will keep all records in the first table listed in the join. Using the same condition in the Where clause will implicitly change the join to an Inner join. The record has to generally be present in both tables to accomplish the conditional comparison in the Where clause.

I generally use the style given in one of the prior answers.

tbl_A as ta
    LEFT OUTER JOIN tbl_B AS tb
            ON ta.[Desc] LIKE '%' + tb.[Desc] + '%'

This way I can control the join type.

Bootstrap 3.0: How to have text and input on same line?

just give mother of div "class="col-lg-12""

<div class="form-group">
<div class="row">
    <div class="col-xs-3">
        <label for="class_type"><h2><span class=" label label-primary">Class Type</span></h2></label>
    </div>
    <div class="col-xs-2">
        <select name="class_type" id="class_type" class="  form-control input-lg" style="width:200px" autocomplete="off">
            <option >Economy</option>
            <option >Premium Economy</option>
            <option >Club World</option>
            <option >First Class</option>
        </select>
    </div>
 </div>

it will be

<div class="form-group">
<div class="col-lg-12">
  <div class="row">
    <div class="col-xs-3">
        <label for="class_type"><h2><span class=" label label-primary">Class Type</span></h2></label>
    </div>
    <div class="col-xs-2">
        <select name="class_type" id="class_type" class="  form-control input-lg" style="width:200px" autocomplete="off">
            <option >Economy</option>
            <option >Premium Economy</option>
            <option >Club World</option>
            <option >First Class</option>
        </select>
    </div>
</div>
</div>

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

This should work.

SELECT a.[CUSTOMER ID], a.[NAME], SUM(b.[AMOUNT]) AS [TOTAL AMOUNT]
FROM RES_DATA a INNER JOIN INV_DATA b
ON a.[CUSTOMER ID]=b.[CUSTOMER ID]
GROUP BY a.[CUSTOMER ID], a.[NAME]

I tested it with SQL Fiddle against SQL Server 2008: http://sqlfiddle.com/#!3/1cad5/1

Basically what's happening here is that, because of the join, you are getting the same row on the "left" (i.e. from the RES_DATA table) for every row on the "right" (i.e. the INV_DATA table) that has the same [CUSTOMER ID] value. When you group by just the columns on the left side, and then do a sum of just the [AMOUNT] column from the right side, it keeps the one row intact from the left side, and sums up the matching values from the right side.

How would I access variables from one class to another?

var1 and var2 are instance variables. That means that you have to send the instance of ClassA to ClassB in order for ClassB to access it, i.e:

class ClassA(object):
    def __init__(self):
        self.var1 = 1
        self.var2 = 2

    def methodA(self):
        self.var1 = self.var1 + self.var2
        return self.var1



class ClassB(ClassA):
    def __init__(self, class_a):
        self.var1 = class_a.var1
        self.var2 = class_a.var2

object1 = ClassA()
sum = object1.methodA()
object2 = ClassB(object1)
print sum

On the other hand - if you were to use class variables, you could access var1 and var2 without sending object1 as a parameter to ClassB.

class ClassA(object):
    var1 = 0
    var2 = 0
    def __init__(self):
        ClassA.var1 = 1
        ClassA.var2 = 2

    def methodA(self):
        ClassA.var1 = ClassA.var1 + ClassA.var2
        return ClassA.var1



class ClassB(ClassA):
    def __init__(self):
        print ClassA.var1
        print ClassA.var2

object1 = ClassA()
sum = object1.methodA()
object2 = ClassB()
print sum

Note, however, that class variables are shared among all instances of its class.

How to make the corners of a button round?

You can also use the card layout like below

  <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        app:cardCornerRadius="30dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"

            >

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="Template"

                />

        </LinearLayout>

    </androidx.cardview.widget.CardView>

How do I get today's date in C# in mm/dd/yyyy format?

Or without the year:

DateTime.Now.ToString("M/dd")

Delete all SYSTEM V shared memory and semaphores on UNIX-like systems

Since you mentioned that you're working on a NFS system, do you have access to those semaphores and shared memory? I think you misunderstood what they are, they are an API code that enables processes to communicate with each other, semaphores are a solution for preventing race conditions and for threads to communicate with each other, in simple answer, they do not leave any residue on any filesystem.

Unless you are using an socket or a pipe? Do you have the necessary permissions to remove them, why are they on an NFS system?

Hope this helps, Best regards, Tom.

How can I handle the warning of file_get_contents() function in PHP?

function custom_file_get_contents($url) {
    return file_get_contents(
        $url,
        false,
        stream_context_create(
            array(
                'http' => array(
                    'ignore_errors' => true
                )
            )
        )
    );
}

$content=FALSE;

if($content=custom_file_get_contents($url)) {
    //play with the result
} else {
    //handle the error
}

How to check if any flags of a flag combination are set?

How about

if ((letter & Letters.AB) > 0)

?

How to update values using pymongo?

You can use the $set syntax if you want to set the value of a document to an arbitrary value. This will either update the value if the attribute already exists on the document or create it if it doesn't. If you need to set a single value in a dictionary like you describe, you can use the dot notation to access child values.

If p is the object retrieved:

existing = p['d']['a']

For pymongo versions < 3.0

db.ProductData.update({
  '_id': p['_id']
},{
  '$set': {
    'd.a': existing + 1
  }
}, upsert=False, multi=False)

For pymongo versions >= 3.0

db.ProductData.update_one({
  '_id': p['_id']
},{
  '$set': {
    'd.a': existing + 1
  }
}, upsert=False)

However if you just need to increment the value, this approach could introduce issues when multiple requests could be running concurrently. Instead you should use the $inc syntax:

For pymongo versions < 3.0:

db.ProductData.update({
  '_id': p['_id']
},{
  '$inc': {
    'd.a': 1
  }
}, upsert=False, multi=False)

For pymongo versions >= 3.0:

db.ProductData.update_one({
  '_id': p['_id']
},{
  '$inc': {
    'd.a': 1
  }
}, upsert=False)

This ensures your increments will always happen.

Programmatically Creating UILabel

here is how to create UILabel Programmatically..

1) Write this in .h file of your project.

UILabel *label;

2) Write this in .m file of your project.

label=[[UILabel alloc]initWithFrame:CGRectMake(10, 70, 50, 50)];//Set frame of label in your viewcontroller.
[label setBackgroundColor:[UIColor lightGrayColor]];//Set background color of label.
[label setText:@"Label"];//Set text in label.
[label setTextColor:[UIColor blackColor]];//Set text color in label.
[label setTextAlignment:NSTextAlignmentCenter];//Set text alignment in label.
[label setBaselineAdjustment:UIBaselineAdjustmentAlignBaselines];//Set line adjustment.
[label setLineBreakMode:NSLineBreakByCharWrapping];//Set linebreaking mode..
[label setNumberOfLines:1];//Set number of lines in label.
[label.layer setCornerRadius:25.0];//Set corner radius of label to change the shape.
[label.layer setBorderWidth:2.0f];//Set border width of label.
[label setClipsToBounds:YES];//Set its to YES for Corner radius to work.
[label.layer setBorderColor:[UIColor blackColor].CGColor];//Set Border color.
[self.view addSubview:label];//Add it to the view of your choice. 

jQuery deferreds and promises - .then() vs .done()

.done() has only one callback and it is the success callback

.then() has both success and fail callbacks

.fail() has only one fail callback

so it is up to you what you must do... do you care if it succeeds or if it fails?

What is the preferred Bash shebang?

Using a shebang line to invoke the appropriate interpreter is not just for BASH. You can use the shebang for any interpreted language on your system such as Perl, Python, PHP (CLI) and many others. By the way, the shebang

#!/bin/sh -

(it can also be two dashes, i.e. --) ends bash options everything after will be treated as filenames and arguments.

Using the env command makes your script portable and allows you to setup custom environments for your script hence portable scripts should use

#!/usr/bin/env bash

Or for whatever the language such as for Perl

#!/usr/bin/env perl

Be sure to look at the man pages for bash:

man bash

and env:

man env

Note: On Debian and Debian-based systems, like Ubuntu, sh is linked to dash not bash. As all system scripts use sh. This allows bash to grow and the system to stay stable, according to Debian.

Also, to keep invocation *nix like I never use file extensions on shebang invoked scripts, as you cannot omit the extension on invocation on executables as you can on Windows. The file command can identify it as a script.

Xcode 5 and iOS 7: Architecture and Valid architectures

Set the architecture in build setting to Standard architectures(armv7,armv7s)

enter image description here

iPhone 5S is powered by A7 64bit processor. From apple docs

Xcode can build your app with both 32-bit and 64-bit binaries included. This combined binary requires a minimum deployment target of iOS 7 or later.

Note: A future version of Xcode will let you create a single app that supports the 32-bit runtime on iOS 6 and later, and that supports the 64-bit runtime on iOS 7.

From the documentation what i understood is

  • Xcode can create both 64bit 32bit binaries for a single app but the deployment target should be iOS7. They are saying in future it will be iOS 6.0
  • 32 bit binary will work fine in iPhone 5S(64 bit processor).

Update (Xcode 5.0.1)
In Xcode 5.0.1 they added the support to create 64 bit binary for iOS 5.1.1 onwards.

Xcode 5.0.1 can build your app with both 32-bit and 64-bit binaries included. This combined binary requires a minimum deployment target of iOS 5.1.1 or later. The 64-bit binary runs only on 64-bit devices running iOS 7.0.3 and later.

Update (Xcode 5.1)
Xcode 5.1 made significant change in the architecture section. This answer will be a followup for you. Check this

How do I make an editable DIV look like a text field?

The problem with all these is they don't address if the lines of text are long and much wider that the div overflow:auto does not ad a scroll bar that works right. Here is the perfect solution I found:

Create two divs. An inner div that is wide enough to handle the widest line of text and then a smaller outer one which acts at the holder for the inner div:

<div style="border:2px inset #AAA;cursor:text;height:120px;overflow:auto;width:500px;">
    <div style="width:800px;">

     now really long text like this can be put in the text area and it will really <br/>
     look and act more like a real text area bla bla bla <br/>

    </div>
</div>

Installing specific laravel version with composer create-project

Installing specific laravel version with composer create-project

composer global require laravel/installer

Then, if you want install specific version then just edit version values "6." , "5.8."

composer create-project --prefer-dist laravel/laravel Projectname "6.*"

Run Local Development Server

php artisan serve

HTML form readonly SELECT tag/input

Rather than the select itself, you could disable all of the options except for the currently selected option. This gives the appearance of a working drop-down, but only the option you want passed in is a valid selection.

In bash, how to store a return value in a variable?

The return value (aka exit code) is a value in the range 0 to 255 inclusive. It's used to indicate success or failure, not to return information. Any value outside this range will be wrapped.

To return information, like your number, use

echo "$value"

To print additional information that you don't want captured, use

echo "my irrelevant info" >&2 

Finally, to capture it, use what you did:

 result=$(password_formula)

In other words:

echo "enter: "
        read input

password_formula()
{
        length=${#input}
        last_two=${input:length-2:length}
        first=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $2}'`
        second=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $1}'`
        let sum=$first+$second
        sum_len=${#sum}
        echo $second >&2
        echo $sum >&2

        if [ $sum -gt 9 ]
        then
               sum=${sum:1}
        fi

        value=$second$sum$first
        echo $value
}
result=$(password_formula)
echo "The value is $result"

How do I tell a Python script to use a particular version

For those using pyenv to control their virtual environments, I have found this to work in a script:

#!/home/<user>/.pyenv/versions/<virt_name>/bin/python

DO_STUFF

What is the difference between Scala's case class and class?

No one mentioned that case classes are also instances of Product and thus inherit these methods:

def productElement(n: Int): Any
def productArity: Int
def productIterator: Iterator[Any]

where the productArity returns the number of class parameters, productElement(i) returns the ith parameter, and productIterator allows iterating through them.

SQL - Update multiple records in one query

Try either multi-table update syntax

UPDATE config t1 JOIN config t2
    ON t1.config_name = 'name1' AND t2.config_name = 'name2'
   SET t1.config_value = 'value',
       t2.config_value = 'value2';

Here is SQLFiddle demo

or conditional update

UPDATE config
   SET config_value = CASE config_name 
                      WHEN 'name1' THEN 'value' 
                      WHEN 'name2' THEN 'value2' 
                      ELSE config_value
                      END
 WHERE config_name IN('name1', 'name2');

Here is SQLFiddle demo

Cannot open include file with Visual Studio

For me, it helped to link the projects current directory as such:

In the properties -> C++ -> General window, instead of linking the path to the file in "additional include directories". Put "." and uncheck "inheret from parent or project defaults".

Hope this helps.

How to print a linebreak in a python function?

>>> A = ['a1', 'a2', 'a3']
>>> B = ['b1', 'b2', 'b3']

>>> for x in A:
        for i in B:
            print ">" + x + "\n" + i

Outputs:

>a1
b1
>a1
b2
>a1
b3
>a2
b1
>a2
b2
>a2
b3
>a3
b1
>a3
b2
>a3
b3

Notice that you are using /n which is not correct!

What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?

VALID padding: this is with zero padding. Hope there is no confusion.

x = tf.constant([[1., 2., 3.], [4., 5., 6.],[ 7., 8., 9.], [ 7., 8., 9.]])
x = tf.reshape(x, [1, 4, 3, 1])
valid_pad = tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID')
print (valid_pad.get_shape()) # output-->(1, 2, 1, 1)

SAME padding: This is kind of tricky to understand in the first place because we have to consider two conditions separately as mentioned in the official docs.

Let's take input as , output as , padding as , stride as and kernel size as (only a single dimension is considered)

Case 01: :

Case 02: :

is calculated such that the minimum value which can be taken for padding. Since value of is known, value of can be found using this formula .

Let's work out this example:

x = tf.constant([[1., 2., 3.], [4., 5., 6.],[ 7., 8., 9.], [ 7., 8., 9.]])
x = tf.reshape(x, [1, 4, 3, 1])
same_pad = tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
print (same_pad.get_shape()) # --> output (1, 2, 2, 1)

Here the dimension of x is (3,4). Then if the horizontal direction is taken (3):

If the vertial direction is taken (4):

Hope this will help to understand how actually SAME padding works in TF.

How to define two fields "unique" as couple

Django 2.2+

Using the constraints features UniqueConstraint is preferred over unique_together.

From the Django documentation for unique_together:

Use UniqueConstraint with the constraints option instead.
UniqueConstraint provides more functionality than unique_together.
unique_together may be deprecated in the future.

For example:

class Volume(models.Model):
    id = models.AutoField(primary_key=True)
    journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name="Journal")
    volume_number = models.CharField('Volume Number', max_length=100)
    comments = models.TextField('Comments', max_length=4000, blank=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['journal_id', 'volume_number'], name='name of constraint')
        ]

Brew doctor says: "Warning: /usr/local/include isn't writable."

The only one that worked for me on El Capitan was:

sudo chown -R $(whoami) /usr/local

The response content cannot be parsed because the Internet Explorer engine is not available, or

In your invoke web request just use the parameter -UseBasicParsing

e.g. in your script (line 2) you should use:

$rss = Invoke-WebRequest -UseBasicParsing

According to the documentation, this parameter is necessary on systems where IE isn't installed or configured.

Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.

Split comma-separated input box values into array in jquery, and loop through it

var array = searchTerms.split(",");

for (var i in array){
     alert(array[i]);
}

Format JavaScript date as yyyy-mm-dd

I suggest using something like formatDate-js instead of trying to replicate it every time. Just use a library that supports all the major strftime actions.

new Date().format("%Y-%m-%d")

Converting dictionary to JSON

json.dumps() converts a dictionary to str object, not a json(dict) object! So you have to load your str into a dict to use it by using json.loads() method

See json.dumps() as a save method and json.loads() as a retrieve method.

This is the code sample which might help you understand it more:

import json

r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
loaded_r = json.loads(r)
loaded_r['rating'] #Output 3.5
type(r) #Output str
type(loaded_r) #Output dict

Can I pass a JavaScript variable to another browser window?

Yes browsers clear all ref. for a window. So you have to search a ClassName of something on the main window or use cookies as Javascript homemade ref.

I have a radio on my project page. And then you turn on for the radio it´s starts in a popup window and i controlling the main window links on the main page and show status of playing and in FF it´s easy but in MSIE not so Easy at all. But it can be done.

Selenium IDE - Command to wait for 5 seconds

This will wait until your link has appeared, and then you can click it.

Command: waitForElementPresent Target: link=do something Value:

Get full path of the files in PowerShell

This should perform much faster than using late filtering:

Get-ChildItem C:\WINDOWS\System32 -Filter *.txt -Recurse | % { $_.FullName }

How can I calculate the difference between two dates?

You can find the difference by converting the date in seconds and take time interval since 1970 for this and then you can find the difference between two dates.

Assign a login to a user created without login (SQL Server)

Through trial and error, it seems if the user was originally created "without login" then this query

select * from sys.database_principals

will show authentication_type = 0 (NONE).

Apparently these users cannot be re-linked to any login (pre-existing or new, SQL or Windows) since this command:

alter user [TempUser] with login [TempLogin]

responds with the Remap Error "Msg 33016" shown in the question.

Also these users do not show up in classic (deprecating) SP report:

exec sp_change_users_login 'Report'

If anyone knows a way around this or how to change authentication_type, please comment.

How to automatically generate getters and setters in Android Studio

Using Alt+ Insert for Windows or Command+ N for Mac in the editor, you may easily generate getter and setter methods for any fields of your class. This has the same effect as using the Menu Bar -> Code -> Generate...

enter image description here

and then using shift or control button, select all the variables you need to add getters and setters

How to send 500 Internal Server Error error from a PHP script

You can just put:

header("HTTP/1.0 500 Internal Server Error");

inside your conditions like:

if (that happened) {
    header("HTTP/1.0 500 Internal Server Error");
}

As for the database query, you can just do that like this:

$result = mysql_query("..query string..") or header("HTTP/1.0 500 Internal Server Error");

You should remember that you have to put this code before any html tag (or output).

ReactJS - Get Height of an element

I found useful npm package https://www.npmjs.com/package/element-resize-detector

An optimized cross-browser resize listener for elements.

Can use it with React component or functional component(Specially useful for react hooks)

How can I have two fixed width columns with one flexible column in the center?

Compatibility with older browsers can be a drag, so be adviced.

If that is not a problem then go ahead. Run the snippet. Go to full page view and resize. Center will resize itself with no changes to the left or right divs.

Change left and right values to meet your requirement.

Thank you.

Hope this helps.

_x000D_
_x000D_
#container {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.column.left {_x000D_
  width: 100px;_x000D_
  flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.right {_x000D_
  width: 100px;_x000D_
  flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.center {_x000D_
  flex: 1;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.column.left,_x000D_
.column.right {_x000D_
  background: orange;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div class="column left">this is left</div>_x000D_
  <div class="column center">this is center</div>_x000D_
  <div class="column right">this is right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is it possible to add dynamically named properties to JavaScript object?

I was looking for a solution where I can use dynamic key-names inside the object declaration (without using ES6 features like ... or [key]: value)

Here's what I came up with:

var obj = (obj = {}, obj[field] = 123, obj)

It looks a little bit complex at first, but it's really simple. We use the Comma Operator to run three commands in a row:

  1. obj = {}: creates a new object and assigns it to the variable obj
  2. obj[field] = 123: adds a computed property name to obj
  3. obj: use the obj variable as the result of the parentheses/comma list

This syntax can be used inside a function parameter without the requirement to explictely declare the obj variable:

_x000D_
_x000D_
// The test function to see the result.
function showObject(obj) {
    console.log(obj);
}

// My dynamic field name.
var field = "myDynamicField";

// Call the function with our dynamic object.
showObject( (obj = {}, obj[field] = 123, obj) );

/*
Output:

{
  "myDynamicField": true
}
*/
_x000D_
_x000D_
_x000D_

Some variations

"strict mode" workaround:

The above code does not work in strict mode because the variable "obj" is not declared.

// This gives the same result, but declares the global variable `this.obj`!
showObject( (this.obj = {}, obj[field] = 123, obj) );

ES2015 code using computed property names in initializer:

// Works in most browsers, same result as the other functions.
showObject( {[field] = 123} );

This solution works in all modern browsers (but not in IE, if I need to mention that)

Super hacky way using JSON.parse():

// Create a JSON string that is parsed instantly. Not recommended in most cases.
showObject( JSON.parse( '{"' + field +'":123}') );
// read: showObject( JSON.parse( '{"myDynamicfield":123}') );

Allows special characters in keys

Note that you can also use spaces and other special characters inside computed property names (and also in JSON.parse).

var field = 'my dynamic field :)';
showObject( {[field] = 123} );
// result: { "my dynamic field :)": 123 }

Those fields cannot be accessed using a dot (obj.my dynamic field :) is obviously syntactically invalid), but only via the bracket-notation, i.e., obj['my dynamic field :)'] returns 123

Xcode error - Thread 1: signal SIGABRT

SIGABRT is, as stated in other answers, a general uncaught exception. You should definitely learn a little bit more about Objective-C. The problem is probably in your UITableViewDelegate method didSelectRowAtIndexPath.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

I can't tell you much more until you show us something of the code where you handle the table data source and delegate methods.

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

Use string instead of string? in all places in your code.

The Nullable<T> type requires that T is a non-nullable value type, for example int or DateTime. Reference types like string can already be null. There would be no point in allowing things like Nullable<string> so it is disallowed.

Also if you are using C# 3.0 or later you can simplify your code by using auto-implemented properties:

public class WordAndMeaning
{
    public string Word { get; set; }
    public string Meaning { get; set; }
}

URL to load resources from the classpath in Java

I dont know if there is one already, but you can make it yourself easilly.

That different protocols example looks to me like a facade pattern. You have a common interface when there are different implementations for each case.

You could use the same principle, make a ResourceLoader class which takes the string from your properties file, and checks for a custom protocol of ours

myprotocol:a.xml
myprotocol:file:///tmp.txt
myprotocol:http://127.0.0.1:8080/a.properties
myprotocol:jar:http://www.foo.com/bar/baz.jar!/COM/foo/Quux.class

strips the myprotocol: from the start of the string and then makes a decision of which way to load the resource, and just gives you the resource.

Can I call a function of a shell script from another shell script?

Refactor your second.sh script like this:

function func1 {
   fun=$1
   book=$2
   printf "fun=%s,book=%s\n" "${fun}" "${book}"
}

function func2 {
   fun2=$1
   book2=$2
   printf "fun2=%s,book2=%s\n" "${fun2}" "${book2}"
}

And then call these functions from script first.sh like this:

source ./second.sh
func1 love horror
func2 ball mystery

OUTPUT:

fun=love,book=horror
fun2=ball,book2=mystery

How can I use iptables on centos 7?

RHEL and CentOS 7 use firewall-cmd instead of iptables. You should use that kind of command:

# add ssh port as permanent opened port
firewall-cmd --zone=public --add-port=22/tcp --permanent

Then, you can reload rules to be sure that everything is ok

firewall-cmd --reload

This is better than using iptable-save, espacially if you plan to use lxc or docker containers. Launching docker services will add some rules that iptable-save command will prompt. If you save the result, you will have a lot of rules that should NOT be saved. Because docker containers can change them ip addresses at next reboot.

Firewall-cmd with permanent option is better for that.

Check "man firewall-cmd" or check the official firewalld docs to see options. There are a lot of options to check zones, configuration, how it works... man page is really complete.

I strongly recommand to not use iptables-service since Centos 7

Make page to tell browser not to cache/preserve input values

Basically, there are two ways to clear the cache:

<form autocomplete="off"></form>

or

$('#Textfiledid').attr('autocomplete', 'off');

TypeError: 'dict_keys' object does not support indexing

Why you need to implement shuffle when it already exists? Stay on the shoulders of giants.

import random

d1 = {0:'zero', 1:'one', 2:'two', 3:'three', 4:'four',
     5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine'}

keys = list(d1)
random.shuffle(keys)

d2 = {}
for key in keys: d2[key] = d1[key]

print(d1)
print(d2)

ARM compilation error, VFP registers used by executable, not object file

I have found on an arm hardfloat system where glibc binutils and gcc were crosscompiled, using gcc gives the same error.

It is solved by exporting-mfloat-abi=hard to flags, then gcc compiles without errors.

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

If you are getting this message from a Maven built war change the scope of the JDBC driver to provided, and put a copy of it in the lib directory. Like this:

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.18</version>
  <!-- put a copy in /usr/share/tomcat7/lib -->
  <scope>provided</scope>
</dependency>

Where is my m2 folder on Mac OS X Mavericks

On the top of the screen you can find the Finder. Click Go -> Go to Folder -> search ~/.m2

If it is not found, as m2 is a hidden file you need to enable visibility by typing the following command in terminal:

defaults write com.apple.finder AppleShowAllFiles YES

Bash script plugin for Eclipse?

Just follow the official instructions from ShellEd's InstallGuide

How to validate email id in angularJs using ng-pattern

There is nice example how to deal with this kind of problem modyfing built-in validators angulardocs. I have only added more strict validation pattern.

app.directive('validateEmail', function() {
  var EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;

  return {
    require: 'ngModel',
    restrict: '',
    link: function(scope, elm, attrs, ctrl) {
      // only apply the validator if ngModel is present and Angular has added the email validator
      if (ctrl && ctrl.$validators.email) {

        // this will overwrite the default Angular email validator
        ctrl.$validators.email = function(modelValue) {
          return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
        };
      }
    }
  };
});

And simply add

<input type='email' validate-email name='email' id='email' ng-model='email' required>  

How do you create a Spring MVC project in Eclipse?

  1. step 1: create a new "Dynamic Web Project" in eclipse.
  2. step 2: right click on the created project.
  3. step 3: click on "configure" option.
  4. step 4: click on "convert to maven project".

here is more detailed information -> [1]: https://crunchify.com/simplest-spring-mvc-hello-world-example-tutorial-spring-model-view-controller-tips/

Linq to SQL .Sum() without group ... into

Try:

itemsCard.ToList().Select(c=>c.Price).Sum();

Actually this would perform better:

var itemsInCart = from o in db.OrderLineItems
              where o.OrderId == currentOrder.OrderId
              select new { o.WishListItem.Price };
var sum = itemsCard.ToList().Select(c=>c.Price).Sum();

Because you'll only be retrieving one column from the database.

Python error message io.UnsupportedOperation: not readable

This will let you read, write and create the file if it don't exist:

f = open('filename.txt','a+')
f = open('filename.txt','r+')

Often used commands:

f.readline() #Read next line
f.seek(0) #Jump to beginning
f.read(0) #Read all file
f.write('test text') #Write 'test text' to file
f.close() #Close file

Bootstrap 3 hidden-xs makes row narrower

.row {
    margin-right: 15px;
}

throw this in your CSS

Add Favicon with React and Webpack

Adding your favicon simply into to the public folder should do. Make sure the favicon is named as favicon.ico.

What does <> mean?

Yes in SQl <> is the same as != which is not equal.....excepts for NULLS of course, in that case you need to use IS NULL or IS NOT NULL

How do I encrypt and decrypt a string in python?

You may use Fernet as follows:

from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
encrypt_value = f.encrypt(b"YourString")
f.decrypt(encrypt_value)

Laravel 4: Redirect to a given url

You can also use redirect() method like this:-

return redirect('https://stackoverflow.com/');

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

Set content of HTML <span> with Javascript

The Maximally Standards Compliant way to do it is to create a text node containing the text you want and append it to the span (removing any currently extant text nodes).

The way I would actually do it is to use jQuery's .text().

How to extract an assembly from the GAC?

just navigate to C:\Windows find the [assembly] folder right click and select add to archive

wait a little

vola you have an archive file containing all the assemblies in your GAC

How to turn off the Eclipse code formatter for certain sections of Java code?

@xpmatteo has the answer to disabling portions of code, but in addition to this, the default eclipse settings should be set to only format edited lines of code instead of the whole file.

Preferences->Java->Editor->Save Actions->Format Source Code->Format Edited Lines

This would have prevented it from happening in the first place since your coworkers are reformatting code they didn't actually change. This is a good practice to prevent mishaps that render diff on your source control useless (when an entire file is reformatted because of minor format setting differences).

It would also prevent the reformatting if the on/off tags option was turned off.

What is the best/simplest way to read in an XML file in Java application?

There are of course a lot of good solutions based on what you need. If it is just configuration, you should have a look at Jakarta commons-configuration and commons-digester.

You could always use the standard JDK method of getting a document :

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

[...]

File file = new File("some/path");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);

Angular 2 router.navigate

If the first segment doesn't start with / it is a relative route. router.navigate needs a relativeTo parameter for relative navigation

Either you make the route absolute:

this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)

or you pass relativeTo

this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})

See also

Spring Boot Java Config Set Session Timeout

server.session.timeout in the application.properties file is now deprecated. The correct setting is:

server.servlet.session.timeout=60s

Also note that Tomcat will not allow you to set the timeout any less than 60 seconds. For details about that minimum setting see https://github.com/spring-projects/spring-boot/issues/7383.

Git clone without .git directory

You can always do

git clone git://repo.org/fossproject.git && rm -rf fossproject/.git

XPath with multiple conditions

Here, we can do this way as well:

//category [@name='category name']/author[contains(text(),'authorname')]

OR

//category [@name='category name']//author[contains(text(),'authorname')]

To Learn XPATH in detail please visit- selenium xpath in detail

What are the obj and bin folders (created by Visual Studio) used for?

The obj directory is for intermediate object files and other transient data files that are generated by the compiler or build system during a build. The bin directory is the directory that final output binaries (and any dependencies or other deployable files) will be written to.

You can change the actual directories used for both purposes within the project settings, if you like.

How can I limit ngFor repeat to some number of items in Angular?

 <div *ngFor="let item of list;trackBy: trackByFunc" >
   {{item.value}}
 </div>

In your ts file

 trackByFunc(index, item){
    return item ? item.id : undefined;
  }

git ignore vim temporary files

Here is the actual VIM code that generates the swap file extensions:

/* 
 * Change the ".swp" extension to find another file that can be used. 
 * First decrement the last char: ".swo", ".swn", etc. 
 * If that still isn't enough decrement the last but one char: ".svz" 
 * Can happen when editing many "No Name" buffers. 
 */
if (fname[n - 1] == 'a')        /* ".s?a" */
{   
    if (fname[n - 2] == 'a')    /* ".saa": tried enough, give up */
    {   
        EMSG(_("E326: Too many swap files found"));
        vim_free(fname);
        fname = NULL;
        break;  
    }
    --fname[n - 2];             /* ".svz", ".suz", etc. */
    fname[n - 1] = 'z' + 1;
}
--fname[n - 1];                 /* ".swo", ".swn", etc. */

This will generate swap files of the format:

[._]*.s[a-v][a-z]
[._]*.sw[a-p]
[._]s[a-v][a-z]
[._]sw[a-p]

Which is pretty much what is included in github's own gitignore file for VIM.

As others have correctly noted, this .gitignore will also ignore .svg image files and .swf adobe flash files.

What is the difference between declarative and imperative paradigm in programming?

I liked an explanation from a Cambridge course + their examples:

  • Declarative - specify what to do, not how to do it
    • E.g.: HTML describes what should appear on a web page, not how it should be drawn on the screen
  • Imperative - specify both what and how
    • int x; - what (declarative)
    • x=x+1; - how

JSON string to JS object

Some modern browsers have support for parsing JSON into a native object:

var var1 = '{"cols": [{"i" ....... 66}]}';
var result = JSON.parse(var1);

For the browsers that don't support it, you can download json2.js from json.org for safe parsing of a JSON object. The script will check for native JSON support and if it doesn't exist, provide the JSON global object instead. If the faster, native object is available it will just exit the script leaving it intact. You must, however, provide valid JSON or it will throw an error — you can check the validity of your JSON with http://jslint.com or http://jsonlint.com.

Trying to SSH into an Amazon Ec2 instance - permission error

BY default permission are not allowing the pem key. You just have to change the permission:

chmod 400 xyz.pem

and if ubuntu instance then connect using:

ssh -i xyz.pem [email protected]

C# equivalent of the IsNull() function in SQL Server

    public static T IsNull<T>(this T DefaultValue, T InsteadValue)
    {

        object obj="kk";

        if((object) DefaultValue == DBNull.Value)
        {
            obj = null;
        }

        if (obj==null || DefaultValue==null || DefaultValue.ToString()=="")
        {
            return InsteadValue;
        }
        else
        {
            return DefaultValue;
        }

    }

//This method can work with DBNull and null value. This method is question's answer

Comma separated results in SQL

I just saw another question very similar to this!

Here is the canonical NORTHWIND (spelled just slightly different for some reason) database example.

SELECT *
FROM [NORTHWND].[dbo].[Products]

enter image description here

SELECT CategoryId,
           MAX( CASE seq WHEN 1 THEN ProductName ELSE '' END ) + ', ' +
           MAX( CASE seq WHEN 2 THEN ProductName ELSE '' END ) + ', ' +
           MAX( CASE seq WHEN 3 THEN ProductName ELSE '' END ) + ', ' +
           MAX( CASE seq WHEN 4 THEN ProductName ELSE '' END )
      FROM ( SELECT p1.CategoryId, p1.ProductName,
                    ( SELECT COUNT(*) 
                        FROM NORTHWND.dbo.Products p2
                        WHERE p2.CategoryId = p1.CategoryId
                        AND p2.ProductName <= p1.ProductName )
             FROM NORTHWND.dbo.Products p1 ) D ( CategoryId, ProductName, seq )
     GROUP BY CategoryId ;

enter image description here

How can an html element fill out 100% of the remaining screen height, using css only?

#Header
{
width: 960px;
height: 150px;
}

#Content
{
min-height:100vh;
height: 100%;
width: 960px;
}

Prevent WebView from displaying "web page not available"

I would just change the webpage to whatever you are using for error handling:

getWindow().requestFeature(Window.FEATURE_PROGRESS);  
webview.getSettings().setJavaScriptEnabled(true);  
final Activity activity = this;  
webview.setWebChromeClient(new WebChromeClient() {  
public void onProgressChanged(WebView view, int progress) {  
 // Activities and WebViews measure progress with different scales.  
 // The progress meter will automatically disappear when we reach 100%  
 activity.setProgress(progress * 1000);  
 }  
});  
webview.setWebViewClient(new WebViewClient() {  
public void onReceivedError(WebView view, int errorCode, String description, String 
failingUrl) {  
 Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();  
}  
});  
webview.loadUrl("http://slashdot.org/");

this can all be found on http://developer.android.com/reference/android/webkit/WebView.html

Purge or recreate a Ruby on Rails database

From the command line run

rake db:migrate:reset

how to append a css class to an element by javascript?

you could use setAttribute.

Example: For adding one class:

 document.getElementById('main').setAttribute("class","classOne"); 

For multiple classes:

 document.getElementById('main').setAttribute("class", "classOne classTwo"); 

Plot yerr/xerr as shaded region rather than error bars

Ignoring the smooth interpolation between points in your example graph (that would require doing some manual interpolation, or just have a higher resolution of your data), you can use pyplot.fill_between():

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape)
y += np.random.normal(0, 0.1, size=y.shape)

plt.plot(x, y, 'k-')
plt.fill_between(x, y-error, y+error)
plt.show()

enter image description here

See also the matplotlib examples.

Add string in a certain position in Python

I think the above answers are fine, but I would explain that there are some unexpected-but-good side effects to them...

def insert(string_s, insert_s, pos_i=0):
    return string_s[:pos_i] + insert_s + string_s[pos_i:]

If the index pos_i is very small (too negative), the insert string gets prepended. If too long, the insert string gets appended. If pos_i is between -len(string_s) and +len(string_s) - 1, the insert string gets inserted into the correct place.

How to declare an array in Python?

To add to Lennart's answer, an array may be created like this:

from array import array
float_array = array("f",values)

where values can take the form of a tuple, list, or np.array, but not array:

values = [1,2,3]
values = (1,2,3)
values = np.array([1,2,3],'f')
# 'i' will work here too, but if array is 'i' then values have to be int
wrong_values = array('f',[1,2,3])
# TypeError: 'array.array' object is not callable

and the output will still be the same:

print(float_array)
print(float_array[1])
print(isinstance(float_array[1],float))

# array('f', [1.0, 2.0, 3.0])
# 2.0
# True

Most methods for list work with array as well, common ones being pop(), extend(), and append().

Judging from the answers and comments, it appears that the array data structure isn't that popular. I like it though, the same way as one might prefer a tuple over a list.

The array structure has stricter rules than a list or np.array, and this can reduce errors and make debugging easier, especially when working with numerical data.

Attempts to insert/append a float to an int array will throw a TypeError:

values = [1,2,3]
int_array = array("i",values)
int_array.append(float(1))
# or int_array.extend([float(1)])

# TypeError: integer argument expected, got float

Keeping values which are meant to be integers (e.g. list of indices) in the array form may therefore prevent a "TypeError: list indices must be integers, not float", since arrays can be iterated over, similar to np.array and lists:

int_array = array('i',[1,2,3])
data = [11,22,33,44,55]
sample = []
for i in int_array:
    sample.append(data[i])

Annoyingly, appending an int to a float array will cause the int to become a float, without throwing an exception.

np.array retain the same data type for its entries too, but instead of giving an error it will change its data type to fit new entries (usually to double or str):

import numpy as np
numpy_int_array = np.array([1,2,3],'i')
for i in numpy_int_array:
    print(type(i))
    # <class 'numpy.int32'>
numpy_int_array_2 = np.append(numpy_int_array,int(1))
# still <class 'numpy.int32'>
numpy_float_array = np.append(numpy_int_array,float(1))
# <class 'numpy.float64'> for all values
numpy_str_array = np.append(numpy_int_array,"1")
# <class 'numpy.str_'> for all values
data = [11,22,33,44,55]
sample = []
for i in numpy_int_array_2:
    sample.append(data[i])
    # no problem here, but TypeError for the other two

This is true during assignment as well. If the data type is specified, np.array will, wherever possible, transform the entries to that data type:

int_numpy_array = np.array([1,2,float(3)],'i')
# 3 becomes an int
int_numpy_array_2 = np.array([1,2,3.9],'i')
# 3.9 gets truncated to 3 (same as int(3.9))
invalid_array = np.array([1,2,"string"],'i')
# ValueError: invalid literal for int() with base 10: 'string'
# Same error as int('string')
str_numpy_array = np.array([1,2,3],'str')
print(str_numpy_array)
print([type(i) for i in str_numpy_array])
# ['1' '2' '3']
# <class 'numpy.str_'>

or, in essence:

data = [1.2,3.4,5.6]
list_1 = np.array(data,'i').tolist()
list_2 = [int(i) for i in data]
print(list_1 == list_2)
# True

while array will simply give:

invalid_array = array([1,2,3.9],'i')
# TypeError: integer argument expected, got float

Because of this, it is not a good idea to use np.array for type-specific commands. The array structure is useful here. list preserves the data type of the values.

And for something I find rather pesky: the data type is specified as the first argument in array(), but (usually) the second in np.array(). :|

The relation to C is referred to here: Python List vs. Array - when to use?

Have fun exploring!

Note: The typed and rather strict nature of array leans more towards C rather than Python, and by design Python does not have many type-specific constraints in its functions. Its unpopularity also creates a positive feedback in collaborative work, and replacing it mostly involves an additional [int(x) for x in file]. It is therefore entirely viable and reasonable to ignore the existence of array. It shouldn't hinder most of us in any way. :D

How to add parameters into a WebRequest?

If these are the parameters of url-string then you need to add them through '?' and '&' chars, for example http://example.com/index.aspx?username=Api_user&password=Api_password.

If these are the parameters of POST request, then you need to create POST data and write it to request stream. Here is sample method:

private static string doRequestWithBytesPostData(string requestUri, string method, byte[] postData,
                                        CookieContainer cookieContainer,
                                        string userAgent, string acceptHeaderString,
                                        string referer,
                                        string contentType, out string responseUri)
        {
            var result = "";
            if (!string.IsNullOrEmpty(requestUri))
            {
                var request = WebRequest.Create(requestUri) as HttpWebRequest;
                if (request != null)
                {
                    request.KeepAlive = true;
                    var cachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
                    request.CachePolicy = cachePolicy;
                    request.Expect = null;
                    if (!string.IsNullOrEmpty(method))
                        request.Method = method;
                    if (!string.IsNullOrEmpty(acceptHeaderString))
                        request.Accept = acceptHeaderString;
                    if (!string.IsNullOrEmpty(referer))
                        request.Referer = referer;
                    if (!string.IsNullOrEmpty(contentType))
                        request.ContentType = contentType;
                    if (!string.IsNullOrEmpty(userAgent))
                        request.UserAgent = userAgent;
                    if (cookieContainer != null)
                        request.CookieContainer = cookieContainer;

                    request.Timeout = Constants.RequestTimeOut;

                    if (request.Method == "POST")
                    {
                        if (postData != null)
                        {
                            request.ContentLength = postData.Length;
                            using (var dataStream = request.GetRequestStream())
                            {
                                dataStream.Write(postData, 0, postData.Length);
                            }
                        }
                    }

                    using (var httpWebResponse = request.GetResponse() as HttpWebResponse)
                    {
                        if (httpWebResponse != null)
                        {
                            responseUri = httpWebResponse.ResponseUri.AbsoluteUri;
                            cookieContainer.Add(httpWebResponse.Cookies);
                            using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                            {
                                result = streamReader.ReadToEnd();
                            }
                            return result;
                        }
                    }
                }
            }
            responseUri = null;
            return null;
        }

How to allow only numeric (0-9) in HTML inputbox using jQuery?

Here is the function I use:

// Numeric only control handler
jQuery.fn.ForceNumericOnly =
function()
{
    return this.each(function()
    {
        $(this).keydown(function(e)
        {
            var key = e.charCode || e.keyCode || 0;
            // allow backspace, tab, delete, enter, arrows, numbers and keypad numbers ONLY
            // home, end, period, and numpad decimal
            return (
                key == 8 || 
                key == 9 ||
                key == 13 ||
                key == 46 ||
                key == 110 ||
                key == 190 ||
                (key >= 35 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        });
    });
};

You can then attach it to your control by doing:

$("#yourTextBoxName").ForceNumericOnly();

Calling startActivity() from outside of an Activity?

This same error I have faced in case of getting Notification in latest Android devices 9 and 10.

It depends on Launch mode how you are handling it. Use below code:- android:launchMode="singleTask"

Add this flag with Intent:- intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

HTML table with 100% width, with vertical scroll inside tbody

For using "overflow: scroll" you must set "display:block" on thead and tbody. And that messes up column widths between them. But then you can clone the thead row with Javascript and paste it in the tbody as a hidden row to keep the exact col widths.

$('.myTable thead > tr').clone().appendTo('.myTable tbody').addClass('hidden-to-set-col-widths');

http://jsfiddle.net/Julesezaar/mup0c5hk/

<table class="myTable">
    <thead>
        <tr>
            <td>Problem</td>
            <td>Solution</td>
            <td>blah</td>
            <td>derp</td>
        </tr>
    </thead>
    <tbody></tbody>
</table>
<p>
  Some text to here
</p>

The css:

table {
  background-color: #aaa;
  width: 100%;
}

thead,
tbody {
  display: block; // Necessary to use overflow: scroll
}

tbody {
  background-color: #ddd;
  height: 150px;
  overflow-y: scroll;
}

tbody tr.hidden-to-set-col-widths,
tbody tr.hidden-to-set-col-widths td {
  visibility: hidden;
  height: 0;
  line-height: 0;
  padding-top: 0;
  padding-bottom: 0;
}

td {
  padding: 3px 10px;
}

Converting Integers to Roman Numerals - Java

After doing some research and analysing answers above, I ended up with this:

package roman;

public class RomanNumbers {


public static final int[] decimal = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
public static final String[] letters = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};

public static String stringToRoman(int num) {
    String roman = "";

    if (num < 1 || num > 3999) {
        System.out.println("Invalid roman number value!");
    }

    while (num > 0) {
        int maxFound = 0;
        for (int i=0; i < decimal.length; i++) {
            if (num >= decimal[i]) {
                maxFound = i;
            }
        }
        roman += letters[maxFound];
        num -= decimal[maxFound];
    }

    return roman;       
  }
}

Unit tests also passed:

package roman;

import static org.junit.Assert.*;

import org.junit.Test;

public class RomanNumbersTest {

@Test
public void testReturn1() {
    String actual = RomanNumbers.stringToRoman(1);
    String expected = "I";
    assertEquals(expected, actual);
}

@Test
public void testReturn5() {
    String actual = RomanNumbers.stringToRoman(5);
    String expected = "V";
    assertEquals(expected, actual);
}

@Test
public void testReturn2() {
    String actual = RomanNumbers.stringToRoman(2);
    String expected = "II";
    assertEquals(expected, actual);
}

@Test
public void testReturn4() {
    String actual = RomanNumbers.stringToRoman(4);
    String expected = "IV";
    assertEquals(expected, actual);
}

@Test
public void testReturn399() {
    String actual = RomanNumbers.stringToRoman(399);
    String expected = "CCCXCIX";
    assertEquals(expected, actual);
}

@Test
public void testReturn3992() {
    String actual = RomanNumbers.stringToRoman(3992);
    String expected = "MMMCMXCII";
    assertEquals(expected, actual);
}
}

What is Linux’s native GUI API?

The linux kernel graphical operations are in /include/linux/fb.h as struct fb_ops. Eventually this is what add-ons like X11, Wayland, or DRM appear to reference. As these operations are only for video cards, not vector or raster hardcopy or tty oriented terminal devices, their usefulness as a GUI is limited; it's just not entirely true you need those add-ons to get graphical output if you don't mind using some assembler to bypass syscall as necessary.

How to load image (and other assets) in Angular an project?

Being specific to Angular2 to 5, we can bind image path using property binding as below. Image path is enclosed by the single quotation marks.

Sample example

<img [src]="'assets/img/klogo.png'" alt="image">

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

Is nested function a good approach when required by only one function?

It's perfectly OK doing it that way, but unless you need to use a closure or return the function I'd probably put in the module level. I imagine in the second code example you mean:

...
some_data = method_b() # not some_data = method_b

otherwise, some_data will be the function.

Having it at the module level will allow other functions to use method_b() and if you're using something like Sphinx (and autodoc) for documentation, it will allow you to document method_b as well.

You also may want to consider just putting the functionality in two methods in a class if you're doing something that can be representable by an object. This contains logic well too if that's all you're looking for.

Is there any simple way to convert .xls file to .csv file? (Excel)

Checkout the .SaveAs() method in Excel object.

wbWorkbook.SaveAs("c:\yourdesiredFilename.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV)

Or following:

public static void SaveAs()
{
    Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();
    Microsoft.Office.Interop.Excel.Workbook wbWorkbook = app.Workbooks.Add(Type.Missing);
    Microsoft.Office.Interop.Excel.Sheets wsSheet = wbWorkbook.Worksheets;
    Microsoft.Office.Interop.Excel.Worksheet CurSheet = (Microsoft.Office.Interop.Excel.Worksheet)wsSheet[1];

    Microsoft.Office.Interop.Excel.Range thisCell = (Microsoft.Office.Interop.Excel.Range)CurSheet.Cells[1, 1];

    thisCell.Value2 = "This is a test.";

    wbWorkbook.SaveAs(@"c:\one.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    wbWorkbook.SaveAs(@"c:\two.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    wbWorkbook.Close(false, "", true);
}

Select2 open dropdown on focus

Here is an alternate solution for version 4.x of Select2. You can use listeners to catch the focus event and then open the select.

$('#test').select2({
    // Initialisation here
}).data('select2').listeners['*'].push(function(name, target) { 
    if(name == 'focus') {
        $(this.$element).select2("open");
    }
});

Find the working example here based the exampel created by @tonywchen

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

If you are using spring-boot for server side coding then please add a servlet filter and add the following code of your spring-boot application. It should work. Adding "Access-Control-Allow-Headers", "*" is mandatory. Creation of proxy.conf.json is not needed.

    @Component
@Order(1)
public class MyProjectFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,PATCH,DELETE,PUT,OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Max-Age", "86400");
        chain.doFilter(req, res);
    }
}

best way to get folder and file list in Javascript

fs/promises and fs.Dirent

Here's an efficient, non-blocking ls program using Node's fast fs.Dirent objects and fs/promises module. This approach allows you to skip wasteful fs.exist or fs.stat calls on every path -

// main.js
import { readdir } from "fs/promises"
import { join } from "path"

async function* ls (path = ".")
{ yield path
  for (const dirent of await readdir(path, { withFileTypes: true }))
    if (dirent.isDirectory())
      yield* ls(join(path, dirent.name))
    else
      yield join(path, dirent.name)
}

async function* empty () {}

async function toArray (iter = empty())
{ let r = []
  for await (const x of iter)
    r.push(x)
  return r
}

toArray(ls(".")).then(console.log, console.error)

Let's get some sample files so we can see ls working -

$ yarn add immutable     # (just some example package)
$ node main.js
[
  '.',
  'main.js',
  'node_modules',
  'node_modules/.yarn-integrity',
  'node_modules/immutable',
  'node_modules/immutable/LICENSE',
  'node_modules/immutable/README.md',
  'node_modules/immutable/contrib',
  'node_modules/immutable/contrib/cursor',
  'node_modules/immutable/contrib/cursor/README.md',
  'node_modules/immutable/contrib/cursor/__tests__',
  'node_modules/immutable/contrib/cursor/__tests__/Cursor.ts.skip',
  'node_modules/immutable/contrib/cursor/index.d.ts',
  'node_modules/immutable/contrib/cursor/index.js',
  'node_modules/immutable/dist',
  'node_modules/immutable/dist/immutable-nonambient.d.ts',
  'node_modules/immutable/dist/immutable.d.ts',
  'node_modules/immutable/dist/immutable.es.js',
  'node_modules/immutable/dist/immutable.js',
  'node_modules/immutable/dist/immutable.js.flow',
  'node_modules/immutable/dist/immutable.min.js',
  'node_modules/immutable/package.json',
  'package.json',
  'yarn.lock'
]

For added explanation and other ways to leverage async generators, see this Q&A.

How to access JSON decoded array in PHP

$data = json_decode($json, true);
echo $data[0]["c_name"]; // "John"


$data = json_decode($json);
echo $data[0]->c_name;      // "John"

How do I compile jrxml to get jasper?

with maven it is automatic:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>jasperreports-maven-plugin</artifactId>
  <configuration>
    <outputDirectory>target/${project.artifactId}/WEB-INF/reports</outputDirectory>
  </configuration>
  <executions>
    <execution>
      <phase>prepare-package</phase>
      <inherited>false</inherited>
      <goals>
         <goal>compile-reports</goal>
      </goals>
    </execution>
  </executions>
  <dependencies>
    <dependency>
       <groupId>net.sf.jasperreports</groupId>
       <artifactId>jasperreports</artifactId>
       <version>3.7.6</version> 
    </dependency>
    <dependency>
       <groupId>log4j</groupId>
       <artifactId>log4j</artifactId>
       <version>1.2.16</version>
       <type>jar</type>
     </dependency>
  </dependencies>
</plugin>

Convert Unicode data to int in python

In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.

So to convert string limit="100" to a number, you need to do

limit = int(limit) # will return new object (integer) and assign to "limit"

If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:

def int_in_place(mutable):
    mutable[0] = int(mutable[0])

mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer

But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).

Markdown and image alignment

Even cleaner would be to just put p#given img { float: right } in the style sheet, or in the <head> and wrapped in style tags. Then, just use the markdown ![Alt text](/path/to/img.jpg).

Finish all activities at a time

Use

finishAffinity ();

Instead of:

System.exit(); or finish();

it exit full application or all activity.

Java: export to an .jar file in eclipse

No need for external plugins. In the Export JAR dialog, make sure you select all the necessary resources you want to export. By default, there should be no problem exporting other resource files as well (pictures, configuration files, etc...), see screenshot below. JAR Export Dialog

"Char cannot be dereferenced" error

If Character.isLetter(ch) looks a bit wordy/ugly you can use a static import.

import static java.lang.Character.*;


if(isLetter(ch)) {

} else if(isDigit(ch)) {

} 

Flask raises TemplateNotFound error even though template file exists

My problem was that the file I was referencing from inside my home.html was a .j2 instead of a .html, and when I changed it back jinja could read it.

Stupid error but it might help someone.

Python - Check If Word Is In A String

find returns an integer representing the index of where the search item was found. If it isn't found, it returns -1.

haystack = 'asdf'

haystack.find('a') # result: 0
haystack.find('s') # result: 1
haystack.find('g') # result: -1

if haystack.find(needle) >= 0:
  print 'Needle found.'
else:
  print 'Needle not found.'

What is the difference between git clone and checkout?

Simply git checkout have 2 uses

  1. Switching between existing local branches like git checkout <existing_local_branch_name>
  2. Create a new branch from current branch using flag -b. Suppose if you are at master branch then git checkout -b <new_feature_branch_name> will create a new branch with the contents of master and switch to newly created branch

You can find more options at the official site

What is and how to fix System.TypeInitializationException error?

i. Please check the InnerException property of the TypeInitializationException

ii. Also, this may occur due to mismatch between the runtime versions of the assemblies. Please verify the runtime versions of the main assembly (calling application) and the referred assembly

how to fetch array keys with jQuery?

you can use the each function:

var a = {};
a['alfa'] = 0;
a['beta'] = 1;
$.each(a, function(key, value) {
      alert(key)
});

it has several nice shortcuts/tricks: check the gory details here

Working copy locked error in tortoise svn while committing

I had no idea what file was having the lock so what I did to get out of this issue was:

  1. Went to the highest level folder
  2. Click clean-up and also ticked from the cleaning-up methods --> Break locks

This worked for me.

Where does R store packages?

The install.packages command looks through the .libPaths variable. Here's what mine defaults to on OSX:

> .libPaths()
[1] "/Library/Frameworks/R.framework/Resources/library"

I don't install packages there by default, I prefer to have them installed in my home directory. In my .Rprofile, I have this line:

.libPaths( "/Users/tex/lib/R" )

This adds the directory "/Users/tex/lib/R" to the front of the .libPaths variable.

How to solve ADB device unauthorized in Android ADB host device?

Delete the folder .android from C:/users/<user name>/.android. It solved the issue for me.

shell-script headers (#!/bin/sh vs #!/bin/csh)

The #! line tells the kernel (specifically, the implementation of the execve system call) that this program is written in an interpreted language; the absolute pathname that follows identifies the interpreter. Programs compiled to machine code begin with a different byte sequence -- on most modern Unixes, 7f 45 4c 46 (^?ELF) that identifies them as such.

You can put an absolute path to any program you want after the #!, as long as that program is not itself a #! script. The kernel rewrites an invocation of

./script arg1 arg2 arg3 ...

where ./script starts with, say, #! /usr/bin/perl, as if the command line had actually been

/usr/bin/perl ./script arg1 arg2 arg3

Or, as you have seen, you can use #! /bin/sh to write a script intended to be interpreted by sh.

The #! line is only processed if you directly invoke the script (./script on the command line); the file must also be executable (chmod +x script). If you do sh ./script the #! line is not necessary (and will be ignored if present), and the file does not have to be executable. The point of the feature is to allow you to directly invoke interpreted-language programs without having to know what language they are written in. (Do grep '^#!' /usr/bin/* -- you will discover that a great many stock programs are in fact using this feature.)

Here are some rules for using this feature:

  • The #! must be the very first two bytes in the file. In particular, the file must be in an ASCII-compatible encoding (e.g. UTF-8 will work, but UTF-16 won't) and must not start with a "byte order mark", or the kernel will not recognize it as a #! script.
  • The path after #! must be an absolute path (starts with /). It cannot contain space, tab, or newline characters.
  • It is good style, but not required, to put a space between the #! and the /. Do not put more than one space there.
  • You cannot put shell variables on the #! line, they will not be expanded.
  • You can put one command-line argument after the absolute path, separated from it by a single space. Like the absolute path, this argument cannot contain space, tab, or newline characters. Sometimes this is necessary to get things to work (#! /usr/bin/awk -f), sometimes it's just useful (#! /usr/bin/perl -Tw). Unfortunately, you cannot put two or more arguments after the absolute path.
  • Some people will tell you to use #! /usr/bin/env interpreter instead of #! /absolute/path/to/interpreter. This is almost always a mistake. It makes your program's behavior depend on the $PATH variable of the user who invokes the script. And not all systems have env in the first place.
  • Programs that need setuid or setgid privileges can't use #!; they have to be compiled to machine code. (If you don't know what setuid is, don't worry about this.)

Regarding csh, it relates to sh roughly as Nutrimat Advanced Tea Substitute does to tea. It has (or rather had; modern implementations of sh have caught up) a number of advantages over sh for interactive usage, but using it (or its descendant tcsh) for scripting is almost always a mistake. If you're new to shell scripting in general, I strongly recommend you ignore it and focus on sh. If you are using a csh relative as your login shell, switch to bash or zsh, so that the interactive command language will be the same as the scripting language you're learning.

Get UTC time in seconds

I bet this is what was intended as a result.

$ date -u --date=@1404372514
Thu Jul  3 07:28:34 UTC 2014

How to add Tomcat Server in eclipse

Do as this:

Windows -> Show View -> Servers

Then in the Servers view, right-click and add new. It will show a pop up containing many server vendors. Under Apache select Tomcat v7.0 (Depending upon your downloaded server version). And in the run time configuration point it to the Tomcat folder you have downloaded.

You can try this article. It has the info you want !!

wget command to download a file and save as a different filename

You would use the command Mechanical snail listed. Notice the uppercase O. Full command line to use could be:

wget www.examplesite.com/textfile.txt --output-document=newfile.txt

or

wget www.examplesite.com/textfile.txt -O newfile.txt

Hope that helps.

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

HTTPScoop is awesome for inspecting the web traffic on your Mac. It's been incredibly helpful for me. I didn't think twice about the $15 price tag. There is a 14 day trial.

How do I insert a JPEG image into a python Tkinter window?

Try this:

import tkinter as tk
from PIL import ImageTk, Image

#This creates the main window of an application
window = tk.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')

path = "Aaron.jpg"

#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img = ImageTk.PhotoImage(Image.open(path))

#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
panel = tk.Label(window, image = img)

#The Pack geometry manager packs widgets in rows or columns.
panel.pack(side = "bottom", fill = "both", expand = "yes")

#Start the GUI
window.mainloop()

Related docs: ImageTk Module, Tkinter Label Widget, Tkinter Pack Geometry Manager

Permission denied for relation

Make sure you log into psql as the owner of the tables. to find out who own the tables use \dt

psql -h CONNECTION_STRING DBNAME -U OWNER_OF_THE_TABLES

then you can run the GRANTS