Programs & Examples On #Visual studio 2005

Visual Studio 2005 is a version of Microsoft's Visual Studio integrated development environment product line for .NET-based and C++ development. Do not use this tag unless you have a specific question about Visual Studio -- not just a coding issue.

What is the difference between Release and Debug modes in Visual Studio?

Debug and Release are just labels for different solution configurations. You can add others if you want. A project I once worked on had one called "Debug Internal" which was used to turn on the in-house editing features of the application. You can see this if you go to Configuration Manager... (it's on the Build menu). You can find more information on MSDN Library under Configuration Manager Dialog Box.

Each solution configuration then consists of a bunch of project configurations. Again, these are just labels, this time for a collection of settings for your project. For example, our C++ library projects have project configurations called "Debug", "Debug_Unicode", "Debug_MT", etc.

The available settings depend on what type of project you're building. For a .NET project, it's a fairly small set: #defines and a few other things. For a C++ project, you get a much bigger variety of things to tweak.

In general, though, you'll use "Debug" when you want your project to be built with the optimiser turned off, and when you want full debugging/symbol information included in your build (in the .PDB file, usually). You'll use "Release" when you want the optimiser turned on, and when you don't want full debugging information included.

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

I know it's a "very long time" since this question was first asked. Just in case, if it helps someone,

Adding relationships is well supported by MS via SQL Server Compact Tool Box (https://sqlcetoolbox.codeplex.com/). Just install it, then you would get the option to connect to the Compact Database using the Server Explorer Window. Right click on the primary table , select "Table Properties". You should have the following window, which contains "Add Relations" tab allowing you to add relations.

Add Relations Tab - SQL Server Compact Tool Box

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

I had the same error message. For me it was happening because I was trying to run the installer from the DVD rather than running the installer from Add/Remove programs.

How do I print to the debug output window in a Win32 app?

If the project is a GUI project, no console will appear. In order to change the project into a console one you need to go to the project properties panel and set:

  • In "linker->System->SubSystem" the value "Console (/SUBSYSTEM:CONSOLE)"
  • In "C/C++->Preprocessor->Preprocessor Definitions" add the "_CONSOLE" define

This solution works only if you had the classic "int main()" entry point.

But if you are like in my case (an openGL project), you don't need to edit the properties, as this works better:

AllocConsole();
freopen("CONIN$", "r",stdin);
freopen("CONOUT$", "w",stdout);
freopen("CONOUT$", "w",stderr);

printf and cout will work as usual.

If you call AllocConsole before the creation of a window, the console will appear behind the window, if you call it after, it will appear ahead.

Update

freopen is deprecated and may be unsafe. Use freopen_s instead:

FILE* fp;

AllocConsole();
freopen_s(&fp, "CONIN$", "r", stdin);
freopen_s(&fp, "CONOUT$", "w", stdout);
freopen_s(&fp, "CONOUT$", "w", stderr);

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

For anyone coming to this latterly, I was having this problem over a Windows network, and offer an additional thing to check:

Python script connecting would work from commandline on my (linux) machine, but some users had problems connecting - that it worked from CLI suggested the DSN and credentials were right. The issue for us was that the group security policy required the ODBC credentials to be set on every machine. Once we added that (for some reason, the user had three of the four ODBC credentials they needed for our various systems), they were able to connect.

You can of course do that at group level, but as it was a simple omission on the part of one machine, I did it in Control Panel > ODBC Drivers > New

How to generate List<String> from SQL query?

I think this is what you're looking for.

List<String> columnData = new List<String>();

using(SqlConnection connection = new SqlConnection("conn_string"))
{
    connection.Open();
    string query = "SELECT Column1 FROM Table1";
    using(SqlCommand command = new SqlCommand(query, connection))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                columnData.Add(reader.GetString(0));
            }         
        }
    }
}

Not tested, but this should work fine.

The name 'controlname' does not exist in the current context

I get the same error after i made changes with my data context. But i encounter something i am unfamiliar with. I get used to publish my files manually. Normally when i do that there is no App_Code folder appears in publishing folder. Bu i started to use VS 12 publishing which directly publishes with your assistance to the web server. And then i get the error about being precompiled application. Then i delete app_code folder it worked. But then it gave me the Data Context error that you are getting. So i just deleted all the files and run the publish again with no file restrictions (every folder & file will be published) then it worked like a charm.

How do I programmatically get the GUID of an application in .NET 2.0

Another way is to use Marshal.GetTypeLibGuidForAssembly.

According to MSDN:

When assemblies are exported to type libraries, the type library is assigned a LIBID. You can set the LIBID explicitly by applying the System.Runtime.InteropServices.GuidAttribute at the assembly level, or it can be generated automatically. The Tlbimp.exe (Type Library Importer) tool calculates a LIBID value based on the identity of the assembly. GetTypeLibGuid returns the LIBID that is associated with the GuidAttribute, if the attribute is applied. Otherwise, GetTypeLibGuidForAssembly returns the calculated value. Alternatively, you can use the GetTypeLibGuid method to extract the actual LIBID from an existing type library.

Unable to copy file - access to the path is denied

I also had this issue. Here's how is resolved this

  • Exclude bin folder from project.
  • Close visual studio.
  • Disk cleanup of C drive.
  • Re-open project in visual studio.
  • And then rebuild solution.
  • Run project.

This process is works for me.

How to fix "Referenced assembly does not have a strong name" error?

To avoid this error you could either:

  • Load the assembly dynamically, or
  • Sign the third-party assembly.

You will find instructions on signing third-party assemblies in .NET-fu: Signing an Unsigned Assembly (Without Delay Signing).

Signing Third-Party Assemblies

The basic principle to sign a thirp-party is to

  1. Disassemble the assembly using ildasm.exe and save the intermediate language (IL):

    ildasm /all /out=thirdPartyLib.il thirdPartyLib.dll 
    
  2. Rebuild and sign the assembly:

    ilasm /dll /key=myKey.snk thirdPartyLib.il
    

Fixing Additional References

The above steps work fine unless your third-party assembly (A.dll) references another library (B.dll) which also has to be signed. You can disassemble, rebuild and sign both A.dll and B.dll using the commands above, but at runtime, loading of B.dll will fail because A.dll was originally built with a reference to the unsigned version of B.dll.

The fix to this issue is to patch the IL file generated in step 1 above. You will need to add the public key token of B.dll to the reference. You get this token by calling

sn -Tp B.dll 

which will give you the following output:

Microsoft (R) .NET Framework Strong Name Utility  Version 4.0.30319.33440
Copyright (c) Microsoft Corporation.  All rights reserved.

Public key (hash algorithm: sha1):
002400000480000094000000060200000024000052534131000400000100010093d86f6656eed3
b62780466e6ba30fd15d69a3918e4bbd75d3e9ca8baa5641955c86251ce1e5a83857c7f49288eb
4a0093b20aa9c7faae5184770108d9515905ddd82222514921fa81fff2ea565ae0e98cf66d3758
cb8b22c8efd729821518a76427b7ca1c979caa2d78404da3d44592badc194d05bfdd29b9b8120c
78effe92

Public key token is a8a7ed7203d87bc9

The last line contains the public key token. You then have to search the IL of A.dll for the reference to B.dll and add the token as follows:

.assembly extern /*23000003*/ MyAssemblyName
{
  .publickeytoken = (A8 A7 ED 72 03 D8 7B C9 )                         
  .ver 10:0:0:0
}

How to debug a referenced dll (having pdb)

I had the *.pdb files in the same folder and used the options from Arindam, but it still didn't work. Turns out I needed to enable Enable native code debugging which can be found under Project properties > Debug.

Cannot find Dumpbin.exe

In Visual Studio Professional 2017 Version 15.9.13:

  • First, either:

    • launch the "Visual Studio Installer" from the start menu, select your Visual Studio product, and click "Modify",

    or

    • from within Visual Studio go to "Tools" -> "Get Tools and Features..."
  • Then, wait for it while it is "getting things ready..." and being "almost there..."

  • Switch to the "Individual components" tab

  • Scroll down to the "Compilers, build tools, and runtimes" section

  • Check "VC++ 2017 version 15.9 v14.16 latest v141 tools"

like this:

enter image description here

After doing this, you will be blessed with not just one, but a whopping four instances of DUMPBIN:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx64\x64\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx64\x86\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx86\x64\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx86\x86\dumpbin.exe

Rename a file using Java

Files.move(file.toPath(), fileNew.toPath()); 

works, but only when you close (or autoclose) ALL used resources (InputStream, FileOutputStream etc.) I think the same situation with file.renameTo or FileUtils.moveFile.

Why I get 'list' object has no attribute 'items'?

If you don't care about the type of the numbers you can simply use:

qs[0].values()

AttributeError: Can only use .dt accessor with datetimelike values

First you need to define the format of date column.

df['Date'] = pd.to_datetime(df.Date, format='%Y-%m-%d %H:%M:%S')

For your case base format can be set to;

df['Date'] = pd.to_datetime(df.Date, format='%Y-%m-%d')

After that you can set/change your desired output as follows;

df['Date'] = df['Date'].dt.strftime('%Y-%m-%d')

Linux find file names with given string recursively

A correct answer has already been supplied, but for you to learn how to help yourself I thought I'd throw in something helpful in a different way; if you can sum up what you're trying to achieve in one word, there's a mighty fine help feature on Linux.

man -k <your search term>

What that does is to list all commands that have your search term in the short description. There's usually a pretty good chance that you will find what you're after. ;)

That output can sometimes be somewhat overwhelming, and I'd recommend narrowing it down to the executables, rather than all available man-pages, like so:

man -k find | egrep '\(1\)'

or, if you also want to look for commands that require higher privilege levels, like this:

man -k find | egrep '\([18]\)'

How to convert int to Integer

As mentioned, one way is to use

new Integer(my_int_value)

But you should not call the constructor for wrapper classes directly

So, modify the code accordingly:

mBitmapCache.put(Integer.valueOf(R.drawable.bg1),object);

Best way to define private methods for a class in Objective-C

One more thing that I haven't seen mentioned here - Xcode supports .h files with "_private" in the name. Let's say you have a class MyClass - you have MyClass.m and MyClass.h and now you can also have MyClass_private.h. Xcode will recognize this and include it in the list of "Counterparts" in the Assistant Editor.

//MyClass.m
#import "MyClass.h"
#import "MyClass_private.h"

Good Linux (Ubuntu) SVN client

To begin with, I will try not to sound flamish here ;)

Sigh.. Why don't people get that file explorer integrated clients is the way to go? It is so much more efficient than opening terminals and typing. Simple math, ~two mouse clicks versus ~10+ key strokes. Though, I must point out that I love command line since I do lot's of administrative work and prefer to automate things as quickly and easy as possible.

Having been spoiled by TortoiseSVN on windows I was amazed by the lack of a tortoisesvn-like integrated client when I moved to ubuntu. For pure programmers an IDE integrated client might be enough but for general purpose use and for say graphics artists or other random office people, the client has to be integrated into the standard file explorer, else most people will not use it, at all, ever.

Some thought's on some clients:

kdesvn, The client I like the best this far, though there is one huge annoyance compared to TortoiseSVN - you have to enter the special subversion layout mode to get overlays indicating file status. Thus I would not call kdesvn integrated.

NautilusSVN, looks promising but as of 0.12 release it has performance problems with big repositories. I work with repositories where working copies can contain ~50 000 files at times, which TortoiseSVN handles but NautilusSVN does not. So I hope NautilusSVN will get a new optimized release soon.

RapidSVN is not integrated, but I gave it a try. It behaved quite weird and crashed a couple of times. It got uninstalled after ~20 minutes..

I really hope the NautilusSVN project will make a new performance optimized release soon.

NaughtySVN seems like it could shape up to be quite nice, but as of now it lacks icon overlays and has not had a release for two years... so I would say NautilusSVN is our only hope.

TypeError: unsupported operand type(s) for /: 'str' and 'str'

I would have written:

percent = 100
while True:
     try:
        pyc = int(input('enter pyc :'))
        tpy = int(input('enter tpy:'))
        percent = (pyc / tpy) * percent
        break
     except ZeroDivisionError as detail:
        print 'Handling run-time error:', detail

Download file inside WebView

Try this out. After going through a lot of posts and forums, I found this.

mWebView.setDownloadListener(new DownloadListener() {       

    @Override
    public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype,
                                    long contentLength) {
            DownloadManager.Request request = new DownloadManager.Request(
                    Uri.parse(url));

            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Name of your downloadble file goes here, example: Mathematics II ");
            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            dm.enqueue(request);
            Toast.makeText(getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded
                    Toast.LENGTH_LONG).show();

        }
    });

Do not forget to give this permission! This is very important! Add this in your Manifest file(The AndroidManifest.xml file)

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />        <!-- for your file, say a pdf to work -->

Hope this helps. Cheers :)

What's the proper value for a checked attribute of an HTML checkbox?

It's pretty crazy town that the only way to make checked false is to omit any values. With Angular 1.x, you can do this:

  <input type="radio" ng-checked="false">

which is a lot more sane, if you need to make it unchecked.

java.lang.UnsupportedClassVersionError

Another option is to delete all the classes and rebuild. Having build file is an ideal solution to control whole process like compilation, packaging and deployment. You can also specify source/target versions

What properties does @Column columnDefinition make redundant?

columnDefinition will override the sql DDL generated by hibernate for this particular column, it is non portable and depends on what database you are using. You can use it to specify nullable, length, precision, scale... ect.

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

There can be many possible reasons for this failure.

Some are listed above. I faced the same issue, it is very hard to find the root cause of the failure.

I will recommend you to check the session timeout for shh from ssh_config file. Try to increase the session timeout and see if it fails again

Convert number of minutes into hours & minutes using PHP

@Martin Bean's answer is perfectly correct but in my point of view it needs some refactoring to fit what a regular user would expect from a website (web system).
I think that when minutes are below 10 a leading zero must be added.
ex: 10:01, not 10:1

I changed code to accept $time = 0 since 0:00 is better than 24:00.

One more thing - there is no case when $time is bigger than 1439 - which is 23:59 and next value is simply 0:00.

function convertToHoursMins($time, $format = '%d:%s') {
    settype($time, 'integer');
    if ($time < 0 || $time >= 1440) {
        return;
    }
    $hours = floor($time/60);
    $minutes = $time%60;
    if ($minutes < 10) {
        $minutes = '0' . $minutes;
    }
    return sprintf($format, $hours, $minutes);
}

Append date to filename in linux

a bit more convoluted solution that fully matches your spec

echo `expr $FILENAME : '\(.*\)\.[^.]*'`_`date +%d-%m-%y`.`expr $FILENAME : '.*\.\([^.]*\)'`

where first 'expr' extracts file name without extension, second 'expr' extracts extension

Test for multiple cases in a switch, like an OR (||)

Forget switch and break, lets play with if. And instead of asserting

if(pageid === "listing-page" || pageid === "home-page")

lets create several arrays with cases and check it with Array.prototype.includes()

var caseA = ["listing-page", "home-page"];
var caseB = ["details-page", "case04", "case05"];

if(caseA.includes(pageid)) {
    alert("hello");
}
else if (caseB.includes(pageid)) {
    alert("goodbye");
}
else {
    alert("there is no else case");
}

List of All Locales and Their Short Codes?

Language List

List of all languages with names and ISO 639-1 codes in all languages and all data formats.

Formats Available

  • Text
  • JSON
  • YAML
  • XML
  • HTML
  • CSV
  • SQL (MySQL, PostgreSQL, SQLite)
  • PHP

https://github.com/umpirsky/language-list

Which language uses .pde extension?

This code is from Processing.org an open source Java based IDE. You can find it Processing.org. The Arduino IDE also uses this extension, although they run on a hardware board.

EDIT - And yes it is C syntax, used mostly for art or live media presentations.

Find the most popular element in int[] array

public class MostFrequentIntegerInAnArray {

    public static void main(String[] args) {
        int[] items = new int[]{2,1,43,1,6,73,5,4,65,1,3,6,1,1};
        System.out.println("Most common item = "+getMostFrequentInt(items));
    }

    //Time Complexity = O(N)
    //Space Complexity = O(N)
    public static int getMostFrequentInt(int[] items){
        Map<Integer, Integer> itemsMap = new HashMap<Integer, Integer>(items.length);
        for(int item : items){
            if(!itemsMap.containsKey(item))
                itemsMap.put(item, 1);
            else
                itemsMap.put(item, itemsMap.get(item)+1);
        }

        int maxCount = Integer.MIN_VALUE;
        for(Entry<Integer, Integer> entry : itemsMap.entrySet()){
            if(entry.getValue() > maxCount)
                maxCount = entry.getValue();
        }
        return maxCount;
    }
}

