Programs & Examples On #Vcbuild

How to write a unit test for a Spring Boot Controller endpoint

The new testing improvements that debuted in Spring Boot 1.4.M2 can help reduce the amount of code you need to write situation such as these.

The test would look like so:

import static org.springframework.test.web.servlet.request.MockMvcRequestB??uilders.get; 
import static org.springframework.test.web.servlet.result.MockMvcResultMat??chers.content; 
import static org.springframework.test.web.servlet.result.MockMvcResultMat??chers.status;

    @RunWith(SpringRunner.class)
    @WebMvcTest(HelloWorld.class)
    public class UserVehicleControllerTests {

        @Autowired
        private MockMvc mockMvc;

        @Test
        public void testSayHelloWorld() throws Exception {
            this.mockMvc.perform(get("/").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
                    .andExpect(status().isOk())
                    .andExpect(content().contentType("application/json"));

        }

    }

See this blog post for more details as well as the documentation

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

For Spring 5.2+ this works for me:

@PostMapping("/foo")
ResponseEntity<Void> foo(@PathVariable UUID fooId) {
    return fooService.findExam(fooId)
            .map(uri -> ResponseEntity.noContent().<Void>build())
            .orElse(ResponseEntity.notFound().build());
}

npm install error - MSB3428: Could not load the Visual C++ component "VCBuild.exe"

Try this from cmd line as Administrator

optional part, if you need to use a proxy:

set HTTP_PROXY=http://login:password@your-proxy-host:your-proxy-port
set HTTPS_PROXY=http://login:password@your-proxy-host:your-proxy-port

run this:

npm install -g --production windows-build-tools

No need for Visual Studio. This has what you need.

References:

https://www.npmjs.com/package/windows-build-tools
https://github.com/felixrieseberg/windows-build-tools

Failed to load ApplicationContext for JUnit test of Spring controller

Solved by adding the following dependency into pom.xml file :

<dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>test</scope>
</dependency>

Spring Test & Security: How to mock authentication?

It turned out that the SecurityContextPersistenceFilter, which is part of the Spring Security filter chain, always resets my SecurityContext, which I set calling SecurityContextHolder.getContext().setAuthentication(principal) (or by using the .principal(principal) method). This filter sets the SecurityContext in the SecurityContextHolder with a SecurityContext from a SecurityContextRepository OVERWRITING the one I set earlier. The repository is a HttpSessionSecurityContextRepository by default. The HttpSessionSecurityContextRepository inspects the given HttpRequest and tries to access the corresponding HttpSession. If it exists, it will try to read the SecurityContext from the HttpSession. If this fails, the repository generates an empty SecurityContext.

Thus, my solution is to pass a HttpSession along with the request, which holds the SecurityContext:

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;

import eu.ubicon.webapp.test.WebappTestEnvironment;

public class Test extends WebappTestEnvironment {

    public static class MockSecurityContext implements SecurityContext {

        private static final long serialVersionUID = -1386535243513362694L;

        private Authentication authentication;

        public MockSecurityContext(Authentication authentication) {
            this.authentication = authentication;
        }

        @Override
        public Authentication getAuthentication() {
            return this.authentication;
        }

        @Override
        public void setAuthentication(Authentication authentication) {
            this.authentication = authentication;
        }
    }

    @Test
    public void signedIn() throws Exception {

        UsernamePasswordAuthenticationToken principal = 
                this.getPrincipal("test1");

        MockHttpSession session = new MockHttpSession();
        session.setAttribute(
                HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, 
                new MockSecurityContext(principal));


        super.mockMvc
            .perform(
                    get("/api/v1/resource/test")
                    .session(session))
            .andExpect(status().isOk());
    }
}

Cannot install node modules that require compilation on Windows 7 x64/VS2012

  1. Install Python 2.7 (not 3.x)
  2. Add the path to the directory containing vcbuild.exe on your environment variable PATH
  3. If you need vcbuild.exe get it here https://github.com/kin9puppy/vcbuildFixForNode

Facebook database design?

You're looking for foreign keys. Basically you can't have an array in a database unless it has it's own table.


Example schema:

    Users Table
        userID PK
        other data
    Friends Table
        userID   -- FK to users's table representing the user that has a friend.
        friendID -- FK to Users' table representing the user id of the friend

Move column by name to front of table in pandas

df.set_index('Mid').reset_index()

seems to be a pretty easy way about this.

How to pass query parameters with a routerLink

queryParams

queryParams is another input of routerLink where they can be passed like

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}">Somewhere</a>

fragment

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}" [fragment]="yyy">Somewhere</a>

routerLinkActiveOptions

To also get routes active class set on parent routes:

[routerLinkActiveOptions]="{ exact: false }"

To pass query parameters to this.router.navigate(...) use

let navigationExtras: NavigationExtras = {
  queryParams: { 'session_id': sessionId },
  fragment: 'anchor'
};

// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);

See also https://angular.io/guide/router#query-parameters-and-fragments

Determine the data types of a data frame's columns

sapply(yourdataframe, class)

Where yourdataframe is the name of the data frame you're using

How to check if internet connection is present in Java?

If you're on java 6 can use NetworkInterface to check for available network interfaces. I.e. something like this:

Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
  NetworkInterface interf = interfaces.nextElement();
  if (interf.isUp() && !interf.isLoopback())
    return true;
}

Haven't tried it myself, yet.

How to check if the given string is palindrome?

Note that in the above C++ solutions, there was some problems.

One solution was inefficient because it passed an std::string by copy, and because it iterated over all the chars, instead of comparing only half the chars. Then, even when discovering the string was not a palindrome, it continued the loop, waiting its end before reporting "false".

The other was better, with a very small function, whose problem was that it was not able to test anything else than std::string. In C++, it is easy to extend an algorithm to a whole bunch of similar objects. By templating its std::string into "T", it would have worked on both std::string, std::wstring, std::vector and std::deque. But without major modification because of the use of the operator <, the std::list was out of its scope.

My own solutions try to show that a C++ solution won't stop at working on the exact current type, but will strive to work an anything that behaves the same way, no matter the type. For example, I could apply my palindrome tests on std::string, on vector of int or on list of "Anything" as long as Anything was comparable through its operator = (build in types, as well as classes).

Note that the template can even be extended with an optional type that can be used to compare the data. For example, if you want to compare in a case insensitive way, or even compare similar characters (like è, é, ë, ê and e).

Like king Leonidas would have said: "Templates ? This is C++ !!!"

So, in C++, there are at least 3 major ways to do it, each one leading to the other:

Solution A: In a c-like way

The problem is that until C++0X, we can't consider the std::string array of chars as contiguous, so we must "cheat" and retrieve the c_str() property. As we are using it in a read-only fashion, it should be ok...


bool isPalindromeA(const std::string & p_strText)
{
   if(p_strText.length() < 2) return true ;
   const char * pStart = p_strText.c_str() ;             
   const char * pEnd = pStart + p_strText.length() - 1 ; 

   for(; pStart < pEnd; ++pStart, --pEnd)
   {
      if(*pStart != *pEnd)
      {
         return false ;
      }
   }

   return true ;
}

Solution B: A more "C++" version

Now, we'll try to apply the same solution, but to any C++ container with random access to its items through operator []. For example, any std::basic_string, std::vector, std::deque, etc. Operator [] is constant access for those containers, so we won't lose undue speed.


template <typename T>
bool isPalindromeB(const T & p_aText)
{
   if(p_aText.empty()) return true ;
   typename T::size_type iStart = 0 ;
   typename T::size_type iEnd = p_aText.size() - 1 ;

   for(; iStart < iEnd; ++iStart, --iEnd)
   {
      if(p_aText[iStart] != p_aText[iEnd])
      {
         return false ;
      }
   }

   return true ;
}

Solution C: Template powah !

It will work with almost any unordered STL-like container with bidirectional iterators For example, any std::basic_string, std::vector, std::deque, std::list, etc. So, this function can be applied on all STL-like containers with the following conditions: 1 - T is a container with bidirectional iterator 2 - T's iterator points to a comparable type (through operator =)


template <typename T>
bool isPalindromeC(const T & p_aText)
{
   if(p_aText.empty()) return true ;
   typename T::const_iterator pStart = p_aText.begin() ;
   typename T::const_iterator pEnd = p_aText.end() ;
   --pEnd ;

   while(true)
   {
      if(*pStart != *pEnd)
      {
         return false ;
      }

      if((pStart == pEnd) || (++pStart == pEnd))
      {
         return true ;
      }

      --pEnd ;
   }
}

Converting integer to digit list

>>>list(map(int, str(number)))  #number is a given integer

It returns a list of all digits of number.

Java: print contents of text file to screen

Before Java 7:

 BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
 String line;
 while ((line = br.readLine()) != null) {
   System.out.println(line);
 }
  • add exception handling
  • add closing the stream

Since Java 7, there is no need to close the stream, because it implements autocloseable

try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
   String line;
   while ((line = br.readLine()) != null) {
       System.out.println(line);
   }
}

Use latest version of Internet Explorer in the webbrowser control

Combine the answers of RooiWillie and MohD
and remember to run your app with administrative right.

var appName = System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe";

RegistryKey Regkey = null;
try
{
    int BrowserVer, RegVal;

    // get the installed IE version
    using (WebBrowser Wb = new WebBrowser())
        BrowserVer = Wb.Version.Major;

    // set the appropriate IE version
    if (BrowserVer >= 11)
        RegVal = 11001;
    else if (BrowserVer == 10)
        RegVal = 10001;
    else if (BrowserVer == 9)
        RegVal = 9999;
    else if (BrowserVer == 8)
        RegVal = 8888;
    else
        RegVal = 7000;

    //For 64 bit Machine 
    if (Environment.Is64BitOperatingSystem)
        Regkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
    else  //For 32 bit Machine 
        Regkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);

    //If the path is not correct or 
    //If user't have priviledges to access registry 
    if (Regkey == null)
    {
        MessageBox.Show("Registry Key for setting IE WebBrowser Rendering Address Not found. Try run the program with administrator's right.");
        return;
    }

    string FindAppkey = Convert.ToString(Regkey.GetValue(appName));

    //Check if key is already present 
    if (FindAppkey == RegVal.ToString())
    {
        Regkey.Close();
        return;
    }

    Regkey.SetValue(appName, RegVal, RegistryValueKind.DWord);
}
catch (Exception ex)
{
    MessageBox.Show("Registry Key for setting IE WebBrowser Rendering failed to setup");
    MessageBox.Show(ex.Message);
}
finally
{
    //Close the Registry 
    if (Regkey != null)
        Regkey.Close();
}

Write HTML file using Java

if it is becoming repetitive work ; i think you shud do code reuse ! why dont you simply write functions that "write" small building blocks of HTML. get the idea? see Eg. you can have a function to which you could pass a string and it would automatically put that into a paragraph tag and present it. Of course you would also need to write some kind of a basic parser to do this (how would the function know where to attach the paragraph!). i dont think you are a beginner .. so i am not elaborating ... do tell me if you do not understand..

Launch an app on OS X with command line

open also has an -a flag, that you can use to open up an app from within the Applications folder by it's name (or by bundle identifier with -b flag). You can combine this with the --args option to achieve the result you want:

open -a APP_NAME --args ARGS

To open up a video in VLC player that should scale with a factor 2x and loop you would for example exectute:

open -a VLC --args -L --fullscreen