Cannot implicitly convert type 'int?' to 'int'.

Check the declaration of your variable. It must be like that

public Nullable<int> x {get; set;}
public Nullable<int> y {get; set;}
public Nullable<int> z {get { return x*y;} }

I hope it is useful for you

Virtual/pure virtual explained

I'd like to comment on Wikipedia's definition of virtual, as repeated by several here. [At the time this answer was written,] Wikipedia defined a virtual method as one that can be overridden in subclasses. [Fortunately, Wikipedia has been edited since, and it now explains this correctly.] That is incorrect: any method, not just virtual ones, can be overridden in subclasses. What virtual does is to give you polymorphism, that is, the ability to select at run-time the most-derived override of a method.

Consider the following code:

#include <iostream>
using namespace std;

class Base {
public:
    void NonVirtual() {
        cout << "Base NonVirtual called.\n";
    }
    virtual void Virtual() {
        cout << "Base Virtual called.\n";
    }
};
class Derived : public Base {
public:
    void NonVirtual() {
        cout << "Derived NonVirtual called.\n";
    }
    void Virtual() {
        cout << "Derived Virtual called.\n";
    }
};

int main() {
    Base* bBase = new Base();
    Base* bDerived = new Derived();

    bBase->NonVirtual();
    bBase->Virtual();
    bDerived->NonVirtual();
    bDerived->Virtual();
}

What is the output of this program?

Base NonVirtual called.
Base Virtual called.
Base NonVirtual called.
Derived Virtual called.

Derived overrides every method of Base: not just the virtual one, but also the non-virtual.

We see that when you have a Base-pointer-to-Derived (bDerived), calling NonVirtual calls the Base class implementation. This is resolved at compile-time: the compiler sees that bDerived is a Base*, that NonVirtual is not virtual, so it does the resolution on class Base.

However, calling Virtual calls the Derived class implementation. Because of the keyword virtual, the selection of the method happens at run-time, not compile-time. What happens here at compile-time is that the compiler sees that this is a Base*, and that it's calling a virtual method, so it insert a call to the vtable instead of class Base. This vtable is instantiated at run-time, hence the run-time resolution to the most-derived override.

I hope this wasn't too confusing. In short, any method can be overridden, but only virtual methods give you polymorphism, that is, run-time selection of the most derived override. In practice, however, overriding a non-virtual method is considered bad practice and rarely used, so many people (including whoever wrote that Wikipedia article) think that only virtual methods can be overridden.

Select multiple columns using Entity Framework

var test_obj = from d in repository.DbPricing
join d1 in repository.DbOfficeProducts on d.OfficeProductId equals d1.Id
join d2 in repository.DbOfficeProductDetails on d1.ProductDetailsId equals d2.Id
    select new
    {
    PricingId = d.Id,
    LetterColor = d2.LetterColor,
    LetterPaperWeight = d2.LetterPaperWeight
    };


http://www.cybertechquestions.com/select-across-multiple-tables-in-entity-framework-resulting-in-a-generic-iqueryable_222801.html

ConcurrentHashMap vs Synchronized HashMap

We can achieve thread safety by using both ConcurrentHashMap and synchronisedHashmap. But there is a lot of difference if you look at their architecture.

  1. synchronisedHashmap

It will maintain the lock at the object level. So if you want to perform any operation like put/get then you have to acquire the lock first. At the same time, other threads are not allowed to perform any operation. So at a time, only one thread can operate on this. So the waiting time will increase here. We can say that performance is relatively low when you are comparing with ConcurrentHashMap.

  1. ConcurrentHashMap

It will maintain the lock at the segment level. It has 16 segments and maintains the concurrency level as 16 by default. So at a time, 16 threads can be able to operate on ConcurrentHashMap. Moreover, read operation doesn't require a lock. So any number of threads can perform a get operation on it.

If thread1 wants to perform put operation in segment 2 and thread2 wants to perform put operation on segment 4 then it is allowed here. Means, 16 threads can perform update(put/delete) operation on ConcurrentHashMap at a time.

So that the waiting time will be less here. Hence the performance is relatively better than synchronisedHashmap.

How to run travis-ci locally

This process allows you to completely reproduce any Travis build job on your computer. Also, you can interrupt the process at any time and debug. Below is an example where I perfectly reproduce the results of job #191.1 on php-school/cli-menu .

Prerequisites

  • You have public repo on GitHub
  • You ran at least one build on Travis
  • You have Docker set up on your computer

Set up the build environment

Reference: https://docs.travis-ci.com/user/common-build-problems/

  1. Make up your own temporary build ID

    BUILDID="build-$RANDOM"
    
  2. View the build log, open the show more button for WORKER INFORMATION and find the INSTANCE line, paste it in here and run (replace the tag after the colon with the newest available one):

    INSTANCE="travisci/ci-garnet:packer-1512502276-986baf0"
    
  3. Run the headless server

    docker run --name $BUILDID -dit $INSTANCE /sbin/init
    
  4. Run the attached client

    docker exec -it $BUILDID bash -l
    

Run the job

Now you are now inside your Travis environment. Run su - travis to begin.

This step is well defined but it is more tedious and manual. You will find every command that Travis runs in the environment. To do this, look for for everything in the right column which has a tag like 0.03s.

On the left side you will see the actual commands. Run those commands, in order.

Result

Now is a good time to run the history command. You can restart the process and replay those commands to run the same test against an updated code base.

  • If your repo is private: ssh-keygen -t rsa -b 4096 -C "YOUR EMAIL REGISTERED IN GITHUB" then cat ~/.ssh/id_rsa.pub and click here to add a key
  • FYI: you can git pull from inside docker to load commits from your dev box before you push them to GitHub
  • If you want to change the commands Travis runs then it is YOUR responsibility to figure out how that translates back into a working .travis.yml.
  • I don't know how to clean up the Docker environment, it looks complicated, maybe this leaks memory

Auto submit form on page load

Try this On window load submit your form.

window.onload = function(){
  document.forms['member_signup'].submit();
}

How do I find an array item with TypeScript? (a modern, easier way)

For some projects it's easier to set your target to es6 in your tsconfig.json.

{
  "compilerOptions": {
    "target": "es6",
    ...

How to use Morgan logger?

Seems you too are confused with the same thing as I was, the reason I stumbled upon this question. I think we associate logging with manual logging as we would do in Java with log4j (if you know java) where we instantiate a Logger and say log 'this'.

Then I dug in morgan code, turns out it is not that type of a logger, it is for automated logging of requests, responses and related data. When added as a middleware to an express/connect app, by default it should log statements to stdout showing details of: remote ip, request method, http version, response status, user agent etc. It allows you to modify the log using tokens or add color to them by defining 'dev' or even logging out to an output stream, like a file.

For the purpose we thought we can use it, as in this case, we still have to use:

console.log(..);

Or if you want to make the output pretty for objects:

var util = require("util");
console.log(util.inspect(..));

'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)

I faced the same error today, using React with Typescript and a back-end using Java Spring boot, if you have a hand on your back-end you can simply add a configuration file for the CORS.

For the below example I set allowed origin to * to allow all but you can be more specific and only set url like http://localhost:3000.

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class AppCorsConfiguration {
    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}

Loop through childNodes

If you do a lot of this sort of thing then it might be worth defining the function for yourself.

if (typeof NodeList.prototype.forEach == "undefined"){
    NodeList.prototype.forEach = function (cb){
        for (var i=0; i < this.length; i++) {
            var node = this[i];
            cb( node, i );
        }
    };
}

Volatile vs. Interlocked vs. lock

I would like to add to mentioned in the other answers the difference between volatile, Interlocked, and lock:

The volatile keyword can be applied to fields of these types:

  • Reference types.
  • Pointer types (in an unsafe context). Note that although the pointer itself can be volatile, the object that it points to cannot. In other words, you cannot declare a "pointer" to be "volatile".
  • Simple types such as sbyte, byte, short, ushort, int, uint, char, float, and bool.
  • An enum type with one of the following base types: byte, sbyte, short, ushort, int, or uint.
  • Generic type parameters known to be reference types.
  • IntPtr and UIntPtr.

Other types, including double and long, cannot be marked "volatile" because reads and writes to fields of those types cannot be guaranteed to be atomic. To protect multi-threaded access to those types of fields, use the Interlocked class members or protect access using the lock statement.

"Too many characters in character literal error"

This is because, in C#, single quotes ('') denote (or encapsulate) a single character, whereas double quotes ("") are used for a string of characters. For example:

var myChar = '=';

var myString = "==";

Convert Data URI to File then append to FormData

BlobBuilder and ArrayBuffer are now deprecated, here is the top comment's code updated with Blob constructor:

function dataURItoBlob(dataURI) {
    var binary = atob(dataURI.split(',')[1]);
    var array = [];
    for(var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], {type: 'image/jpeg'});
}

How to increase Bootstrap Modal Width?

The easiest way can be inline style on modal-dialog div :

<div class="modal" id="myModal">
   <div class="modal-dialog" style="width:1250px;">
      <div class="modal-content">
            ...

        </div>
     </div>
 </div>

Unable to find valid certification path to requested target - error even after cert imported

I had the same problem with sbt.
It tried to fetch dependencies from repo1.maven.org over ssl
but said it was "unable to find valid certification path to requested target url".
so I followed this post and still failed to verify a connection.
So I read about it and found that the root cert is not enough, as was suggested by the post,so -
the thing that worked for me was importing the intermediate CA certificates into the keystore.
I actually added all the certificates in the chain and it worked like a charm.

CSS: Set Div height to 100% - Pixels

Now with css3 you could try to use calc()

.main{
  height: calc(100% - 111px);
}

have a look at this answer: Div width 100% minus fixed amount of pixels

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

I hope that you will find helpfull the following trick.

You can bind both the events

combobox.SelectionChanged += OnSelectionChanged;
combobox.DropDownOpened += OnDropDownOpened;

And force selected item to null inside the OnDropDownOpened

private void OnDropDownOpened(object sender, EventArgs e)
{
    combobox.SelectedItem = null;
}

And do what you need with the item inside the OnSelectionChanged. The OnSelectionChanged will be raised every time you will open the combobox, but you can check if SelectedItem is null inside the method and skip the command

private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (combobox.SelectedItem != null)
        {
           //Do something with the selected item
        }
    }

android.app.Application cannot be cast to android.app.Activity

You are passing the Application Context not the Activity Context with

getApplicationContext();

Wherever you are passing it pass this or ActivityName.this instead.

Since you are trying to cast the Context you pass (Application not Activity as you thought) to an Activity with

(Activity)

you get this exception because you can't cast the Application to Activity since Application is not a sub-class of Activity.

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

To get the value of my drop down box on page load, I use

document.addEventListener('DOMContentLoaded',fnName);

Hope this helps some one.

Get value of Span Text

The accepted answer is close... but no cigar!

Use textContent instead of innerHTML if you strictly want a string to be returned to you.

innerHTML can have the side effect of giving you a node element if there's other dom elements in there. textContent will guard against this possibility.

Android: How to change CheckBox size?

Here is a better solution which does not clip and/or blur the drawable, but only works if the checkbox doesn't have text itself (but you can still have text, it's just more complicated, see at the end).

<CheckBox
    android:id="@+id/item_switch"
    android:layout_width="160dp"    <!-- This is the size you want -->
    android:layout_height="160dp"
    android:button="@null"
    android:background="?android:attr/listChoiceIndicatorMultiple"/>

The result:

What the previous solution with scaleX and scaleY looked like:

You can have a text checkbox by adding a TextView beside it and adding a click listener on the parent layout, then triggering the checkbox programmatically.

Difference Between One-to-Many, Many-to-One and Many-to-Many?

Looks like everyone is answering One-to-many vs. Many-to-many:

The difference between One-to-many, Many-to-one and Many-to-Many is:

One-to-many vs Many-to-one is a matter of perspective. Unidirectional vs Bidirectional will not affect the mapping but will make difference on how you can access your data.

  • In Many-to-one the many side will keep reference of the one side. A good example is "A State has Cities". In this case State is the one side and City is the many side. There will be a column state_id in the table cities.

In unidirectional, Person class will have List<Skill> skills but Skill will not have Person person. In bidirectional, both properties are added and it allows you to access a Person given a skill( i.e. skill.person).

  • In One-to-Many the one side will be our point of reference. For example, "A User has Addresses". In this case we might have three columns address_1_id, address_2_id and address_3_id or a look up table with multi column unique constraint on user_id on address_id.

In unidirectional, a User will have Address address. Bidirectional will have an additional List<User> users in the Address class.

  • In Many-to-Many members of each party can hold reference to arbitrary number of members of the other party. To achieve this a look up table is used. Example for this is the relationship between doctors and patients. A doctor can have many patients and vice versa.

C read file line by line

Implement method to read, and get content from a file (input1.txt)

#include <stdio.h>
#include <stdlib.h>

void testGetFile() {
    // open file
    FILE *fp = fopen("input1.txt", "r");
    size_t len = 255;
    // need malloc memory for line, if not, segmentation fault error will occurred.
    char *line = malloc(sizeof(char) * len);
    // check if file exist (and you can open it) or not
    if (fp == NULL) {
        printf("can open file input1.txt!");
        return;
    }
    while(fgets(line, len, fp) != NULL) {
        printf("%s\n", line);
    }
    free(line);
}

Hope this help. Happy coding!

how can select from drop down menu and call javascript function

<select name="aa" onchange="report(this.value)"> 
  <option value="">Please select</option>
  <option value="daily">daily</option>
  <option value="monthly">monthly</option>
</select>

using

function report(period) {
  if (period=="") return; // please select - possibly you want something else here

  const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
  loadXMLDoc(report,'responseTag');
  document.getElementById('responseTag').style.visibility='visible';
  document.getElementById('list_report').style.visibility='hidden';
  document.getElementById('formTag').style.visibility='hidden'; 
} 

Unobtrusive version:

<select id="aa" name="aa"> 
  <option value="">Please select</option>
  <option value="daily">daily</option>
  <option value="monthly">monthly</option>
</select>

using

window.addEventListener("load",function() {
  document.getElementById("aa").addEventListener("change",function() {
    const period = this.value;
    if (period=="") return; // please select - possibly you want something else here

    const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
    loadXMLDoc(report,'responseTag');
    document.getElementById('responseTag').style.visibility='visible';
    document.getElementById('list_report').style.visibility='hidden';
    document.getElementById('formTag').style.visibility='hidden'; 
  }); 
});

jQuery version - same select with ID

$(function() {
  $("#aa").on("change",function() {
    const period = this.value;
    if (period=="") return; // please select - possibly you want something else here

    var report = "script/"+((period == "daily")?"d":"m")+"_report.php";
    loadXMLDoc(report,'responseTag');
    $('#responseTag').show();
    $('#list_report').hide();
    $('#formTag').hide(); 
  }); 
});

Expression must be a modifiable lvalue

You test k = M instead of k == M.
Maybe it is what you want to do, in this case, write if (match == 0 && (k = M))

Making a PowerShell POST request if a body param starts with '@'

Use Invoke-RestMethod to consume REST-APIs. Save the JSON to a string and use that as the body, ex:

$JSON = @'
{"@type":"login",
 "username":"[email protected]",
 "password":"yyy"
}
'@

$response = Invoke-RestMethod -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"

If you use Powershell 3, I know there have been some issues with Invoke-RestMethod, but you should be able to use Invoke-WebRequest as a replacement:

$response = Invoke-WebRequest -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"

If you don't want to write your own JSON every time, you can use a hashtable and use PowerShell to convert it to JSON before posting it. Ex.

$JSON = @{
    "@type" = "login"
    "username" = "[email protected]"
    "password" = "yyy"
} | ConvertTo-Json

Mocking python function based on input arguments

As indicated at Python Mock object with method called multiple times

A solution is to write my own side_effect

def my_side_effect(*args, **kwargs):
    if args[0] == 42:
        return "Called with 42"
    elif args[0] == 43:
        return "Called with 43"
    elif kwargs['foo'] == 7:
        return "Foo is seven"

mockobj.mockmethod.side_effect = my_side_effect

That does the trick

PHP + MySQL transactions examples

One more procedural style example with mysqli_multi_query, assumes $query is filled with semicolon-separated statements.

mysqli_begin_transaction ($link);

for (mysqli_multi_query ($link, $query);
    mysqli_more_results ($link);
    mysqli_next_result ($link) );

! mysqli_errno ($link) ?
    mysqli_commit ($link) : mysqli_rollback ($link);

how to iterate through dictionary in a dictionary in django template?

This answer didn't work for me, but I found the answer myself. No one, however, has posted my question. I'm too lazy to ask it and then answer it, so will just put it here.

This is for the following query:

data = Leaderboard.objects.filter(id=custom_user.id).values(
    'value1',
    'value2',
    'value3')

In template:

{% for dictionary in data %}
  {% for key, value in dictionary.items %}
    <p>{{ key }} : {{ value }}</p>
  {% endfor %}
{% endfor %}

How to generate a QR Code for an Android application?

zxing does not (only) provide a web API; really, that is Google providing the API, from source code that was later open-sourced in the project.

As Rob says here you can use the Java source code for the QR code encoder to create a raw barcode and then render it as a Bitmap.

I can offer an easier way still. You can call Barcode Scanner by Intent to encode a barcode. You need just a few lines of code, and two classes from the project, under android-integration. The main one is IntentIntegrator. Just call shareText().

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

int total = 0;
protected void gvEmp_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Amount"));
}
if(e.Row.RowType==DataControlRowType.Footer)
{
Label lblamount = (Label)e.Row.FindControl("lblTotal");
lblamount.Text = total.ToString();
}
}

Indirectly referenced from required .class file

I was getting this error:

The type com.ibm.portal.state.exceptions.StateException cannot be resolved. It is indirectly referenced from required .class files

Doing the following fixed it for me:

Properties -> Java build path -> Libraries -> Server Library[wps.base.v61]unbound -> Websphere Portal v6.1 on WAS 7 -> Finish -> OK

Conditional Count on a field

SELECT  Priority, COALESCE(cnt, 0)
FROM    (
        SELECT  1 AS Priority
        UNION ALL
        SELECT  2 AS Priority
        UNION ALL
        SELECT  3 AS Priority
        UNION ALL
        SELECT  4 AS Priority
        UNION ALL
        SELECT  5 AS Priority
        ) p
LEFT JOIN
        (
        SELECT  Priority, COUNT(*) AS cnt
        FROM    jobs
        GROUP BY
                Priority
        ) j
ON      j.Priority = p.Priority

Why am I seeing "TypeError: string indices must be integers"?

TypeError for Slice Notation str[a:b]

tl;dr: use a colon : instead of a comma in between the two indices a and b in str[a:b]


When working with strings and slice notation (a common sequence operation), it can happen that a TypeError is raised, pointing out that the indices must be integers, even if they obviously are.

Example

>>> my_string = "hello world"
>>> my_string[0,5]
TypeError: string indices must be integers

We obviously passed two integers for the indices to the slice notation, right? So what is the problem here?

This error can be very frustrating - especially at the beginning of learning Python - because the error message is a little bit misleading.

Explanation

We implicitly passed a tuple of two integers (0 and 5) to the slice notation when we called my_string[0,5] because 0,5 (even without the parentheses) evaluates to the same tuple as (0,5) would do.

A comma , is actually enough for Python to evaluate something as a tuple:

>>> my_variable = 0,
>>> type(my_variable)
<class 'tuple'>

So what we did there, this time explicitly:

>>> my_string = "hello world"
>>> my_tuple = 0, 5
>>> my_string[my_tuple]
TypeError: string indices must be integers

Now, at least, the error message makes sense.

Solution

We need to replace the comma , with a colon : to separate the two integers correctly:

>>> my_string = "hello world"
>>> my_string[0:5]
'hello'

A clearer and more helpful error message could have been something like:

TypeError: string indices must be integers (not tuple)

A good error message shows the user directly what they did wrong and it would have been more obvious how to solve the problem.

[So the next time when you find yourself responsible for writing an error description message, think of this example and add the reason or other useful information to error message to let you and maybe other people understand what went wrong.]

Lessons learned

  • slice notation uses colons : to separate its indices (and step range, e.g. str[from:to:step])
  • tuples are defined by commas , (e.g. t = 1,)
  • add some information to error messages for users to understand what went wrong

Cheers and happy programming
winklerrr


[I know this question was already answered and this wasn't exactly the question the thread starter asked, but I came here because of the above problem which leads to the same error message. At least it took me quite some time to find that little typo.

So I hope that this will help someone else who stumbled upon the same error and saves them some time finding that tiny mistake.]

Looping through dictionary object

One way is to loop through the keys of the dictionary, which I recommend:

foreach(int key in sp.Keys)
    dynamic value = sp[key];

Another way, is to loop through the dictionary as a sequence of pairs:

foreach(KeyValuePair<int, dynamic> pair in sp)
{
    int key = pair.Key;
    dynamic value = pair.Value;
}

I recommend the first approach, because you can have more control over the order of items retrieved if you decorate the Keys property with proper LINQ statements, e.g., sp.Keys.OrderBy(x => x) helps you retrieve the items in ascending order of the key. Note that Dictionary uses a hash table data structure internally, therefore if you use the second method the order of items is not easily predictable.

Update (01 Dec 2016): replaced vars with actual types to make the answer more clear.

How to evaluate http response codes from bash/shell script?

i didn't like the answers here that mix the data with the status. found this: you add the -f flag to get curl to fail and pick up the error status code from the standard status var: $?

https://unix.stackexchange.com/questions/204762/return-code-for-curl-used-in-a-command-substitution

i don't know if it's perfect for every scenario here, but it seems to fit my needs and i think it's much easier to work with

How to merge 2 JSON objects from 2 files using jq?

Use jq -s add:

$ echo '{"a":"foo","b":"bar"} {"c":"baz","a":0}' | jq -s add
{
  "a": 0,
  "b": "bar",
  "c": "baz"
}

This reads all JSON texts from stdin into an array (jq -s does that) then it "reduces" them.

(add is defined as def add: reduce .[] as $x (null; . + $x);, which iterates over the input array's/object's values and adds them. Object addition == merge.)

What does the Ellipsis object do?

This is equivalent.

l=[..., 1,2,3]
l=[Ellipsis, 1,2,3]

... is a constant defined inside built-in constants.

Ellipsis

The same as the ellipsis literal “...”. Special value used mostly in conjunction with extended slicing syntax for user-defined container data types.

Read specific columns with pandas or other python module

Got a solution to above problem in a different way where in although i would read entire csv file, but would tweek the display part to show only the content which is desired.

import pandas as pd

df = pd.read_csv('data.csv', skipinitialspace=True)
print df[['star_name', 'ra']]

This one could help in some of the scenario's in learning basics and filtering data on the basis of columns in dataframe.

How to get datetime in JavaScript?

@Shadow Wizard's code should return 02:45 PM instead of 14:45 PM. So I modified his code a bit:

function getNowDateTimeStr(){
 var now = new Date();
 var hour = now.getHours() - (now.getHours() >= 12 ? 12 : 0);
return [[AddZero(now.getDate()), AddZero(now.getMonth() + 1), now.getFullYear()].join("/"), [AddZero(hour), AddZero(now.getMinutes())].join(":"), now.getHours() >= 12 ? "PM" : "AM"].join(" ");
}

//Pad given value to the left with "0"
function AddZero(num) {
    return (num >= 0 && num < 10) ? "0" + num : num + "";
}

How to fix java.net.SocketException: Broken pipe?

In our case we experienced this while performing a load test on our app server. The issue turned out that we need to add additional memory to our JVM because it was running out. This resolved the issue.

Try increasing the memory available to the JVM and or monitor the memory usage when you get those errors.

How would you make two <div>s overlap?

Just use negative margins, in the second div say:

<div style="margin-top: -25px;">

And make sure to set the z-index property to get the layering you want.

Most efficient way to convert an HTMLCollection to an Array

var arr = Array.prototype.slice.call( htmlCollection )

will have the same effect using "native" code.

Edit

Since this gets a lot of views, note (per @oriol's comment) that the following more concise expression is effectively equivalent:

var arr = [].slice.call(htmlCollection);

But note per @JussiR's comment, that unlike the "verbose" form, it does create an empty, unused, and indeed unusable array instance in the process. What compilers do about this is outside the programmer's ken.

Edit

Since ECMAScript 2015 (ES 6) there is also Array.from:

var arr = Array.from(htmlCollection);

Edit

ECMAScript 2015 also provides the spread operator, which is functionally equivalent to Array.from (although note that Array.from supports a mapping function as the second argument).

var arr = [...htmlCollection];

I've confirmed that both of the above work on NodeList.

A performance comparison for the mentioned methods: http://jsben.ch/h2IFA

Loop through an array php

Using foreach loop without key

foreach($array as $item) {
    echo $item['filename'];
    echo $item['filepath'];

    // to know what's in $item
    echo '<pre>'; var_dump($item);
}

Using foreach loop with key

foreach($array as $i => $item) {
    echo $item[$i]['filename'];
    echo $item[$i]['filepath'];

    // $array[$i] is same as $item
}

Using for loop

for ($i = 0; $i < count($array); $i++) {
    echo $array[$i]['filename'];
    echo $array[$i]['filepath'];
}

var_dump is a really useful function to get a snapshot of an array or object.

How to create unique keys for React elements?

Do not use this return `${ pre }_${ new Date().getTime()}`;. It's better to have the array index instead of that because, even though it's not ideal, that way you will at least get some consistency among the list components, with the new Date function you will get constant inconsistency. That means every new iteration of the function will lead to a new truly unique key.

The unique key doesn't mean that it needs to be globally unique, it means that it needs to be unique in the context of the component, so it doesn't run useless re-renders all the time. You won't feel the problem associated with new Date initially, but you will feel it, for example, if you need to get back to the already rendered list and React starts getting all confused because it doesn't know which component changed and which didn't, resulting in memory leaks, because, you guessed it, according to your Date key, every component changed.

Now to my answer. Let's say you are rendering a list of YouTube videos. Use the video id (arqTu9Ay4Ig) as a unique ID. That way, if that ID doesn't change, the component will stay the same, but if it does, React will recognize that it's a new Video and change it accordingly.

It doesn't have to be that strict, the little more relaxed variant is to use the title, like Erez Hochman already pointed out, or a combination of the attributes of the component (title plus category), so you can tell React to check if they have changed or not.

edited some unimportant stuff

File Upload to HTTP server in iphone programming

The code below uses HTTP POST to post NSData to a webserver. You also need minor knowledge of PHP.

NSString *urlString = @"http://yourserver.com/upload.php";
NSString *filename = @"filename";
request= [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:YOUR_NSDATA_HERE]];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@", returnString);

Selenium Finding elements by class name in python

Use nth-child, for example: http://www.w3schools.com/cssref/sel_nth-child.asp

driver.find_element(By.CSS_SELECTOR, 'p.content:nth-child(1)')

or http://www.w3schools.com/cssref/sel_firstchild.asp

driver.find_element(By.CSS_SELECTOR, 'p.content:first-child')

Unable to install pyodbc on Linux

I resolved my issue by following correct directions on pyodbc - Building wiki which states:

On Linux, pyodbc is typically built using the unixODBC headers, so you will need unixODBC and its headers installed. On a RedHat/CentOS/Fedora box, this means you would need to install unixODBC-devel:

yum install unixODBC-devel

Overlay normal curve to histogram in R

Here's a nice easy way I found:

h <- hist(g, breaks = 10, density = 10,
          col = "lightgray", xlab = "Accuracy", main = "Overall") 
xfit <- seq(min(g), max(g), length = 40) 
yfit <- dnorm(xfit, mean = mean(g), sd = sd(g)) 
yfit <- yfit * diff(h$mids[1:2]) * length(g) 

lines(xfit, yfit, col = "black", lwd = 2)

Text that shows an underline on hover

Fairly simple process I am using SCSS obviously but you don't have to as it's just CSS in the end!

HTML

<span class="menu">Menu</span>

SCSS

.menu {
    position: relative;
    text-decoration: none;
    font-weight: 400;
    color: blue;
    transition: all .35s ease;

    &::before {
        content: "";
        position: absolute;
        width: 100%;
        height: 2px;
        bottom: 0;
        left: 0;
        background-color: yellow;
        visibility: hidden;
        -webkit-transform: scaleX(0);
        transform: scaleX(0);
        -webkit-transition: all 0.3s ease-in-out 0s;
        transition: all 0.3s ease-in-out 0s;
    }

    &:hover {
        color: yellow;

        &::before {
            visibility: visible;
            -webkit-transform: scaleX(1);
            transform: scaleX(1);
        }
    }
}

Show datalist labels but submit the actual value

I realize this may be a bit late, but I stumbled upon this and was wondering how to handle situations with multiple identical values, but different keys (as per bigbearzhu's comment).

So I modified Stephan Muller's answer slightly:

A datalist with non-unique values:

<input list="answers" name="answer" id="answerInput">
<datalist id="answers">
  <option value="42">The answer</option>
  <option value="43">The answer</option>
  <option value="44">Another Answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">

When the user selects an option, the browser replaces input.value with the value of the datalist option instead of the innerText.

The following code then checks for an option with that value, pushes that into the hidden field and replaces the input.value with the innerText.

document.querySelector('#answerInput').addEventListener('input', function(e) {
    var input = e.target,   
        list = input.getAttribute('list'),
        options = document.querySelectorAll('#' + list + ' option[value="'+input.value+'"]'),
        hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden');

    if (options.length > 0) {
      hiddenInput.value = input.value;
      input.value = options[0].innerText;
      }

});

As a consequence the user sees whatever the option's innerText says, but the unique id from option.value is available upon form submit. Demo jsFiddle

How to upgrade pip3?

pip3 install --upgrade pip worked for me

H2 database error: Database may be already in use: "Locked by another process"

answer for this question => Exception in thread "main" org.h2.jdbc.JdbcSQLException: Database may be already in use: "Locked by another process". Possible solutions: close all other connection(s); use the server mode [90020-161]

close all tab from your browser where open h2 database also Exit h2 engine from your pc

Switch: Multiple values in one case?

you can try this.

switch (Valor)
            {
                case (Valor1 & Valor2):

                    break;               
            }

Java: getMinutes and getHours

tl;dr

ZonedDateTime.now().getHour()

… or …

LocalTime.now().getHour() 

ZonedDateTime

The Answer by J.D. is good but not optimal. That Answer uses the LocalDateTime class. Lacking any concept of time zone or offset-from-UTC, that class cannot represent a moment.

Better to use ZonedDateTime.

ZoneId z = ZoneID.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

Specify time zone

If you omit the ZoneId argument, one is applied implicitly at runtime using the JVM’s current default time zone.

So this:

ZonedDateTime.now()

…is the same as this:

ZonedDateTime.now( ZoneId.systemDefault() )

Better to be explicit, passing your desired/expected time zone. The default can change at any moment during runtime.

If critical, confirm the time zone with the user.

Hour-minute

Interrogate the ZonedDateTime for the hour and minute.

int hour = zdt.getHour() ;
int minute = zdt.getMinute() ;

LocalTime

If you want just the time-of-day without the time zone, extract LocalTime.

LocalTime lt = zdt.toLocalTime() ;

Or skip ZonedDateTime entirely, going directly to LocalTime.

LocalTime lt = LocalTime.now( z ) ;  // Capture the current time-of-day as seen in the wall-clock time used by the people of a particular region (a time zone).

java.time types

Table of types of date-time classes in modern java.time versus legacy.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

What are the parameters for the number Pipe - Angular 2

From the DOCS

Formats a number as text. Group sizing and separator and other locale-specific configurations are based on the active locale.

SYNTAX:

number_expression | number[:digitInfo[:locale]]

where expression is a number:

digitInfo is a string which has a following format:

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
  • minIntegerDigits is the minimum number of integer digits to use.Defaults to 1
  • minFractionDigits is the minimum number of digits
  • after fraction. Defaults to 0. maxFractionDigits is the maximum number of digits after fraction. Defaults to 3.
  • locale is a string defining the locale to use (uses the current LOCALE_ID by default)

DEMO

android - setting LayoutParams programmatically

after creating the view we have to add layout parameters .

change like this

TextView tv = new TextView(this);
tv.setLayoutParams(new ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT));

llview.addView(tv);
tv.setTextColor(Color.WHITE);
tv.setTextSize(2,25);
tv.setText(chat);
if (mine) {
    leftMargin = 5;
    tv.setBackgroundColor(0x7C5B77);
}
else {
    leftMargin = 50;
    tv.setBackgroundColor(0x778F6E);
}
final ViewGroup.MarginLayoutParams lpt =(MarginLayoutParams)tv.getLayoutParams();
lpt.setMargins(leftMargin,lpt.topMargin,lpt.rightMargin,lpt.bottomMargin);

Git: How to update/checkout a single file from remote origin master?

I think I have found an easy hack out.

Delete the file that you have on the local repository (the file that you want updated from the latest commit in the remote server)

And then do a git pull