Note that I could not get the output of the commands to the terminal. (although I didn't try anything to resolve that)

How can I call the 'base implementation' of an overridden virtual method?

Using the C# language constructs, you cannot explicitly call the base function from outside the scope of A or B. If you really need to do that, then there is a flaw in your design - i.e. that function shouldn't be virtual to begin with, or part of the base function should be extracted to a separate non-virtual function.

You can from inside B.X however call A.X

class B : A
{
  override void X() { 
    base.X();
    Console.WriteLine("y"); 
  }
}

But that's something else.

As Sasha Truf points out in this answer, you can do it through IL. You can probably also accomplish it through reflection, as mhand points out in the comments.

How to get the list of all database users

Whenever you 'see' something in the GUI (SSMS) and you're like "that's what I need", you can always run Sql Profiler to fish for the query that was used.

Run Sql Profiler. Attach it to your database of course.

Then right click in the GUI (in SSMS) and click "Refresh".
And then go see what Profiler "catches".

I got the below when I was in MyDatabase / Security / Users and clicked "refresh" on the "Users".

Again, I didn't come up with the WHERE clause and the LEFT OUTER JOIN, it was a part of the SSMS query. And this query is something that somebody at Microsoft has written (you know, the peeps who know the product inside and out, aka, the experts), so they are familiar with all the weird "flags" in the database.

But the SSMS/GUI -> Sql Profiler tricks works in many scenarios.

SELECT
u.name AS [Name],
'Server[@Name=' + quotename(CAST(
        serverproperty(N'Servername')
       AS sysname),'''') + ']' + '/Database[@Name=' + quotename(db_name(),'''') + ']' + '/User[@Name=' + quotename(u.name,'''') + ']' AS [Urn],
u.create_date AS [CreateDate],
u.principal_id AS [ID],
CAST(CASE dp.state WHEN N'G' THEN 1 WHEN 'W' THEN 1 ELSE 0 END AS bit) AS [HasDBAccess]
FROM
sys.database_principals AS u
LEFT OUTER JOIN sys.database_permissions AS dp ON dp.grantee_principal_id = u.principal_id and dp.type = 'CO'
WHERE
(u.type in ('U', 'S', 'G', 'C', 'K' ,'E', 'X'))
ORDER BY
[Name] ASC

Difference between core and processor

Intel's picture is helpful, as shown by Tortuga's best answer. Here's a caption for it.

Processor: One semiconductor chip, the CPU (central processing unit) seated in one socket, circa 1950s-2010s. Over time, more functions have been packed onto the CPU chip. Prior to the 1950s releases of single-chip processors, one processor might have spread across multiple chips. In the mid 2010s the system-on-a-chip chips made it slightly more sketchy to equate one processor to one chip, though that's generally what people mean by processor, as in "this computer has an i7 processor" or "this computer system has four processors."

Core: One block of a CPU, executing one instruction at a time. (You'll see people say one instruction per clock cycle, but some CPUs use multiple clock cycles for some instructions.)

CSS: how to position element in lower right?

Set the CSS position: relative; on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:

position: absolute;
bottom: 0;
right: 0;

If you need to space the text farther away from the edge, you could change 0 to 2px or similar.

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

Look for GSpread.NET. It's also an OpenSource project and it doesn't require Office installed. You can work with Google Spreadsheets by using API from Microsoft Excel. If you want to re-use the old code to get access to Google Spreadsheets, GSpread.NET is the best way. You need to add a few row:

Set objExcel = CreateObject("GSpreadCOM.Application")
// Name             - User name, any you like
// ClientIdAndSecret - `client_id|client_secret` format
// ScriptId         - Google Apps script ID
app.MailLogon(Name, ClientIdAndSecret, ScriptId);

Further code remain unchanged.

http://scand.com/products/gspread/index.html

What are POD types in C++?

Plain Old Data

In short, it is all built-in data types (e.g. int, char, float, long, unsigned char, double, etc.) and all aggregation of POD data. Yes, it's a recursive definition. ;)

To be more clear, a POD is what we call "a struct": a unit or a group of units that just store data.

Get everything after the dash in a string in JavaScript

var the_string = "sometext-20202";
var parts = the_string.split('-', 2);

// After calling split(), 'parts' is an array with two elements:
// parts[0] is 'sometext'
// parts[1] is '20202'

var the_text = parts[0];
var the_num  = parts[1];

Parsing XML in Python using ElementTree example

If I understand your question correctly:

for elem in doc.findall('timeSeries/values/value'):
    print elem.get('dateTime'), elem.text

or if you prefer (and if there is only one occurrence of timeSeries/values:

values = doc.find('timeSeries/values')
for value in values:
    print value.get('dateTime'), elem.text

The findall() method returns a list of all matching elements, whereas find() returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values element, in this case leading to the same result.

I don't see where the problem with not finding timeSeries comes from however. Maybe you just forgot the getroot() call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values or //timeSeries/values)

How to get numeric value from a prompt box?

parseInt() or parseFloat() are functions in JavaScript which can help you convert the values into integers or floats respectively.

Syntax:

 parseInt(string, radix);
 parseFloat(string); 
  • string: the string expression to be parsed as a number.
  • radix: (optional, but highly encouraged) the base of the numeral system to be used - a number between 2 and 36.

Example:

 var x = prompt("Enter a Value", "0");
 var y = prompt("Enter a Value", "0");
 var num1 = parseInt(x);
 var num2 = parseInt(y);

After this you can perform which ever calculations you want on them.

On select change, get data attribute value

You need to find the selected option:

$(this).find(':selected').data('id')

or

$(this).find(':selected').attr('data-id')

although the first method is preferred.

String date to xmlgregoriancalendar conversion

Found the solution as below.... posting it as it could help somebody else too :)

DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = format.parse("2014-04-24 11:15:00");

GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);

XMLGregorianCalendar xmlGregCal =  DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);

System.out.println(xmlGregCal);

Output:

2014-04-24T11:15:00.000+02:00

Java Best Practices to Prevent Cross Site Scripting

The normal practice is to HTML-escape any user-controlled data during redisplaying in JSP, not during processing the submitted data in servlet nor during storing in DB. In JSP you can use the JSTL (to install it, just drop jstl-1.2.jar in /WEB-INF/lib) <c:out> tag or fn:escapeXml function for this. E.g.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<p>Welcome <c:out value="${user.name}" /></p>

and

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<input name="username" value="${fn:escapeXml(param.username)}">

That's it. No need for a blacklist. Note that user-controlled data covers everything which comes in by a HTTP request: the request parameters, body and headers(!!).

If you HTML-escape it during processing the submitted data and/or storing in DB as well, then it's all spread over the business code and/or in the database. That's only maintenance trouble and you will risk double-escapes or more when you do it at different places (e.g. & would become &amp;amp; instead of &amp; so that the enduser would literally see &amp; instead of & in view. The business code and DB are in turn not sensitive for XSS. Only the view is. You should then escape it only right there in view.

See also:

Override and reset CSS style: auto or none don't work

I believe the reason why the first set of properties will not work is because there is no auto value for display, so that property should be ignored. In that case, inline-table will still take effect, and as width do not apply to inline elements, that set of properties will not do anything.

The second set of properties will simply hide the table, as that's what display: none is for.

Try resetting it to table instead:

table.other {
    width: auto;
    min-width: 0;
    display: table;
}

Edit: min-width defaults to 0, not auto

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

Add Content-Type: application/json and Accept: application/json in REST Client header section

How to use \n new line in VB msgbox() ...?

msgbox("your text here" & Environment.NewLine & "more text") is the easist way. no point in making your code harder or more ocmplicated than you need it to be...

Better way of getting time in milliseconds in javascript?

Try Date.now().

The skipping is most likely due to garbage collection. Typically garbage collection can be avoided by reusing variables as much as possible, but I can't say specifically what methods you can use to reduce garbage collection pauses.

How do I analyze a program's core dump file with GDB when it has command-line parameters?

You can use the core with GDB in many ways, but passing parameters which is to be passed to the executable to GDB is not the way to use the core file. This could also be the reason you got that error. You can use the core file in the following ways:

gdb <executable> <core-file> or gdb <executable> -c <core-file> or

gdb <executable>
...
(gdb) core <core-file>

When using the core file you don't have to pass arguments. The crash scenario is shown in GDB (checked with GDB version 7.1 on Ubuntu).

For example:

$ ./crash -p param1 -o param2
Segmentation fault (core dumped)
$ gdb ./crash core
GNU gdb (GDB) 7.1-ubuntu
...
Core was generated by `./crash -p param1 -o param2'. <<<<< See this line shows crash scenario
Program terminated with signal 11, Segmentation fault.
#0  __strlen_ia32 () at ../sysdeps/i386/i686/multiarch/../../i586/strlen.S:99
99    ../sysdeps/i386/i686/multiarch/../../i586/strlen.S: No such file or directory.
    in ../sysdeps/i386/i686/multiarch/../../i586/strlen.S
(gdb)

If you want to pass parameters to the executable to be debugged in GDB, use --args.

For example:

$ gdb --args ./crash -p param1 -o param2
GNU gdb (GDB) 7.1-ubuntu
...
(gdb) r
Starting program: /home/@@@@/crash -p param1 -o param2

Program received signal SIGSEGV, Segmentation fault.
__strlen_ia32 () at ../sysdeps/i386/i686/multiarch/../../i586/strlen.S:99
99    ../sysdeps/i386/i686/multiarch/../../i586/strlen.S: No such file or directory.
    in ../sysdeps/i386/i686/multiarch/../../i586/strlen.S
(gdb)

Man pages will be helpful to see other GDB options.

Is bool a native C type?

C99 defines bool, true and false in stdbool.h.

Remove Elements from a HashSet while Iterating

you can also refactor your solution removing the first loop:

Set<Integer> set = new HashSet<Integer>();
Collection<Integer> removeCandidates = new LinkedList<Integer>(set);

for(Integer element : set)
   if(element % 2 == 0)
       removeCandidates.add(element);

set.removeAll(removeCandidates);

Trim spaces from start and end of string

You can use trimLeft() and trimRight() also.

const str1 = "   string   ";
console.log(str1.trimLeft()); 
// => "string   "

const str2 = "   string   ";
console.log(str2.trimRight());
// => "    string"

Extract directory path and filename

bash:

fspec="/exp/home1/abc.txt"
fname="${fspec##*/}"

How can I convert a PFX certificate file for use with Apache on a linux server?

To get it to work with Apache, we needed one extra step.

openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes  -out domain_encrypted.key
openssl rsa -in domain_encrypted.key -out domain.key

The final command decrypts the key for use with Apache. The domain.key file should look like this:

-----BEGIN RSA PRIVATE KEY-----
MjQxODIwNTFaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3d3d3
LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxp
YWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEG
A1UEAxMqRW50cnVzdC5uZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgp
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArU1LqRKGsuqjIAcVFmQq
-----END RSA PRIVATE KEY-----

HttpServletRequest - Get query string parameters, no form data

As the other answers state there is no way getting query string parameters using servlet api.

So, I think the best way to get query parameters is parsing the query string yourself. ( It is more complicated iterating over parameters and checking if query string contains the parameter)

I wrote below code to get query string parameters. Using apache StringUtils and ArrayUtils which supports CSV separated query param values as well.

Example: username=james&username=smith&password=pwd1,pwd2 will return

password : [pwd1, pwd2] (length = 2)

username : [james, smith] (length = 2)

public static Map<String, String[]> getQueryParameters(HttpServletRequest request) throws UnsupportedEncodingException {
    Map<String, String[]> queryParameters = new HashMap<>();
    String queryString = request.getQueryString();
    if (StringUtils.isNotEmpty(queryString)) {
        queryString = URLDecoder.decode(queryString, StandardCharsets.UTF_8.toString());
        String[] parameters = queryString.split("&");
        for (String parameter : parameters) {
            String[] keyValuePair = parameter.split("=");
            String[] values = queryParameters.get(keyValuePair[0]);
            //length is one if no value is available.
            values = keyValuePair.length == 1 ? ArrayUtils.add(values, "") :
                    ArrayUtils.addAll(values, keyValuePair[1].split(",")); //handles CSV separated query param values.
            queryParameters.put(keyValuePair[0], values);
        }
    }
    return queryParameters;
}

How to convert list to string

L = ['L','O','L']
makeitastring = ''.join(map(str, L))

How to figure out the SMTP server host?

this really is a question for Serverfault.

Windows:

  1. Open up a command prompt (CMD.exe)
  2. Type nslookup and hit enter
  3. Type set type=MX and hit enter
  4. Type the domain name and hit enter, for example: google.com
  5. The results will be a list of host names that are set up for SMTP

Linux:

  1. Open a command prompt
  2. Type dig domain.name MX and hit enter where domain.name is the domain you are trying to find out the smtp server for.

If you do not get any answers back from your dns server, there is a good chance that there isn't any SMTP Servers set up for that domain. If this is the case, do like other's have suggested and call the hosting companies tech support.

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Not going to be everyone's fix, but it was for me:

So, i ran across this exact issue. The problem I seemed to have was when my DataTable didnt have an ID column, but the target destination had one with a primary key.

When i adapted my DataTable to have an id, the copy worked perfectly.

In my scenario, the Id column isnt very important to have the primary key so i deleted this column from the target destination table and the SqlBulkCopy is working without issue.

How to use ES6 Fat Arrow to .filter() an array of objects

It appears I cannot use an if statement.

Arrow functions either allow to use an expression or a block as their body. Passing an expression

foo => bar

is equivalent to the following block

foo => { return bar; }

However,

if (person.age > 18) person

is not an expression, if is a statement. Hence you would have to use a block, if you wanted to use if in an arrow function:

foo => {  if (person.age > 18) return person; }

While that technically solves the problem, this a confusing use of .filter, because it suggests that you have to return the value that should be contained in the output array. However, the callback passed to .filter should return a Boolean, i.e. true or false, indicating whether the element should be included in the new array or not.

So all you need is

family.filter(person => person.age > 18);

In ES5:

family.filter(function (person) {
  return person.age > 18;
});

How to find all duplicate from a List<string>?

In .NET framework 3.5 and above you can use Enumerable.GroupBy which returns an enumerable of enumerables of duplicate keys, and then filter out any of the enumerables that have a Count of <=1, then select their keys to get back down to a single enumerable:

var duplicateKeys = list.GroupBy(x => x)
                        .Where(group => group.Count() > 1)
                        .Select(group => group.Key);

MySQL: Invalid use of group function

First, the error you're getting is due to where you're using the COUNT function -- you can't use an aggregate (or group) function in the WHERE clause.

Second, instead of using a subquery, simply join the table to itself:

SELECT a.pid 
FROM Catalog as a LEFT JOIN Catalog as b USING( pid )
WHERE a.sid != b.sid
GROUP BY a.pid

Which I believe should return only rows where at least two rows exist with the same pid but there is are at least 2 sids. To make sure you get back only one row per pid I've applied a grouping clause.

Netbeans - Error: Could not find or load main class

I had the same issue once. The problem was not in the code. The cause was... renaming the project folder to some other non supporting name. My project name was "MobStick" and I renamed it to "MobStick - May 26, 2014 04:00PM". Renaming it back to normal solved my problem.

What is the use of BindingResult interface in spring MVC?

From the official Spring documentation:

General interface that represents binding results. Extends the interface for error registration capabilities, allowing for a Validator to be applied, and adds binding-specific analysis and model building.

Serves as result holder for a DataBinder, obtained via the DataBinder.getBindingResult() method. BindingResult implementations can also be used directly, for example to invoke a Validator on it (e.g. as part of a unit test).

Why does multiplication repeats the number several times?

It's the difference between strings and integers. See:

>>> "1" * 9
'111111111'

>>> 1 * 9
9

Normalize numpy array columns in python

If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using broadcasting.

Starting with your example array:

import numpy as np

x = np.array([[1000,  10,   0.5],
              [ 765,   5,  0.35],
              [ 800,   7,  0.09]])

x_normed = x / x.max(axis=0)

print(x_normed)
# [[ 1.     1.     1.   ]
#  [ 0.765  0.5    0.7  ]
#  [ 0.8    0.7    0.18 ]]

x.max(0) takes the maximum over the 0th dimension (i.e. rows). This gives you a vector of size (ncols,) containing the maximum value in each column. You can then divide x by this vector in order to normalize your values such that the maximum value in each column will be scaled to 1.


If x contains negative values you would need to subtract the minimum first:

x_normed = (x - x.min(0)) / x.ptp(0)

Here, x.ptp(0) returns the "peak-to-peak" (i.e. the range, max - min) along axis 0. This normalization also guarantees that the minimum value in each column will be 0.

Setting size for icon in CSS

Funnily enough, adjusting the padding seems to do it.

_x000D_
_x000D_
.arrow {
  border: solid rgb(2, 0, 0);
  border-width: 0 3px 3px 0;
  display: inline-block;
}

.first{
  padding: 2vh;
}

.second{
  padding: 4vh;
}

.left {
    transform: rotate(135deg);
    -webkit-transform: rotate(135deg);
 }
_x000D_
<i class="arrow first left"></i>
<i class="arrow second left"></i>
_x000D_
_x000D_
_x000D_

What's the fastest way to do a bulk insert into Postgres?

UNNEST function with arrays can be used along with multirow VALUES syntax. I'm think that this method is slower than using COPY but it is useful to me in work with psycopg and python (python list passed to cursor.execute becomes pg ARRAY):

INSERT INTO tablename (fieldname1, fieldname2, fieldname3)
VALUES (
    UNNEST(ARRAY[1, 2, 3]), 
    UNNEST(ARRAY[100, 200, 300]), 
    UNNEST(ARRAY['a', 'b', 'c'])
);

without VALUES using subselect with additional existance check:

INSERT INTO tablename (fieldname1, fieldname2, fieldname3)
SELECT * FROM (
    SELECT UNNEST(ARRAY[1, 2, 3]), 
           UNNEST(ARRAY[100, 200, 300]), 
           UNNEST(ARRAY['a', 'b', 'c'])
) AS temptable
WHERE NOT EXISTS (
    SELECT 1 FROM tablename tt
    WHERE tt.fieldname1=temptable.fieldname1
);

the same syntax to bulk updates:

UPDATE tablename
SET fieldname1=temptable.data
FROM (
    SELECT UNNEST(ARRAY[1,2]) AS id,
           UNNEST(ARRAY['a', 'b']) AS data
) AS temptable
WHERE tablename.id=temptable.id;

Python naming conventions for modules

Just nib. Name the class Nib, with a capital N. For more on naming conventions and other style advice, see PEP 8, the Python style guide.

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

To do this easily, the use of Stack is better. Create a Stack Then inside Stack add Align or Positioned and set position according to your needed, You can add multiple Container.

Container
  child: Stack(
    children: <Widget>[
      Align(
         alignment: FractionalOffset.center,
         child: Text(
            "? 1000",
         )
      ),
      Positioned(
        bottom: 0,
        child: Container(
           width: double.infinity,
           height: 30,
           child: Text(
             "Balance", ,
           )
         ),
       )
    ],
  )
)

enter image description here

Stack a widget that positions its children relative to the edges of its box.

Stack class is useful if you want to overlap several children in a simple way, for example having some text and an image, overlaid with a gradient and a button attached to the bottom.

How can I list all the deleted files in a Git repository?

Citing this Stack Overflow answer.

It is a pretty neat way to get type-of-change (A:Added, M:Modified, D:Deleted) for each file that got changed.

git diff --name-status

Ruby get object keys as array

Use the keys method: {"apple" => "fruit", "carrot" => "vegetable"}.keys == ["apple", "carrot"]

syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

I stumbled on this question as I had the same error. Mine was due to a slightly different problem and since I resolved it on my own I thought it useful to share here. Original code with issue:

$comment = "$_POST['comment']";

Because of the enclosing double-quotes, the index is not dereferenced properly leading to the assignment error. In my case I chose to fix it like this:

$comment = "$_POST[comment]";

but dropping either pair of quotes works; it's a matter of style I suppose :)

How can I detect if a selector returns null?

My preference, and I have no idea why this isn't already in jQuery:

$.fn.orElse = function(elseFunction) {
  if (!this.length) {
    elseFunction();
  }
};

Used like this:

$('#notAnElement').each(function () {
  alert("Wrong, it is an element")
}).orElse(function() {
  alert("Yup, it's not an element")
});

Or, as it looks in CoffeeScript:

$('#notAnElement').each ->
  alert "Wrong, it is an element"; return
.orElse ->
  alert "Yup, it's not an element"

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

Prevent content from expanding grid items

The existing answers solve most cases. However, I ran into a case where I needed the content of the grid-cell to be overflow: visible. I solved it by absolutely positioning within a wrapper (not ideal, but the best I know), like this:


.month-grid {
  display: grid;
  grid-template: repeat(6, 1fr) / repeat(7, 1fr);
  background: #fff;
  grid-gap: 2px;  
}

.day-item-wrapper {
  position: relative;
}

.day-item {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 10px;

  background: rgba(0,0,0,0.1);
}

https://codepen.io/bjnsn/pen/vYYVPZv

Move SQL Server 2008 database files to a new folder location

You forgot to mention the name of your database (is it "my"?).

ALTER DATABASE my SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

ALTER DATABASE my SET OFFLINE;

ALTER DATABASE my MODIFY FILE 
(
   Name = my_Data,
   Filename = 'D:\DATA\my.MDF'
);

ALTER DATABASE my MODIFY FILE 
(
   Name = my_Log, 
   Filename = 'D:\DATA\my_1.LDF'
);

Now here you must manually move the files from their current location to D:\Data\ (and remember to rename them manually if you changed them in the MODIFY FILE command) ... then you can bring the database back online:

ALTER DATABASE my SET ONLINE;

ALTER DATABASE my SET MULTI_USER;

This assumes that the SQL Server service account has sufficient privileges on the D:\Data\ folder. If not you will receive errors at the SET ONLINE command.

What was the strangest coding standard rule that you were forced to follow?

I am not allowed to use this-> to reference local variables in our c++ code...

How to get option text value using AngularJS?

The best way is to use the ng-options directive on the select element.

Controller

function Ctrl($scope) {
  // sort options
  $scope.products = [{
    value: 'prod_1',
    label: 'Product 1'
  }, {
    value: 'prod_2',
    label: 'Product 2'
  }];   
}

HTML

<select ng-model="selected_product" 
        ng-options="product as product.label for product in products">           
</select>

This will bind the selected product object to the ng-model property - selected_product. After that you can use this:

<p>Ordered by: {{selected_product.label}}</p>

jsFiddle: http://jsfiddle.net/bmleite/2qfSB/

How To Raise Property Changed events on a Dependency Property?

I agree with Sam and Xaser and have actually taken this a bit farther. I don't think you should be implementing the INotifyPropertyChanged interface in a UserControl at all...the control is already a DependencyObject and therefore already comes with notifications. Adding INotifyPropertyChanged to a DependencyObject is redundant and "smells" wrong to me.

What I did is implement both properties as DependencyProperties, as Sam suggests, but then simply had the PropertyChangedCallback from the "first" dependency property alter the value of the "second" dependency property. Since both are dependency properties, both will automatically raise change notifications to any interested subscribers (e.g. data binding etc.)

In this case, dependency property A is the string InviteText, which triggers a change in dependency property B, the Visibility property named ShowInvite. This would be a common use case if you have some text that you want to be able to hide completely in a control via data binding.

public string InviteText  
{
    get { return (string)GetValue(InviteTextProperty); }
    set { SetValue(InviteTextProperty, value); }
}

public static readonly DependencyProperty InviteTextProperty =
    DependencyProperty.Register("InviteText", typeof(string), typeof(InvitePrompt), new UIPropertyMetadata(String.Empty, OnInviteTextChanged));

private static void OnInviteTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    InvitePrompt prompt = d as InvitePrompt;
    if (prompt != null)
    {
        string text = e.NewValue as String;
        prompt.ShowInvite = String.IsNullOrWhiteSpace(text) ? Visibility.Collapsed : Visibility.Visible;
    }
}

public Visibility ShowInvite
{
    get { return (Visibility)GetValue(ShowInviteProperty); }
    set { SetValue(ShowInviteProperty, value); }
}

public static readonly DependencyProperty ShowInviteProperty =
    DependencyProperty.Register("ShowInvite", typeof(Visibility), typeof(InvitePrompt), new PropertyMetadata(Visibility.Collapsed));

Note I'm not including the UserControl signature or constructor here because there is nothing special about them; they don't need to subclass from INotifyPropertyChanged at all.

How to make a node.js application run permanently?

You could simply use this

nohup node /srv/www/MyUserAccount/server/server.js &

This will keep the application running and to shut it down you will have to kill it.

For that you could install htop and then search for node and then kill it

HTML5 tag for horizontal line break

Simply use hr tag in HTML file and add below code in CSS file .

    hr {
       display: block;
       position: relative;
       padding: 0;
       margin: 8px auto;
       height: 0;
       width: 100%;
       max-height: 0;
       font-size: 1px;
       line-height: 0;
       clear: both;
       border: none;
       border-top: 1px solid #aaaaaa;
       border-bottom: 1px solid #ffffff;
    }

it works perfectly .

What is the purpose of the "role" attribute in HTML?

Is this role attribute necessary?

Answer: Yes.

  • The role attribute is necessary to support Accessible Rich Internet Applications (WAI-ARIA) to define roles in XML-based languages, when the languages do not define their own role attribute.
  • Although this is the reason the role attribute is published by the Protocols and Formats Working Group, the attribute has more general use cases as well.

It provides you:

  • Accessibility
  • Device adaptation
  • Server-side processing
  • Complex data description,...etc.

How do you convert CString and std::string std::wstring to each other?

One interesting approach is to cast CString to CStringA inside a string constructor. Unlike std::string s((LPCTSTR)cs); this will work even if _UNICODE is defined. However, if that is the case, this will perform conversion from Unicode to ANSI, so it is unsafe for higher Unicode values beyond the ASCII character set. Such conversion is subject to the _CSTRING_DISABLE_NARROW_WIDE_CONVERSION preprocessor definition. https://msdn.microsoft.com/en-us/library/5bzxfsea.aspx

        CString s1("SomeString");
        string s2((CStringA)s1);

How to add default signature in Outlook

I have made this a Community Wiki answer because I could not have created it without PowerUser's research and the help in earlier comments.

I took PowerUser's Sub X and added

Debug.Print "n------"    'with different values for n
Debug.Print ObjMail.HTMLBody

after every statement. From this I discovered the signature is not within .HTMLBody until after ObjMail.Display and then only if I haven't added anything to the body.

I went back to PowerUser's earlier solution that used C:\Users\" & Environ("username") & "\AppData\Roaming\Microsoft\Signatures\Mysig.txt"). PowerUser was unhappy with this because he wanted his solution to work for others who would have different signatures.

My signature is in the same folder and I cannot find any option to change this folder. I have only one signature so by reading the only HTM file in this folder, I obtained my only/default signature.

I created an HTML table and inserted it into the signature immediately following the <body> element and set the html body to the result. I sent the email to myself and the result was perfectly acceptable providing you like my formatting which I included to check that I could.

My modified subroutine is:

Sub X()

  Dim OlApp As Outlook.Application
  Dim ObjMail As Outlook.MailItem

  Dim BodyHtml As String
  Dim DirSig As String
  Dim FileNameHTMSig As String
  Dim Pos1 As Long
  Dim Pos2 As Long
  Dim SigHtm As String

  DirSig = "C:\Users\" & Environ("username") & _
                               "\AppData\Roaming\Microsoft\Signatures"

  FileNameHTMSig = Dir$(DirSig & "\*.htm")

  ' Code to handle there being no htm signature or there being more than one

  SigHtm = GetBoiler(DirSig & "\" & FileNameHTMSig)
  Pos1 = InStr(1, LCase(SigHtm), "<body")

  ' Code to handle there being no body

  Pos2 = InStr(Pos1, LCase(SigHtm), ">")

  ' Code to handle there being no closing > for the body element

   BodyHtml = "<table border=0 width=""100%"" style=""Color: #0000FF""" & _
         " bgColor=#F0F0F0><tr><td align= ""center"">HTML table</td>" & _
         "</tr></table><br>"
  BodyHtml = Mid(SigHtm, 1, Pos2 + 1) & BodyHtml & Mid(SigHtm, Pos2 + 2)

  Set OlApp = Outlook.Application
  Set ObjMail = OlApp.CreateItem(olMailItem)
  ObjMail.BodyFormat = olFormatHTML
  ObjMail.Subject = "Subject goes here"
  ObjMail.Recipients.Add "my email address"
  ObjMail.Display

End Sub

Since both PowerUser and I have found our signatures in C:\Users\" & Environ("username") & "\AppData\Roaming\Microsoft\Signatures I suggest this is the standard location for any Outlook installation. Can this default be changed? I cannot find anything to suggest it can. The above code clearly needs some development but it does achieve PowerUser's objective of creating an email body containing an HTML table above a signature.

How to delete history of last 10 commands in shell?

for x in `seq $1 $2`
do
  history -d $1
done

How do I see the extensions loaded by PHP?

You asked where do you see loaded extensions in phpinfo() output.

Answer:

They are listed towards the bottom as separate sections/tables and ONLY if they are loaded. Here is an example of extension Curl loaded.

enter image description here ...

... enter image description here

I installed it on Linux Debian with

sudo apt-get install php7.4-curl

How do I generate a random int number?

Use one instance of Random repeatedly

// Somewhat better code...
Random rng = new Random();
for (int i = 0; i < 100; i++)
{
    Console.WriteLine(GenerateDigit(rng));
}
...
static int GenerateDigit(Random rng)
{
    // Assume there'd be more logic here really
    return rng.Next(10);
}

This article takes a look at why randomness causes so many problems, and how to address them. http://csharpindepth.com/Articles/Chapter12/Random.aspx

What is the point of "final class" in Java?

Relevant reading: The Open-Closed Principle by Bob Martin.

Key quote:

Software Entities (Classes, Modules, Functions, etc.) should be open for Extension, but closed for Modification.

The final keyword is the means to enforce this in Java, whether it's used on methods or on classes.

What is a good naming convention for vars, methods, etc in C++?

consistency and readability (self-documenting code) are important. some clues (such as case) can and should be used to avoid collisions, and to indicate whether an instance is required.

one of the best practices i got into was the use of code formatters (astyle and uncrustify are 2 examples). code formatters can destroy your code formatting - configure the formatter, and let it do its job. seriously, forget about manual formatting and get into the practice of using them. they will save a ton of time.

as mentioned, be very descriptive with naming. also, be very specific with scoping (class types/data/namespaces/anonymous namespaces). in general, i really like much of java's common written form - that is a good reference and similar to c++.

as for specific appearance/naming, this is a small sample similar to what i use (variables/arguments are lowerCamel and this only demonstrates a portion of the language's features):

/** MYC_BEGIN_FILE_ID::FD_Directory_nanotimer_FN_nanotimer_hpp_::MYC_BEGIN_FILE_DIR::Directory/nanotimer::MYC_BEGIN_FILE_FILE::nanotimer.hpp::Copyright... */
#ifndef FD_Directory_nanotimer_FN_nanotimer_hpp_
#define FD_Directory_nanotimer_FN_nanotimer_hpp_

/* typical commentary omitted -- comments detail notations/conventions. also, no defines/macros other than header guards */

namespace NamespaceName {

/* types prefixed with 't_' */
class t_nanotimer : public t_base_timer {
    /* private types */
    class t_thing {
        /*...*/
    };
public:
    /* public types */
    typedef uint64_t t_nanosecond;

    /* factory initializers -- UpperCamel */
    t_nanotimer* WithFloat(const float& arg);
    /* public/protected class interface -- UpperCamel */
    static float Uptime();
protected:
    /* static class data -- UpperCamel -- accessors, if needed, use Get/Set prefix */
    static const t_spoke Spoke;
public:
    /* enums in interface are labeled as static class data */
    enum { Granularity = 4 };
public:
    /* construction/destruction -- always use proper initialization list */
    explicit t_nanotimer(t_init);
    explicit t_nanotimer(const float& arg);

    virtual ~t_nanotimer();

    /*
       public and protected instance methods -- lowercaseCamel()
       - booleans prefer is/has
       - accessors use the form: getVariable() setVariable().
       const-correctness is important
     */
    const void* address() const;
    virtual uint64_t hashCode() const;
protected:
    /* interfaces/implementation of base pure virtuals (assume this was pure virtual in t_base_timer) */
    virtual bool hasExpired() const;
private:
    /* private methods and private static data */
    void invalidate();
private:
    /*
       instance variables
       - i tend to use underscore suffix, but d_ (for example) is another good alternative
       - note redundancy in visibility
     */
    t_thing ivar_;
private:
    /* prohibited stuff */
    explicit t_nanotimer();
    explicit t_nanotimer(const int&);
};
} /* << NamespaceName */
/* i often add a multiple include else block here, preferring package-style inclusions */    
#endif /* MYC_END_FILE::FD_Directory_nanotimer_FN_nanotimer_hpp_ */

Create patch or diff file from git repository and apply it to another different git repository

You can just use git diff to produce a unified diff suitable for git apply:

git diff tag1..tag2 > mypatch.patch

You can then apply the resulting patch with:

git apply mypatch.patch

How to create byte array from HttpPostedFile

in your question, both buffer and byteArray seem to be byte[]. So:

ImageElement image = ImageElement.FromBinary(buffer);

How to Get XML Node from XDocument

The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:

XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
                    where xml2.Element("ID").Value == variable
                    select xml2).FirstOrDefault();

This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.

Marc

Custom Listview Adapter with filter Android

You can use the Filterable interface on your Adapter, have a look at the example below:

public class SearchableAdapter extends BaseAdapter implements Filterable {
    
    private List<String>originalData = null;
    private List<String>filteredData = null;
    private LayoutInflater mInflater;
    private ItemFilter mFilter = new ItemFilter();
    
    public SearchableAdapter(Context context, List<String> data) {
        this.filteredData = data ;
        this.originalData = data ;
        mInflater = LayoutInflater.from(context);
    }
 
    public int getCount() {
        return filteredData.size();
    }
 
    public Object getItem(int position) {
        return filteredData.get(position);
    }
 
    public long getItemId(int position) {
        return position;
    }
 
    public View getView(int position, View convertView, ViewGroup parent) {
        // A ViewHolder keeps references to children views to avoid unnecessary calls
        // to findViewById() on each row.
        ViewHolder holder;
 
        // When convertView is not null, we can reuse it directly, there is no need
        // to reinflate it. We only inflate a new View when the convertView supplied
        // by ListView is null.
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item, null);
 
            // Creates a ViewHolder and store references to the two children views
            // we want to bind data to.
            holder = new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.list_view);
 
            // Bind the data efficiently with the holder.
 
            convertView.setTag(holder);
        } else {
            // Get the ViewHolder back to get fast access to the TextView
            // and the ImageView.
            holder = (ViewHolder) convertView.getTag();
        }
 
        // If weren't re-ordering this you could rely on what you set last time
        holder.text.setText(filteredData.get(position));
 
        return convertView;
    }
    
    static class ViewHolder {
        TextView text;
    }
 
    public Filter getFilter() {
        return mFilter;
    }
 
    private class ItemFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            
            String filterString = constraint.toString().toLowerCase();
            
            FilterResults results = new FilterResults();
            
            final List<String> list = originalData;
 
            int count = list.size();
            final ArrayList<String> nlist = new ArrayList<String>(count);
 
            String filterableString ;
            
            for (int i = 0; i < count; i++) {
                filterableString = list.get(i);
                if (filterableString.toLowerCase().contains(filterString)) {
                    nlist.add(filterableString);
                }
            }
            
            results.values = nlist;
            results.count = nlist.size();
 
            return results;
        }
 
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            filteredData = (ArrayList<String>) results.values;
            notifyDataSetChanged();
        }
 
    }
}

In your Activity or Fragment where of Adapter is instantiated :

editTxt.addTextChangedListener(new TextWatcher() {
  
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        System.out.println("Text ["+s+"]");
        
        mSearchableAdapter.getFilter().filter(s.toString());                           
    }
     
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
         
    }
     
    @Override
    public void afterTextChanged(Editable s) {
    }
});

Here are the links for the original source and another example

How to pass parameter to click event in Jquery

As DOC says, you can pass data to the handler as next:

// say your selector and click handler looks something like this...
$("some selector").on('click',{param1: "Hello", param2: "World"}, cool_function);

// in your function, just grab the event object and go crazy...
function cool_function(event){
    alert(event.data.param1);
    alert(event.data.param2);

    // access element's id where click occur
    alert( event.target.id ); 
}

jQuery ID starts with

Here you go:

$('td[id^="' + value +'"]')

so if the value is for instance 'foo', then the selector will be 'td[id^="foo"]'.

Note that the quotes are mandatory: [id^="...."].

Source: http://api.jquery.com/attribute-starts-with-selector/

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

FFmpeg does not write to a specific log file, but rather sends its output to standard error. To capture that, you need to either

  • capture and parse it as it is generated
  • redirect standard error to a file and read that afterward the process is finished

Example for std error redirection:

ffmpeg -i myinput.avi {a-bunch-of-important-params} out.flv 2> /path/to/out.txt

Once the process is done, you can inspect out.txt.

It's a bit trickier to do the first option, but it is possible. (I've done it myself. So have others. Have a look around SO and the net for details.)

What is the purpose of "pip install --user ..."?

pip defaults to installing Python packages to a system directory (such as /usr/local/lib/python3.4). This requires root access.

--user makes pip install packages in your home directory instead, which doesn't require any special privileges.

Commenting code in Notepad++

In your n++ editor, you can go to Setting > Shortcut mapper and find all shortcut information as well as you can edit them :)

stopPropagation vs. stopImmediatePropagation

From the jQuery API:

In addition to keeping any additional handlers on an element from being executed, this method also stops the bubbling by implicitly calling event.stopPropagation(). To simply prevent the event from bubbling to ancestor elements but allow other event handlers to execute on the same element, we can use event.stopPropagation() instead.

Use event.isImmediatePropagationStopped() to know whether this method was ever called (on that event object).

In short: event.stopPropagation() allows other handlers on the same element to be executed, while event.stopImmediatePropagation() prevents every event from running.

Handling the window closing event with WPF / MVVM Light Toolkit

I haven't done much testing with this but it seems to work. Here's what I came up with:

namespace OrtzIRC.WPF
{
    using System;
    using System.Windows;
    using OrtzIRC.WPF.ViewModels;

    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private MainViewModel viewModel = new MainViewModel();
        private MainWindow window = new MainWindow();

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            viewModel.RequestClose += ViewModelRequestClose;

            window.DataContext = viewModel;
            window.Closing += Window_Closing;
            window.Show();
        }

        private void ViewModelRequestClose(object sender, EventArgs e)
        {
            viewModel.RequestClose -= ViewModelRequestClose;
            window.Close();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            window.Closing -= Window_Closing;
            viewModel.RequestClose -= ViewModelRequestClose; //Otherwise Close gets called again
            viewModel.CloseCommand.Execute(null);
        }
    }
}

Android Studio gradle takes too long to build

The second thing i did was Uninstall my Anti-Virus software (AVG Antivirus) {sounds crazy but, i had to}. it reduced gradle build time upto 40%

The first thing i did was enable offline mode (1. click on Gradle usually on the right side of the editor 2. click on the connection button to toggle) it reduced the gradle build time for upto 20%

so my Gradle build time was reduced for upto 60% by doing these two things

Remove multiple objects with rm()

Another variation you can try is(expanding @mnel's answer) if you have many temp'x'.

here "n" could be the number of temp variables present

rm(list = c(paste("temp",c(1:n),sep="")))

Are HTTPS URLs encrypted?

While you already have very good answers, I really like the explanation on this website: https://https.cio.gov/faq/#what-information-does-https-protect

in short: using HTTPS hides:

  • HTTP method
  • query params
  • POST body (if present)
  • Request headers (cookies included)
  • Status code

Resizing a button

If you want to call a different size for the button inline, you would probably do it like this:

<div class="button" style="width:60px;height:100px;">This is a button</div>

Or, a better way to have different sizes (say there will be 3 standard sizes for the button) would be to have classes just for size.

For example, you would call your button like this:

<div class="button small">This is a button</div>

And in your CSS

.button.small { width: 60px; height: 100px; }

and just create classes for each size you wish to have. That way you still have the perks of using a stylesheet in case say, you want to change the size of all the small buttons at once.

Display more Text in fullcalendar

I needed the ability to display quite a bit of info (without a tooltip) and it turned out quite nice. I used FullCalendars title prop to store all my HTML. The only thing you have to do to ensure it works after render is to parse the title fields HTML.

// `data` ismy JSON object.
$.each(data, function(index, value) {
  value.title = '<div class="title">' + value.title + '</div>';
  value.title += '<div class="deets"><span class="time"><img src="/themes/custom/bp/images/clock.svg">' + value.start_time + ' - ' + value.end_time + '</span>';
  value.title += '<span class="location"><img src="/themes/custom/bp/images/pin.svg">' + value.location + '</span></div>';
  value.title += '<div class="learn-more">LEARN MORE <span class="arrow"></span></span>';
});

// Initialize the calendar object.
calendar = new FullCalendar.Calendar(cal, {
  events: data,
  plugins: ['dayGrid'],
  eventRender: function(event) {
    // This is required to parse the HTML.
    const title = $(event.el).find('.fc-title');
    title.html(title.text());
  }
});
calendar.render();

I would have used template literals, but had to support IE11

calender

In Java, how can I determine if a char array contains a particular character?

Some other options if you do not want your own "Utils"-class:

Use Apache commons lang (ArrayUtils):

@Test
public void arrayCommonLang(){
    char[] test = {'h', 'e', 'l', 'l', 'o'};
    Assert.assertTrue(ArrayUtils.contains(test, 'o'));
    Assert.assertFalse(ArrayUtils.contains(test, 'p'));
}

Or use the builtin Arrays:

@Test
public void arrayTest(){
    char[] test = {'h', 'e', 'l', 'l', 'o'};
    Assert.assertTrue(Arrays.binarySearch(test, 'o') >= 0);
    Assert.assertTrue(Arrays.binarySearch(test, 'p') < 0);
}

Or use the Chars class from Google Guava:

@Test
public void testGuava(){
    char[] test = {'h', 'e', 'l', 'l', 'o'};
    Assert.assertTrue(Chars.contains(test, 'o'));
    Assert.assertFalse(Chars.contains(test, 'p'));
}

Slightly off-topic, the Chars class allows to find a subarray in an array.

Cocoa: What's the difference between the frame and the bounds?

Let me add my 5 cents.

Frame is used by the view's parent view to place it inside the parent view.

Bounds is used by the view itself to place it's own content (like a scroll view does while scrolling). See also clipsToBounds. Bounds also can be used to zoom in/out content of the view.

Analogy:
Frame ~ TV screen
Bounds ~ Camera (zoom, move, rotate)

Remove object from a list of objects in python

del array[0]

where 0 is the index of the object in the list (there is no array in python)

If...Then...Else with multiple statements after Then

This works with multiple statements:

if condition1 Then stmt1:stmt2 Else if condition2 Then stmt3:stmt4 Else stmt5:stmt6

Or you can split it over multiple lines:

if condition1 Then stmt1:stmt2
Else if condition2 Then stmt3:stmt4
Else stmt5:stmt6

Update div with jQuery ajax response html

It's also possible to use jQuery's .load()

$('#submitform').click(function() {
  $('#showresults').load('getinfo.asp #showresults', {
    txtsearch: $('#appendedInputButton').val()
  }, function() {
    // alert('Load was performed.')
    // $('#showresults').slideDown('slow')
  });
});

unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

We could modify the example above to use only part of the document that is fetched:

$( "#result" ).load( "ajax/test.html #container" );

When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.

Configuration System Failed to Initialize

I restarted Visual studio and even the whole PC. I cleaned the project, rebuild, and deleted bin file.

Nothing helped until i changed the configuration from x64 to x86. It worked on x86 but when i changed it back it also worked!

How to convert php array to utf8?

In case of a PDO connection, the following might help, but the database should be in UTF-8:

//Connect
$db = new PDO(
    'mysql:host=localhost;dbname=database_name;', 'dbuser', 'dbpassword',
    array('charset'=>'utf8')
);
$db->query("SET CHARACTER SET utf8");

How do I change tab size in Vim?

As a one-liner into vim:

:set tabstop=4 shiftwidth=4

For permanent setup, add these lines to ~/.vimrc:

set tabstop=4
set shiftwidth=4

NOTE: Add set expandtab if you prefer 4-spaces indentation, instead of a tab indentation.

Remove special symbols and extra spaces and replace with underscore using the replace method

Your regular expression [^a-zA-Z0-9]\s/g says match any character that is not a number or letter followed by a space.

Remove the \s and you should get what you are after if you want a _ for every special character.

var newString = str.replace(/[^A-Z0-9]/ig, "_");

That will result in hello_world___hello_universe

If you want it to be single underscores use a + to match multiple

var newString = str.replace(/[^A-Z0-9]+/ig, "_");

That will result in hello_world_hello_universe

Display UIViewController as Popup in iPhone

NOTE : This solution is broken in iOS 8. I will post new solution ASAP.

I am going to answer here using storyboard but it is also possible without storyboard.

  1. Init: Create two UIViewController in storyboard.

    • lets say FirstViewController which is normal and SecondViewController which will be the popup.

  2. Modal Segue: Put UIButton in FirstViewController and create a segue on this UIButton to SecondViewController as modal segue.

  3. Make Transparent: Now select UIView (UIView Which is created by default with UIViewController) of SecondViewController and change its background color to clear color.

  4. Make background Dim: Add an UIImageView in SecondViewController which covers whole screen and sets its image to some dimmed semi transparent image. You can get a sample from here : UIAlertView Background Image

  5. Display Design: Now add an UIView and make any kind of design you want to show. Here is a screenshot of my storyboard storyboard

    • Here I have add segue on login button which open SecondViewController as popup to ask username and password
  6. Important: Now that main step. We want that SecondViewController doesn't hide FirstViewController completely. We have set clear color but this is not enough. By default it adds black behind model presentation so we have to add one line of code in viewDidLoad of FirstViewController. You can add it at another place also but it should run before segue.

    [self setModalPresentationStyle:UIModalPresentationCurrentContext];

  7. Dismiss: When to dismiss depends on your use case. This is a modal presentation so to dismiss we do what we do for modal presentation:

    [self dismissViewControllerAnimated:YES completion:Nil];

Thats all.....

Any kind of suggestion and comment are welcome.

Demo : You can get demo source project from Here : Popup Demo

NEW : Someone have done very nice job on this concept : MZFormSheetController
New : I found one more code to get this kind of function : KLCPopup


iOS 8 Update : I made this method to work with both iOS 7 and iOS 8

+ (void)setPresentationStyleForSelfController:(UIViewController *)selfController presentingController:(UIViewController *)presentingController
{
    if (iOSVersion >= 8.0)
    {
        presentingController.providesPresentationContextTransitionStyle = YES;
        presentingController.definesPresentationContext = YES;

        [presentingController setModalPresentationStyle:UIModalPresentationOverCurrentContext];
    }
    else
    {
        [selfController setModalPresentationStyle:UIModalPresentationCurrentContext];
        [selfController.navigationController setModalPresentationStyle:UIModalPresentationCurrentContext];
    }
}

Can use this method inside prepareForSegue deligate like this

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    PopUpViewController *popup = segue.destinationViewController;
    [self setPresentationStyleForSelfController:self presentingController:popup]
}

Regex pattern to match at least 1 number and 1 character in a string

I can see that other responders have given you a complete solution. Problem with regexes is that they can be difficult to maintain/understand.

An easier solution would be to retain your existing regex, then create two new regexes to test for your "at least one alphabetic" and "at least one numeric".

So, test for this :-

/^([a-zA-Z0-9]+)$/

Then this :-

/\d/

Then this :-

/[A-Z]/i

If your string passes all three regexes, you have the answer you need.

Assign static IP to Docker container

If you want your container to have it's own virtual ethernet socket (with it's own MAC address), iptables, then use the Macvlan driver. This may be necessary to route traffic out to your/ISPs router.

https://docs.docker.com/engine/userguide/networking/get-started-macvlan

Get safe area inset top and bottom heights

Swift 4, 5

To pin a view to a safe area anchor using constraints can be done anywhere in the view controller's lifecycle because they're queued by the API and handled after the view has been loaded into memory. However, getting safe-area values requires waiting toward the end of a view controller's lifecycle, like viewDidLayoutSubviews().

This plugs into any view controller:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    let topSafeArea: CGFloat
    let bottomSafeArea: CGFloat

    if #available(iOS 11.0, *) {
        topSafeArea = view.safeAreaInsets.top
        bottomSafeArea = view.safeAreaInsets.bottom
    } else {
        topSafeArea = topLayoutGuide.length
        bottomSafeArea = bottomLayoutGuide.length
    }

    // safe area values are now available to use
}

I prefer this method to getting it off of the window (when possible) because it’s how the API was designed and, more importantly, the values are updated during all view changes, like device orientation changes.

However, some custom presented view controllers cannot use the above method (I suspect because they are in transient container views). In such cases, you can get the values off of the root view controller, which will always be available anywhere in the current view controller's lifecycle.

anyLifecycleMethod()
    guard let root = UIApplication.shared.keyWindow?.rootViewController else {
        return
    }
    let topSafeArea: CGFloat
    let bottomSafeArea: CGFloat

    if #available(iOS 11.0, *) {
        topSafeArea = root.view.safeAreaInsets.top
        bottomSafeArea = root.view.safeAreaInsets.bottom
    } else {
        topSafeArea = root.topLayoutGuide.length
        bottomSafeArea = root.bottomLayoutGuide.length
    }

    // safe area values are now available to use
}

How to change fontFamily of TextView in Android

Try this:

TextView textview = (TextView) findViewById(R.id.textview);

Typeface tf= Typeface.createFromAsset(getAssets(),"fonts/Tahoma.ttf");
textview .setTypeface(tf);

How to initialise memory with new operator in C++?

std::fill is one way. Takes two iterators and a value to fill the region with. That, or the for loop, would (I suppose) be the more C++ way.

For setting an array of primitive integer types to 0 specifically, memset is fine, though it may raise eyebrows. Consider also calloc, though it's a bit inconvenient to use from C++ because of the cast.

For my part, I pretty much always use a loop.

(I don't like to second-guess people's intentions, but it is true that std::vector is, all things being equal, preferable to using new[].)

Is __init__.py not required for packages in Python 3.3+

I would say that one should omit the __init__.py only if one wants to have the implicit namespace package. If you don't know what it means, you probably don't want it and therefore you should continue to use the __init__.py even in Python 3.

VBA error 1004 - select method of range class failed

Removing the range select before the copy worked for me. Thanks for the posts.

OOP vs Functional Programming vs Procedural

For GUI I'd say that the Object-Oriented Paradigma is very well suited. The Window is an Object, the Textboxes are Objects, and the Okay-Button is one too. On the other Hand stuff like String Processing can be done with much less overhead and therefore more straightforward with simple procedural paradigma.

I don't think it is a question of the language neither. You can write functional, procedural or object-oriented in almost any popular language, although it might be some additional effort in some.

File to import not found or unreadable: compass

I'm seeing this issue using Rails 4.0.2 and compass-rails 1.1.3

I got past this error by moving gem 'compass-rails' outside of the :assets group in my Gemfile

It looks something like this:

# stuff
gem 'compass-rails', '~> 1.1.3'
group :assets do
  # more stuff
end

Play an audio file using jQuery when a button is clicked

JSFiddle Demonstration

This is what I use with JQuery:

$('.button').on('click', function () { 
    var obj = document.createElement("audio");
        obj.src = "linktoyourfile.wav"; 
        obj.play(); 
});

SQL LEFT JOIN Subquery Alias

I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.

SELECT wpoi.order_id As No_Commande
FROM  wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id 
                            AND wpp.meta_key = '_shipping_first_name'
WHERE  wpoi.order_id =2198 

Function to close the window in Tkinter

class App():
    def __init__(self):
        self.root = Tkinter.Tk()
        button = Tkinter.Button(self.root, text = 'root quit', command=self.quit)
        button.pack()
        self.root.mainloop()

    def quit(self):
        self.root.destroy()

app = App()

How do you run a command for each line of a file?

if you have a nice selector (for example all .txt files in a dir) you could do:

for i in *.txt; do chmod 755 "$i"; done

bash for loop

or a variant of yours:

while read line; do chmod 755 "$line"; done < file.txt

Convert integers to strings to create output filenames at run time

Try the following:

    ....
    character(len=30) :: filename  ! length depends on expected names
    integer           :: inuit
    ....
    do i=1,n
        write(filename,'("output",i0,".txt")') i
        open(newunit=iunit,file=filename,...)
        ....
        close(iunit)
    enddo
    ....

Where "..." means other appropriate code for your purpose.

What is ToString("N0") format?

This is where the documentation is:

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

The numeric ("N") format specifier converts a number to a string of the form "-d,ddd,ddd.ddd…", where "-" indicates a negative number symbol if required, "d" indicates a digit (0-9) ...

And this is where they talk about the default (2):

http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.numberdecimaldigits.aspx

      // Displays a negative value with the default number of decimal digits (2).
      Int64 myInt = -1234;
      Console.WriteLine( myInt.ToString( "N", nfi ) );

MySQL - SELECT all columns WHERE one column is DISTINCT

If what your asking is to only show rows that have 1 link for them then you can use the following:

SELECT * FROM posted WHERE link NOT IN 
(SELECT link FROM posted GROUP BY link HAVING COUNT(LINK) > 1)

Again this is assuming that you want to cut out anything that has a duplicate link.

Pip freeze vs. pip list

pip list shows ALL installed packages.

pip freeze shows packages YOU installed via pip (or pipenv if using that tool) command in a requirements format.

Remark below that setuptools, pip, wheel are installed when pipenv shell creates my virtual envelope. These packages were NOT installed by me using pip:

test1 % pipenv shell
Creating a virtualenv for this project…
Pipfile: /Users/terrence/Development/Python/Projects/test1/Pipfile
Using /usr/local/Cellar/pipenv/2018.11.26_3/libexec/bin/python3.8 (3.8.1) to create virtualenv…
? Creating virtual environment...
<SNIP>
Installing setuptools, pip, wheel...
done.
? Successfully created virtual environment! 
<SNIP>

Now review & compare the output of the respective commands where I've only installed cool-lib and sampleproject (of which peppercorn is a dependency):

test1 % pip freeze       <== Packages I'VE installed w/ pip

-e git+https://github.com/gdamjan/hello-world-python-package.git@10<snip>71#egg=cool_lib
peppercorn==0.6
sampleproject==1.3.1


test1 % pip list         <== All packages, incl. ones I've NOT installed w/ pip

Package       Version Location                                                                    
------------- ------- --------------------------------------------------------------------------
cool-lib      0.1  /Users/terrence/.local/share/virtualenvs/test1-y2Zgz1D2/src/cool-lib           <== Installed w/ `pip` command
peppercorn    0.6       <== Dependency of "sampleproject"
pip           20.0.2  
sampleproject 1.3.1     <== Installed w/ `pip` command
setuptools    45.1.0  
wheel         0.34.2

How to return a part of an array in Ruby?

I like ranges for this:

def first_half(list)
  list[0...(list.length / 2)]
end

def last_half(list)
  list[(list.length / 2)..list.length]
end

However, be very careful about whether the endpoint is included in your range. This becomes critical on an odd-length list where you need to choose where you're going to break the middle. Otherwise you'll end up double-counting the middle element.

The above example will consistently put the middle element in the last half.

Django model "doesn't declare an explicit app_label"

I ran into this error when I tried generating migrations for a single app which had existing malformed migrations due to a git merge. e.g.

manage.py makemigrations myapp

When I deleted it's migrations and then ran:

manage.py makemigrations

the error did not occur and the migrations generated successfully.

Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat

Got the solution and it's working fine. Set the environment variables as:

  • CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59 (path where your Apache Tomcat is)
  • JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25; (path where your JDK is)
  • JRE_Home=C:\Program Files\Java\jre1.8.0_25; (path where your JRE is)
  • CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib

Get a list of resources from classpath directory

My way, no Spring, used during a unit test:

URI uri = TestClass.class.getResource("/resources").toURI();
Path myPath = Paths.get(uri);
Stream<Path> walk = Files.walk(myPath, 1);
for (Iterator<Path> it = walk.iterator(); it.hasNext(); ) {
    Path filename = it.next();   
    System.out.println(filename);
}

Eclipse hangs on loading workbench

I had this problem in Windows 7, this is what fixed it for me.

http://letsgetdugg.com/2009/04/19/recovering-a-corrupt-eclipse-workspace/

cd ~/Documents/workspace/.metalog/.plugins

rm -rf org.eclipse.core.resources

Recursive search and replace in text files on Mac and Linux

On Mac OSX 10.11.5 this works fine:

grep -rli 'old-word' * | xargs -I@ sed -i '' 's/old-word/new-word/g' @

What are all possible pos tags of NLTK?

The below can be useful to access a dict keyed by abbreviations:

>>> from nltk.data import load
>>> tagdict = load('help/tagsets/upenn_tagset.pickle')
>>> tagdict['NN'][0]
'noun, common, singular or mass'
>>> tagdict.keys()
['PRP$', 'VBG', 'VBD', '``', 'VBN', ',', "''", 'VBP', 'WDT', ...

c# datatable insert column at position 0

Just to improve Wael's answer and put it on a single line:

dt.Columns.Add("Better", typeof(Boolean)).SetOrdinal(0);

UPDATE: Note that this works when you don't need to do anything else with the DataColumn. Add() returns the column in question, SetOrdinal() returns nothing.

Python 2: AttributeError: 'list' object has no attribute 'strip'

Hope this helps :)

>>> x = [i.split(";") for i in l]
>>> x
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]
>>> z = [j for i in x for j in i]
>>> z
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
>>> 

Android TextView Text not getting wrapped

Set the height of the text view android:minHeight="some pixes" or android:width="some pixels". It will solve the problem.

Why does this CSS margin-top style not work?

Create new block formatting context

You can use display: flow-root on the parent element to prevent margin collapsing through the containing element as it creates new Block Formatting Context.

Changing the value of the overflow property to auto or using flexbox will have the same effect.

https://codepen.io/rachelandrew/pen/VJXjEp

Received fatal alert: handshake_failure through SSLHandshakeException

Assuming you're using the proper SSL/TLS protocols, properly configured your keyStore and trustStore, and confirmed that there doesn't exist any issues with the certificates themselves, you may need to strengthen your security algorithms.

As mentioned in Vineet's answer, one possible reason you receive this error is due to incompatible cipher suites being used. By updating my local_policy and US_export_policy jars in my JDK's security folder with the ones provided in the Java Cryptography Extension (JCE), I was able to complete the handshake successfully.

Make div stay at bottom of page's content all the time even when there are scrollbars

You didn't close your ; after position: absolute. Otherwise your above code would have worked perfectly!

#footer {
   position:absolute;
   bottom:30px;
   width:100%;
}

How to clear the cache in NetBeans

Just install cache eraser plugin, it is compatible with nb6.9, 7.0,7.1,7.2 and 7.3: To configure the plugin you have to provide the cache dir which is in netbean's about screen. Then with Tools->erase cache, you clear the netbeans cache. That is all, good luck.

http://plugins.netbeans.org/plugin/40014/cache-eraser

frequent issues arising in android view, Error parsing XML: unbound prefix

I got this error in Xamarin when I was using

  <android.support.v7.widget.CardView  
    android:layout_width="match_parent"  
    android:layout_height="wrap_content"  
    card_view:cardElevation="4dp"  
    card_view:cardCornerRadius="5dp"  
    card_view:cardUseCompatPadding="true">  
  </android.support.v7.widget.CardView>

in a layout file without installing the nuget package for android.support.v7.widget.CardView

Installing the applicable nuget package fixed the issue. Hope it helps, I didn't see this answer anywhere in the list

Converting bytes to megabytes

In general, it's wrong to use decimal SI prefixes (e.g. kilo, mega) when referring to binary data sizes (except in casual usage). It's ambiguous and causes confusion. To be precise you can use binary prefixes (e.g. 1 mebibyte = 1 MiB = 1024 kibibytes = 2^20 bytes). When someone else uses decimal SI prefixes for binary data you need to get more information before you can know what is meant.

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

How to get file_get_contents() to work with HTTPS?

In my case, the issue was due to WAMP using a different php.ini for CLI than Apache, so your settings made through the WAMP menu don't apply to CLI. Just modify the CLI php.ini and it works.

Calculate MD5 checksum for a file

I know this question was already answered, but this is what I use:

using (FileStream fStream = File.OpenRead(filename)) {
    return GetHash<MD5>(fStream)
}

Where GetHash:

public static String GetHash<T>(Stream stream) where T : HashAlgorithm {
    StringBuilder sb = new StringBuilder();

    MethodInfo create = typeof(T).GetMethod("Create", new Type[] {});
    using (T crypt = (T) create.Invoke(null, null)) {
        byte[] hashBytes = crypt.ComputeHash(stream);
        foreach (byte bt in hashBytes) {
            sb.Append(bt.ToString("x2"));
        }
    }
    return sb.ToString();
}

Probably not the best way, but it can be handy.

Search and get a line in Python

items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:

you can also get the line if there are other characters before token

items=re.findall("^.*token.*$",s,re.MULTILINE)

The above works like grep token on unix and keyword 'in' or .contains in python and C#

s='''
qwertyuiop
asdfghjkl

zxcvbnm
token qwerty

asdfghjklñ
'''

http://pythex.org/ matches the following 2 lines

....
....
token qwerty

Why does visual studio 2012 not find my tests?

I copy-pasted the method declaration, which included an input string parameter. Forgot to delete the input parameter.

  public void ExtractValueFromLineTest(string input) {}//test not discovered because of the string input param

The PowerShell -and conditional operator

You can simplify it to

if ($user_sam -and $user_case) {
  ...
}

because empty strings coerce to $false (and so does $null, for that matter).

How to detect scroll direction

$(function(){
    var _top = $(window).scrollTop();
    var _direction;
    $(window).scroll(function(){
        var _cur_top = $(window).scrollTop();
        if(_top < _cur_top)
        {
            _direction = 'down';
        }
        else
        {
            _direction = 'up';
        }
        _top = _cur_top;
        console.log(_direction);
    });
});

Demo: http://jsfiddle.net/AlienWebguy/Bka6F/

php: check if an array has duplicates

Find this useful solution

function get_duplicates( $array ) {
    return array_unique( array_diff_assoc( $array, array_unique( $array ) ) );
}

After that count result if greater than 0 than duplicates else unique.

How do I find out what License has been applied to my SQL Server installation?

I presume you mean via SSMS?

For a SQL Server Instance:

SELECT SERVERPROPERTY('productversion'), 
       SERVERPROPERTY ('productlevel'), 
       SERVERPROPERTY ('edition')

For a SQL Server Installation:

Select @@Version

How to close a GUI when I push a JButton?

Create a method and call it to close the JFrame, for example:

public void CloseJframe(){
    super.dispose();
}

How to check if a column exists in a datatable

myDataTable.Columns.Contains("col_name")

What is the difference between association, aggregation and composition?

Association

Association represents the relationship between two classes.It can be unidirectional(one way) or bidirectional(two way)

for example:

  1. unidirectional

Customer places orders

  1. bidirectional

A is married to B

B is married to A

Aggregation

Aggregation is a kind of association.But with specific features.Aggregation is the relationship in one larger "whole" class contains one or more smaller "parts" classes.Conversely, a smaller "part" class is a part of "whole" larger class.

for example:

club has members

A club("whole") is made up of several club members("parts").Member have life to outside the club. If the club("whole") were to die, members("parts") would not die with it. Because member can belong to multiple clubs("whole").

Composition

This is a stronger form of aggregation."Whole" is responsible for the creation or destruction of its "parts"

For example:

A school has departments

In this case school("whole") were to die, department("parts") would die with it. Because each part can belong to only one "whole".

Why do I need to do `--set-upstream` all the time?

You can also do git push -u origin $(current_branch)

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

Kenny is right, just want to clear some things out.

  1. Create the file border.xml and put it in the folder res/drawable/
  2. add the code

    <shape xmlns:android="http://schemas.android.com/apk/res/android"> 
       <stroke android:width="4dp" android:color="#FF00FF00" /> 
       <solid android:color="#ffffff" /> 
       <padding android:left="7dp" android:top="7dp" 
            android:right="7dp" android:bottom="0dp" /> 
       <corners android:radius="4dp" /> 
    </shape>
    
  3. set back ground like android:background="@drawable/border" wherever you want the border

Mine first didn't work cause i put the border.xml in the wrong folder!

How to use format() on a moment.js duration?

Based on ni-ko-o-kin's answer:

meassurements = ["years", "months", "weeks", "days", "hours", "minutes", "seconds"];
withPadding = (duration) => {
    var step = null;
    return meassurements.map((m) => duration[m]()).filter((n,i,a) => {
        var nonEmpty = Boolean(n);
        if (nonEmpty || step || i >= a.length - 2) {
            step = true;
        }
        return step;
    }).map((n) => ('0' + n).slice(-2)).join(':')
}

duration1 = moment.duration(1, 'seconds');
duration2 = moment.duration(7200, 'seconds');
duration3 = moment.duration(604800, 'seconds');

withPadding(duration1); // 00:01
withPadding(duration2); // 02:00:00
withPadding(duration3); // 01:07:00:00:00

How do I convert the date from one format to another date object in another format without using any deprecated classes?

Since Java 8, we can achieve this as follows:

private static String convertDate(String strDate) 
{
    //for strdate = 2017 July 25

    DateTimeFormatter f = new DateTimeFormatterBuilder().appendPattern("yyyy MMMM dd")
                                        .toFormatter();

    LocalDate parsedDate = LocalDate.parse(strDate, f);
    DateTimeFormatter f2 = DateTimeFormatter.ofPattern("MM/d/yyyy");

    String newDate = parsedDate.format(f2);

    return newDate;
}

The output will be : "07/25/2017"

How do I change the figure size for a seaborn plot?

This shall also work.

from matplotlib import pyplot as plt
import seaborn as sns    

plt.figure(figsize=(15,16))
sns.countplot(data=yourdata, ...)

How to Apply Mask to Image in OpenCV?

Well, this question appears on top of search results, so I believe we need code example here. Here's the Python code:

import cv2

def apply_mask(frame, mask):
    """Apply binary mask to frame, return in-place masked image."""
    return cv2.bitwise_and(frame, frame, mask=mask)

Mask and frame must be the same size, so pixels remain as-is where mask is 1 and are set to zero where mask pixel is 0.

And for C++ it's a little bit different:

cv::Mat inFrame; // Original (non-empty) image
cv::Mat mask; // Original (non-empty) mask

// ...

cv::Mat outFrame;  // Result output
inFrame.copyTo(outFrame, mask);

calling another method from the main method in java

If you want to use do() in your main method there are 2 choices because one is static but other (do()) not

  1. Create new instance and invoke do() like new Foo().do();
  2. make static do() method

Have a look at this sun tutorial

IF EXISTS in T-SQL

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

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

Redirecting to a page after submitting form in HTML

For anyone else having the same problem, I figured it out myself.

_x000D_
_x000D_
    <html>_x000D_
      <body>_x000D_
        <form target="_blank" action="https://website.com/action.php" method="POST">_x000D_
          <input type="hidden" name="fullname" value="Sam" />_x000D_
          <input type="hidden" name="city" value="Dubai&#32;" />_x000D_
          <input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />_x000D_
        </form>_x000D_
      </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.

How can I roll back my last delete command in MySQL?

If you didn't commit the transaction yet, try rollback. If you have already committed the transaction (by commit or by exiting the command line client), you must restore the data from your last backup.

iPhone app could not be installed at this time

clear your cache and cookies in Safari, make sure your device is in provisioning profile and provisioning profile is installed on the device.

If everything mentioned above didn't help, try to create a new build with higher build number and try to distribute your app again

How to solve error message: "Failed to map the path '/'."

I Think this is because of IIS is unable to find the root folder. i.e wwwroot. Restarting the IIS wont be helpful in some scenarios. if the root path has changed, you should bring it back to %SystemDrive%\inetpub\wwwroot

by right clicking sites node in IIS and changing physical path to the above one.

and make sure that your application pool is asp.net v4.0 and running in integrated mode

How to write UTF-8 in a CSV file

It's very simple for Python 3.x (docs).

import csv

with open('output_file_name', 'w', newline='', encoding='utf-8') as csv_file:
    writer = csv.writer(csv_file, delimiter=';')
    writer.writerow('my_utf8_string')

For Python 2.x, look here.

Convert output of MySQL query to utf8

You can use CAST and CONVERT to switch between different types of encodings. See: http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html

SELECT column1, CONVERT(column2 USING utf8)
FROM my_table 
WHERE my_condition;

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

Even though this question is quite old and there are great answers already, I thought I should put one more which explains 3 different approaches to solve this problem.

1st Approach

Explicitly map DateTime property public virtual DateTime Start { get; set; } to datetime2 in corresponding column in the table. Because by default EF will map it to datetime.

This can be done by fluent API or data annotation.

  1. Fluent API

    In DbContext class overide OnModelCreating and configure property Start (for explanation reasons it's a property of EntityClass class).

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Configure only one property 
        modelBuilder.Entity<EntityClass>()
            .Property(e => e.Start)
            .HasColumnType("datetime2");
    
       //or configure all DateTime Preperties globally(EF 6 and Above)
        modelBuilder.Properties<DateTime>()
            .Configure(c => c.HasColumnType("datetime2"));
    }
    
  2. Data annotation

    [Column(TypeName="datetime2")]
    public virtual DateTime Start { get; set; }
    

2nd Approach

Initialize Start to a default value in EntityClass constructor.This is good as if for some reason the value of Start is not set before saving the entity into the database start will always have a default value. Make sure default value is greater than or equal to SqlDateTime.MinValue ( from January 1, 1753 to December 31, 9999)

public class EntityClass
{
    public EntityClass()
    {
        Start= DateTime.Now;
    }
    public DateTime Start{ get; set; }
}

3rd Approach

Make Start to be of type nullable DateTime -note ? after DateTime-

public virtual DateTime? Start { get; set; }

For more explanation read this post

Convert serial.read() into a useable string using Arduino?

Credit for this goes to magma. Great answer, but here it is using c++ style strings instead of c style strings. Some users may find that easier.

String string = "";
char ch; // Where to store the character read

void setup() {
    Serial.begin(9600);
    Serial.write("Power On");
}
    
boolean Comp(String par) {
    while (Serial.available() > 0) // Don't read unless
                                       // there you know there is data
    {
        ch = Serial.read(); // Read a character
        string += ch; // Add it
    }
    
    if (par == string) {
       string = "";
       return(true);
    }
    else {
       //dont reset string
       return(false);
    }
}
    
void loop()
{
    if (Comp("m1 on")) {
        Serial.write("Motor 1 -> Online\n");
    }
    if (Comp("m1 off")) {
        Serial.write("Motor 1 -> Offline\n");
    }
}

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

For anyone looking for a UI option using IIS Manager.

  1. Open the Website in IIS Manager
  2. Go To Request Filtering and open the Request Filtering Window.
  3. Go to Verbs Tab and Add HTTP Verbs to "Allow Verb..." or "Deny Verb...". This allow to add the HTTP Verbs in the "Deny Verb.." Collection.

Request Filtering Window in IIS Manager Request Filtering Window in IIS Manager

Add Verb... or Deny Verb... enter image description here

Best way to copy a database (SQL Server 2008)

If you want to take a copy of a live database, do the Backup/Restore method.

[In SQLS2000, not sure about 2008:] Just keep in mind that if you are using SQL Server accounts in this database, as opposed to Windows accounts, if the master DB is different or out of sync on the development server, the user accounts will not translate when you do the restore. I've heard about an SP to remap them, but I can't remember which one it was.

How to install gem from GitHub source?

Bundler allows you to use gems directly from git repositories. In your Gemfile:

# Use the http(s), ssh, or git protocol
gem 'foo', git: 'https://github.com/dideler/foo.git'
gem 'foo', git: '[email protected]:dideler/foo.git'
gem 'foo', git: 'git://github.com/dideler/foo.git'

# Specify a tag, ref, or branch to use
gem 'foo', git: '[email protected]:dideler/foo.git', tag: 'v2.1.0'
gem 'foo', git: '[email protected]:dideler/foo.git', ref: '4aded'
gem 'foo', git: '[email protected]:dideler/foo.git', branch: 'development'

# Shorthand for public repos on GitHub (supports all the :git options)
gem 'foo', github: 'dideler/foo'

For more info, see https://bundler.io/v2.0/guides/git.html

How to print from Flask @app.route to python console

I tried running @Viraj Wadate's code, but couldn't get the output from app.logger.info on the console.

To get INFO, WARNING, and ERROR messages in the console, the dictConfig object can be used to create logging configuration for all logs (source):

from logging.config import dictConfig
from flask import Flask


dictConfig({
    'version': 1,
    'formatters': {'default': {
        'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
    }},
    'handlers': {'wsgi': {
        'class': 'logging.StreamHandler',
        'stream': 'ext://flask.logging.wsgi_errors_stream',
        'formatter': 'default'
    }},
    'root': {
        'level': 'INFO',
        'handlers': ['wsgi']
    }
})


app = Flask(__name__)

@app.route('/')
def index():
    return "Hello from Flask's test environment"

@app.route('/print')
def printMsg():
    app.logger.warning('testing warning log')
    app.logger.error('testing error log')
    app.logger.info('testing info log')
    return "Check your console"

if __name__ == '__main__':
    app.run(debug=True)

How to return a value from a Form in C#?

If you want to pass data to form2 from form1 without passing like new form(sting "data");

Do like that in form 1

using (Form2 form2= new Form2())
{
   form2.ReturnValue1 = "lalala";
   form2.ShowDialog();
}

in form 2 add

public string ReturnValue1 { get; set; }

private void form2_Load(object sender, EventArgs e)
{
   MessageBox.Show(ReturnValue1);
}

Also you can use value in form1 like this if you want to swap something in form1

just in form1

textbox.Text =form2.ReturnValue1

How to log Apache CXF Soap Request and Soap Response using Log4j?

cxf.xml

<cxf:bus>
    <cxf:ininterceptors>
        <ref bean="loggingInInterceptor" />
    </cxf:ininterceptors>
    <cxf:outinterceptors>
        <ref bean="logOutInterceptor" />
    </cxf:outinterceptors>
</cxf:bus>

org.apache.cxf.Logger

org.apache.cxf.common.logging.Log4jLogger

Please check screenshot here

How to pass credentials to httpwebrequest for accessing SharePoint Library

If you need to run request as the current user from desktop application use CredentialCache.DefaultCredentials (see on MSDN).

Your code looks fine if you need to run a request from server side code or under a different user.

Please note that you should be careful when storing passwords - consider using the SecureString version of the constructor.

Sites not accepting wget user agent header

It seems Yahoo server does some heuristic based on User-Agent in a case Accept header is set to */*.

Accept: text/html

did the trick for me.

e.g.

wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0"  http://yahoo.com

Note: if you don't declare Accept header then wget automatically adds Accept:*/* which means give me anything you have.

What is the meaning of ImagePullBackOff status on a Kubernetes pod?

I had similar problem when using minikube over hyperv with 2048GB memory. I found that in HyperV manager the Memory Demand was higher than allocated.

So I stopped minikube and assigned somewhere between 4096-6144GB. It worked fine after that, all pods running!

I don't know if this can nail down the issue in every case. But just have a look at the memory and disk allocated to the minikube.

How to find row number of a value in R code

Instead of 1:nrow(mydata_2) you can simply use the which() function: which(mydata_2[,4] == 1578)

Although as it was pointed out above, the 3rd column contains 1578, not the fourth: which(mydata_2[,3] == 1578)

Bootstrap full-width text-input within inline-form

With Bootstrap >4.1 it's just a case of using the flexbox utility classes. Just have a flexbox container inside your column, and then give all the elements within it the "flex-fill" class. As with inline forms you'll need to set the margins/padding on the elements yourself.

_x000D_
_x000D_
.prop-label {_x000D_
    margin: .25rem 0 !important;_x000D_
}_x000D_
_x000D_
.prop-field {_x000D_
    margin-left: 1rem;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row">_x000D_
 <div class="col-12">_x000D_
  <div class="d-flex">_x000D_
   <label class="flex-fill prop-label">Label:</label>_x000D_
   <input type="text" class="flex-fill form-control prop-field">_x000D_
  </div>_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to set focus on an input field after rendering?

Since there is a lot of reasons for this error I thought that I would also post the problem I was facing. For me, problem was that I rendered my inputs as content of another component.

export default ({ Content }) => {
  return (
  <div className="container-fluid main_container">
    <div className="row">
      <div className="col-sm-12 h-100">
        <Content />                                 // I rendered my inputs here
      </div>
    </div>
  </div>
  );
}

This is the way I called the above component:

<Component Content={() => {
  return (
    <input type="text"/>
  );
}} />

invalid_client in google oauth2

Did the error also report that it was missing an application name? I had this issue until I created a project name (e.g. "Project X") in the project settings dialog.

Python recursive folder read

If you want a flat list of all paths under a given dir (like find . in the shell):

   files = [ 
       os.path.join(parent, name)
       for (parent, subdirs, files) in os.walk(YOUR_DIRECTORY)
       for name in files + subdirs
   ]

To only include full paths to files under the base dir, leave out + subdirs.

How to use if statements in underscore.js templates?

From here:

"You can also refer to the properties of the data object via that object, instead of accessing them as variables." Meaning that for OP's case this will work (with a significantly smaller change than other possible solutions):

<% if (obj.date) { %><span class="date"><%= date %></span><% }  %>

How to do a simple file search in cmd

Problem with DIR is that it will return wrong answers. If you are looking for DOC in a folder by using DIR *.DOC it will also give you the DOCX. Searching for *.HTM will also give the HTML and so on...

How to compare timestamp dates with date-only parameter in MySQL?

You can use the DATE() function to extract the date portion of the timestamp:

SELECT * FROM table
WHERE DATE(timestamp) = '2012-05-25'

Though, if you have an index on the timestamp column, this would be faster because it could utilize an index on the timestamp column if you have one:

SELECT * FROM table
WHERE timestamp BETWEEN '2012-05-25 00:00:00' AND '2012-05-25 23:59:59'

How to search a specific value in all tables (PostgreSQL)?

-- Below function will list all the tables which contain a specific string in the database

 select TablesCount(‘StringToSearch’);

--Iterates through all the tables in the database

CREATE OR REPLACE FUNCTION **TablesCount**(_searchText TEXT)
RETURNS text AS 
$$ -- here start procedural part
   DECLARE _tname text;
   DECLARE cnt int;
   BEGIN
    FOR _tname IN SELECT table_name FROM information_schema.tables where table_schema='public' and table_type='BASE TABLE'  LOOP
         cnt= getMatchingCount(_tname,Columnames(_tname,_searchText));
                                RAISE NOTICE 'Count% ', CONCAT('  ',cnt,' Table name: ', _tname);
                END LOOP;
    RETURN _tname;
   END;
$$ -- here finish procedural part
LANGUAGE plpgsql; -- language specification

-- Returns the count of tables for which the condition is met. -- For example, if the intended text exists in any of the fields of the table, -- then the count will be greater than 0. We can find the notifications -- in the Messages section of the result viewer in postgres database.

CREATE OR REPLACE FUNCTION **getMatchingCount**(_tname TEXT, _clause TEXT)
RETURNS int AS 
$$
Declare outpt text;
    BEGIN
    EXECUTE 'Select Count(*) from '||_tname||' where '|| _clause
       INTO outpt;
       RETURN outpt;
    END;
$$ LANGUAGE plpgsql;

--Get the fields of each table. Builds the where clause with all columns of a table.

CREATE OR REPLACE FUNCTION **Columnames**(_tname text,st text)
RETURNS text AS 
$$ -- here start procedural part
DECLARE
                _name text;
                _helper text;
   BEGIN
                FOR _name IN SELECT column_name FROM information_schema.Columns WHERE table_name =_tname LOOP
                                _name=CONCAT('CAST(',_name,' as VarChar)',' like ','''%',st,'%''', ' OR ');
                                _helper= CONCAT(_helper,_name,' ');
                END LOOP;
                RETURN CONCAT(_helper, ' 1=2');

   END;
$$ -- here finish procedural part
LANGUAGE plpgsql; -- language specification

python numpy/scipy curve fitting

You'll first need to separate your numpy array into two separate arrays containing x and y values.

x = [1, 2, 3, 9]
y = [1, 4, 1, 3]

curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like

def func(x, a, b):
    return a*x + b

scipy.optimize.curve_fit(func, x, y) will return a numpy array containing two arrays: the first will contain values for a and b that best fit your data, and the second will be the covariance of the optimal fit parameters.

Here's an example for a linear fit with the data you provided.

import numpy as np
from scipy.optimize import curve_fit

x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])

def fit_func(x, a, b):
    return a*x + b

params = curve_fit(fit_func, x, y)

[a, b] = params[0]

This code will return a = 0.135483870968 and b = 1.74193548387

Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.

enter image description here

Sort Array of object by object field in Angular 6

You can simply use Arrays.sort()

array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));

Working Example :

_x000D_
_x000D_
var array = [{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"VPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""},},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"adfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"bbfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}}];_x000D_
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));_x000D_
 _x000D_
 console.log(array);
_x000D_
_x000D_
_x000D_

How do you create a Spring MVC project in Eclipse?

Download Spring STS (SpringSource Tool Suite) and choose Spring Template Project from the Dashboard. This is the easiest way to get a preconfigured spring mvc project, ready to go.

How can I print the contents of a hash in Perl?

If you want to be pedantic and keep it to one line (without use statements and shebang), then I'll sort of piggy back off of tetromino's answer and suggest:

print Dumper( { 'abc' => 123, 'def' => [4,5,6] } );

Not doing anything special other than using the anonymous hash to skip the temp variable ;)

Reading a List from properties file and load with spring annotation @Value

Using Spring EL:

@Value("#{'${my.list.of.strings}'.split(',')}") 
private List<String> myList;

Assuming your properties file is loaded correctly with the following:

my.list.of.strings=ABC,CDE,EFG

Eclipse projects not showing up after placing project files in workspace/projects

Yeah.... i kinda see what you need. I just came across same problem.

Here is exactly what i did. Now, bear in mind, this some low level knowledge, since i'm just starting. I made my life complicated, so i needed solution. I kinda found it on my own, using different directions from above answers.

I switched from win 10 on HDD to linux on SSD, so i needed my few of .class and .java imported into new workspace.

First i made a mistake, not using export option on windows and i just simply copied all of files from src and bin folders on win 10 to src and bin folders on linux. Of course workspace did not see those files.

Solution was found in IMPORT tool (which i should have used right away).

  1. I put all of files in src folder into zipp file, and moved this file to some arbitrary folder (Home folder in my case).

  2. Go back to src folder and delete all of .java files (you won't be needing them anymore).

  3. Then i opened my empty project and selected import from File menu in Eclipse. In import window, under option General (first one) select Import Archive.

  4. Now simply find your zip file, and Voila! All is where it should be.

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

I face the same problem and changing

 $cfg['Servers'][$i]['host'] = 'localhost';

to

 $cfg['Servers'][$i]['host'] = '127.0.0.1';

Solved this issue.

Extract Data from PDF and Add to Worksheet

Using Bytescout PDF Extractor SDK is a good option. It is cheap and gives plenty of PDF related functionality. One of the answers above points to the dead page Bytescout on GitHub. I am providing a relevant working sample to extract table from PDF. You may use it to export in any format.

Set extractor = CreateObject("Bytescout.PDFExtractor.StructuredExtractor")

extractor.RegistrationName = "demo"
extractor.RegistrationKey = "demo"

' Load sample PDF document
extractor.LoadDocumentFromFile "../../sample3.pdf"

For ipage = 0 To extractor.GetPageCount() - 1 

    ' starting extraction from page #"
    extractor.PrepareStructure ipage

    rowCount = extractor.GetRowCount(ipage)

    For row = 0 To rowCount - 1 
        columnCount = extractor.GetColumnCount(ipage, row)

        For col = 0 To columnCount-1
            WScript.Echo "Cell at page #" +CStr(ipage) + ", row=" & CStr(row) & ", column=" & _
                CStr(col) & vbCRLF & extractor.GetCellValue(ipage, row, col)
        Next
    Next
Next

Many more samples available here: https://github.com/bytescout/pdf-extractor-sdk-samples

Can't specify the 'async' modifier on the 'Main' method of a console app

You can solve this with this simple construct:

class Program
{
    static void Main(string[] args)
    {
        Task.Run(async () =>
        {
            // Do any async anything you need here without worry
        }).GetAwaiter().GetResult();
    }
}

That will put everything you do out on the ThreadPool where you'd want it (so other Tasks you start/await don't attempt to rejoin a Thread they shouldn't), and wait until everything's done before closing the Console app. No need for special loops or outside libs.

Edit: Incorporate Andrew's solution for uncaught Exceptions.

Create GUI using Eclipse (Java)

Yes, there is one. It is an eclipse-plugin called Visual Editor. You can download it here

How to suspend/resume a process in Windows?

You can't do it from the command line, you have to write some code (I assume you're not just looking for an utility otherwise Super User may be a better place to ask). I also assume your application has all the required permissions to do it (examples are without any error checking).

Hard Way

First get all the threads of a given process then call the SuspendThread function to stop each one (and ResumeThread to resume). It works but some applications may crash or hung because a thread may be stopped in any point and the order of suspend/resume is unpredictable (for example this may cause a dead lock). For a single threaded application this may not be an issue.

void suspend(DWORD processId)
{
    HANDLE hThreadSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);

    THREADENTRY32 threadEntry; 
    threadEntry.dwSize = sizeof(THREADENTRY32);

    Thread32First(hThreadSnapshot, &threadEntry);

    do
    {
        if (threadEntry.th32OwnerProcessID == processId)
        {
            HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE,
                threadEntry.th32ThreadID);

            SuspendThread(hThread);
            CloseHandle(hThread);
        }
    } while (Thread32Next(hThreadSnapshot, &threadEntry));

    CloseHandle(hThreadSnapshot);
}

Please note that this function is even too much naive, to resume threads you should skip threads that was suspended and it's easy to cause a dead-lock because of suspend/resume order. For single threaded applications it's prolix but it works.

Undocumented way

Starting from Windows XP there is the NtSuspendProcess but it's undocumented. Read this post for a code example (reference for undocumented functions: news://comp.os.ms-windows.programmer.win32).

typedef LONG (NTAPI *NtSuspendProcess)(IN HANDLE ProcessHandle);

void suspend(DWORD processId)
{
    HANDLE processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId));

    NtSuspendProcess pfnNtSuspendProcess = (NtSuspendProcess)GetProcAddress(
        GetModuleHandle("ntdll"), "NtSuspendProcess");

    pfnNtSuspendProcess(processHandle);
    CloseHandle(processHandle);
}

"Debugger" Way

To suspend a program is what usually a debugger does, to do it you can use the DebugActiveProcess function. It'll suspend the process execution (with all threads all together). To resume you may use DebugActiveProcessStop.

This function lets you stop a process (given its Process ID), syntax is very simple: just pass the ID of the process you want to stop et-voila. If you'll make a command line application you'll need to keep its instance running to keep the process suspended (or it'll be terminated). See the Remarks section on MSDN for details.

void suspend(DWORD processId)
{
    DebugActiveProcess(processId);
}

From Command Line

As I said Windows command line has not any utility to do that but you can invoke a Windows API function from PowerShell. First install Invoke-WindowsApi script then you can write this:

Invoke-WindowsApi "kernel32" ([bool]) "DebugActiveProcess" @([int]) @(process_id_here)

Of course if you need it often you can make an alias for that.

How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles?

i used hasAnyRole('ROLE_ADMIN','ROLE_USER') but i was getting bean creation below error

Error creating bean with name     'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0': Cannot create inner bean '(inner bean)' of type [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] while setting bean property 'securityMetadataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#2': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Expected a single expression attribute for [/user/*]

then i tried

access="hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')" and it's working fine for me.

as one of my user is admin as well as user.

for this you need to add use-expressions="true" auto-config="true" followed by http tag

<http use-expressions="true" auto-config="true" >.....</http>

How to find Oracle Service Name

TO FIND ORACLE_SID USE $. oraenv

DateTime2 vs DateTime in SQL Server

Select ValidUntil + 1
from Documents

The above SQL won't work with a DateTime2 field. It returns and error "Operand type clash: datetime2 is incompatible with int"

Adding 1 to get the next day is something developers have been doing with dates for years. Now Microsoft have a super new datetime2 field that cannot handle this simple functionality.

"Let's use this new type that is worse than the old one", I don't think so!

In OS X Lion, LANG is not set to UTF-8, how to fix it?

This is a headbreaker for a long time. I see now it's OSX.. i change it system-wide and it works perfect

When i add this the LANG in Centos6 and Fedora is also my preferred LANG. You can also "uncheck" export or set locale in terminal settings (OSX) /etc/profile

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

I got the same error and when I search here on Stack Overflow and out I've combined what I found and it works for me. Just follow this:

  1. Go to the icon of oracle right click on it choose : open file location.
  2. Choose the get started right click on it choose properties on the URL add what is between brackets to the end of the URL (:1:405838811476023). Or just copy this URL: http://127.0.0.1:8080/apex/f?p=4950:1:1486912860795003 and put it there instead of the old one
  3. Click on apply.
  4. Go back to the first step double clicks and it will work.

How to convert an array to a string in PHP?

I would turn it into a json object, with the added benefit of keeping the keys if you are using an associative array:

 $stringRepresentation= json_encode($arr);

How does C compute sin() and other math functions?

As many people pointed out, it is implementation dependent. But as far as I understand your question, you were interested in a real software implemetnation of math functions, but just didn't manage to find one. If this is the case then here you are:

  • Download glibc source code from http://ftp.gnu.org/gnu/glibc/
  • Look at file dosincos.c located in unpacked glibc root\sysdeps\ieee754\dbl-64 folder
  • Similarly you can find implementations of the rest of the math library, just look for the file with appropriate name

You may also have a look at the files with the .tbl extension, their contents is nothing more than huge tables of precomputed values of different functions in a binary form. That is why the implementation is so fast: instead of computing all the coefficients of whatever series they use they just do a quick lookup, which is much faster. BTW, they do use Tailor series to calculate sine and cosine.

I hope this helps.

How do I use spaces in the Command Prompt?

You should try using quotes.

cmd /C "C:\Program Files (x86)\WinRar\Rar.exe" a "D:\Hello 2\File.rar" "D:\Hello 2\*.*"

Difference between setUp() and setUpBeforeClass()

From the Javadoc:

Sometimes several tests need to share computationally expensive setup (like logging into a database). While this can compromise the independence of tests, sometimes it is a necessary optimization. Annotating a public static void no-arg method with @BeforeClass causes it to be run once before any of the test methods in the class. The @BeforeClass methods of superclasses will be run before those the current class.

Using Mockito to stub and execute methods for testing

SHORT ANSWER

How to do in your case:

int argument = 5; // example with int but could be another type
Mockito.when(mockMyAgent.otherMethod(Mockito.anyInt()).thenReturn(requiredReturnArg(argument));

LONG ANSWER

Actually what you want to do is possible, at least in Java 8. Maybe you didn't get this answer by other people because I am using Java 8 that allows that and this question is before release of Java 8 (that allows to pass functions, not only values to other functions).

Let's simulate a call to a DataBase query. This query returns all the rows of HotelTable that have FreeRoms = X and StarNumber = Y. What I expect during testing, is that this query will give back a List of different hotel: every returned hotel has the same value X and Y, while the other values and I will decide them according to my needs. The following example is simple but of course you can make it more complex.

So I create a function that will give back different results but all of them have FreeRoms = X and StarNumber = Y.

static List<Hotel> simulateQueryOnHotels(int availableRoomNumber, int starNumber) {
    ArrayList<Hotel> HotelArrayList = new ArrayList<>();
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Rome, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Krakow, 7, 15));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Madrid, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Athens, 4, 1));

    return HotelArrayList;
}

Maybe Spy is better (please try), but I did this on a mocked class. Here how I do (notice the anyInt() values):

//somewhere at the beginning of your file with tests...
@Mock
private DatabaseManager mockedDatabaseManager;

//in the same file, somewhere in a test...
int availableRoomNumber = 3;
int starNumber = 4;
// in this way, the mocked queryOnHotels will return a different result according to the passed parameters
when(mockedDatabaseManager.queryOnHotels(anyInt(), anyInt())).thenReturn(simulateQueryOnHotels(availableRoomNumber, starNumber));

Targeting both 32bit and 64bit with Visual Studio in same solution/project

If you use Custom Actions written in .NET as part of your MSI installer then you have another problem.

The 'shim' that runs these custom actions is always 32bit then your custom action will run 32bit as well, despite what target you specify.

More info & some ninja moves to get around (basically change the MSI to use the 64 bit version of this shim)

Building an MSI in Visual Studio 2005/2008 to work on a SharePoint 64

64-bit Managed Custom Actions with Visual Studio