Because the file is deleted, there will be no conflict

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

it means ONLY one byte will be allocated per character - so if you're using multi-byte charsets, your 1 character won't fit

if you know you have to have at least room enough for 1 character, don't use the BYTE syntax unless you know exactly how much room you'll need to store that byte

when in doubt, use VARCHAR2(1 CHAR)

same thing answered here Difference between BYTE and CHAR in column datatypes

Also, in 12c the max for varchar2 is now 32k, not 4000. If you need more than that, use CLOB

in Oracle, don't use VARCHAR

How to view/delete local storage in Firefox?

There is now a great plugin for Firebug that clones this nice feature in chrome. Check out:

https://addons.mozilla.org/en-US/firefox/addon/firestorage-plus/

It's developed by Nick Belhomme and updated regularly

How can I run multiple curl requests processed sequentially?

According to the curl man page:

You can specify any amount of URLs on the command line. They will be fetched in a sequential manner in the specified order.

So the simplest and most efficient (curl will send them all down a single TCP connection [those to the same origin]) approach would be put them all on a single invocation of curl e.g.:

curl http://example.com/?update_=1 http://example.com/?update_=2

How to run Gulp tasks sequentially one after the other

By default, gulp runs tasks simultaneously, unless they have explicit dependencies. This isn't very useful for tasks like clean, where you don't want to depend, but you need them to run before everything else.

I wrote the run-sequence plugin specifically to fix this issue with gulp. After you install it, use it like this:

var runSequence = require('run-sequence');

gulp.task('develop', function(done) {
    runSequence('clean', 'coffee', function() {
        console.log('Run something else');
        done();
    });
});

You can read the full instructions on the package README — it also supports running some sets of tasks simultaneously.

Please note, this will be (effectively) fixed in the next major release of gulp, as they are completely eliminating the automatic dependency ordering, and providing tools similar to run-sequence to allow you to manually specify run order how you want.

However, that is a major breaking change, so there's no reason to wait when you can use run-sequence today.

Install specific version using laravel installer

The direct way as mentioned in the documentation:

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

https://laravel.com/docs/6.x/installation

LDAP root query syntax to search more than one specific OU

I don't think this is possible with AD. The distinguishedName attribute is the only thing I know of that contains the OU piece on which you're trying to search, so you'd need a wildcard to get results for objects under those OUs. Unfortunately, the wildcard character isn't supported on DNs.

If at all possible, I'd really look at doing this in 2 queries using OU=Staff... and OU=Vendors... as the base DNs.

How to store images in mysql database using php

I found the answer, For those who are looking for the same thing here is how I did it. You should not consider uploading images to the database instead you can store the name of the uploaded file in your database and then retrieve the file name and use it where ever you want to display the image.

HTML CODE

<input type="file" name="imageUpload" id="imageUpload">

PHP CODE

if(isset($_POST['submit'])) {

    //Process the image that is uploaded by the user

    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }

    $image=basename( $_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable

    //storind the data in your database
    $query= "INSERT INTO items VALUES ('$id','$title','$description','$price','$value','$contact','$image')";
    mysql_query($query);

    require('heading.php');
    echo "Your add has been submited, you will be redirected to your account page in 3 seconds....";
    header( "Refresh:3; url=account.php", true, 303);
}

CODE TO DISPLAY THE IMAGE

while($row = mysql_fetch_row($result)) {
    echo "<tr>";
    echo "<td><img src='uploads/$row[6].jpg' height='150px' width='300px'></td>";
    echo "</tr>\n";
}

Remove characters before character "."

A couple of methods that, if the char does not exists, return the original string.

This one cuts the string after the first occurrence of the pivot:

public static string truncateStringAfterChar(string input, char pivot){         
    int index = input.IndexOf(pivot);   
    if(index >= 0) {
        return input.Substring(index + 1);          
    }           
    return input;       
}

This one instead cuts the string after the last occurrence of the pivot:

public static string truncateStringAfterLastChar(string input, char pivot){         
    return input.Split(pivot).Last();   
}

Force decimal point instead of comma in HTML5 number input (client-side)

With the step attribute specified to the precision of the decimals you want, and the lang attribute [which is set to a locale that formats decimals with period], your html5 numeric input will accept decimals. eg. to take values like 10.56; i mean 2 decimal place numbers, do this:

<input type="number" step="0.01" min="0" lang="en" value="1.99">

You can further specify the max attribute for the maximum allowable value.

Edit Add a lang attribute to the input element with a locale value that formats decimals with point instead of comma

Why isn't my Pandas 'apply' function referencing multiple columns working?

Seems you forgot the '' of your string.

In [43]: df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1)

In [44]: df
Out[44]:
                    a    b         c     Value
          0 -1.674308  foo  0.343801  0.044698
          1 -2.163236  bar -2.046438 -0.116798
          2 -0.199115  foo -0.458050 -0.199115
          3  0.918646  bar -0.007185 -0.001006
          4  1.336830  foo  0.534292  0.268245
          5  0.976844  bar -0.773630 -0.570417

BTW, in my opinion, following way is more elegant:

In [53]: def my_test2(row):
....:     return row['a'] % row['c']
....:     

In [54]: df['Value'] = df.apply(my_test2, axis=1)

Utils to read resource text file to String (Java)

If you want to get your String from a project resource like the file testcase/foo.json in src/main/resources in your project, do this:

String myString= 
 new String(Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("testcase/foo.json").toURI())));

Note that the getClassLoader() method is missing on some of the other examples.

Trigger change event of dropdown

For some reason, the other jQuery solutions provided here worked when running the script from console, however, it did not work for me when triggered from Chrome Bookmarklets.

Luckily, this Vanilla JS solution (the triggerChangeEvent function) did work:

_x000D_
_x000D_
/**_x000D_
  * Trigger a `change` event on given drop down option element._x000D_
  * WARNING: only works if not already selected._x000D_
  * @see https://stackoverflow.com/questions/902212/trigger-change-event-of-dropdown/58579258#58579258_x000D_
  */_x000D_
function triggerChangeEvent(option) {_x000D_
  // set selected property_x000D_
  option.selected = true;_x000D_
  _x000D_
  // raise event on parent <select> element_x000D_
  if ("createEvent" in document) {_x000D_
    var evt = document.createEvent("HTMLEvents");_x000D_
    evt.initEvent("change", false, true);_x000D_
    option.parentNode.dispatchEvent(evt);_x000D_
  }_x000D_
  else {_x000D_
    option.parentNode.fireEvent("onchange");_x000D_
  }_x000D_
}_x000D_
_x000D_
// ################################################_x000D_
// Setup our test case_x000D_
// ################################################_x000D_
_x000D_
(function setup() {_x000D_
  const sel = document.querySelector('#fruit');_x000D_
  sel.onchange = () => {_x000D_
    document.querySelector('#result').textContent = sel.value;_x000D_
  };_x000D_
})();_x000D_
_x000D_
function runTest() {_x000D_
  const sel = document.querySelector('#selector').value;_x000D_
  const optionEl = document.querySelector(sel);_x000D_
  triggerChangeEvent(optionEl);_x000D_
}
_x000D_
<select id="fruit">_x000D_
  <option value="">(select a fruit)</option>_x000D_
  <option value="apple">Apple</option>_x000D_
  <option value="banana">Banana</option>_x000D_
  <option value="pineapple">Pineapple</option>_x000D_
</select>_x000D_
_x000D_
<p>_x000D_
  You have selected: <b id="result"></b>_x000D_
</p>_x000D_
<p>_x000D_
  <input id="selector" placeholder="selector" value="option[value='banana']">_x000D_
  <button onclick="runTest()">Trigger select!</button>_x000D_
</p>
_x000D_
_x000D_
_x000D_

How to import classes defined in __init__.py

Maybe this could work:

import __init__ as lib

HTML5 Canvas vs. SVG vs. div

Knowing the differences between SVG and Canvas would be helpful in selecting the right one.

Canvas

SVG

  • Resolution independent
  • Support for event handlers
  • Best suited for applications with large rendering areas (Google Maps)
  • Slow rendering if complex (anything that uses the DOM a lot will be slow)
  • Not suited for game application

Count words in a string method?

public class TestStringCount {

  public static void main(String[] args) {
    int count=0;
    boolean word= false;
    String str = "how ma ny wo rds are th ere in th is sente nce";
    char[] ch = str.toCharArray();
    for(int i =0;i<ch.length;i++){
        if(!(ch[i]==' ')){
            for(int j=i;j<ch.length;j++,i++){
                if(!(ch[j]==' ')){
                    word= true;
                    if(j==ch.length-1){
                        count++;
                    }
                    continue;
                }
                else{
                    if(word){
                        count++;
                    }
                    word = false;
                }
            }
        }
        else{
            continue;
        }
    }
    System.out.println("there are "+(count)+" words");      
    }
}

SQL Query Where Field DOES NOT Contain $x

What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:

-- subquery
SELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);
-- predefined list
SELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);

If you are searching a string, go for the LIKE operator (but this will be slow):

-- Finds all rows where a does not contain "text"
SELECT * FROM x WHERE x.a NOT LIKE '%text%';

If you restrict it so that the string you are searching for has to start with the given string, it can use indices (if there is an index on that field) and be reasonably fast:

-- Finds all rows where a does not start with "text"
SELECT * FROM x WHERE x.a NOT LIKE 'text%';

Importing json file in TypeScript

In your TS Definition file, e.g. typings.d.ts`, you can add this line:

declare module "*.json" {
const value: any;
export default value;
}

Then add this in your typescript(.ts) file:-

import * as data from './colors.json';
const word = (<any>data).name;

Best Way to read rss feed in .net Using C#

Use this :

private string GetAlbumRSS(SyndicationItem album)
    {

        string url = "";
        foreach (SyndicationElementExtension ext in album.ElementExtensions)
            if (ext.OuterName == "itemRSS") url = ext.GetObject<string>();
        return (url);

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string albumRSS;
        string url = "http://www.SomeSite.com/rss?";
        XmlReader r = XmlReader.Create(url);
        SyndicationFeed albums = SyndicationFeed.Load(r);
        r.Close();
        foreach (SyndicationItem album in albums.Items)
        {

            cell.InnerHtml = cell.InnerHtml +string.Format("<br \'><a href='{0}'>{1}</a>", album.Links[0].Uri, album.Title.Text);
            albumRSS = GetAlbumRSS(album);

        }



    }

Passing parameter to controller action from a Html.ActionLink

Addition to the accepted answer:

if you are going to use

 @Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 },null)

this will create actionlink where you can't create new custom attribute or style for the link.

However, the 4th parameter in ActionLink extension will solve that problem. Use the 4th parameter for customization in your way.

 @Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 }, new { @class = "btn btn-info", @target = "_blank" })

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ' '

For the OP's command:

select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0,  Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from  #tmp_CTF** 

I get this error:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.

when debugging something like this split the long line up so you'll get a better row number:

select compid
,2
, convert(datetime
, '01/01/' 
+ CONVERT(char(4)
,cal_yr) 
,101) 
,0
,  Update_dt
, th1
, th2
, th3_pc 
, Update_id
, Update_dt
,1
from  #tmp_CTF** 

this now results in:

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.

which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:

from [#tmp_CTF**]

if that is the table name.

"Full screen" <iframe>

Impossible to say without seeing a live example, but try giving both bodies margin: 0px

What is the use of the JavaScript 'bind' method?

Bind Method

A bind implementation might look something like so:

Function.prototype.bind = function () {
  const self = this;
  const args = [...arguments];
  const context = args.shift();

  return function () {
    return self.apply(context, args.concat([...arguments]));
  };
};

The bind function can take any number of arguments and return a new function.

The new function will call the original function using the JS Function.prototype.apply method.
The apply method will use the first argument passed to the target function as its context (this), and the second array argument of the apply method will be a combination of the rest of the arguments from the target function, concat with the arguments used to call the return function (in that order).

An example can look something like so:

_x000D_
_x000D_
function Fruit(emoji) {_x000D_
  this.emoji = emoji;_x000D_
}_x000D_
_x000D_
Fruit.prototype.show = function () {_x000D_
  console.log(this.emoji);_x000D_
};_x000D_
_x000D_
const apple = new Fruit('');_x000D_
const orange = new Fruit('');_x000D_
_x000D_
apple.show();  // _x000D_
orange.show(); // _x000D_
_x000D_
const fruit1 = apple.show;_x000D_
const fruit2 = apple.show.bind();_x000D_
const fruit3 = apple.show.bind(apple);_x000D_
const fruit4 = apple.show.bind(orange);_x000D_
_x000D_
fruit1(); // undefined_x000D_
fruit2(); // undefined_x000D_
fruit3(); // _x000D_
fruit4(); // 
_x000D_
_x000D_
_x000D_

How to "scan" a website (or page) for info, and bring it into my program?

I would use JTidy - it is simlar to JSoup, but I don't know JSoup well. JTidy handles broken HTML and returns a w3c Document, so you can use this as a source to XSLT to extract the content you are really interested in. If you don't know XSLT, then you might as well go with JSoup, as the Document model is nicer to work with than w3c.

EDIT: A quick look on the JSoup website shows that JSoup may indeed be the better choice. It seems to support CSS selectors out the box for extracting stuff from the document. This may be a lot easier to work with than getting into XSLT.

I want to use CASE statement to update some records in sql server 2005

Add a WHERE clause

UPDATE dbo.TestStudents  
SET     LASTNAME =  CASE  
                        WHEN LASTNAME = 'AAA' THEN 'BBB' 
                        WHEN LASTNAME = 'CCC' THEN 'DDD' 
                        WHEN LASTNAME = 'EEE' THEN 'FFF' 
                        ELSE LASTNAME
                    END 
WHERE   LASTNAME IN ('AAA', 'CCC', 'EEE')

Window.Open with PDF stream instead of PDF location

It looks like window.open will take a Data URI as the location parameter.

So you can open it like this from the question: Opening PDF String in new window with javascript:

window.open("data:application/pdf;base64, " + base64EncodedPDF);

Here's an runnable example in plunker, and sample pdf file that's already base64 encoded.

Then on the server, you can convert the byte array to base64 encoding like this:

string fileName = @"C:\TEMP\TEST.pdf";
byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);
string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);

NOTE: This seems difficult to implement in IE because the URL length is prohibitively small for sending an entire PDF.

How do I check for equality using Spark Dataframe without SQL Query?

To get the negation, do this ...

df.filter(not( ..expression.. ))

eg

df.filter(not($"state" === "TX"))

How to set focus on a view when a layout is created and displayed?

Set focus: The framework will handled moving focus in response to user input. To force focus to a specific view, call requestFocus()

.NET Core vs Mono

Necromancing.
Providing an actual answer.

What is the difference between .Net Core and Mono?

.NET Core now officially is the future of .NET. It started for most part with a re-write of the ASP.NET MVC framework and console applications, which of course includes server applications. (Since it's Turing-complete and supports interop with C dlls, you could, if you absolutely wanted to, also write your own desktop applications with it, for example through 3rd-party libraries like Avalonia, which were a bit very basic at the time I first wrote this, which meant you were pretty much limited to web or server stuff.) Over time, many APIs have been added to .NET Core, so much so that after version 3.1, .NET Core will jump to version 5.0, be known as .NET 5.0 without the "Core", and that then will be the future of the .NET Framework. What used to be the full .NET Framework will linger around in maintenance mode as Full .NET Framework 4.8.x for a few decades, until it will die (maybe there are still going to be some upgrades, but I doubt it). In other words, .NET Core is the future of .NET, and Full .NET Framework will go the way of the Dodo/Silverlight/WindowsPhone.

The main point of .NET Core, apart from multi-platform support, is to improve performance, and to enable "native compilation"/self-contained-deployment (so you don't need .NET framework/VM installed on the target machine.
On the one hand, this means docker.io support on Linux, and on the other, self-contained deployment is useful in "cloud-computing", since then you can just use whatever version of the dotnet-CORE framework you like, and you don't have to worry about which version(s) of the .NET framework the sysadmin has actually installed.

While the .NET Core runtime supports multiple operating systems and processors, the SDK is a different story. And while the SDK supports multiple OS, ARM support for the SDK is/was still work in progress. .NET Core is supported by Microsoft. Dotnet-Core did not come with WinForms or WPF or anything like that.

  • As of version 3.0, WinForms and WPF is also supported by .NET Core, but only on Windows, and only by C#. Not by VB.NET (VB.NET support planned for v5 in 2020). And there is no Forms Designer in .NET Core: it's being shipped with a Visual Studio update later, at an unspecified time.
  • WebForms are still not supported by .NET Core, and there are no plans to support them, ever (Blazor is the new kid in town for that).
  • .NET Core also comes with System.Runtime, which replaces mscorelib.
  • Oftentimes, .NET Core is mixed up with NetStandard, which is a bit of a wrapper around System.Runtime/mscorelib (and some others), that allows you to write libraries that target .NET Core, Full .NET Framework and Xamarin (iOS/Android), all at the same time.
  • the .NET Core SDK does not/did not work on ARM, at least not last time I checked.

"The Mono Project" is much older than .NET Core.
Mono is Spanish and means Monkey, and as a side-remark, the name has nothing to do with mononucleosis (hint: you could get a list of staff under http://primates.ximian.com/).
Mono was started in 2005 by Miguel de Icaza (the guy that started GNOME - and a few others) as an implementation of the .NET Framework for Linux (Ximian/SuSe/Novell). Mono includes Web-Forms, Winforms, MVC, Olive, and an IDE called MonoDevelop (also knows as Xamarin Studio or Visual Studio Mac). Basically the equivalent of (OpenJDK) JVM and (OpenJDK) JDK/JRE (as opposed to SUN/Oracle JDK). You can use it to get ASP.NET-WebForms + WinForms + ASP.NET-MVC applications to work on Linux.

Mono is supported by Xamarin (the new company name of what used to be Ximian, when they focused on the Mobile market, instead of the Linux market), and not by Microsoft.
(since Xamarin was bought by Microsoft, that's technically [but not culturally] Microsoft.)
You will usually get your C# stuff to compile on mono, but not the VB.NET stuff.
Mono misses some advanced features, like WSE/WCF and WebParts.
Many of the Mono implementations are incomplete (e.g. throw NotImplementedException in ECDSA encryption), buggy (e.g. ODBC/ADO.NET with Firebird), behave differently than on .NET (for example XML-serialization) or otherwise unstable (ASP.NET MVC) and unacceptably slow (Regex). On the upside, the Mono toolchain also works on ARM.

As far as .NET Core is concerned, when they say cross-platform, don't expect that cross-platform means that you could actually just apt-get install .NET Core on ARM-Linux, like you can with ElasticSearch. You'll have to compile the entire framework from source.
That is, if you have that space (e.g. on a Chromebook, which has a 16 to 32 GB total HD).
It also used to have issues of incompatibility with OpenSSL 1.1 and libcurl.
Those have been rectified in the latest version of .NET Core Version 2.2.
So much for cross-platform.

I found a statement on the official site that said, "Code written for it is also portable across application stacks, such as Mono".

As long as that code doesn't rely on WinAPI-calls, Windows-dll-pinvokes, COM-Components, a case-insensitive file system, the default-system-encoding (codepage) and doesn't have directory separator issues, that's correct. However, .NET Core code runs on .NET Core, and not on Mono. So mixing the two will be difficult. And since Mono is quite unstable and slow (for web applications), I wouldn't recommend it anyway. Try image-processing on .NET core, e.g. WebP or moving GIF or multipage-tiff or writing text on an image, you'll be nastily surprised.

Note:
As of .NET Core 2.0, there is System.Drawing.Common (NuGet), which contains most of the functionality of System.Drawing. It should be more or less feature-complete in .NET-Core 2.1. However, System.Drawing.Common uses GDI+, and therefore won't work on Azure (System.Drawing libraries are available in Azure Cloud Service [basically just a VM], but not in Azure Web App [basically shared hosting?])
So far, System.Drawing.Common works fine on Linux/Mac, but has issues on iOS/Android - if it works at all, there.
Prior to .NET Core 2.0, that is to say sometime mid-February 2017, you could use SkiaSharp for imaging (example) (you still can).
Post .net-core 2.0, you'll notice that SixLabors ImageSharp is the way to go, since System.Drawing is not necessarely secure, and has a lot of potential or real memory leaks, which is why you shouldn't use GDI in web-applications; Note that SkiaSharp is a lot faster than ImageSharp, because it uses native-libraries (which can also be a drawback). Also, note that while GDI+ works on Linux & Mac, that doesn't mean it works on iOS/Android.

Code not written for .NET (non-Core) is not portable to .NET Core.
Meaning, if you want a non-GPL C# library like PDFSharp to create PDF-documents (very commonplace), you're out of luck (at the moment) (not anymore). Never mind ReportViewer control, which uses Windows-pInvokes (to encrypt, create mcdf documents via COM, and to get font, character, kerning, font embedding information, measure strings and do line-breaking, and for actually drawing tiffs of acceptable quality), and doesn't even run on Mono on Linux
(I'm working on that).

Also, code written in .NET Core is not portable to Mono, because Mono lacks the .NET Core runtime libraries (so far).

My goal is to use C#, LINQ, EF7, visual studio to create a website that can be ran/hosted in linux.

EF in any version that I tried so far was so goddamn slow (even on such simple things like one table with one left-join), I wouldn't recommend it ever - not on Windows either.
I would particularly not recommend EF if you have a database with unique-constrains, or varbinary/filestream/hierarchyid columns. (Not for schema-update either.)
And also not in a situation where DB-performance is critical (say 10+ to 100+ concurrent users).
Also, running a website/web-application on Linux will sooner or later mean you'll have to debug it.
There is no debugging support for .NET Core on Linux. (Not anymore, but requires JetBrains Rider.)
MonoDevelop does not (yet) support debugging .NET Core projects.
If you have problems, you're on your own. You'll have to use extensive logging.
Be careful, be advised extensive logging will fill your disk in no time, particularly if your program enters an infinite loop or recursion.
This is especially dangerous if your web-app runs as root, because log-in requires logfile-space - if there's no free space left, you won't be able to login anymore.
(Normally, about 5% of diskspace is reserved for user root [aka administrator on Windows], so at least the administrator can still log in if the disk is almost full. But if your applications run as root, that restriction does not apply for their disk usage, and so their logfiles can use 100% of the remaining free space, so not even the administrator can log in any more.)
It's therefore better not to encrypt that disk, that is, if you value your data/system.

Someone told me that he wanted it to be "in Mono", but I don't know what that means.

It either means he doesn't want to use .NET Core, or he just wants to use C# on Linux/Mac. My guess is he just wants to use C# for a Web-App on Linux. .NET Core is the way to go for that, if you absolutely want to do it in C#. Don't go with "Mono proper"; on the surface, it would seem to work at first - but believe me you will regret it because Mono's ASP.NET MVC isn't stable when your server runs long-term (longer than 1 day) - you have now been warned. See also the "did not complete" references when measuring Mono performance on the techempower benchmarks.

fortunes

I know I want to use the .Net Core 1.0 framework with the technologies I listed above. He also said he wanted to use "fast cgi". I don't know what that means either.

It means he wants to use a high-performance full-featured WebServer like nginx (Engine-X), possibly Apache.
Then he can run mono/dotnetCore with virtual name based hosting (multiple domain names on the same IP) and/or load-balancing. He can also run other websites with other technologies, without requiring a different port-number on the web-server. It means your website runs on a fastcgi-server, and nginx forwards all web-requests for a certain domain via the fastcgi-protocol to that server. It also means your website runs in a fastcgi-pipeline, and you have to be careful what you do, e.g. you can't use HTTP 1.1 when transmitting files.
Otherwise, files will be garbled at the destination.
See also here and here.

To conclude:
.NET Core at present (2016-09-28) is not really portable, nor is is really cross-platform (in particular the debug-tools).
Nor is native-compilation easy, especially for ARM.
And to me, it also does not look like its development is "really finished", yet.
For example, System.Data.DataTable/DataAdaper.Update is missing... (not anymore with .NET Core 2.0)
Together with the System.Data.Common.IDB* interfaces. (not anymore with .NET Core 1.1)
if there ever was one class that is often used, DataTable/DataAdapter would be it...
Also, the Linux-installer (.deb) fails, at least on my machine, and I'm sure I'm not the only one that has that problem.
Debug, maybe with Visual Studio Code, if you can build it on ARM (I managed to do that - do NOT follow Scott Hanselman's blog-post if you do that - there's a howto in the wiki of VS-Code on github), because they don't offer the executable.
Yeoman also fails. (I guess it has something to do with the nodejs version you installed - VS Code requires one version, Yeoman another... but it should run on the same computer. pretty lame
Never mind that it should run on the node version shipped by default on the OS.
Never mind that there should be no dependency on NodeJS in the first place.
The kestell server is also work in progress.
And judging by my experience with the mono-project, I highly doubt they ever tested .NET Core on FastCGI, or that they have any idea what FastCGI-support means for their framework, let alone that they tested it to make sure "everything works". In fact, I just tried making a fastcgi-application with .NET Core and just realized there is no FastCGI library for .NET Core "RTM"...

So when you're going to run .NET Core "RTM" behind nginx, you can only do it by proxying requests to kestrell (that semi-finished nodeJS-derived web-server) - there's no fastcgi support at present in .NET Core "RTM", AFAIK. Since there is no .net core fastcgi library, and no samples, it's also highly unlikely that anybody did any testing on the framework to make sure fastcgi works as expected.

I also question the performance.
In the (preliminary) techempower-benchmark (round 13), aspnetcore-linux ranks on 25% relative to the best performance, while comparable frameworks like Go (golang) rank at 96.9% of peak performance (and that is when returning plaintext without file-system access only). .NET Core does a little better on JSON-serialization, but it does not look compelling either (go reaches 98.5% of peak, .NET core 65%). That said, it can't possibly be worse than "mono proper".

Also, since it's still relatively new, not all of the major libraries have been ported (yet), and I doubt that some of them will ever be ported.
Imaging support is also questionable at best.
For anything encryption, use BouncyCastle instead.

Can you help me make sense of all these terms and if my expectations are realistic?

I hope i helped you making more sense with all these terms.
As far as your expecations go:
Developing a Linux application without knowing anything about Linux is a really stupid idea in the first place, and it's also bound to fail in some horrible way one way or the other. That said, because Linux comes at no licensing costs, it's a good idea in principle, BUT ONLY IF YOU KNOW WHAT YOU DO.
Developing an application for a platform where you can't debug your application on is another really bad idea.
Developing for fastcgi without knowing what consequences there are is yet another really bad idea.

Doing all these things on a "experimental" platform without any knowledge of that platform's specifics and without debugging support is suicide, if your project is more than just a personal homepage. On the other hand, I guess doing it with your personal homepage for learning purposes would probably be a very good experience - then you get to know what the framework and what the non-framework problems are.
You can for example (programmatically) loop-mount a case-insensitive fat32, hfs or JFS for your application, to get around the case-sensitivity issues (loop-mount not recommended in production).

To summarize
At present (2016-09-28), I would stay away from .NET Core (for production usage). Maybe in one to two years, you can take another look, but probably not before.
If you have a new web-project that you develop, start it in .NET Core, not mono.

If you want a framework that works on Linux (x86/AMD64/ARMhf) and Windows and Mac, that has no dependencies, i.e. only static linking and no dependency on .NET, Java or Windows, use Golang instead. It's more mature, and its performance is proven (Baidu uses it with 1 million concurrent users), and golang has a significantly lower memory footprint. Also golang is in the repositories, the .deb installs without problems, the sourcecode compiles - without requiring changes - and golang (in the meantime) has debugging support with delve and JetBrains Gogland on Linux (and Windows and Mac). Golang's build process (and runtime) also doesn't depend on NodeJS, which is yet another plus.

As far as mono goes, stay away from it.
It is nothing short of amazing how far mono has come, but unfortunately that's no substitute for its performance/scalability and stability issues for production applications.
Also, mono-development is quite dead, they largely only develop the parts relevant to Android and iOS anymore, because that's where Xamarin makes their money.
Don't expect Web-Development to be a first-class Xamarin/mono citizen.
.NET Core might be worth it, if you start a new project, but for existing large web-forms projects, porting over is largely out of the question, the changes required are huge. If you have a MVC-project, the amount of changes might be manageable, if your original application design was sane, which is mostly not the case for most existing so-called "historically grown" applications.

December 2016 Update:
Native compilation has been removed from .NET Core preview, as it is not yet ready...

Seems like they have improved pretty heavily on the raw text-file benchmark, but on the other hand, it's gotten pretty buggy. Also, it further deteriorated in the JSON benchmarks. Curious also that entity framework shall be faster for updates than Dapper - although both at record slowness. This is very unlikely to be true. Looks like there still are more than just a few bugs to hunt.

Also, there seems to be relief coming on the Linux IDE front.
JetBrains released "Project Rider", an early access preview of a C#/.NET Core IDE for Linux (and Mac and Windows), that can handle Visual Studio Project files. Finally a C# IDE that is usable & that isn't slow as hell.

Conclusion: .NET Core still is pre-release quality software as we march into 2017. Port your libraries, but stay away from it for production usage, until framework quality stabilizes.
And keep an eye on Project Rider.

buggy .net core

2017 Update
Have migrated my (brother's) homepage to .NET Core for now.
So far, the runtime on Linux seems to be stable enough (at least for small projects) - it survived a load test with ease - mono never did.
Also, it looks like I mixed up .NET-Core-native and .NET-Core-self-contained-deployment. Self-contained deployment works, but it is a bit underdocumented, although it's super easy (the build/publish tools are a bit unstable, yet - if you encounter "Positive number required. - Build FAILED." - run the same command again, and it works).

You can run

dotnet restore -r win81-x64
dotnet build -r win81-x64
dotnet publish -f netcoreapp1.1 -c Release -r win81-x64

Note: As per .NET Core 3, you can publish everything minified as a single file:

dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true
dotnet publish -r linux-x64 -c Release /p:PublishSingleFile=true

However, unlike go, it's not a statically linked executable, but a self-extracting zip file, so when deploying, you might run into problems, especially if the temp directory is locked down by group policy, or some other issues. Works fine for a hello-world program, though. And if you don't minify, the executable size will clock in at something around 100 MB.

And you get a self-contained .exe-file (in the publish directory), which you can move to a Windows 8.1 machine without .NET framework installed and let it run. Nice. It's here that dotNET-Core just starts to get interesting. (mind the gaps, SkiaSharp doesn't work on Windows 8.1 / Windows Server 2012 R2, [yet] - the ecosystem has to catch up first - but interestingly, the Skia-dll-load-fail doesn't crash the entire server/application - so everything else works)

(Note: SkiaSharp on Windows 8.1 is missing the appropriate VC runtime files - msvcp140.dll and vcruntime140.dll. Copy them into the publish-directory, and Skia will work on Windows 8.1.)

August 2017 Update
.NET Core 2.0 released.
Be careful - comes with (huge breaking) changes in authentication...
On the upside, it brought the DataTable/DataAdaper/DataSet classes back, and many more.
Realized .NET Core is still missing support for Apache SparkSQL, because Mobius isn't yet ported. That's bad, because that means no SparkSQL support for my IoT Cassandra Cluster, so no joins...
Experimental ARM support (runtime only, not SDK - too bad for devwork on my Chromebook - looking forward to 2.1 or 3.0).
PdfSharp is now experimentally ported to .NET Core.
JetBrains Rider left EAP. You can now use it to develop & debug .NET Core on Linux - though so far only .NET Core 1.1 until the update for .NET Core 2.0 support goes live.

May 2018 Update
.NET Core 2.1 release imminent. Maybe this will fix NTLM-authentication on Linux (NTLM authentication doesn't work on Linux {and possibly Mac} in .NET-Core 2.0 with multiple authenticate headers, such as negotiate, commonly sent with ms-exchange, and they're apparently only fixing it in v2.1, no bugfix release for 2.0).
But I'm not installing preview releases on my machine. So waiting.
v2.1 is also said to greatly reduce compile times. That would be good.

Also, note that on Linux, .NET Core is 64-Bit only !
There is no, and there will be no, x86-32 version of .NET Core on Linux.
And the ARM port is ARM-32 only. No ARM-64, yet.
And on ARM, you (at present) only have the runtime, not the dotnet-SDK.

And one more thing:
Because .NET-Core uses OpenSSL 1.0, .NET Core on Linux doesn't run on Arch Linux, and by derivation not on Manjaro (the most popular Linux distro by far at this point in time), because Arch Linux uses OpenSSL 1.1. So if you're using Arch Linux, you're out of luck (with Gentoo, too).

Edit:

Latest version of .NET Core 2.2+ supports OpenSSL 1.1. So you can use it on Arch or (k)Ubuntu 19.04+. You might have to use the .NET-Core install script though, because there are no packages, yet.

On the upside, performance has definitely improved: fortunes

plaintext

.NET Core 3:
.NET-Core v 3.0 is said to bring WinForms and WPF to .NET-Core.
However, while WinForms and WPF will be .NET Core, WinForms and WPF in .NET-Core will run on Windows only, because WinForms/WPF will use the Windows-API.

Note:
.NET Core 3.0 is now out (RTM), and there is WinForms and WPF support, but only for C# (on Windows). There is no WinForms-Core-Designer. The designer will, eventually, come with a Visual Studio update, somewhen. WinForms support for VB.NET is not supported, but is planned for .NET 5.0 somewhen in 2020.

PS:

echo "DOTNET_CLI_TELEMETRY_OPTOUT=1" >> /etc/environment
export DOTNET_CLI_TELEMETRY_OPTOUT=1 

If you've used it on windows, you probably never saw this:

The .NET Core tools collect usage data in order to improve your experience.
The data is anonymous and does not include command-line arguments.
The data is collected by Microsoft and shared with the community.
You can opt out of telemetry by setting a DOTNET_CLI_TELEMETRY_OPTOUT environment variable to 1 using your favorite shell.
You can read more about .NET Core tools telemetry @ https://aka.ms/dotnet-cli-telemetry.

I thought I'd mention that I think monodevelop (aka Xamarin Studio, the Mono IDE, or Visual Studio Mac as it is now called on Mac) has evolved quite nicely, and is - in the meantime - largely usable.
However, JetBrains Rider (2018 EAP at this point in time) is definitely a lot nicer and more reliable (and the included decompiler is a life-safer), that is to say, if you develop .NET-Core on Linux or Mac. MonoDevelop does not support Debug-StepThrough on Linux in .NET Core, though, since MS does not license their debugging API dll (except for VisualStudio Mac ... ). However, you can use the Samsung debugger for .NET Core through the .NET Core debugger extension for Samsung Debugger for MonoDevelop

Disclaimer:
I don't use Mac, so I can't say if what I wrote here applies to FreeBSD-Unix based Mac as well. I am refering to the Linux (Debian/Ubuntu/Mint) version of JetBrains Rider, mono, MonoDevelop/VisualStudioMac/XamarinStudio and .NET-Core. Also, Apple is contemplating a move from Intel-processors to self-manufactured ARM(ARM-64?)-based processors, so much of what applies to Mac right now might not apply to Mac in the future (2020+).

Also, when I write "mono is quite unstable and slow", the unstable relates to WinFroms & WebForms applications, specifically executing web-applications via fastcgi or with XSP (on the 4.x version of mono), as well as XML-serialization-handling peculiarities, and the quite-slow relates to WinForms, and regular expressions in particular (ASP.NET-MVC uses regular expressions for routing as well).

When I write about my experience about mono 2.x, 3.x and 4.x, that also does not necessarely mean these issues haven't been resolved by now, or by the time you are reading this, nor that if they are fixed now, that there can't be a regression later that reintroduces any of these bugs/features. Nor does that mean that if you embed the mono-runtime, you'll get the same results as when you use the (dev) system's mono runtime. It also doesn't mean that embedding the mono-runtime (anywhere) is necessarely free.

All that doesn't necessarely mean mono is ill-suited for iOS or Android, or that it has the same issues there. I don't use mono on Android or IOS, so I'm in no positon to say anything about stability, usability, costs and performance on these platforms. Obviously, if you use .NET on Android, you have some other costs considerations to do as well, such as weighting xamarin-costs vs. costs and time for porting existing code to Java. One hears mono on Android and IOS shall be quite good. Take it with a grain of salt. For one, don't expect the default-system-encoding to be the same on android/ios vs. Windows, and don't expect the android filesystem to be case-insensitive, and don't expect any windows fonts to be present.

Reading and writing binary file

It can be done with simple commands in the following snippet.

Copies the whole file of any size. No size constraint!

Just use this. Tested And Working!!

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
  ifstream infile;
  infile.open("source.pdf",ios::binary|ios::in);

  ofstream outfile;
  outfile.open("temppdf.pdf",ios::binary|ios::out);

  int buffer[2];
  while(infile.read((char *)&buffer,sizeof(buffer)))
  {
      outfile.write((char *)&buffer,sizeof(buffer));
  }

  infile.close();
  outfile.close();
  return 0;
}

Having a smaller buffer size would be helpful in copying tiny files. Even "char buffer[2]" would do the job.

How to condense if/else into one line in Python?

Python's if can be used as a ternary operator:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'

How do I run a PowerShell script when the computer starts?

Try this. Create a shortcut in startup folder and iuput

PowerShell "&.'PathToFile\script.ps1'"

This is the easiest way.

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

JavaScript variable assignments from tuples

As an update to The Minister's answer, you can now do this with es2015:

function Tuple(...args) {
  args.forEach((val, idx) => 
    Object.defineProperty(this, "item"+idx, { get: () => val })
  )
}


var t = new Tuple("a", 123)
console.log(t.item0) // "a"
t.item0 = "b"
console.log(t.item0) // "a"

https://jsbin.com/fubaluwimo/edit?js,console

Method call if not null in C#

From C# 6 onwards, you can just use:

MyEvent?.Invoke();

or:

obj?.SomeMethod();

The ?. is the null-propagating operator, and will cause the .Invoke() to be short-circuited when the operand is null. The operand is only accessed once, so there is no risk of the "value changes between check and invoke" problem.

===

Prior to C# 6, no: there is no null-safe magic, with one exception; extension methods - for example:

public static void SafeInvoke(this Action action) {
    if(action != null) action();
}

now this is valid:

Action act = null;
act.SafeInvoke(); // does nothing
act = delegate {Console.WriteLine("hi");}
act.SafeInvoke(); // writes "hi"

In the case of events, this has the advantage of also removing the race-condition, i.e. you don't need a temporary variable. So normally you'd need:

var handler = SomeEvent;
if(handler != null) handler(this, EventArgs.Empty);

but with:

public static void SafeInvoke(this EventHandler handler, object sender) {
    if(handler != null) handler(sender, EventArgs.Empty);
}

we can use simply:

SomeEvent.SafeInvoke(this); // no race condition, no null risk

How to open spss data files in excel?

(Not exactly an answer for you, since do you want avoid opening the files, but maybe this helps others).

I have been using the open source GNU PSPP package to convert the sav tile to csv. You can download the Windows version at least from SourceForge [1]. Once you have the software, you can convert sav file to csv with following command line:

pspp-convert <input.sav> <output.csv>

[1] http://sourceforge.net/projects/pspp4windows/files/?source=navbar

How do you strip a character out of a column in SQL Server?

Use the "REPLACE" string function on the column in question:

UPDATE (yourTable)
SET YourColumn = REPLACE(YourColumn, '*', '')
WHERE (your conditions)

Replace the "*" with the character you want to strip out and specify your WHERE clause to match the rows you want to apply the update to.

Of course, the REPLACE function can also be used - as other answerer have shown - in a SELECT statement - from your question, I assumed you were trying to update a table.

Marc

@Directive vs @Component in Angular

If you refer the official angular docs

https://angular.io/guide/attribute-directives

There are three kinds of directives in Angular:

  1. Components—directives with a template.
  2. Structural directives—change the DOM layout by adding and removing DOM elements. e.g *ngIf
  3. Attribute directives—change the appearance or behavior of an element, component, or another directive. e.g [ngClass].

As the Application grows we find difficulty in maintaining all these codes. For reusability purpose, we separate our logic in smart components and dumb components and we use directives (structural or attribute) to make changes in the DOM.

Thymeleaf using path variables to th:href

I was trying to go through a list of objects, display them as rows in a table, with each row being a link. This worked for me. Hope it helps.

// CUSTOMER_LIST is a model attribute
<table>
    <th:block th:each="customer : ${CUSTOMER_LIST}">
        <tr>
            <td><a th:href="@{'/main?id=' + ${customer.id}}" th:text="${customer.fullName}" /></td>
        </tr>
    </th:block>
</table>

Is there a WebSocket client implemented for Python?

http://pypi.python.org/pypi/websocket-client/

Ridiculously easy to use.

 sudo pip install websocket-client

Sample client code:

#!/usr/bin/python

from websocket import create_connection
ws = create_connection("ws://localhost:8080/websocket")
print "Sending 'Hello, World'..."
ws.send("Hello, World")
print "Sent"
print "Receiving..."
result =  ws.recv()
print "Received '%s'" % result
ws.close()

Sample server code:

#!/usr/bin/python
import websocket
import thread
import time

def on_message(ws, message):
    print message

def on_error(ws, error):
    print error

def on_close(ws):
    print "### closed ###"

def on_open(ws):
    def run(*args):
        for i in range(30000):
            time.sleep(1)
            ws.send("Hello %d" % i)
        time.sleep(1)
        ws.close()
        print "thread terminating..."
    thread.start_new_thread(run, ())


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://echo.websocket.org/",
                                on_message = on_message,
                                on_error = on_error,
                                on_close = on_close)
    ws.on_open = on_open

    ws.run_forever()

jQuery AJAX Character Encoding

$str=iconv("windows-1250","UTF-8",$str);

what helped me on the eventually

Should Jquery code go in header or footer?

Standard practice is to put all of your scripts at the bottom of the page, but I use ASP.NET MVC with a number of jQuery plugins, and I find that it all works better if I put my jQuery scripts in the <head> section of the master page.

In my case, there are artifacts that occur when the page is loaded, if the scripts are at the bottom of the page. I'm using the jQuery TreeView plugin, and if the scripts are not loaded at the beginning, the tree will render without the necessary CSS classes imposed on it by the plugin. So you get this funny-looking mess when the page first loads, followed by the proper rendering of the TreeView. Very bad looking. Putting the jQuery plugins in the <head> section of the master page eliminates this problem.

How can I create a UIColor from a hex string?

Polished Extension from the original answer by @Tom feel free to update the code here

extension UIColor{
    convenience init (hexString:String) {
        var cleanString:String = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString

        if (cleanString.hasPrefix("#")) {
            cleanString = cleanString.substringFromIndex(cleanString.startIndex.advancedBy(1))
        }

        if (cleanString.characters.count != 6) {
            self.init()
        }
        else{
            var rgbValue = UInt32()
            let scanner = NSScanner(string: cleanString)
            scanner.scanHexInt(&rgbValue)

            self.init(
                red: CGFloat((rgbValue & 0xFF0000) >> 16)/255.0,
                green: CGFloat((rgbValue & 0xFF00) >> 8)/255.0,
                blue: CGFloat(rgbValue & 0xFF)/255.0,
                alpha: 1.0)
        }
    }
}

Mean filter for smoothing images in Matlab

I see good answers have already been given, but I thought it might be nice to just give a way to perform mean filtering in MATLAB using no special functions or toolboxes. This is also very good for understanding exactly how the process works as you are required to explicitly set the convolution kernel. The mean filter kernel is fortunately very easy:

I = imread(...)
kernel = ones(3, 3) / 9; % 3x3 mean kernel
J = conv2(I, kernel, 'same'); % Convolve keeping size of I

Note that for colour images you would have to apply this to each of the channels in the image.

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

I know this thread is old and there are already comprehensive answers.

Just in case you don't know this:

<meta http-equiv="X-UA-Compatible" content="IE=edge" >

You don't have to hardcode IE version number as

<meta http-equiv="X-UA-Compatible" content="IE=9" >

How do DATETIME values work in SQLite?

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:

TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS"). REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar. INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC. Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.

Having said that, I would use INTEGER and store seconds since Unix epoch (1970-01-01 00:00:00 UTC).

Change File Extension Using C#

try this.

filename = Path.ChangeExtension(".blah") 

in you Case:

myfile= c:/my documents/my images/cars/a.jpg;
string extension = Path.GetExtension(myffile);
filename = Path.ChangeExtension(myfile,".blah") 

You should look this post too:

http://msdn.microsoft.com/en-us/library/system.io.path.changeextension.aspx

apache redirect from non www to www

The code I use is:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

Following up on Kev's answer, using the Postgres docs:

First, create an array of the elements, then use the built-in array_to_string function.

CREATE AGGREGATE array_accum (anyelement)
(
 sfunc = array_append,
 stype = anyarray,
 initcond = '{}'
);

select array_to_string(array_accum(name),'|') from table group by id;

CSS: how do I create a gap between rows in a table?

In my opinion, the easiest way to do is adding padding to your tag.

td {
 padding: 10px 0
}

Hope this will help you! Cheer!

Disable Pinch Zoom on Mobile Web

I think what you may be after is the CSS property touch-action. You just need a CSS rule like this:

html, body {touch-action: none;}

You will see it has pretty good support (https://caniuse.com/#feat=mdn-css_properties_touch-action_none), including Safari, as well as back to IE10.

Good Hash Function for Strings

Here's a simple hash function that I use for a hash table I built. Its basically for taking a text file and stores every word in an index which represents the alphabetical order.

int generatehashkey(const char *name)
{
        int x = tolower(name[0])- 97;
        if (x < 0 || x > 25)
           x = 26;
        return x;
}

What this basically does is words are hashed according to their first letter. So, word starting with 'a' would get a hash key of 0, 'b' would get 1 and so on and 'z' would be 25. Numbers and symbols would have a hash key of 26. THere is an advantage this provides; You can calculate easily and quickly where a given word would be indexed in the hash table since its all in an alphabetical order, something like this: Code can be found here: https://github.com/abhijitcpatil/general

Giving the following text as input: Atticus said to Jem one day, “I’d rather you shot at tin cans in the backyard, but I know you’ll go after birds. Shoot all the blue jays you want, if you can hit ‘em, but remember it’s a sin to kill a mockingbird.” That was the only time I ever heard Atticus say it was a sin to do something, and I asked Miss Maudie about it. “Your father’s right,” she said. “Mockingbirds don’t do one thing except make music for us to enjoy. They don’t eat up people’s gardens, don’t nest in corn cribs, they don’t do one thing but sing their hearts out for us. That’s why it’s a sin to kill a mockingbird.

This would be the output:

0 --> a a about asked and a Atticus a a all after at Atticus
1 --> but but blue birds. but backyard
2 --> cribs corn can cans
3 --> do don’t don’t don’t do don’t do day
4 --> eat enjoy. except ever
5 --> for for father’s
6 --> gardens go
7 --> hearts heard hit
8 --> it’s in it. I it I it’s if I in
9 --> jays Jem
10 --> kill kill know
11 --> 
12 --> mockingbird. music make Maudie Miss mockingbird.”
13 --> nest
14 --> out one one only one
15 --> people’s
16 --> 17 --> right remember rather
18 --> sin sing said. she something sin say sin Shoot shot said
19 --> to That’s their thing they They to thing to time the That to the the tin to
20 --> us. up us
21 --> 
22 --> why was was want
23 --> 
24 --> you you you’ll you
25 --> 
26 --> “Mockingbirds ” “Your ‘em “I’d

Read file from aws s3 bucket using node fs

Since you seem to want to process an S3 text file line-by-line. Here is a Node version that uses the standard readline module and AWS' createReadStream()

const readline = require('readline');

const rl = readline.createInterface({
    input: s3.getObject(params).createReadStream()
});

rl.on('line', function(line) {
    console.log(line);
})
.on('close', function() {
});

AngularJS: factory $http.get JSON file

this answer helped me out a lot and pointed me in the right direction but what worked for me, and hopefully others, is:

menuApp.controller("dynamicMenuController", function($scope, $http) {
$scope.appetizers= [];
$http.get('config/menu.json').success(function(data) { 
    console.log("success!");
    $scope.appetizers = data.appetizers;
        console.log(data.appetizers);
    });    
});

Turn off enclosing <p> tags in CKEditor 3.0

Found it!

ckeditor.js line #91 ... search for

B.config.enterMode==3?'div':'p'

change to

B.config.enterMode==3?'div':'' (NO P!)

Dump your cache and BAM!

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

More importantly, the 2013 versions of Visual Studio Express have all the languages that comes with the commercial versions. You can use the Windows desktop versions not only to program using Windows Forms, it is possible to write those windowed applications with any language that comes with the software, may it be C++ using the windows.h header if you want to actually learn how to create windows applications from scratch, or use Windows form to create windows in C# or visual Basic.

In the past, you had to download one version for each language or type of content. Or just download an all-in-one that still installed separate versions of the software for different languages. Now with 2013 you get all the languages needed in each content oriented version of the 2013 express.

You pick what matters the most to you.

Besides, it might be a good way to learn using notepad and the command line to write and compile, but I find that a bit tedious to use. While using an IDE might be overwhelming at first, you start small, learning how to create a project, write code, compile your code. They have gone way over their heads to ease up your day when you take it for the first time.

How do I make a C++ macro behave like a function?

If you're willing to adopt the practice of always using curly braces in your if statements,

Your macro would simply be missing the last semicolon:

#define MACRO(X,Y)                       \
cout << "1st arg is:" << (X) << endl;    \
cout << "2nd arg is:" << (Y) << endl;    \
cout << "Sum is:" << ((X)+(Y)) << endl

Example 1: (compiles)

if (x > y) {
    MACRO(x, y);
}
do_something();

Example 2: (compiles)

if (x > y) {
    MACRO(x, y);
} else {
    MACRO(y - x, x - y);
}

Example 3: (doesn't compile)

do_something();
MACRO(x, y)
do_something();

Send JavaScript variable to PHP variable

PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:

<script type="text/javascript">
  var foo = '<?php echo $foo ?>';
</script>

To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):

var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});

On your server, you would need to receive the variable sent in the post:

$variable = $_POST['variable'];

Freeze screen in chrome debugger / DevTools panel for popover inspection?

To be able to inspect any element do the following. This should work even if it's hard to duplicate the hover state:

  • Run the following javascript in the console. This will break into the debugger in 5 seconds.

    setTimeout(function(){debugger;}, 5000)

  • Go show your element (by hovering or however) and wait until Chrome breaks into the Debugger.

  • Now click on the Elements tab in the Chrome Inspector, and you can look for your element there.
  • You may also be able to click on the Find Element icon (looks like a magnifying glass) and Chrome will let you go and inspect and find your element on the page by right clicking on it, then choosing Inspect Element

Note that this approach is a slight variation to this other great answer on this page.

iPhone is not available. Please reconnect the device

I had the same issue with Xcode 11.6 and iOS 13.6. Unpairing the device and adding it again solved the problem.

I forgot the password I entered during postgres installation

What I did to resolve the same problem was:

Open pg_hba.conf file with gedit editor from the terminal:

sudo gedit /etc/postgresql/9.5/main/pg_hba.conf

It will ask for password. Enter your admin login password. This will open gedit with the file. Paste the following line:

host  all   all  127.0.0.1/32  trust

just below -

# Database administrative login by Unix domain socket

Save and close it. Close the terminal and open it again and run this command:

psql -U postgres

You will now enter the psql console. Now change the password by entering this:

ALTER USER [your prefered user name] with password '[desired password]';

If it says user does not exist then instead of ALTER use CREATE.

Lastly, remove that certain line you pasted in pg_hba and save it.

Import Python Script Into Another?

It's worth mentioning that (at least in python 3), in order for this to work, you must have a file named __init__.py in the same directory.

Where does one get the "sys/socket.h" header/source file?

Try to reinstall cygwin with selected package:gcc-g++ : gnu compiler collection c++ (from devel category), openssh server and client program (net), make: the gnu version (devel), ncurses terminal (utils), enhanced vim editors (editors), an ANSI common lisp implementation (math) and libncurses-devel (lib).

This library files should be under cygwin\usr\include

Regards.

How to launch an Activity from another Application in Android

If you want to open specific activity of another application we can use this.

Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.fuelgauge.PowerUsageSummary");
intent.setComponent(cn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try 
{
    startActivity(intent)
}catch(ActivityNotFoundException e){
    Toast.makeText(context,"Activity Not Found",Toast.LENGTH_SHORT).show()
}

If you must need other application, instead of showing Toast you can show a dialog. Using dialog you can bring the user to Play-Store to download required application.

scale Image in an UIButton to AspectFit?

Background image can actually be set to scale aspect fill pretty easily. Just need to do something like this in a subclass of UIButton:

- (CGRect)backgroundRectForBounds:(CGRect)bounds
{
    // you'll need the original size of the image, you 
    // can save it from setBackgroundImage:forControlState
    return CGRectFitToFillRect(__original_image_frame_size__, bounds);
}

// Utility function, can be saved elsewhere
CGRect CGRectFitToFillRect( CGRect inRect, CGRect maxRect )
{
    CGFloat origRes = inRect.size.width / inRect.size.height;
    CGFloat newRes = maxRect.size.width / maxRect.size.height;

    CGRect retRect = maxRect;

    if (newRes < origRes)
    {
        retRect.size.width = inRect.size.width * maxRect.size.height / inRect.size.height;
        retRect.origin.x = roundf((maxRect.size.width - retRect.size.width) / 2);
    }
    else
    {
        retRect.size.height = inRect.size.height * maxRect.size.width / inRect.size.width;
        retRect.origin.y = roundf((maxRect.size.height - retRect.size.height) / 2);
    }

    return retRect;
}

How to disable EditText in Android

Edittext edittext = (EditText)findViewById(R.id.edit);
edittext.setEnabled(false);

How to add values in a variable in Unix shell scripting?

In ksh ,bash ,sh:

$ count7=0                     
$ count1=5
$ 
$ (( count7 += count1 ))
$ echo $count7
$ 5

How to write and save html file in python?

You can do it using write() :

#open file with *.html* extension to write html
file= open("my.html","w")
#write then close file
file.write(html)
file.close()

Visual Studio Code - Convert spaces to tabs

In my case, the problem was JS-CSS-HTML Formatter extension installed after january update. The default indent_char property is space. I uninstalled it and the weird behavior stops.

Is there a quick change tabs function in Visual Studio Code?

@Combii I found a way to swap

CMD+1, CMD+2, CMD+3 with CTRL+1, CTRL+2, CTRL+3, ...

In macOS, go to:

Code > Preferences > Keyboard Shortcuts

On that page, click the button on the top right of the page...

edit keybindings.json button

and append the configuration below, then save.

[
    {
        "key": "cmd+0",
        "command": "workbench.action.openLastEditorInGroup"
    },
    {
        "key": "cmd+1",
        "command": "workbench.action.openEditorAtIndex1"
    },
    {
        "key": "cmd+2",
        "command": "workbench.action.openEditorAtIndex2"
    },
    {
        "key": "cmd+3",
        "command": "workbench.action.openEditorAtIndex3"
    },
    {
        "key": "cmd+4",
        "command": "workbench.action.openEditorAtIndex4"
    },
    {
        "key": "cmd+5",
        "command": "workbench.action.openEditorAtIndex5"
    },
    {
        "key": "cmd+6",
        "command": "workbench.action.openEditorAtIndex6"
    },
    {
        "key": "cmd+7",
        "command": "workbench.action.openEditorAtIndex7"
    },
    {
        "key": "cmd+8",
        "command": "workbench.action.openEditorAtIndex8"
    },
    {
        "key": "cmd+9",
        "command": "workbench.action.openEditorAtIndex9"
    },
    {
        "key": "ctrl+1",
        "command": "workbench.action.focusFirstEditorGroup"
    },
    {
        "key": "ctrl+2",
        "command": "workbench.action.focusSecondEditorGroup"
    },
    {
        "key": "ctrl+3",
        "command": "workbench.action.focusThirdEditorGroup"
    }
]

You now can use CMD+[1-9] to switch between tabs and CTRL+[1-3] to focus editor groups! Hope this answer is helpful.

Verilog: How to instantiate a module

This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.

The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  clk, rst_n, data_rx_1, data_tx ); 

endmodule

This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.

This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.

module subcomponent(
  input        rst_n,       
  input        clk,
  ...

It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) ); 

endmodule

This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.

Giving each port its own line and indenting correctly adds to the readability and code quality.

subcomponent subcomponent_instance_name (
  .clk      ( clk       ), // input
  .rst_n    ( rst_n     ), // input
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:

clk_gen( 
  .clk      ( clk_sub   ), // output
  .en       ( enable    )  // input

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:

Note that the instance name for the second component has been changed

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.

wire [9:0] data_temp
subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.

Use .port with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk,                    // input **Auto connect**
  .rst_n,                  // input **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

endmodule

This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.

Another trick that I think is even worse than the one above is .* which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.

subcomponent subcomponent_instance_name (
  .*,                      // **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.

Unable to resolve host "<URL here>" No address associated with host name

If you are running the app on an emulator, make sure that it is properly connected to the internet. If it is not, the easiest way of solving it is reopening the emulator or creating a new device.

Gradients on UIView and UILabels On iPhone

Note: The results below apply to older versions of iOS, but when testing on iOS 13 the stepping doesn't occur. I don't know for which version of iOS the stepping was removed.


When using CAGradientLayer, as opposed to CGGradient, the gradient is not smooth, but has noticeable stepping to it. See this example:

To get more attractive results it is better to use CGGradient.

Regular Expression for alphanumeric and underscores

use lookaheads to do the "at least one" stuff. Trust me it's much easier.

Here's an example that would require 1-10 characters, containing at least one digit and one letter:

^(?=.*\d)(?=.*[A-Za-z])[A-Za-z0-9]{1,10}$

NOTE: could have used \w but then ECMA/Unicode considerations come into play increasing the character coverage of the \w "word character".

Get div to take up 100% body height, minus fixed-height header and footer

This question has been pretty well answered, but I'm taking the liberty of adding a javascript solution. Just give the element that you want to 'expand' the id footerspacerdiv, and this javascript snippet will expand that div until the page takes up the full height of the browser window.

It works based on the observation that, when a page is less than the full height of the browser window, document.body.scrollHeight is equal to document.body.clientHeight. The while loop increases the height of footerspacerdiv until document.body.scrollHeight is greater than document.body.clientHeight. At this point, footerspacerdiv will actually be 1 pixel too tall, and the browser will show a vertical scroll bar. So, the last line of the script reduces the height of footerspacerdiv by one pixel to make the page height exactly the height of the browser window.

By placing footerspacerdiv just above the 'footer' of the page, this script can be used to 'push the footer down' to the bottom of the page, so that on short pages, the footer is flush with the bottom of the browser window.

<script>    
//expand footerspacer div so that footer goes to bottom of page on short pages        
  var objSpacerDiv=document.getElementById('footerspacer');          
  var bresize=0;   

  while(document.body.scrollHeight<=document.body.clientHeight) {
    objSpacerDiv.style.height=(objSpacerDiv.clientHeight+1)+"px";
    bresize=1;
  }             
  if(bresize) { objSpacerDiv.style.height=(objSpacerDiv.clientHeight-1)+"px"; }               
 </script>

Setting Spring Profile variable

For Eclipse, setting -Dspring.profiles.active variable in the VM arguments would do the trick.

Go to

Right Click Project --> Run as --> Run Configurations --> Arguments

And add your -Dspring.profiles.active=dev in the VM arguments

Difference between CR LF, LF and CR line break types?

NL derived from EBCDIC NL = x'15' which would logically compare to CRLF x'odoa ascii... this becomes evident when physcally moving data from mainframes to midrange. Coloquially (as only arcane folks use ebcdic) NL has been equated with either CR or LF or CRLF

Where does PHP store the error log? (php5, apache, fastcgi, cpanel)

Search the httpd.conf file for ErrorLog by running cat <file location> | grep ErrorLog on the command line. For example:

$ cat /etc/apache2/httpd.conf | grep ErrorLog

Output:

# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
ErrorLog "/private/var/log/apache2/error_log"

Find the line that starts with ErrorLog and there's your answer.

Note: For virtual hosts, you can edit the virtual hosts file httpd-vhosts.conf to specify a different log file location.

Is it possible to find out the users who have checked out my project on GitHub?

If by "checked out" you mean people who have cloned your project, then no it is not possible. You don't even need to be a GitHub user to clone a repository, so it would be infeasible to track this.

How can I check if a directory exists in a Bash shell script?

Using the -e check will check for files and this includes directories.

if [ -e ${FILE_PATH_AND_NAME} ]
then
    echo "The file or directory exists."
fi

How to tell Maven to disregard SSL errors (and trusting all certs)?

Create a folder ${USER_HOME}/.mvn and put a file called maven.config in it.

The content should be:

-Dmaven.wagon.http.ssl.insecure=true
-Dmaven.wagon.http.ssl.allowall=true
-Dmaven.wagon.http.ssl.ignore.validity.dates=true

Hope this helps.

Pinging an IP address using PHP and echoing the result

I use this function :

<?php
function is_ping_address($ip) {
    exec('ping -c1 -w1 '.$ip, $outcome, $status);
    preg_match('/([0-9]+)% packet loss/', $outcome[3], $arr);
    return ( $arr[1] == 100 ) ? false : true;
}

Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio?

In SQL Management Studio you can:

  1. Right click on the result set grid, select 'Save Result As...' and save in.

  2. On a tool bar toggle 'Result to Text' button. This will prompt for file name on each query run.

If you need to automate it, use bcp tool.

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

Why?

You asked why it happens, let's see:

The official language specificaion dictates a call to the internal [[GetValue]] method. Your .attr returns undefined and you're trying to access its length.

If Type(V) is not Reference, return V.

This is true, since undefined is not a reference (alongside null, number, string and boolean)

Let base be the result of calling GetBase(V).

This gets the undefined part of myVar.length .

If IsUnresolvableReference(V), throw a ReferenceError exception.

This is not true, since it is resolvable and it resolves to undefined.

If IsPropertyReference(V), then

This happens since it's a property reference with the . syntax.

Now it tries to convert undefined to a function which results in a TypeError.

Button Center CSS

The problem is with the following CSS line on .nav_button:

margin: 0 auto;

That would only work if you had one button, that's why they're off-centered when there are more than one nav_button divs.

If you want all your buttons centered nest the nav_buttons in another div:

<div class="nav">
    <div class="centerButtons">
        <div class="nav_button">
            <div class="b_left"></div>
            <div class="b_middle">Home</div>
            <div class="b_right"></div>
        </div>
        <div class="nav_button">
            <div class="b_left"></div>
            <div class="b_middle">Contact Us</div>
            <div class="b_right"></div>
        </div>
    </div>
</div>

And style it this way:

.nav{
    margin-top:167px;
    width:1024px;
    height:34px;
}

/* Centers the div that nests the nav_buttons */
.centerButtons {
    margin: 0 auto;
    float: left;
} 

.nav_button{
    height:34px;
    margin-right:10px;
    float: left;
}

Change form size at runtime in C#

You can change the height of a form by doing the following where you want to change the size (substitute '10' for your size):

this.Height = 10;

This can be done with the width as well:

this.Width = 10;

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Using python PIL to turn a RGB image into a pure black and white image

Another option (which is useful e.g. for scientific purposes when you need to work with segmentation masks) is simply apply a threshold:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Binarize (make it black and white) an image with Python."""

from PIL import Image
from scipy.misc import imsave
import numpy


def binarize_image(img_path, target_path, threshold):
    """Binarize an image."""
    image_file = Image.open(img_path)
    image = image_file.convert('L')  # convert image to monochrome
    image = numpy.array(image)
    image = binarize_array(image, threshold)
    imsave(target_path, image)


def binarize_array(numpy_array, threshold=200):
    """Binarize a numpy array."""
    for i in range(len(numpy_array)):
        for j in range(len(numpy_array[0])):
            if numpy_array[i][j] > threshold:
                numpy_array[i][j] = 255
            else:
                numpy_array[i][j] = 0
    return numpy_array


def get_parser():
    """Get parser object for script xy.py."""
    from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
    parser = ArgumentParser(description=__doc__,
                            formatter_class=ArgumentDefaultsHelpFormatter)
    parser.add_argument("-i", "--input",
                        dest="input",
                        help="read this file",
                        metavar="FILE",
                        required=True)
    parser.add_argument("-o", "--output",
                        dest="output",
                        help="write binarized file hre",
                        metavar="FILE",
                        required=True)
    parser.add_argument("--threshold",
                        dest="threshold",
                        default=200,
                        type=int,
                        help="Threshold when to show white")
    return parser


if __name__ == "__main__":
    args = get_parser().parse_args()
    binarize_image(args.input, args.output, args.threshold)

It looks like this for ./binarize.py -i convert_image.png -o result_bin.png --threshold 200:

enter image description here

How can I force component to re-render with hooks in React?

You can (ab)use normal hooks to force a rerender by taking advantage of the fact that React doesn't print booleans in JSX code

// create a hook
const [forceRerender, setForceRerender] = React.useState(true);

// ...put this line where you want to force a rerender
setForceRerender(!forceRerender);

// ...make sure that {forceRerender} is "visible" in your js code
// ({forceRerender} will not actually be visible since booleans are
// not printed, but updating its value will nonetheless force a
// rerender)
return (
  <div>{forceRerender}</div>
)

Cross compile Go on OSX?

With Go 1.5 they seem to have improved the cross compilation process, meaning it is built in now. No ./make.bash-ing or brew-ing required. The process is described here but for the TLDR-ers (like me) out there: you just set the GOOS and the GOARCH environment variables and run the go build.

For the even lazier copy-pasters (like me) out there, do something like this if you're on a *nix system:

env GOOS=linux GOARCH=arm go build -v github.com/path/to/your/app

You even learned the env trick, which let you set environment variables for that command only, completely free of charge.

Include headers when using SELECT INTO OUTFILE?

I would like to add to the answer provided by Sangam Belose. Here's his code:

select ('id') as id, ('time') as time, ('unit') as unit
UNION ALL
SELECT * INTO OUTFILE 'C:/Users/User/Downloads/data.csv'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM sensor

However, if you have not set up your "secure_file_priv" within the variables, it may not work. For that, check the folder set on that variable by:

SHOW VARIABLES LIKE "secure_file_priv"

The output should look like this:

mysql> show variables like "%secure_file_priv%";
+------------------+------------------------------------------------+
| Variable_name    | Value                                          |
+------------------+------------------------------------------------+
| secure_file_priv | C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\ |
+------------------+------------------------------------------------+
1 row in set, 1 warning (0.00 sec)

You can either change this variable or change the query to output the file to the default path showing.

How to read from standard input in the console?

I'm late to the party. But how about one liner:

data, err := ioutil.ReadAll(os.Stdin)

and press ctrl+d (EOT) once input is entered on command line.

How do I make WRAP_CONTENT work on a RecyclerView

I have not worked on my answer but the way I know it StaggridLayoutManager with no. of grid 1 can solve your problem as StaggridLayout will automatically adjust its height and width on the size of the content. if it works dont forget to check it as a right answer.Cheers..

Converting an int to a binary string representation in Java?

public static string intToBinary(int n)
{
    String s = "";
    while (n > 0)
    {
        s =  ( (n % 2 ) == 0 ? "0" : "1") +s;
        n = n / 2;
    }
    return s;
}

What's a Good Javascript Time Picker?

You could read jQuery creator John Resig's post about it here: http://ejohn.org/blog/picking-time/.

MySQL: Enable LOAD DATA LOCAL INFILE

For those of you looking for answers to make LOAD DATA LOCAL INFILE work like me, this might probably work. Well it worked for me, so here it goes. Install percona as your mysql server and client by following the steps from the link. A password will be prompted for during the installation, so provide one that you'll remember and use it later. One the installation is done, reboot your system and test if the server is up and running by going to the terminal and typing mysql -u root -p and then the password. Try running the command LOAD DATA LOCAL INFILE now.. Hope it works :)

BTW I was working on Rails 2.3 with Ruby 1.9.3 on Ubuntu 12.04.

Sockets - How to find out what port and address I'm assigned

The comment in your code is wrong. INADDR_ANY doesn't put server's IP automatically'. It essentially puts 0.0.0.0, for the reasons explained in mark4o's answer.

What is the basic difference between the Factory and Abstract Factory Design Patterns?

Factory pattern: The factory produces IProduct-implementations

Abstract Factory Pattern: A factory-factory produces IFactories, which in turn produces IProducts :)

[Update according to the comments]
What I wrote earlier is not correct according to Wikipedia at least. An abstract factory is simply a factory interface. With it, you can switch your factories at runtime, to allow different factories in different contexts. Examples could be different factories for different OS'es, SQL providers, middleware-drivers etc..

Round double value to 2 decimal places

To remove the decimals from your double, take a look at this output

Obj C

double hellodouble = 10.025;
NSLog(@"Your value with 2 decimals: %.2f", hellodouble);
NSLog(@"Your value with no decimals: %.0f", hellodouble);

The output will be:

10.02 
10

Swift 2.1 and Xcode 7.2.1

let hellodouble:Double = 3.14159265358979
print(String(format:"Your value with 2 decimals: %.2f", hellodouble))
print(String(format:"Your value with no decimals: %.0f", hellodouble))

The output will be:

3.14 
3

Installing Python library from WHL file

From How do I install a Python package with a .whl file? [sic], How do I install a Python package USING a .whl file ?

For all Windows platforms:

1) Download the .WHL package install file.

2) Make Sure path [C:\Progra~1\Python27\Scripts] is in the system PATH string. This is for using both [pip.exe] and [easy-install.exe].

3) Make sure the latest version of pip.EXE is now installed. At this time of posting:

pip.EXE --version

  pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

4) Run pip.EXE in an Admin command shell.

 - Open an Admin privileged command shell.

 > easy_install.EXE --upgrade  pip

 - Check the pip.EXE version:
 > pip.EXE --version

 pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

 > pip.EXE install --use-wheel --no-index 
     --find-links="X:\path to wheel file\DownloadedWheelFile.whl"

Be sure to double-quote paths or path\filenames with embedded spaces in them ! Alternatively, use the MSW 'short' paths and filenames.

Angular 2 - innerHTML styling

We pull in content frequently from our CMS as [innerHTML]="content.title". We place the necessary classes in the application's root styles.scss file rather than in the component's scss file. Our CMS purposely strips out in-line styles so we must have prepared classes that the author can use in their content. Remember using {{content.title}} in the template will not render html from the content.

A better way to check if a path exists or not in PowerShell

If you just want an alternative to the cmdlet syntax, specifically for files, use the File.Exists() .NET method:

if(![System.IO.File]::Exists($path)){
    # file with path $path doesn't exist
}

If, on the other hand, you want a general purpose negated alias for Test-Path, here is how you should do it:

# Gather command meta data from the original Cmdlet (in this case, Test-Path)
$TestPathCmd = Get-Command Test-Path
$TestPathCmdMetaData = New-Object System.Management.Automation.CommandMetadata $TestPathCmd

# Use the static ProxyCommand.GetParamBlock method to copy 
# Test-Path's param block and CmdletBinding attribute
$Binding = [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($TestPathCmdMetaData)
$Params  = [System.Management.Automation.ProxyCommand]::GetParamBlock($TestPathCmdMetaData)

# Create wrapper for the command that proxies the parameters to Test-Path 
# using @PSBoundParameters, and negates any output with -not
$WrappedCommand = { 
    try { -not (Test-Path @PSBoundParameters) } catch { throw $_ }
}

# define your new function using the details above
$Function:notexists = '{0}param({1}) {2}' -f $Binding,$Params,$WrappedCommand

notexists will now behave exactly like Test-Path, but always return the opposite result:

PS C:\> Test-Path -Path "C:\Windows"
True
PS C:\> notexists -Path "C:\Windows"
False
PS C:\> notexists "C:\Windows" # positional parameter binding exactly like Test-Path
False

As you've already shown yourself, the opposite is quite easy, just alias exists to Test-Path:

PS C:\> New-Alias exists Test-Path
PS C:\> exists -Path "C:\Windows"
True

Change select box option background color

$htmlIngressCss='<style>';
$multiOptions = array("" => "All");
$resIn = $this->commonDB->getIngressTrunk();
while ($row = $resIn->fetch()) {
    if($row['IsActive']==0){
        $htmlIngressCss .= '.ingressClass select, option[value="'.$row['TrunkInfoID'].'"] {color:red;font-weight:bold;}';
    }
    $multiOptions[$row['TrunkInfoID']] = $row['IngressTrunkName'];
}
$htmlIngressCss.='</style>';

add $htmlIngressCss in your html portion :)

Is there a native jQuery function to switch elements?

I have done it with this snippet

// Create comments
var t1 = $('<!-- -->');
var t2 = $('<!-- -->');
// Position comments next to elements
$(ui.draggable).before(t1);
$(this).before(t2);
// Move elements
t1.after($(this));
t2.after($(ui.draggable));
// Remove comments
t1.remove();
t2.remove();

SSRS the definition of the report is invalid

This occurred for me due to changing the names of certain dataset fields within BIDS that were being referenced by parameters. I forgot to go into the parameters and reassign a default value (the default value of the parameter didn't automatically change to the newly renamed dataset field. Instead .

How to install Openpyxl with pip

  1. https://pypi.python.org/pypi/openpyxl download zip file and unzip it on local system.
  2. go to openpyxl folder where setup.py is present.
  3. open command prompt under the same path.
  4. Run a command: python setup.py install
  5. It will install openpyxl.

How does System.out.print() work?

It is a very sensitive point to understand how to work System.out.print. If the first element is String then plus(+) operator works as String concate operator. If the first element is integer plus(+) operator works as mathematical operator.

public static void main(String args[]) {
    System.out.println("String" + 8 + 8); //String88
    System.out.println(8 + 8+ "String"); //16String
}

Getting return value from stored procedure in C#

When we return a value from Stored procedure without select statement. We need to use "ParameterDirection.ReturnValue" and "ExecuteScalar" command to get the value.

CREATE PROCEDURE IsEmailExists
    @Email NVARCHAR(20)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    IF EXISTS(SELECT Email FROM Users where Email = @Email)
    BEGIN
        RETURN 0 
    END
    ELSE
    BEGIN
        RETURN 1
    END
END

in C#

GetOutputParaByCommand("IsEmailExists")

public int GetOutputParaByCommand(string Command)
        {
            object identity = 0;
            try
            {
                mobj_SqlCommand.CommandText = Command;
                SqlParameter SQP = new SqlParameter("returnVal", SqlDbType.Int);
                SQP.Direction = ParameterDirection.ReturnValue;
                mobj_SqlCommand.Parameters.Add(SQP);
                mobj_SqlCommand.Connection = mobj_SqlConnection;
                mobj_SqlCommand.ExecuteScalar();
                identity = Convert.ToInt32(SQP.Value);
                CloseConnection();
            }
            catch (Exception ex)
            {

                CloseConnection();
            }
            return Convert.ToInt32(identity);
        }

We get the returned value of SP "IsEmailExists" using above c# function.

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

var array = $('#searchKeywords').val().split(",");

then

$.each(array,function(i){
   alert(array[i]);
});

OR

for (i=0;i<array.length;i++){
     alert(array[i]);
}

Best HTTP Authorization header type for JWT

The best HTTP header for your client to send an access token (JWT or any other token) is the Authorization header with the Bearer authentication scheme.

This scheme is described by the RFC6750.

Example:

GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIXVCJ9TJV...r7E20RMHrHDcEfxjoYZgeFONFh7HgQ

If you need stronger security protection, you may also consider the following IETF draft: https://tools.ietf.org/html/draft-ietf-oauth-pop-architecture. This draft seems to be a good alternative to the (abandoned?) https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac.

Note that even if this RFC and the above specifications are related to the OAuth2 Framework protocol, they can be used in any other contexts that require a token exchange between a client and a server.

Unlike the custom JWT scheme you mention in your question, the Bearer one is registered at the IANA.

Concerning the Basic and Digest authentication schemes, they are dedicated to authentication using a username and a secret (see RFC7616 and RFC7617) so not applicable in that context.

mappedBy reference an unknown target entity property

public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "USER_ID")
    Long userId;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
    List<Notification> sender;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
    List<Notification> receiver;
}

public class Notification implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id

    @Column(name = "NOTIFICATION_ID")
    Long notificationId;

    @Column(name = "TEXT")
    String text;

    @Column(name = "ALERT_STATUS")
    @Enumerated(EnumType.STRING)
    AlertStatus alertStatus = AlertStatus.NEW;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SENDER_ID")
    @JsonIgnore
    User sender;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "RECEIVER_ID")
    @JsonIgnore
    User receiver;
}

What I understood from the answer. mappedy="sender" value should be the same in the notification model. I will give you an example..

User model:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "**sender**", cascade = CascadeType.ALL)
    List<Notification> sender;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "**receiver**", cascade = CascadeType.ALL)
    List<Notification> receiver;

Notification model:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
    List<Notification> **sender**;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
    List<Notification> **receiver**;

I gave bold font to user model and notification field. User model mappedBy="sender " should be equal to notification List sender; and mappedBy="receiver" should be equal to notification List receiver; If not, you will get error.

A completely free agile software process tool

EDIT: Kanbanize is a commercial product and offers a 30 day free trial.

Disclosing: I am a co-founder of http://kanbanize.com/

Mark, I understand your desire to find the perfect application with all these features inside, but I really doubt that you will get it for free. There's a bunch of super cool apps (including Kanbanize) out there, but none of them is completely free.

Be careful what you call a Kanban board and what not, though. Trello is definitely NOT a kanban system (no WIP limits, no analytics, etc.). It is a great visual management system, but not a Kanban one.

Finally, to answer your question, tools that deserve attention in my opinion are: Kanbanize (of course), LeanKit, KanbanTool, Kanbanery and probably a few others. My personal bias is that LeanKit is the most advanced to date followed by Kanbanize and KanbanTool.

I hope that helps.

X11/Xlib.h not found in Ubuntu

Andrew White's answer is sufficient to get you moving. Here's a step-by-step for beginners.

A simple get started:

Create test.cpp: (This will be built and run to verify you got things set up right.)

#include <X11/Xlib.h>
#include <unistd.h>


main()
{
  // Open a display.
  Display *d = XOpenDisplay(0);

  if ( d )
    {
      // Create the window
      Window w = XCreateWindow(d, DefaultRootWindow(d), 0, 0, 200,
                   100, 0, CopyFromParent, CopyFromParent,
                   CopyFromParent, 0, 0);

      // Show the window
      XMapWindow(d, w);
      XFlush(d);

      // Sleep long enough to see the window.
      sleep(10);
    }
  return 0;
}

(Source: LinuxGazette)

Try: g++ test.cpp -lX11 If it builds to a.out, try running it. If you see a simple window drawn, you have the necessary libraries, and some other root problem is afoot.

If your response is:

    test.cpp:1:22: fatal error: X11/Xlib.h: No such file or directory
    compilation terminated.

you need to install X11 development libraries. sudo apt-get install libx11-dev

Retry g++ test.cpp -lX11

If it works, you're golden.

Tested using a fresh install of libX11-dev_2%3a1.5.0-1_i386.deb

How can I close a window with Javascript on Mozilla Firefox 3?

This code will work it out definitely

function closing() {
var answer = confirm("Do you wnat to close this window ?");
    if (answer){
        netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserWrite');
        window.close();
    }
    else{
        stop;
    }
}

CSS selector for first element with class

According to your updated problem

<div class="home">
  <span>blah</span>
  <p class="red">first</p>
  <p class="red">second</p>
  <p class="red">third</p>
  <p class="red">fourth</p>
</div>

how about

.home span + .red{
      border:1px solid red;
    }

This will select class home, then the element span and finally all .red elements that are placed immediately after span elements.

Reference: http://www.w3schools.com/cssref/css_selectors.asp

Execute command without keeping it in history

An extension of @John Doe & @user3270492's answer. But, this seems to work for me.

<your_secret_command>; history -d $((HISTCMD-1))

You should not see the entry of the command in your history.

Here's the explanation..

The 'history -d' deletes the mentioned entry from the history.

The HISTCMD stores the command_number of the one to be executed next. So, (HISTCMD-1) refers to the last executed command.

Remove a certain line from Bash history file

Is it better practice to use String.format over string Concatenation in Java?

There could be a perceptible difference.

String.format is quite complex and uses a regular expression underneath, so don't make it a habit to use it everywhere, but only where you need it.

StringBuilder would be an order of magnitude faster (as someone here already pointed out).

Reverse Singly Linked List Java

package com.three;

public class Link {

    int a;
    Link Next;

    public Link(int i){
        a=i;
    }

}

public class LinkList {

    Link First = null;

    public void insertFirst(int a){
        Link objLink = new Link(a);

        objLink.Next=First;
        First = objLink;

    }

    public void displayLink(){

        Link current = First;
        while(current!=null){
            System.out.println(current.a);
            current = current.Next;
        }

    }

    public void ReverseLink(){
        Link current = First;
        Link Previous = null;
        Link temp = null;

        while(current!=null){

            if(current==First)
                temp = current.Next;
            else
                temp=current.Next;

            if(temp==null){
                First = current;
                //return;
            }
            current.Next=Previous;
            Previous=current;
            //System.out.println(Previous);
            current = temp;
        }

    }

    public static void main(String args[]){

        LinkList objLinkList = new LinkList();
        objLinkList.insertFirst(1);
        objLinkList.insertFirst(2);
        objLinkList.insertFirst(3);
        objLinkList.insertFirst(4);
        objLinkList.insertFirst(5);
        objLinkList.insertFirst(6);
        objLinkList.insertFirst(7);
        objLinkList.insertFirst(8);
        objLinkList.displayLink();
        System.out.println("-----------------------------");
        objLinkList.ReverseLink();
        objLinkList.displayLink();

    }

}

Laravel whereIn OR whereIn

Yes, orWhereIn is a method that you can use.

I'm fairly sure it should give you the result you're looking for, however, if it doesn't you could simply use implode to create a string and then explode it (this is a guess at your array structure):

$values = implode(',', array_map(function($value)
{
    return trim($value, ',');
}, $filters));

$query->whereIn('products.value', explode(',' $values));