Programs & Examples On #Precompiled

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:

multiDexEnabled true

And it worked!

Example

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.1'
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

And clean the project.

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

Look at https://stackoverflow.com/a/4726838/2963099

Turn off pre compiled headers:

Project Properties -> C++ -> Precompiled Headers

set Precompiled Header to "Not Using Precompiled Header".

How to set up googleTest as a shared library on Linux

I was similarly underwhelmed by this situation and ended up making my own Ubuntu source packages for this. These source packages allow you to easily produce a binary package. They are based on the latest gtest & gmock source as of this post.

Google Test DEB Source Package

Google Mock DEB Source Package

To build the binary package do this:

tar -xzvf gtest-1.7.0.tar.gz
cd gtest-1.7.0
dpkg-source -x gtest_1.7.0-1.dsc
cd gtest-1.7.0
dpkg-buildpackage

It may tell you that you need some pre-requisite packages in which case you just need to apt-get install them. Apart from that, the built .deb binary packages should then be sitting in the parent directory.

For GMock, the process is the same.

As a side note, while not specific to my source packages, when linking gtest to your unit test, ensure that gtest is included first (https://bbs.archlinux.org/viewtopic.php?id=156639) This seems like a common gotcha.

Unexpected end of file error

You did forget to include stdafx.h in your source (as I cannot see it your code). If you didn't, then make sure #include "stdafx.h" is the first line in your .cpp file, otherwise you will see the same error even if you've included "stdafx.h" in your source file (but not in the very beginning of the file).

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

For all those who are reading this but do not have problem with application.css and instead with their custom CSS classes e.g. admin.css, base.css etc.

Solution is to use as mentioned

bundle exec rake assets:precompile

And in stylesheets references just reference application.css

<%= stylesheet_link_tag    "application", :media => "all" %>

Since assets pipeline will precompile all of your stylesheets in application.css. This also happens in development so using any other references is wrong when using assets pipeline.

How to avoid precompiled headers

The .cpp file is configured to use precompiled header, therefore it must be included first (before iostream). For Visual Studio, it's name is usually "stdafx.h".

If there are no stdafx* files in your project, you need to go to this file's options and set it as “Not using precompiled headers”.

How to fix .pch file missing on build?

If everything is right, but this mistake is present, it need check next section in ****.vcxproj file:

<ClCompile Include="stdafx.cpp">
  <PrecompiledHeader Condition=

In my case it there was an incorrect name of a configuration: only first word.

Using FFmpeg in .net?

The original question is now more than 5 years old. In the meantime there is now a solution for a WinRT solution from ffmpeg and an integration sample from Microsoft.

Could not load file or assembly 'System.Data.SQLite'

Can you delete your bin debug folder and recompile again?

Or check your project reference to the System.Data.SQLite, track down where it is located, then open the dll in reflector. If you can't open it, that means that the dll is corrupted, you might want to find a correct one or reinstall the .net framework.

Update React component every second

You need to use setInterval to trigger the change, but you also need to clear the timer when the component unmounts to prevent it leaving errors and leaking memory:

componentDidMount() {
  this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000);
}
componentWillUnmount() {
  clearInterval(this.interval);
}

How to use localization in C#

  • Add a Resource file to your project (you can call it "strings.resx") by doing the following:
    Right-click Properties in the project, select Add -> New Item... in the context menu, then in the list of Visual C# Items pick "Resources file" and name it strings.resx.
  • Add a string resouce in the resx file and give it a good name (example: name it "Hello" with and give it the value "Hello")
  • Save the resource file (note: this will be the default resource file, since it does not have a two-letter language code)
  • Add references to your program: System.Threading and System.Globalization

Run this code:

Console.WriteLine(Properties.strings.Hello);

It should print "Hello".

Now, add a new resource file, named "strings.fr.resx" (note the "fr" part; this one will contain resources in French). Add a string resource with the same name as in strings.resx, but with the value in French (Name="Hello", Value="Salut"). Now, if you run the following code, it should print Salut:

Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fr-FR");
Console.WriteLine(Properties.strings.Hello);

What happens is that the system will look for a resource for "fr-FR". It will not find one (since we specified "fr" in your file"). It will then fall back to checking for "fr", which it finds (and uses).

The following code, will print "Hello":

Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
Console.WriteLine(Properties.strings.Hello);

That is because it does not find any "en-US" resource, and also no "en" resource, so it will fall back to the default, which is the one that we added from the start.

You can create files with more specific resources if needed (for instance strings.fr-FR.resx and strings.fr-CA.resx for French in France and Canada respectively). In each such file you will need to add the resources for those strings that differ from the resource that it would fall back to. So if a text is the same in France and Canada, you can put it in strings.fr.resx, while strings that are different in Canadian french could go into strings.fr-CA.resx.

How to read a line from a text file in c/c++?

im not really that good at C , but i believe this code should get you complete single line till the end...

 #include<stdio.h>

 int main()   
{      
  char line[1024];    
  FILE *f=fopen("filename.txt","r");    
  fscanf(*f,"%[^\n]",line);    
  printf("%s",line);    
 }    

How to justify navbar-nav in Bootstrap 3

You can justify the navbar contents by using:

@media (min-width: 768px){
  .navbar-nav{
     margin: 0 auto;
     display: table;
     table-layout: fixed;
     float: none;
  }
}  

See this live: http://jsfiddle.net/panchroma/2fntE/

Good luck!

Difference between using Throwable and Exception in a try catch

Thowable catches really everything even ThreadDeath which gets thrown by default to stop a thread from the now deprecated Thread.stop() method. So by catching Throwable you can be sure that you'll never leave the try block without at least going through your catch block, but you should be prepared to also handle OutOfMemoryError and InternalError or StackOverflowError.

Catching Throwable is most useful for outer server loops that delegate all sorts of requests to outside code but may itself never terminate to keep the service alive.

How to write macro for Notepad++?

I just did this in v5.9.1. Just go to the Macro Menu, click "Start Recording", perform your 3 replace all commands, then stop recording. You can then select "Save Current Recorded Macro", and play it back as often as you like, and it will perform the replaces as you expect.

Full width layout with twitter bootstrap

The easiest way with BS3 is to reset the max-width and padding set by BS3 CSS simply like this. You get again a container-fluid :

.container{
  max-width:100%;
  padding:0;
}

Using await outside of an async function

There is always this of course:

(async () => {
    await ...

    // all of the script.... 

})();
// nothing else

This makes a quick function with async where you can use await. It saves you the need to make an async function which is great! //credits Silve2611

How to convert string to date to string in Swift iOS?

Swift 2 and below

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)

And in Swift 3 and higher this would now be written as:

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.string(from: date)

What's the difference between a null pointer and a void pointer?

Both void and null pointers point to a memory location in the end.

A null pointer points to place (in a memory segment) which is usually the 0th address of memory segment. It is almost all about how the underlying OS treat that "reserved" memory location (an implementation detail) when you try to access it to read/write or dereference. For example, that particular memory location can be marked as "non-accessible" and throws an expection when it's accessed.

A void pointer can point to anywhere and potentially represent any type (primitive, reference-type, and including null).

As someone nicely put above, null pointer represents a value whereas void* represents a type more than a value.

Create instance of generic type in Java?

what you can do is -

  1. First declare the variable of that generic class

    2.Then make a constructor of it and instantiate that object

  2. Then use it wherever you want to use it

example-

1

private Class<E> entity;

2

public xyzservice(Class<E> entity) {
        this.entity = entity;
    }



public E getEntity(Class<E> entity) throws InstantiationException, IllegalAccessException {
        return entity.newInstance();
    }

3.

E e = getEntity(entity);

PHP Echo a large block of text

Heredoc syntax can be very useful:

// start the string with 3 <'s and then a word
// it doesn't have to be any particular string or length
// but it's common to make it in all caps.
echo <<< EOT
    in here is your string
    it has the same variable substitution rules
    as a double quoted string.
    when you end it, put the indicator word at the
    start of the line (no spaces before it)
    and put a semicolon after it
EOT;

javac: invalid target release: 1.8

Installing a newer release of IDEA Community (2018.3 instead of 2017.x) was solved my issue with same error but java version:11. Reimport hadn't worked for me. But it worth a try.

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

The annotation @JoinColumn indicates that this entity is the owner of the relationship (that is: the corresponding table has a column with a foreign key to the referenced table), whereas the attribute mappedBy indicates that the entity in this side is the inverse of the relationship, and the owner resides in the "other" entity. This also means that you can access the other table from the class which you've annotated with "mappedBy" (fully bidirectional relationship).

In particular, for the code in the question the correct annotations would look like this:

@Entity
public class Company {
    @OneToMany(mappedBy = "company",
               orphanRemoval = true,
               fetch = FetchType.LAZY,
               cascade = CascadeType.ALL)
    private List<Branch> branches;
}

@Entity
public class Branch {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "companyId")
    private Company company;
}

How to use string.substr() function?

Possible solution without using substr()

#include<iostream>
#include<string>

using namespace std;


int main() {
    string c="12345";
    int p=0;

    for(int i=0;i<c.length();i++) {
        cout<<c[i];
        p++;

        if (p % 2 == 0 && i != c.length()-1) {
            cout<<" "<<c[i];
            p++;
        }
    }
}

How to select clear table contents without destroying the table?

How about:

ACell.ListObject.DataBodyRange.Rows.Delete

That will keep your table structure and headings, but clear all the data and rows.

EDIT: I'm going to just modify a section of my answer from your previous post, as it does mostly what you want. This leaves just one row:

With loSource
   .Range.AutoFilter
   .DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
   .DataBodyRange.Rows(1).Specialcells(xlCellTypeConstants).ClearContents
End With

If you want to leave all the rows intact with their formulas and whatnot, just do:

With loSource
   .Range.AutoFilter
   .DataBodyRange.Specialcells(xlCellTypeConstants).ClearContents
End With

Which is close to what @Readify suggested, except it won't clear formulas.

function to return a string in java

Your code is fine. There's no problem with returning Strings in this manner.

In Java, a String is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String around without worrying that it would disapper on you, or that someone somewhere would modify it.

If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:

public String time_to_string(long t) // time in milliseconds
{
    if (t < 0)
    {
        return "-";
    }
    else
    {
        int secs = (int)(t/1000);
        int mins = secs/60;
        secs = secs - (mins * 60);
        return String.format("%d:%02d", mins, secs);
    }
}

As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans and have replaced the mix of string concatenation and String.format() with a single call to String.format().

How can I save an image with PIL?

The error regarding the file extension has been handled, you either use BMP (without the dot) or pass the output name with the extension already. Now to handle the error you need to properly modify your data in the frequency domain to be saved as an integer image, PIL is telling you that it doesn't accept float data to save as BMP.

Here is a suggestion (with other minor modifications, like using fftshift and numpy.array instead of numpy.asarray) for doing the conversion for proper visualization:

import sys
import numpy
from PIL import Image

img = Image.open(sys.argv[1]).convert('L')

im = numpy.array(img)
fft_mag = numpy.abs(numpy.fft.fftshift(numpy.fft.fft2(im)))

visual = numpy.log(fft_mag)
visual = (visual - visual.min()) / (visual.max() - visual.min())

result = Image.fromarray((visual * 255).astype(numpy.uint8))
result.save('out.bmp')

Develop Android app using C#

You could use Mono for Android:

http://xamarin.com/monoforandroid

An alternative is dot42:

http://www.dot42.com/

dot42 provides a free community licence as well as a professional licence for $399.

How to get file size in Java

Try this:

long length = f.length();

How to make Python speak

Combining the following sources, the following code works on Windows, Linux and macOS using just the platform and os modules:

tx = input("Text to say >>> ")
tx = repr(tx)

import os
import platform

syst = platform.system()
if syst == 'Linux' and platform.linux_distribution()[0] == "Ubuntu":
    os.system('spd-say %s' % tx)
elif syst == 'Windows':
    os.system('PowerShell -Command "Add-Type –AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak(%s);"' % tx)
elif syst == 'Darwin':
    os.system('say %s' % tx)
else:
    raise RuntimeError("Operating System '%s' is not supported" % syst)

Note: This method is not secure and could be exploited by malicious text.

Convert list of dictionaries to a pandas DataFrame

How do I convert a list of dictionaries to a pandas DataFrame?

The other answers are correct, but not much has been explained in terms of advantages and limitations of these methods. The aim of this post will be to show examples of these methods under different situations, discuss when to use (and when not to use), and suggest alternatives.


DataFrame(), DataFrame.from_records(), and .from_dict()

Depending on the structure and format of your data, there are situations where either all three methods work, or some work better than others, or some don't work at all.

Consider a very contrived example.

np.random.seed(0)
data = pd.DataFrame(
    np.random.choice(10, (3, 4)), columns=list('ABCD')).to_dict('r')

print(data)
[{'A': 5, 'B': 0, 'C': 3, 'D': 3},
 {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 {'A': 2, 'B': 4, 'C': 7, 'D': 6}]

This list consists of "records" with every keys present. This is the simplest case you could encounter.

# The following methods all produce the same output.
pd.DataFrame(data)
pd.DataFrame.from_dict(data)
pd.DataFrame.from_records(data)

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

Word on Dictionary Orientations: orient='index'/'columns'

Before continuing, it is important to make the distinction between the different types of dictionary orientations, and support with pandas. There are two primary types: "columns", and "index".

orient='columns'
Dictionaries with the "columns" orientation will have their keys correspond to columns in the equivalent DataFrame.

For example, data above is in the "columns" orient.

data_c = [
 {'A': 5, 'B': 0, 'C': 3, 'D': 3},
 {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 {'A': 2, 'B': 4, 'C': 7, 'D': 6}]
pd.DataFrame.from_dict(data_c, orient='columns')

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

Note: If you are using pd.DataFrame.from_records, the orientation is assumed to be "columns" (you cannot specify otherwise), and the dictionaries will be loaded accordingly.

orient='index'
With this orient, keys are assumed to correspond to index values. This kind of data is best suited for pd.DataFrame.from_dict.

data_i ={
 0: {'A': 5, 'B': 0, 'C': 3, 'D': 3},
 1: {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 2: {'A': 2, 'B': 4, 'C': 7, 'D': 6}}
pd.DataFrame.from_dict(data_i, orient='index')

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

This case is not considered in the OP, but is still useful to know.

Setting Custom Index

If you need a custom index on the resultant DataFrame, you can set it using the index=... argument.

pd.DataFrame(data, index=['a', 'b', 'c'])
# pd.DataFrame.from_records(data, index=['a', 'b', 'c'])

   A  B  C  D
a  5  0  3  3
b  7  9  3  5
c  2  4  7  6

This is not supported by pd.DataFrame.from_dict.

Dealing with Missing Keys/Columns

All methods work out-of-the-box when handling dictionaries with missing keys/column values. For example,

data2 = [
     {'A': 5, 'C': 3, 'D': 3},
     {'A': 7, 'B': 9, 'F': 5},
     {'B': 4, 'C': 7, 'E': 6}]
# The methods below all produce the same output.
pd.DataFrame(data2)
pd.DataFrame.from_dict(data2)
pd.DataFrame.from_records(data2)

     A    B    C    D    E    F
0  5.0  NaN  3.0  3.0  NaN  NaN
1  7.0  9.0  NaN  NaN  NaN  5.0
2  NaN  4.0  7.0  NaN  6.0  NaN

Reading Subset of Columns

"What if I don't want to read in every single column"? You can easily specify this using the columns=... parameter.

For example, from the example dictionary of data2 above, if you wanted to read only columns "A', 'D', and 'F', you can do so by passing a list:

pd.DataFrame(data2, columns=['A', 'D', 'F'])
# pd.DataFrame.from_records(data2, columns=['A', 'D', 'F'])

     A    D    F
0  5.0  3.0  NaN
1  7.0  NaN  5.0
2  NaN  NaN  NaN

This is not supported by pd.DataFrame.from_dict with the default orient "columns".

pd.DataFrame.from_dict(data2, orient='columns', columns=['A', 'B'])
ValueError: cannot use columns parameter with orient='columns'

Reading Subset of Rows

Not supported by any of these methods directly. You will have to iterate over your data and perform a reverse delete in-place as you iterate. For example, to extract only the 0th and 2nd rows from data2 above, you can use:

rows_to_select = {0, 2}
for i in reversed(range(len(data2))):
    if i not in rows_to_select:
        del data2[i]

pd.DataFrame(data2)
# pd.DataFrame.from_dict(data2)
# pd.DataFrame.from_records(data2)

     A    B  C    D    E
0  5.0  NaN  3  3.0  NaN
1  NaN  4.0  7  NaN  6.0

The Panacea: json_normalize for Nested Data

A strong, robust alternative to the methods outlined above is the json_normalize function which works with lists of dictionaries (records), and in addition can also handle nested dictionaries.

pd.json_normalize(data)

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6
pd.json_normalize(data2)

     A    B  C    D    E
0  5.0  NaN  3  3.0  NaN
1  NaN  4.0  7  NaN  6.0

Again, keep in mind that the data passed to json_normalize needs to be in the list-of-dictionaries (records) format.

As mentioned, json_normalize can also handle nested dictionaries. Here's an example taken from the documentation.

data_nested = [
  {'counties': [{'name': 'Dade', 'population': 12345},
                {'name': 'Broward', 'population': 40000},
                {'name': 'Palm Beach', 'population': 60000}],
   'info': {'governor': 'Rick Scott'},
   'shortname': 'FL',
   'state': 'Florida'},
  {'counties': [{'name': 'Summit', 'population': 1234},
                {'name': 'Cuyahoga', 'population': 1337}],
   'info': {'governor': 'John Kasich'},
   'shortname': 'OH',
   'state': 'Ohio'}
]
pd.json_normalize(data_nested, 
                          record_path='counties', 
                          meta=['state', 'shortname', ['info', 'governor']])

         name  population    state shortname info.governor
0        Dade       12345  Florida        FL    Rick Scott
1     Broward       40000  Florida        FL    Rick Scott
2  Palm Beach       60000  Florida        FL    Rick Scott
3      Summit        1234     Ohio        OH   John Kasich
4    Cuyahoga        1337     Ohio        OH   John Kasich

For more information on the meta and record_path arguments, check out the documentation.


Summarising

Here's a table of all the methods discussed above, along with supported features/functionality.

enter image description here

* Use orient='columns' and then transpose to get the same effect as orient='index'.

Python JSON serialize a Decimal object

this can be done by adding

    elif isinstance(o, decimal.Decimal):
        yield str(o)

in \Lib\json\encoder.py:JSONEncoder._iterencode, but I was hoping for a better solution

npm start error with create-react-app

it's possible that conflict with other library, delete node_modules and again npm install.

Download a file from HTTPS using download.file()

You can set global options and try-

options('download.file.method'='curl')
download.file(URL, destfile = "./data/data.csv", method="auto")

For issue refer to link- https://stat.ethz.ch/pipermail/bioconductor/2011-February/037723.html

Python's "in" set operator

Sets behave different than dicts, you need to use set operations like issubset():

>>> k
{'ip': '123.123.123.123', 'pw': 'test1234', 'port': 1234, 'debug': True}
>>> set('ip,port,pw'.split(',')).issubset(set(k.keys()))
True
>>> set('ip,port,pw'.split(',')) in set(k.keys())
False

how much memory can be accessed by a 32 bit machine?

What's typically meant by 32-bit or 64-bit machine is the size of the externally visible ("architected") general-purpose integer registers.

This has very little to do with how the hardware is built though. For example, let's consider the (long obsolete) Intel Pentium Pro. It's normally considered a "32-bit" processor, even though it supports up to 36-bit physical addresses, has a 64-bit wide data bus, and internally computations on all supported operand types are carried out in a single set of registers (which are therefore 80 bits wide, to support the largest floating point type).

At least in the case of Intel processors, even though larger physical addressing has been available for a long time, the largest amount of memory directly visible within the address space of any one process on a 32-bit processor is also limited to 4 gigabytes (32-bit addressing). The 36-bit physical addressing allows addressing up to 64 gigabytes of RAM, but only 4 gigabytes of that can be directly visible at any given time.

The change to 64-bit machines mostly involved changing what was made visible to the user (or to code at the assembly language level). Again, what you see is rarely identical to what's real. For example, most 64-bit code sees pointers/addresses as being 64 bits, but actual processors don't support that large of addresses. Current CPUs support 48-bit virtual addresses, and (at least as far as I've noticed) a maximum of 40 bits of physical addressing. On the other hand, they're designed so in the future, when larger memory becomes practical, they can extend the physical addressing out to 48 bits without affecting software at all. Even when they increase the 48-bit virtual addressing, in a typical case it'll only affect a small amount of the operating system kernel (normal code is unaffected, because it already assumed addresses are 64 bits).

So, no: a 64-bit machine does not really support up to 64 bits of physical addressing, but most typical 64-bit software should remain compatible with a future processor that did support directly addressing that much RAM.

CKEditor instance already exists

If you know the name of the editor then it is pretty simple to do this..

For example if the name of the editor is editor1 (this is the id of div or textarea) then you simply check like this

if(CKEDITOR.instances['editor1']){
   // Instance present
}else{
   // Instance not present 
} 

If you want to get the number of initialized editor's then do like the below

for(let inst of CKEDITOR.instances){
   // inst is an Obj of editor instance
   // inst.name will give the name of the editor instance
}

"Parse Error : There is a problem parsing the package" while installing Android application

I'm not repeating what is instructed here to input the Key store, password, etc. Try

Build -> Generate Signed APK -> [ Input ] ---Next---> select BOTH

  • V1 (Jar Signature)
  • V2 (Full APK Signature)

I don't know why, but at least it worked in my situation.

Array to String PHP?

implode():

<?php
$string = implode('|',$types);

However, Incognito is right, you probably don't want to store it that way -- it's a total waste of the relational power of your database.

If you're dead-set on serializing, you might also consider using json_encode()

How do I split a string in Rust?

Use split()

let mut split = "some string 123 ffd".split("123");

This gives an iterator, which you can loop over, or collect() into a vector.

for s in split {
    println!("{}", s)
}
let vec = split.collect::<Vec<&str>>();
// OR
let vec: Vec<&str> = split.collect();

How to insert a new key value pair in array in php?

foreach($test_package_data as $key=>$data ) {

   $category_detail_arr = $test_package_data[$key]['category_detail'];

   foreach( $category_detail_arr as $i=>$value ) {
     $test_package_data[$key]['category_detail'][$i]['count'] = $some_value;////<----Here
   }

}

Uploading images using Node.js, Express, and Mongoose

See, the best thing you can do is to just upload the image to the disk and save the URL in MongoDB. Rest when you retrieve the image again. Just specify the URL, and you will get an image. The code for uploading is as follows.

app.post('/upload', function(req, res) {
    // Get the temporary location of the file
    var tmp_path = req.files.thumbnail.path;
    // Set where the file should actually exists - in this case it is in the "images" directory.
    target_path = '/tmp/' + req.files.thumbnail.name;
    // Move the file from the temporary location to the intended location
    fs.rename(tmp_path, target_path, function(err) {
        if (err)
            throw err;
        // Delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files.
        fs.unlink(tmp_path, function() {
            if (err)
                throw err;
            //
        });
    });
});

Now save the target path in your MongoDB database.

Again, while retrieving the image, just extract the URL from the MongoDB database, and use it on this method.

fs.readFile(target_path, "binary", function(error, file) {
    if(error) {
        res.writeHead(500, {"Content-Type": "text/plain"});
        res.write(error + "\n");
        res.end();
    }
    else {
        res.writeHead(200, {"Content-Type": "image/png"});
        res.write(file, "binary");
    }
});

Removing duplicate values from a PowerShell array

Use Select-Object (whose alias is select) with the -Unique switch; e.g.:

$a = @(1,2,3,4,5,5,6,7,8,9,0,0)
$a = $a | select -Unique

Assign static IP to Docker container

Not a direct answer but it could help.

I run most of my dockerized services tied to own static ips using the next approach:

  1. I create ip aliases for all services on docker host
  2. Then I run each service redirecting ports from this ip into container so each service have own static ip which could be used by external users and other containers.

Sample:

docker run --name dns --restart=always -d -p 172.16.177.20:53:53/udp dns
docker run --name registry --restart=always -d -p 172.16.177.12:80:5000 registry
docker run --name cache --restart=always -d -p 172.16.177.13:80:3142 -v /data/cache:/var/cache/apt-cacher-ng cache
docker run --name mirror --restart=always -d -p 172.16.177.19:80:80 -v /data/mirror:/usr/share/nginx/html:ro mirror
...

Clear the cache in JavaScript

You can call window.location.reload(true) to reload the current page. It will ignore any cached items and retrieve new copies of the page, css, images, JavaScript, etc from the server. This doesn't clear the whole cache, but has the effect of clearing the cache for the page you are on.

However, your best strategy is to version the path or filename as mentioned in various other answers. In addition, see Revving Filenames: don’t use querystring for reasons not to use ?v=n as your versioning scheme.

Why does only the first line of this Windows batch file execute but all three lines execute in a command shell?

It should be that the particular mvn command execs and does not return, thereby not executing the rest of the commands.

How to remove the last character from a string?

For kotlin check out

    val string = "<<<First Grade>>>"
    println(string.drop(6)) // st Grade>>>
    println(string.dropLast(6)) // <<<First Gr
    println(string.dropWhile { !it.isLetter() }) // First Grade>>>
    println(string.dropLastWhile { !it.isLetter() }) // <<<First Grade

SQL Server table creation date query

For SQL Server 2005 upwards:

SELECT [name] AS [TableName], [create_date] AS [CreatedDate] FROM sys.tables

For SQL Server 2000 upwards:

SELECT so.[name] AS [TableName], so.[crdate] AS [CreatedDate]
FROM INFORMATION_SCHEMA.TABLES AS it, sysobjects AS so 
WHERE it.[TABLE_NAME] = so.[name]

How do I close a tkinter window?

def quit()
    root.quit()

or

def quit()
    root.destroy()

Should import statements always be at the top of a module?

Just to complete Moe's answer and the original question:

When we have to deal with circular dependences we can do some "tricks". Assuming we're working with modules a.py and b.py that contain x() and b y(), respectively. Then:

  1. We can move one of the from imports at the bottom of the module.
  2. We can move one of the from imports inside the function or method that is actually requiring the import (this isn't always possible, as you may use it from several places).
  3. We can change one of the two from imports to be an import that looks like: import a

So, to conclude. If you aren't dealing with circular dependencies and doing some kind of trick to avoid them, then it's better to put all your imports at the top because of the reasons already explained in other answers to this question. And please, when doing this "tricks" include a comment, it's always welcome! :)

Creating a "logical exclusive or" operator in Java

Here is a var arg XOR method for java...

public static boolean XOR(boolean... args) {
  boolean r = false;
  for (boolean b : args) {
    r = r ^ b;
  }
  return r;
}

Enjoy

jquery validate check at least one checkbox

Mmm first your id attributes must be unique, your code is likely to be

<form>
<input class='roles' name='roles' type='checkbox' value='1' />
<input class='roles' name='roles' type='checkbox' value='2' />
<input class='roles' name='roles' type='checkbox' value='3' />
<input class='roles' name='roles' type='checkbox' value='4' />
<input class='roles' name='roles' type='checkbox' value='5' />
<input type='submit' value='submit' />
</form>

For your problem :

if($('.roles:checkbox:checked').length == 0)
  // no checkbox checked, do something...
else
  // at least one checkbox checked...

BUT, remember that a JavaScript form validation is only indicative, all validations MUST be done server-side.

Printing out a number in assembly language?

Assuming you are writing a bootloader or other application that has access to the BIOS, here is a rough sketch of what you can do:

  • Isolate the first digit of the hex byte
  • If it is greater than 9 (i.e. 0x0A to 0x0F), subtract 10 from it (scaling it down to 0 to 5), and add 'A' (0x41).
  • If it is less than or equal to 9 (i.e. 0x00 to 0x09), add '0' to it.
  • Repeat this with the next hex digit.

Here is my implementation of this:

; Prints AL in hex.
printhexb:
    push ax
    shr al, 0x04
    call print_nibble
    pop ax
    and al, 0x0F
    call print_nibble
    ret
print_nibble:
    cmp al, 0x09
    jg .letter
    add al, 0x30
    mov ah, 0x0E
    int 0x10
    ret
.letter:
    add al, 0x37
    mov ah, 0x0E
    int 0x10
    ret   

pandas three-way joining multiple dataframes on columns

Assumed imports:

import pandas as pd

John Galt's answer is basically a reduce operation. If I have more than a handful of dataframes, I'd put them in a list like this (generated via list comprehensions or loops or whatnot):

dfs = [df0, df1, df2, dfN]

Assuming they have some common column, like name in your example, I'd do the following:

df_final = reduce(lambda left,right: pd.merge(left,right,on='name'), dfs)

That way, your code should work with whatever number of dataframes you want to merge.

Edit August 1, 2016: For those using Python 3: reduce has been moved into functools. So to use this function, you'll first need to import that module:

from functools import reduce

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

I was getting this same warning everytime I was doing 'maven clean'. I found the solution :

Step - 1 Right click on your project in Eclipse

Step - 2 Click Properties

Step - 3 Select Maven in the left hand side list.

Step - 4 You will notice "pom.xml" in the Active Maven Profiles text box on the right hand side. Clear it and click Apply.

Below is the screen shot :

Properties dialog box

Hope this helps. :)

Declare an empty two-dimensional array in Javascript?

Create an object and push that object into an array

 var jSONdataHolder = function(country, lat, lon) {

    this.country = country;
    this.lat = lat;
    this.lon = lon;
}

var jSONholderArr = [];

jSONholderArr.push(new jSONdataHolder("Sweden", "60", "17"));
jSONholderArr.push(new jSONdataHolder("Portugal", "38", "9"));
jSONholderArr.push(new jSONdataHolder("Brazil", "23", "-46"));

var nObj = jSONholderArr.length;
for (var i = 0; i < nObj; i++) {
   console.log(jSONholderArr[i].country + "; " + jSONholderArr[i].lat + "; " + 
   jSONholderArr[i].lon);

}

Button text toggle in jquery

Use a custom ID if possible if you would like to apply the action to only that button.

HTML

<button class="pushDontpush">PUSH ME</button>

jQuery

$("#pushDontpush").click(function() { 
    if ($(this).text() == "PUSH ME") { 
        $(this).text("DON'T PUSH ME"); 
    } else { 
        $(this).text("PUSH ME"); 
    }; 
});

Working CodePen: Toggle text in button

Laravel Checking If a Record Exists

Simple, comfortable and understandable with Validator

class CustomerController extends Controller
{
    public function register(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:customers',
            'phone' => 'required|string|max:255|unique:customers',
            'password' => 'required|string|min:6|confirmed',
        ]);

        if ($validator->fails()) {
            return response(['errors' => $validator->errors()->all()], 422);
        }

connecting MySQL server to NetBeans

I just had the same issue with Netbeans 8.2 and trying to connect to mySQL server on a Mac OS machine. The only thing that worked for me was to add the following to the url of the connection string: &serverTimezone=UTC (or if you are connecting via Hibernate.cfg.xml then escape the & as &) Not surprisingly I found the solution on this stack overflow post also:

MySQL JDBC Driver 5.1.33 - Time Zone Issue

Best Regards, Claudio

How to disable horizontal scrolling of UIScrollView?

UPDATED: (After @EranMarom pointed out on his comment)

You can stop horizontal scrolling or vertical scrolling in the ScrollViewDelegate Method. Here it is how,

Stops Horizontal Scrolling:

If you want to scroll horizontally, then you need to increase the contentOffset.x. Preventing that stops the scrollview scroll in horizontal direction.

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    sender.contentOffset.x = 0.0
}

Stops Vertical Scrolling:

If you want to scroll vertically, then you need to increase the contentOffset.y. Preventing that stops the scrollview scroll in vertical direction.

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    sender.contentOffset.y = 0.0
}

Above code prevents the changes in x and y of a scrollview contentOffset and it leads to stop the scrolling in scrollViewDidScroll: method.

How to get child element by index in Jquery?

Doesn't nth-child return siblings rather than children?

var $selFirst = $(".second:nth-child(1)");

will return the first element with the class '.second'.

var $selFirst = $(".selector:nth-child(1)");

should give you the first sibling of class '.selector'

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

The accepted answer seems not adequate in several situations.

To check whether the localStorage or sessionStorage are supported, I use the following snippet from MDN.

function storageAvailable(type) {
    var storage;
    try {
        storage = window[type];
        var x = '__storage_test__';
        storage.setItem(x, x);
        storage.removeItem(x);
        return true;
    }
    catch(e) {
        return e instanceof DOMException && (
            // everything except Firefox
            e.code === 22 ||
            // Firefox
            e.code === 1014 ||
            // test name field too, because code might not be present
            // everything except Firefox
            e.name === 'QuotaExceededError' ||
            // Firefox
            e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
            // acknowledge QuotaExceededError only if there's something already stored
            (storage && storage.length !== 0);
    }
}

Use this snippet like this, and fallback to, for example, using cookie:

if (storageAvailable('localStorage')) {
  // Yippee! We can use localStorage awesomeness
}
else {
  // Too bad, no localStorage for us
  document.cookie = key + "=" + encodeURIComponent(value) + expires + "; path=/";
}

I have made the fallbackstorage package which uses this snippet to check for the storage availability and fallback to a manually implemented MemoryStorage.

import {getSafeStorage} from 'fallbackstorage'

getSafeStorage().setItem('test', '1') // always work

Javascript get object key name

Here is a simple example, it will help you to get object key name.

var obj ={parts:{costPart:1000, salesPart: 2000}}; console.log(Object.keys(obj));

the output would be parts.

Regular expression to find two strings anywhere in input

you don't have to use regex. In your favourite language, split on spaces, go over the splitted words, check for cat and mat. eg in Python

>>> for line in open("file"):
...     g=0;f=0
...     s = line.split()
...     for item in s:
...         if item =="cat": f=1
...         if item =="mat": g=1
...     if (g,f)==(1,1): print "found: " ,line.rstrip()

found:  The cat slept on the mat in front of the fire.
found:  At 5:00 pm, I found the cat scratching the wool off the mat.

Sequence contains no elements?

Well, what is ID here? In particular, is it a local variable? There are some scope / capture issues, which mean that it may be desirable to use a second variable copy, just for the query:

var id = ID;
BlogPost post = (from p in dc.BlogPosts
                 where p.BlogPostID == id
                 select p).Single();

Also; if this is LINQ-to-SQL, then in the current version you get a slightly better behaviour if you use the form:

var id = ID;
BlogPost post = dc.BlogPosts.Single(p => p.BlogPostID == id);

How to set the font size in Emacs?

Here's an option for resizing the font heights interactively, one point at a time:

;; font sizes
(global-set-key (kbd "s-=")
                (lambda ()
                  (interactive)
                  (let ((old-face-attribute (face-attribute 'default :height)))
                    (set-face-attribute 'default nil :height (+ old-face-attribute 10)))))

(global-set-key (kbd "s--")
                (lambda ()
                  (interactive)
                  (let ((old-face-attribute (face-attribute 'default :height)))
                    (set-face-attribute 'default nil :height (- old-face-attribute 10)))))

This is preferable when you want to resize text in all buffers. I don't like solutions using text-scale-increase and text-scale-decrease as line numbers in the gutter can get cut off afterwards.

Why are you not able to declare a class as static in Java?

Everything we code in java goes into a class. Whenever we run a class JVM instantiates an object. JVM can create a number of objects, by definition Static means you have the same set of copy to all objects.

So, if Java would have allowed the top class to be static whenever you run a program it creates an Object and keeps overriding on to the same Memory Location.

If You are just replacing the object every time you run it whats the point of creating it?

So that is the reason Java got rid of the static for top-Level Class.

There might be more concrete reasons but this made much logical sense to me.

How to bring back "Browser mode" in IE11?

[UPDATE]

The original question, and the answer below applied specifically to the IE11 preview releases.

The final release version of IE11 does in fact provide the ability to switch browser modes from the Emulation tab in the dev tools:

Screenshot showing browser mode selection in the emulation tab

Having said that, the advice I've given here (and elsewhere) to avoid using compatibility modes for testing is still valid: If you want to test your site for compatibility with older IE versions, you should always do your testing in a real copy of those IE version.

However, this does mean that the registry hack described in @EugeneXa's answer to bring back the old dev tools is no longer necessary, since the new dev tools do now have the feature he was missing.


[ORIGINAL ANSWER]

The IE devs have deliberately deprecated the ability to switch browser mode.

There are not many reasons why people would be switching modes in the dev tools, but one of the main reasons is because they want to test their site in old IE versions. Unfortunately, the various compatibility modes that IE supplies have never really been fully compatible with old versions of IE, and testing using compat mode is simply not a good enough substitute for testing in real copies of IE8, IE9, etc.

The IE devs have recognised this and are deliberately making it harder for devs to make this mistake.

The best practice is to use real copies of each IE version to test your site instead.

The various compatiblity modes are still available inside IE11, but can only be accessed if a site explicitly states that it wants to run in compat mode. You would do this by including an X-UA-Compatible header on your page.

And the Document Mode drop-box is still available, but will only ever offer the options of "Edge" (that is, the best mode available to the current IE version, so IE11 mode in IE11) or the mode that the page is running in.

So if you go to a page that is loaded in compat mode, you will have the option to switch between the specific compat mode that the page was loaded in or IE11 "Edge" mode.

And if you go to a page that loads in IE11 mode, then you will only be offered the 'edge' mode and nothing else.

This means that it does still allow you to test how a compat mode page reacts to being updated to work in Edge mode, which is about the only really legitimate use-case for the document mode drop-box anyway.

The IE11 Document Mode drop box has an i icon next to it which takes you to the modern.ie website. The point of this is to encourage you to download the VMs that MS are supplying for us to test our sites using real copies of each version of IE. This will give you a much more accurate testing experience, and is strongly enouraged as a much better practice than testing by switching the mode in dev tools.

Hope that explains things a bit for you.

Pass form data to another page with php

The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

index.php

<html>
<body>

<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>

</body>
</html> 

site2.php

 <html>
 <body>

 Hello <?php echo $_POST["name"]; ?>!<br>
 Your mail is <?php echo $_POST["mail"]; ?>.

 </body>
 </html> 

output

Hello "name" !

Your email is "[email protected]" .

_tkinter.TclError: no display name and no $DISPLAY environment variable

I had this same issue trying to run a simple tkinter app remotely on a Raspberry Pi. In my case I did want to display the tkinter GUI on the pi display, but I want to be able to execute it over SSH from my host machine. I was also not using matplotlib, so that wasn't the cause of my issue. I was able to resolve the issue by setting the DISPLAY environment variable as the error suggests with the command:

export DISPLAY=:0.0

A good explanation of what the display environment variable is doing and why the syntax is so odd can be found here: https://askubuntu.com/questions/432255/what-is-display-environment-variable

Redirect to external URI from ASP.NET MVC controller

Try this (I've used Home controller and Index View):

return RedirectToAction("Index", "Home");

How to use a keypress event in AngularJS?

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
Informe your name:<input type="text" ng-model="pergunta" ng-keypress="pressionou_enter($event)" ></input> 
<button ng-click="chamar()">submit</button>
<h1>{{resposta}}</h1> 
</div>
<script>
var app = angular.module('myApp', []);
//create a service mitsuplik
app.service('mitsuplik', function() {
    this.myFunc = function (parametro) {
        var tmp = ""; 
        for (var x=0;x<parametro.length;x++)
            {
            tmp = parametro.substring(x,x+1) + tmp;
            } 
        return tmp;
    }
});
//Calling our service
app.controller('myCtrl', function($scope, mitsuplik) { 
  $scope.chamar = function() { 
        $scope.resposta = mitsuplik.myFunc($scope.pergunta); 
    };
  //if mitsuplik press [ENTER], execute too
  $scope.pressionou_enter = function(keyEvent) {
             if (keyEvent.which === 13) 
                { 
                $scope.chamar();
                }

    }
});
</script>
</body>
</html>

taking input of a string word by word

Put the line in a stringstream and extract word by word back:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    string t;
    getline(cin,t);

    istringstream iss(t);
    string word;
    while(iss >> word) {
        /* do stuff with word */
    }
}

Of course, you can just skip the getline part and read word by word from cin directly.

And here you can read why is using namespace std considered bad practice.

cast a List to a Collection

There have multiple solusions to convert list to a collection

Solution 1

List<Contact> CONTACTS = new ArrayList<String>();
// fill CONTACTS
Collection<Contact> c = CONTACTS;

Solution 2

private static final Collection<String> c = new ArrayList<String>(
                                                Arrays.asList("a", "b", "c"));

Solution 3

private static final Collection<Contact> = new ArrayList<Contact>(
                       Arrays.asList(new Contact("text1", "name1")
                                     new Contact("text2", "name2")));

Solution 4

List<? extends Contact> col = new ArrayList<Contact>(CONTACTS);

How to know if an object has an attribute in Python

I think what you are looking for is hasattr. However, I'd recommend something like this if you want to detect python properties-

try:
    getattr(someObject, 'someProperty')         
except AttributeError:
    print "Doesn't exist"
else
    print "Exists"

The disadvantage here is that attribute errors in the properties __get__ code are also caught.

Otherwise, do-

if hasattr(someObject, 'someProp'):
    #Access someProp/ set someProp
    pass

Docs:http://docs.python.org/library/functions.html
Warning:
The reason for my recommendation is that hasattr doesn't detect properties.
Link:http://mail.python.org/pipermail/python-dev/2005-December/058498.html

How do you grep a file and get the next 5 lines

Here is a sed solution:

sed '/19:55/{
N
N
N
N
N
s/\n/ /g
}' file.txt

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

    private const string strconneciton = "Data Source=.;Initial Catalog=Employees;Integrated Security=True";
    SqlConnection con = new SqlConnection(strconneciton);

    private void button1_Click(object sender, EventArgs e)
    {

        con.Open();
        SqlCommand cmd = new SqlCommand("insert into EmployeeData (Name,S/O,Address,Phone,CellNo,CNICNO,LicenseNo,LicenseDistrict,LicenseValidPhoto,ReferenceName,ReferenceContactNo) values ( '" + textName.Text + "','" + textSO.Text + "','" + textAddress.Text + "','" + textPhone.Text + "','" + textCell.Text + "','" + textCNIC.Text + "','" + textLicenseNo.Text + "','" + textLicenseDistrict.Text + "','" + textLicensePhoto.Text + "','" + textReferenceName.Text + "','" + textContact.Text + "' )", con);
        cmd.ExecuteNonQuery();
        con.Close();
    }

How do I detect a page refresh using jquery?

$('body').bind('beforeunload',function(){
   //do something
});

But this wont save any info for later, unless you were planning on saving that in a cookie somewhere (or local storage) and the unload event does not always fire in all browsers.


Example: http://jsfiddle.net/maniator/qpK7Y/

Code:

$(window).bind('beforeunload',function(){

     //save info somewhere

    return 'are you sure you want to leave?';

});

Should I use typescript? or I can just use ES6?

I've been using Typescript in my current angular project for about a year and a half and while there are a few issues with definitions every now and then the DefinitelyTyped project does an amazing job at keeping up with the latest versions of most popular libraries.

Having said that there is a definite learning curve when transitioning from vanilla JavaScript to TS and you should take into account the ability of you and your team to make that transition. Also if you are going to be using angular 1.x most of the examples you will find online will require you to translate them from JS to TS and overall there are not a lot of resources on using TS and angular 1.x together right now.

If you plan on using angular 2 there are a lot of examples using TS and I think the team will continue to provide most of the documentation in TS, but you certainly don't have to use TS to use angular 2.

ES6 does have some nice features and I personally plan on getting more familiar with it but I would not consider it a production-ready language at this point. Mainly due to a lack of support by current browsers. Of course, you can write your code in ES6 and use a transpiler to get it to ES5, which seems to be the popular thing to do right now.

Overall I think the answer would come down to what you and your team are comfortable learning. I personally think both TS and ES6 will have good support and long futures, I prefer TS though because you tend to get language features quicker and right now the tooling support (in my opinion) is a little better.

VBA copy rows that meet criteria to another sheet

You need to specify workseet. Change line

If Worksheet.Cells(i, 1).Value = "X" Then

to

If Worksheets("Sheet2").Cells(i, 1).Value = "X" Then

UPD:

Try to use following code (but it's not the best approach. As @SiddharthRout suggested, consider about using Autofilter):

Sub LastRowInOneColumn()
   Dim LastRow As Long
   Dim i As Long, j As Long

   'Find the last used row in a Column: column A in this example
   With Worksheets("Sheet2")
      LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
   End With

   MsgBox (LastRow)
   'first row number where you need to paste values in Sheet1'
   With Worksheets("Sheet1")
      j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
   End With 

   For i = 1 To LastRow
       With Worksheets("Sheet2")
           If .Cells(i, 1).Value = "X" Then
               .Rows(i).Copy Destination:=Worksheets("Sheet1").Range("A" & j)
               j = j + 1
           End If
       End With
   Next i
End Sub

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Below worked for me:

When you come to Server Configuration Screen, Change the Account Name of Database Engine Service to NT AUTHORITY\NETWORK SERVICE and continue installation and it will successfully install all components without any error. - See more at: https://superpctricks.com/sql-install-error-database-engine-recovery-handle-failed/

Can I access variables from another file?

Using Node.js you can export the variable via module.

//first.js
const colorCode = {
    black: "#000",
    white: "#fff"
};
module.exports = { colorCode };

Then, import the module/variable in second file using require.

//second.js
const { colorCode } = require('./first.js')

You can use the import and export aproach from ES6 using Webpack/Babel, but in Node.js you need to enable a flag, and uses the .mjs extension.

What is Dependency Injection?

The best definition I've found so far is one by James Shore:

"Dependency Injection" is a 25-dollar term for a 5-cent concept. [...] Dependency injection means giving an object its instance variables. [...].

There is an article by Martin Fowler that may prove useful, too.

Dependency injection is basically providing the objects that an object needs (its dependencies) instead of having it construct them itself. It's a very useful technique for testing, since it allows dependencies to be mocked or stubbed out.

Dependencies can be injected into objects by many means (such as constructor injection or setter injection). One can even use specialized dependency injection frameworks (e.g. Spring) to do that, but they certainly aren't required. You don't need those frameworks to have dependency injection. Instantiating and passing objects (dependencies) explicitly is just as good an injection as injection by framework.

IIS_IUSRS and IUSR permissions in IIS8

IIS_IUSRS group has prominence only if you are using ApplicationPool Identity. Even though you have this group looks empty at run time IIS adds to this group to run a worker process according to microsoft literature.

HTTP Request in Kotlin

If you are using Kotlin, you might as well keep your code as succinct as possible. The run method turns the receiver into this and returns the value of the block. this as HttpURLConnection creates a smart cast. bufferedReader().readText() avoids a bunch of boilerplate code.

return URL(url).run {
        openConnection().run {
            this as HttpURLConnection
            inputStream.bufferedReader().readText()
        }
}

You can also wrap this into an extension function.

fun URL.getText(): String {
    return openConnection().run {
                this as HttpURLConnection
                inputStream.bufferedReader().readText()
            }
}

And call it like this

return URL(url).getText()

Finally, if you are super lazy, you can extend the String class instead.

fun String.getUrlText(): String {
    return URL(this).run {
            openConnection().run {
                this as HttpURLConnection
                inputStream.bufferedReader().readText()
            }
    }
}

And call it like this

return "http://somewhere.com".getUrlText()

How to overcome "'aclocal-1.15' is missing on your system" warning?

The problem is not automake package, is the repository

sudo apt-get install automake

Installs version aclocal-1.4, that's why you can't find 1.5 (In Ubuntu 14,15)

Use this script to install latest https://github.com/gp187/nginx-builder/blob/master/fix/aclocal.sh

How to set editable true/false EditText in Android programmatically?

Since setEditable(false) is deprecated, use textView.setKeyListener(null); to make editText non-clickable.

SSRS - Checking whether the data is null

try like this

= IIF( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ) ) = -1, "",  FormatNumber(  MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ), "CellReading_Reading"),3)) )

Generate random string/characters in JavaScript

I have made a String prototype which can generate a random String with a given length.

You also can secify if you want special chars and you can avoid some.

/**
 * STRING PROTOTYPE RANDOM GENERATOR
 * Used to generate a random string
 * @param {Boolean} specialChars
 * @param {Number} length
 * @param {String} avoidChars
 */
String.prototype.randomGenerator = function (specialChars = false, length = 1, avoidChars = '') {
    let _pattern = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    _pattern += specialChars === true ? '(){}[]+-*/=' : '';
    if (avoidChars && avoidChars.length) {
        for (let char of avoidChars) {
            _pattern = _pattern.replace(char, '');
        }
    }
    let _random = '';
    for (let element of new Array(parseInt(length))) {
        _random += _pattern.charAt(Math.floor(Math.random() * _pattern.length));
    }
    return _random;
};

You can use like this :

// Generate password with specialChars which contains 10 chars and avoid iIlL chars
var password = String().randomGenerator(true, 10, 'iIlL');

Hope it helps.

Total memory used by Python process?

import os, win32api, win32con, win32process
han = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION|win32con.PROCESS_VM_READ, 0, os.getpid())
process_memory = int(win32process.GetProcessMemoryInfo(han)['WorkingSetSize'])

When does socket.recv(recv_size) return?

It'll have the same behavior as the underlying recv libc call see the man page for an official description of behavior (or read a more general description of the sockets api).

HTTPS setup in Amazon EC2

An old question but worth mentioning another option in the answers. In case the DNS system of your domain has been defined in Amazon Route 53, you can use Amazon CloudFront service in front of your EC2 and attach a free Amazon SSL certificate to it. This way you will benefit from both having a CDN for a faster content delivery and also securing you domain with HTTPS protocol.

How to run Java program in command prompt

A very general command prompt how to for java is

javac mainjava.java
java mainjava

You'll very often see people doing

javac *.java
java mainjava

As for the subclass problem that's probably occurring because a path is missing from your class path, the -c flag I believe is used to set that.

Format Date time in AngularJS

v.Dt is likely not a Date() object.

See http://jsfiddle.net/southerd/xG2t8/

but in your controller:

scope.v.Dt = Date.parse(scope.v.Dt);

How to write log to file

I prefer the simplicity and flexibility of the 12 factor app recommendation for logging. To append to a log file you can use shell redirection. The default logger in Go writes to stderr (2).

./app 2>> logfile

See also: http://12factor.net/logs

Memory address of an object in C#

Switch the alloc type:

GCHandle handle = GCHandle.Alloc(a, GCHandleType.Normal);

How do I discard unstaged changes in Git?

It seems like the complete solution is:

git clean -df
git checkout -- .

git clean removes all untracked files (warning: while it won't delete ignored files mentioned directly in .gitignore, it may delete ignored files residing in folders) and git checkout clears all unstaged changes.

Celery Received unregistered task of type (run example)

Using --settings did not work for me. I had to use the following to get it all to work:

celery --config=celeryconfig --loglevel=INFO

Here is the celeryconfig file that has the CELERY_IMPORTS added:

# Celery configuration file
BROKER_URL = 'amqp://'
CELERY_RESULT_BACKEND = 'amqp://'

CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'America/Los_Angeles'
CELERY_ENABLE_UTC = True

CELERY_IMPORTS = ("tasks",)

My setup was a little bit more tricky because I'm using supervisor to launch celery as a daemon.

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

Not sure about List<T> but Arrays are certainly do-able. And a little bit of magic makes it really easy to get to a List again.

public class UserHolder {
   [XmlElement("list")]
   public User[] Users { get; set; }

   [XmlIgnore]
   public List<User> UserList { get { return new List<User>(Users); } }
}

Python - Locating the position of a regex match in a string?

re.Match objects have a number of methods to help you with this:

>>> m = re.search("is", String)
>>> m.span()
(2, 4)
>>> m.start()
2
>>> m.end()
4

python - checking odd/even numbers and changing outputs on number size

Sample Instruction Given an integer, n, performing the following conditional actions:

  • If n is odd, print Weird
  • If n is even and in the inclusive range of 2 to 5, print Not Weird
  • If n is even and in the inclusive range of 6 to 20, print Weird
  • If n is even and greater than 20, print Not Weird
import math
n = int(input())

if n % 2 ==1:
    print("Weird")
elif n % 2==0 and n in range(2,6):
    print("Not Weird")
elif n % 2 == 0 and n in range(6,21):
    print("Weird")
elif n % 2==0 and n>20:
    print("Not Weird")

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

WE had this issue. everything was setup fine in terms of permissions and security.

after MUCH needling around in the haystack. the issue was some sort of heuristics. in the email body , anytime a certain email address was listed, we would get the above error message from our exchange server.

it took 2 days of crazy testing and hair pulling to find this.

so if you have checked everything out, try changing the email body to only the word 'test'. If after that, your email goes out fine, you are having some sort of spam/heuristic filter issue like we were

Git Pull is Not Possible, Unmerged Files

Ryan Stewart's answer was almost there. In the case where you actually don't want to delete your local changes, there's a workflow you can use to merge:

  • Run git status. It will give you a list of unmerged files.
  • Merge them (by hand, etc.)
  • Run git commit

Git will commit just the merges into a new commit. (In my case, I had additional added files on disk, which weren't lumped into that commit.)

Git then considers the merge successful and allows you to move forward.

is inaccessible due to its protection level

In your base class Clubs the following are declared protected

  • club;
  • distance;
  • cleanclub;
  • scores;
  • par;
  • hole;

which means these can only be accessed by the class itself or any class which derives from Clubs.

In your main code, you try to access these outside of the class itself. eg:

Console.WriteLine("How far to the hole?");
myClub.distance = Console.ReadLine();

You have (somewhat correctly) provided public accessors to these variables. eg:

public string mydistance
{
    get
    {
        return distance;
    }
    set
    {
        distance = value;
    }
}        

which means your main code could be changed to

Console.WriteLine("How far to the hole?");
myClub.mydistance = Console.ReadLine();

String replace method is not replacing characters

package com.tulu.ds;

public class EmailSecurity {
    public static void main(String[] args) {
        System.out.println(returnSecuredEmailID("[email protected]"));
    }
    private static String returnSecuredEmailID(String email){
        String str=email.substring(1, email.lastIndexOf("@")-1);
        return email.replaceAll(email.substring(1, email.lastIndexOf("@")-1),replacewith(str.length(),"*"));
    }
    private static String replacewith(int length,String replace) {
        String finalStr="";
        for(int i=0;i<length;i++){
            finalStr+=replace;
        }
        return finalStr;
    }   
}

How To change the column order of An Existing Table in SQL Server 2008

If your table doesn't have any records you can just drop then create your table.

If it has records you can do it using your SQL Server Management Studio.

Just click your table > right click > click Design then you can now arrange the order of the columns by dragging the fields on the order that you want then click save.

Best Regards

CSS styling in Django forms

You could use this library: https://pypi.python.org/pypi/django-widget-tweaks

It allows you to do the following:

{% load widget_tweaks %}
<!-- add 2 extra css classes to field element -->
{{ form.title|add_class:"css_class_1 css_class_2" }}

Inserting data into a MySQL table using VB.NET

You need to open the connection first:

 SQLConnection.Open();

Describe table structure

This depends on your database vendor. Mostly it's the "information schema" you should Google for (applies to MySQL, MSSQL and perhaps others).

How to get response using cURL in PHP

The ultimate curl php function:

function getURL($url,$fields=null,$method=null,$file=null){
    // author   = Ighor Toth <[email protected]>
    // required:
    //      url     = include http or https 
    // optionals:
    //      fields  = must be array (e.g.: 'field1' => $field1, ...)
    //      method  = "GET", "POST"
    //      file    = if want to download a file, declare store location and file name (e.g.: /var/www/img.jpg, ...)
    // please crete 'cookies' dir to store local cookies if neeeded

    // do not modify below
    $useragent = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
    $timeout= 240;
    $dir = dirname(__FILE__);
    $_SERVER["REMOTE_ADDR"] = $_SERVER["REMOTE_ADDR"] ?? '127.0.0.1';
    $cookie_file    = $dir . '/cookies/' . md5($_SERVER['REMOTE_ADDR']) . '.txt';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);    
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
    curl_setopt($ch, CURLOPT_ENCODING, "" );
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt($ch, CURLOPT_AUTOREFERER, true );
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
    curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com/');
    if($file!=null){
        if (!curl_setopt($ch, CURLOPT_FILE, $file)){ // Handle error
                die("curl setopt bit the dust: " . curl_error($ch));
        }
        //curl_setopt($ch, CURLOPT_FILE, $file);
        $timeout= 3600;
    }
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout );
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout );
    if($fields!=null){
        $postvars = http_build_query($fields); // build the urlencoded data
        if($method=="POST"){
            // set the url, number of POST vars, POST data
            curl_setopt($ch, CURLOPT_POST, count($fields));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
        }
        if($method=="GET"){
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
            $url = $url.'?'.$postvars;
        }
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    $content = curl_exec($ch);
    if (!$content){
        $error = curl_error($ch);
        $info = curl_getinfo($ch);
        die("cURL request failed, error = {$error}; info = " . print_r($info, true));
    }
    if(curl_errno($ch)){
        echo 'error:' . curl_error($ch);
    } else {
        return $content;        
    }
    curl_close($ch);
}

How do I view events fired on an element in Chrome DevTools?

Visual Event is a nice little bookmarklet that you can use to view an element's event handlers. On online demo can be viewed here.

Fatal error: Class 'Illuminate\Foundation\Application' not found

i was having same problem with this error. It turn out my Kenel.php is having a wrong syntax when i try to comply with wrong php8 syntax

The line should be

protected $commands = [
    //
];

instead of

protected array $commands = [
        //
];

How to remove a TFS Workspace Mapping?

If the mentioned clues are not helping you then download Team Foundation Sidekick and using that you can delete the workspaces.

Flutter - Wrap text on overflow, like insert ellipsis or fade

There are many answers but Will some more observation it.

1. clip

Clip the overflowing text to fix its container.

SizedBox(
          width: 120.0,
          child: Text(
            "Enter Long Text",
            maxLines: 1,
            overflow: TextOverflow.clip,
            softWrap: false,
            style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0),
          ),
        ),

Output:

enter image description here

2.fade

Fade the overflowing text to transparent.

SizedBox(
          width: 120.0,
          child: Text(
            "Enter Long Text",
            maxLines: 1,
            overflow: TextOverflow.fade,
            softWrap: false,
            style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0),
          ),
        ), 

Output:

enter image description here

3.ellipsis

Use an ellipsis to indicate that the text has overflowed.

SizedBox(
          width: 120.0,
          child: Text(
            "Enter Long Text",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            softWrap: false,
            style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0),
          ),
        ),

Output:

enter image description here

4.visible

Render overflowing text outside of its container.

SizedBox(
          width: 120.0,
          child: Text(
            "Enter Long Text",
            maxLines: 1,
            overflow: TextOverflow.visible,
            softWrap: false,
            style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0),
          ),
        ),

Output:

enter image description here

Please Blog: https://medium.com/flutterworld/flutter-text-wrapping-ellipsis-4fa70b19d316

Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

Using btoa with unescape and encodeURIComponent didn't work for me. Replacing all the special characters with XML/HTML entities and then converting to the base64 representation was the only way to solve this issue for me. Some code:

base64 = btoa(str.replace(/[\u00A0-\u2666]/g, function(c) {
    return '&#' + c.charCodeAt(0) + ';';
}));

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

In case it helps anyone, the C# equivalent of ZloiAdun's answer is:

element.SendKeys(Keys.Control + "a");
element.SendKeys("55");

How to get .pem file from .key and .crt files?

Your keys may already be in PEM format, but just named with .crt or .key.

If the file's content begins with -----BEGIN and you can read it in a text editor:

The file uses base64, which is readable in ASCII, not binary format. The certificate is already in PEM format. Just change the extension to .pem.

If the file is in binary:

For the server.crt, you would use

openssl x509 -inform DER -outform PEM -in server.crt -out server.crt.pem

For server.key, use openssl rsa in place of openssl x509.

The server.key is likely your private key, and the .crt file is the returned, signed, x509 certificate.

If this is for a Web server and you cannot specify loading a separate private and public key:

You may need to concatenate the two files. For this use:

cat server.crt server.key > server.includesprivatekey.pem

I would recommend naming files with "includesprivatekey" to help you manage the permissions you keep with this file.

How to save DataFrame directly to Hive?

I don't see df.write.saveAsTable(...) deprecated in Spark 2.0 documentation. It has worked for us on Amazon EMR. We were perfectly able to read data from S3 into a dataframe, process it, create a table from the result and read it with MicroStrategy. Vinays answer has also worked though.

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

I think this is what you want, I already tested this code and works

The tools used are: (all these tools can be downloaded as Nuget packages)

http://fluentassertions.codeplex.com/

http://autofixture.codeplex.com/

http://code.google.com/p/moq/

https://nuget.org/packages/AutoFixture.AutoMoq

var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();

var sut = fixture.CreateAnonymous<Transfer>();

myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
        .Throws<System.IO.IOException>();

sut.Invoking(x => 
        x.TransferFiles(
            myInterface.Object, 
            It.IsAny<string>(), 
            It.IsAny<string>()
        ))
        .ShouldThrow<System.IO.IOException>();

Edited:

Let me explain:

When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer

So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code

When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs

In this case your external dependency is IFileConnection so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected

  • var fixture = new Fixture().Customize(new AutoMoqCustomization());: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq

  • var myInterface = fixture.Freeze<Mock<IFileConnection>>();: This freezes the IFileConnection dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object

  • var sut = fixture.CreateAnonymous<Transfer>();: Here AutoFixture is creating the SUT for us

  • myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>(); Here you are configuring the dependency to throw an exception whenever the Get method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception

  • sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles real method from the SUT and as parameters it receives the mocked IFileConnection so whenever you call the IFileConnection.Get in the normal flow of your SUT TransferFiles method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>() (from the FluentAssertions library)

References recommended:

http://martinfowler.com/articles/mocksArentStubs.html

http://misko.hevery.com/code-reviewers-guide/

http://misko.hevery.com/presentations/

http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded

http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded

Laravel 5.1 - Checking a Database Connection

You can also run this:

php artisan migrate:status

It makes a db connection connection to get migrations from migrations table. It'll throw an exception if the connection fails.

Blade if(isset) is not working Laravel

Use ?? , 'or' not supported in updated version.

{{ $usersType or '' }}  ?
{{ $usersType ?? '' }} ?

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

ES6 export all values from object

Why not just do a named export of the object:

let values = { a: 1, b: 2, c: 3 }
export { values }

or

export let values = { a: 1, b: 2, c: 3 }

and then a named import where you need it:

import { values } from './my-module'

let foo = values.a
let { a, b, c } = values

or

import { values as myModule } from './my-module'

let foo = myModule.a
let { a, b, c } = myModule

can do default export as well:

let values = { a: 1, b: 2, c: 3 }
export default values 

or

export default { a: 1, b: 2, c: 3 }

and then consume it:

import whateverIcallIt from './my-Module'

let foo = whateverIcallIt.a
let {a, b, c } = whateverIcallIt

If you want to export a bunch of individual values, say a bunch of constants, you can:

export const a = 1
export const b = 2
//...

or even

export const a = 1,
             b = 2,
             c = 3,
//...

and then import them individually:

import { a, b, c } from './my-module'

How to import .py file from another directory?

Python3:

import importlib.machinery

loader = importlib.machinery.SourceFileLoader('report', '/full/path/report/other_py_file.py')
handle = loader.load_module('report')

handle.mainFunction(parameter)

This method can be used to import whichever way you want in a folder structure (backwards, forwards doesn't really matter, i use absolute paths just to be sure).

There's also the more normal way of importing a python module in Python3,

import importlib
module = importlib.load_module('folder.filename')
module.function()

Kudos to Sebastian for spplying a similar answer for Python2:

import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

How to create an Array, ArrayList, Stack and Queue in Java?

I am guessing you're confused with the parameterization of the types:

// This works, because there is one class/type definition in the parameterized <> field
ArrayList<String> myArrayList = new ArrayList<String>(); 


// This doesn't work, as you cannot use primitive types here
ArrayList<char> myArrayList = new ArrayList<char>();

Convert a list of objects to an array of one of the object's properties

This should also work:

AggregateValues("hello", MyList.ConvertAll(c => c.Name).ToArray())

Git keeps asking me for my ssh key passphrase

It sounds like you may be having trouble with SSH-Agent itself. I would try troubleshooting that.

1) Did you do ssh-add to add your key to SSH?

2) Are you closing the terminal window between uses, because if you close the window you will have to enter the password again when you reopen it.

Failed to decode downloaded font

Changing format('woff') to format('font-woff') solves the problem.

Just a little change compared to Germano Plebani's answer

 @font-face {
  font-family: 'MyWebFont';
  src: url('webfont.eot'); /* IE9 Compat Modes */
  src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('webfont.woff2') format('woff2'), /* Super Modern Browsers */
       url('webfont.woff') format('font-woff'), /* Pretty Modern Browsers */
       url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

Please check if your browser sources can open it and what is the type

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

You can set cascadeDelete to false or true (in your migration Up() method). Depends upon your requirement.

AddForeignKey("dbo.Stories", "StatusId", "dbo.Status", "StatusID", cascadeDelete: false);

Output array to CSV in Ruby

To a file:

require 'csv'
CSV.open("myfile.csv", "w") do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

To a string:

require 'csv'
csv_string = CSV.generate do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

Here's the current documentation on CSV: http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

After hours of analysis reading tons of logs and internet, finally found problem.

If you use docker and php 7.4 (my case) you probably get error because default security level in OpenSSL it too high for wsdl cert. Even if you disable verify and allow self-signed in SoapClient options.

You need lower seclevel in /etc/ssl/openssl.cnf from DEFAULT@SECLEVEL=2 to

DEFAULT@SECLEVEL=1

Or just add into Dockerfile

RUN sed -i "s|DEFAULT@SECLEVEL=2|DEFAULT@SECLEVEL=1|g" /etc/ssl/openssl.cnf

Source: https://github.com/dotnet/runtime/issues/30667#issuecomment-566482876


You can verify it by run on container

curl -A 'cURL User Agent' -4 https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/Auth?wsdl

Before that change I got error:

SSL routines:tls_process_ske_dhe:dh key too small

How can I save application settings in a Windows Forms application?

The ApplicationSettings class doesn't support saving settings to the app.config file. That's very much by design; applications that run with a properly secured user account (think Vista UAC) do not have write access to the program's installation folder.

You can fight the system with the ConfigurationManager class. But the trivial workaround is to go into the Settings designer and change the setting's scope to User. If that causes hardships (say, the setting is relevant to every user), you should put your Options feature in a separate program so you can ask for the privilege elevation prompt. Or forego using a setting.

PHP fopen() Error: failed to open stream: Permission denied

You may need to change the permissions as an administrator. Open up terminal on your Mac and then open the directory that markers.xml is located in. Then type:

sudo chmod 777 markers.xml

You may be prompted for a password. Also, it could be the directories that don't allow full access. I'm not familiar with WordPress, so you may have to change the permission of each directory moving upward to the mysite directory.

Representing null in JSON

null is not zero. It is not a value, per se: it is a value outside the domain of the variable indicating missing or unknown data.

There is only one way to represent null in JSON. Per the specs (RFC 4627 and json.org):

2.1.  Values

A JSON value MUST be an object, array, number, or string, or one of
the following three literal names:

  false null true

enter image description here

How to add display:inline-block in a jQuery show() function?

Setting the CSS property after you have used .show() should work. Maybe you are targeting the wrong element on your HTML page.

 $('#foo').css('display', 'inline-block');

But if you are not using any effects of .show(), .hide() why don't you set those CSS properties manually like:

$('#foo').css('display','none'); 
$('#foo').css('display','inline-block');

Splitting a string at every n-th character

Late Entry.

Following is a succinct implementation using Java8 streams, a one liner:

String foobarspam = "foobarspam";
AtomicInteger splitCounter = new AtomicInteger(0);
Collection<String> splittedStrings = foobarspam
                                    .chars()
                                    .mapToObj(_char -> String.valueOf((char)_char))
                                    .collect(Collectors.groupingBy(stringChar -> splitCounter.getAndIncrement() / 3
                                                                ,Collectors.joining()))
                                    .values();

Output:

[foo, bar, spa, m]

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

WebDriver: check if an element exists?

As the comment stated, this is in C# not Java but the idea is the same. I've researched this issue extensively and ultimately the issue is, FindElement always returns an exception when the element doesn't exist. There isn't an overloaded option that allows you to get null or anything else. Here is why I prefer this solution over others.

  1. Returning a list of elements then checking if the list size is 0 works but you lose functionality that way. You can't do a .click() on a collection of links even if the collection size is 1.
  2. You could assert that the element exists but often that stops your testing. In some cases, I have an extra link to click depending on how I got to that page and I want to click it if it exists or move on otherwise.
  3. It's only slow if you don't set the timeout driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(0));
  4. It's actually a very simple and elegant once the method is created. By using FindElementSafe instead of FindElement, I don't "see" the ugly try/catch block and I can use a simple Exists method. That would look something like this:

    IWebElement myLink = driver.FindElementSafe(By.Id("myId"));
    if (myLink.Exists)
    {
       myLink.Click();
    }
    

Here is how you extend IWebElement & IWebDriver

IWebDriver.FindElementSafe

    /// <summary>
    /// Same as FindElement only returns null when not found instead of an exception.
    /// </summary>
    /// <param name="driver">current browser instance</param>
    /// <param name="by">The search string for finding element</param>
    /// <returns>Returns element or null if not found</returns>
    public static IWebElement FindElementSafe(this IWebDriver driver, By by)
    {
        try
        {
            return driver.FindElement(by);
        }
        catch (NoSuchElementException)
        {
            return null;
        }
    }

IWebElement.Exists

    /// <summary>
    /// Requires finding element by FindElementSafe(By).
    /// Returns T/F depending on if element is defined or null.
    /// </summary>
    /// <param name="element">Current element</param>
    /// <returns>Returns T/F depending on if element is defined or null.</returns>
    public static bool Exists(this IWebElement element)
    {
        if (element == null)
        { return false; }
        return true;
    }

You could use polymorphism to modify the IWebDriver class instance of FindElement but that's a bad idea from a maintenance standpoint.

How to mount a single file in a volume

I had been suffering from a similar issue. I was trying to import my config file to my container so that I can fix it every time I need without re-building the image.

I mean I thought the below command would map $(pwd)/config.py from Docker host to /root/app/config.py into the container as a file.

docker run -v $(pwd)/config.py:/root/app/config.py my_docker_image

However, it always created a directory named config.py, not a file.

while looking for clue, I found the reason(from here)

If you use -v or --volume to bind-mount a file or directory that does not yet exist on the Docker host, -v will create the endpoint for you. It is always created as a directory.

Therefore, it is always created as a directory because my docker host does not have $(pwd)/config.py.

Even if I create config.py in docker host. $(pwd)/config.py just overwirte /root/app/config.py not exporting /root/app/config.py.

Is there any way to start with a POST request using Selenium?

from selenium import webdriver

driver = webdriver.Firefox()
driver.implicitly_wait(12)
driver.set_page_load_timeout(10)

def _post_selenium(self, url: str, data: dict):
    input_template = '{k} <input type="text" name="{k}" id="{k}" value="{v}"><BR>\n'
    inputs = ""
    if data:
        for k, v in data.items():
            inputs += input_template.format(k=k, v=v)
    html = f'<html><body>\n<form action="{url}" method="post" id="formid">\n{inputs}<input type="submit" id="inputbox">\n</form></body></html>'

    html_file = os.path.join(os.getcwd(), 'temp.html')
    with open(html_file, "w") as text_file:
        text_file.write(html)

    driver.get(f"file://{html_file}")
    driver.find_element_by_id('inputbox').click()

_post_selenium("post.to.my.site.url", {"field1": "val1"})

driver.close()

maven "cannot find symbol" message unhelpful

If you are using Intellij and the above solutions are not working try: File > Invalidate Caches / Restart

This worked for me. Sometimes when you are working through multiple branches, the IDE uses its cache and cannot find the file in the cache hence it shows error during compilation.

Error "The input device is not a TTY"

It's not exactly what you are asking, but:

The -T key would help people who are using docker-compose exec!

docker-compose -f /srv/backend_bigdata/local.yml exec -T postgres backup

Java SSLException: hostname in certificate didn't match

Updating the java version from 1.8.0_40 to 1.8.0_181 resolved the issue.

Excel cell value as string won't store as string

Use Range("A1").Text instead of .Value

post comment edit:
Why?
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what's stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
now,
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn't much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

How can I get a vertical scrollbar in my ListBox?

XAML ListBox Scroller - Windows 10(UWP)

<Style TargetType="ListBox">
    <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Visible"/>
    <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Visible"/>
</Style>

Is it possible to see more than 65536 rows in Excel 2007?

I am not 100% sure where all of the other suggestions are trying to go, but the issue is basically related to the extension that you have on the file. If you save the file as a Excel 97/2003 workbook it will not allow you to see all million rows. Create a new sheet and save it as a workbook and you will see all million. Note: the extension will be .xlsx

Multiple line code example in Javadoc comment

I just read the Javadoc 1.5 reference here, and only the code with <and > must be enclosed inside {@code ...}. Here a simple example:

 /** 
 * Bla bla bla, for example:
 *
 * <pre>
 * void X() {
 *    List{@code <String>} a = ...;
 *    ...
 * }
 * </pre>
 *
 * @param ...
 * @return ...
 */
 .... your code then goes here ...

Use .htaccess to redirect HTTP to HTTPs

In my case, the htaccess file contained lots of rules installed by plugins like Far Future Expiration and WPSuperCache and also the lines from wordpress itself.

In order to not mess things up, I had to put the solution at the top of htaccess (this is important, if you put it at the end it causes some wrong redirects due to conflicts with the cache plugin)

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

This way, your lines don't get messed up by wordpress in case some settings change. Also, the <IfModule> section can be repeated without any problems.

I have to thank Jason Shah for the neat htaccess rule.

What's an appropriate HTTP status code to return by a REST API service for a validation failure?

I would say technically it might not be an HTTP failure, since the resource was (presumably) validly specified, the user was authenticated, and there was no operational failure (however even the spec does include some reserved codes like 402 Payment Required which aren't strictly speaking HTTP-related either, though it might be advisable to have that at the protocol level so that any device can recognize the condition).

If that's actually the case, I would add a status field to the response with application errors, like

<status><code>4</code><message>Date range is invalid</message></status>

How to activate an Anaconda environment

As you can see from the error message the paths, that you specified, are wrong. Try it like this:

activate ..\..\temp\venv\test

However, when I needed to install Anaconda, I downloaded it from here and installed it to the default paths (C:\Anaconda), than I put this path to the environment variables, so now Anacondas interpreter is used as default. If you are using PyCharm, for example, you can specify the interpreter there directly.

How to calculate the sentence similarity using word2vec model of gensim with python

Once you compute the sum of the two sets of word vectors, you should take the cosine between the vectors, not the diff. The cosine can be computed by taking the dot product of the two vectors normalized. Thus, the word count is not a factor.

A default document is not configured for the requested URL, and directory browsing is not enabled on the server

I was having this issue in a WebForms application, the error clearly says that A default document is not configured and it was true in my case, the default document was not configured. What worked for me is that I clicked on my site and on the middle pane in iis there is an option named Default Document. In the Default Document you have to check if the default page of the application exists or not.

The default page of my application was index.aspx and it wasnt present on iis Default Document window. So I made a new entry of index.aspx and it started working.

ng-change not working on a text input

Maybe you can try something like this:

Using a directive

directive('watchChange', function() {
    return {
        scope: {
            onchange: '&watchChange'
        },
        link: function(scope, element, attrs) {
            element.on('input', function() {
                scope.onchange();
            });
        }
    };
});

http://jsfiddle.net/H2EAB/

How can I refresh or reload the JFrame?

Try

SwingUtilities.updateComponentTreeUI(frame);

If it still doesn't work then after completing the above step try

frame.invalidate();
frame.validate();
frame.repaint();

Is there a way to disable initial sorting for jquery DataTables?

Try this:

$(document).ready( function () {
  $('#example').dataTable({
    "order": []
  });
});

this will solve your problem.

Tesseract running error

You can call tesseract API function from C code:

#include <tesseract/baseapi.h>
#include <tesseract/ocrclass.h>; // ETEXT_DESC

using namespace tesseract;

class TessAPI : public TessBaseAPI {
    public:
    void PrintRects(int len);
};

...
TessAPI *api = new TessAPI();
int res = api->Init(NULL, "rus");
api->SetAccuracyVSpeed(AVS_MOST_ACCURATE);
api->SetImage(data, w0, h0, bpp, stride);
api->SetRectangle(x0,y0,w0,h0);

char *text;
ETEXT_DESC monitor;
api->RecognizeForChopTest(&monitor);
text = api->GetUTF8Text();
printf("text: %s\n", text);
printf("m.count: %s\n", monitor.count);
printf("m.progress: %s\n", monitor.progress);

api->RecognizeForChopTest(&monitor);
text = api->GetUTF8Text();
printf("text: %s\n", text);
...
api->End();

And build this code:

g++ -g -I. -I/usr/local/include -o _test test.cpp -ltesseract_api -lfreeimageplus

(i need FreeImage for picture loading)

Pad a number with leading zeros in JavaScript

function padToFour(number) {
  if (number<=9999) { number = ("000"+number).slice(-4); }
  return number;
}

Something like that?

Bonus incomprehensible-but-slicker single-line ES6 version:

let padToFour = number => number <= 9999 ? `000${number}`.slice(-4) : number;

ES6isms:

  • let is a block scoped variable (as opposed to var’s functional scoping)
  • => is an arrow function that among other things replaces function and is prepended by its parameters
  • If a arrow function takes a single parameter you can omit the parentheses (hence number =>)
  • If an arrow function body has a single line that starts with return you can omit the braces and the return keyword and simply use the expression
  • To get the function body down to a single line I cheated and used a ternary expression

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

HTML5 video - show/hide controls programmatically

CARL LANGE also showed how to get hidden, autoplaying audio in html5 on a iOS device. Works for me.

In HTML,

<div id="hideme">
    <audio id="audioTag" controls>
        <source src="/path/to/audio.mp3">
    </audio>
</div>

with JS

<script type="text/javascript">
window.onload = function() {
    var audioEl = document.getElementById("audioTag");
    audioEl.load();
    audioEl.play();
};
</script>

In CSS,

#hideme {display: none;}

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

If you need the digit to be at the end of any word, this worked for me:

/\b([a-zA-Z]+[0-9]+)\b/g
  • \b word boundary
  • [a-zA-Z] any letter
  • [0-9] any number
  • "+" unlimited search (show all results)

Visual Studio opens the default browser instead of Internet Explorer

In visual studio 2013, this can be done as follows:

1) Ensure you have selected a start up project from your solution explore window 2) This brings a drop down to the left of the debug drop down. You can choose browser from this new drop down.

Key is there should be a project selected as start up

Use of Finalize/Dispose method in C#

Some aspects of another answer are slightly incorrect for 2 reasons:

First,

using(NoGateway objNoGateway = new NoGateway())

actually is equivalent to:

try
{
    NoGateway = new NoGateway();
}
finally
{
    if(NoGateway != null)
    {
        NoGateway.Dispose();
    }
}

This may sound ridiculous since the 'new' operator should never return 'null' unless you have an OutOfMemory exception. But consider the following cases: 1. You call a FactoryClass that returns an IDisposable resource or 2. If you have a type that may or may not inherit from IDisposable depending on its implementation - remember that I've seen the IDisposable pattern implemented incorrectly many times at many clients where developers just add a Dispose() method without inheriting from IDisposable (bad, bad, bad). You could also have the case of an IDisposable resource being returned from a property or method (again bad, bad, bad - don't 'give away your IDisposable resources)

using(IDisposable objNoGateway = new NoGateway() as IDisposable)
{
    if (NoGateway != null)
    {
        ...

If the 'as' operator returns null (or property or method returning the resource), and your code in the 'using' block protects against 'null', your code will not blow up when trying to call Dispose on a null object because of the 'built-in' null check.

The second reason your reply is not accurate is because of the following stmt:

A finalizer is called upon the GC destroying your object

First, Finalization (as well as GC itself) is non-deterministic. THe CLR determines when it will call a finalizer. i.e. the developer/code has no idea. If the IDisposable pattern is implemented correctly (as I've posted above) and GC.SuppressFinalize() has been called, the the Finalizer will NOT be called. This is one of the big reasons to properly implement the pattern correctly. Since there is only 1 Finalizer thread per managed process, regardless of the number of logical processors, you can easily degrade performance by backing up or even hanging the Finalizer thread by forgetting to call GC.SuppressFinalize().

I've posted a correct implementation of the Dispose Pattern on my blog: How to Properly Implement the Dispose Pattern

How to tell if node.js is installed or not

(This is for windows OS but concept can be applied to other OS)

Running command node -v will be able to confirm if it is installed, however it will not be able to confirm if it is NOT installed. (Executable may not be on your PATH)

Two ways you can check if it is actually installed:

  1. Check default install location C:\Program Files\nodejs\

or

  1. Go to System Settings -> Add or Remove Programs and filter by node, it should show you if you have it installed. For me, it shows as title:"Node.js" and description "Node.js Foundation", with no version specified. Install size is 52.6MB

If you don't have it installed, get it from here https://nodejs.org/en/download/

Increase max execution time for php

This is old question, but if somebody finds it today chances are php will be run via php-fpm and mod_fastcgi. In that case nothing here will help with extending execution time because Apache will terminate connection to a process which does not output anything for 30 seconds. Only way to extend it is to change -idle-timeout in apache (module/site/vhost) config.

FastCgiExternalServer /usr/lib/cgi-bin/php7-fcgi -socket /run/php/php7.0-fpm.sock -idle-timeout 900 -pass-header Authorization

More details - Increase PHP-FPM idle timeout setting

How to work with string fields in a C struct?

While Richard's is what you want if you do want to go with a typedef, I'd suggest that it's probably not a particularly good idea in this instance, as you lose sight of it being a pointer, while not gaining anything.

If you were treating it a a counted string, or something with additional functionality, that might be different, but I'd really recommend that in this instance, you just get familiar with the 'standard' C string implementation being a 'char *'...

ORA-06508: PL/SQL: could not find program unit being called

I suspect you're only reporting the last error in a stack like this:

ORA-04068: existing state of packages has been discarded
ORA-04061: existing state of package body "schema.package" has been invalidated
ORA-04065: not executed, altered or dropped package body "schema.package"
ORA-06508: PL/SQL: could not find program unit being called: "schema.package"

If so, that's because your package is stateful:

The values of the variables, constants, and cursors that a package declares (in either its specification or body) comprise its package state. If a PL/SQL package declares at least one variable, constant, or cursor, then the package is stateful; otherwise, it is stateless.

When you recompile the state is lost:

If the body of an instantiated, stateful package is recompiled (either explicitly, with the "ALTER PACKAGE Statement", or implicitly), the next invocation of a subprogram in the package causes Oracle Database to discard the existing package state and raise the exception ORA-04068.

After PL/SQL raises the exception, a reference to the package causes Oracle Database to re-instantiate the package, which re-initializes it...

You can't avoid this if your package has state. I think it's fairly rare to really need a package to be stateful though, so you should revisit anything you have declared in the package, but outside a function or procedure, to see if it's really needed at that level. Since you're on 10g though, that includes constants, not just variables and cursors.

But the last paragraph from the quoted documentation means that the next time you reference the package in the same session, you won't get the error and it will work as normal (until you recompile again).

Java Garbage Collection Log messages

  1. PSYoungGen refers to the garbage collector in use for the minor collection. PS stands for Parallel Scavenge.
  2. The first set of numbers are the before/after sizes of the young generation and the second set are for the entire heap. (Diagnosing a Garbage Collection problem details the format)
  3. The name indicates the generation and collector in question, the second set are for the entire heap.

An example of an associated full GC also shows the collectors used for the old and permanent generations:

3.757: [Full GC [PSYoungGen: 2672K->0K(35584K)] 
            [ParOldGen: 3225K->5735K(43712K)] 5898K->5735K(79296K) 
            [PSPermGen: 13533K->13516K(27584K)], 0.0860402 secs]

Finally, breaking down one line of your example log output:

8109.128: [GC [PSYoungGen: 109884K->14201K(139904K)] 691015K->595332K(1119040K), 0.0454530 secs]
  • 107Mb used before GC, 14Mb used after GC, max young generation size 137Mb
  • 675Mb heap used before GC, 581Mb heap used after GC, 1Gb max heap size
  • minor GC occurred 8109.128 seconds since the start of the JVM and took 0.04 seconds

How do I tell if an object is a Promise?

To see if the given object is a ES6 Promise, we can make use of this predicate:

function isPromise(p) {
  return p && Object.prototype.toString.call(p) === "[object Promise]";
}

Calling toString directly from the Object.prototype returns a native string representation of the given object type which is "[object Promise]" in our case. This ensures that the given object

  • Bypasses false positives such as..:
    • Self-defined object type with the same constructor name ("Promise").
    • Self-written toString method of the given object.
  • Works across multiple environment contexts (e.g. iframes) in contrast to instanceof or isPrototypeOf.

However, any particular host object, that has its tag modified via Symbol.toStringTag, can return "[object Promise]". This may be the intended result or not depending on the project (e.g. if there is a custom Promise implementation).


To see if the object is from a native ES6 Promise, we can use:

function isNativePromise(p) {
  return p && typeof p.constructor === "function"
    && Function.prototype.toString.call(p.constructor).replace(/\(.*\)/, "()")
    === Function.prototype.toString.call(/*native object*/Function)
      .replace("Function", "Promise") // replacing Identifier
      .replace(/\(.*\)/, "()"); // removing possible FormalParameterList 
}

According to this and this section of the spec, the string representation of function should be:

"function Identifier ( FormalParameterListopt ) { FunctionBody }"

which is handled accordingly above. The FunctionBody is [native code] in all major browsers.

MDN: Function.prototype.toString

This works across multiple environment contexts as well.

Can't connect to MySQL server on 'localhost' (10061)

  1. Right click on My Computer
  2. Click on Manage
  3. Go to Services and Application
  4. Select Services and find MySQL service
  5. Right click on MySQL and select Start

Remove menubar from Electron app

Use this:

mainWindow = new BrowserWindow({width: 640, height: 360})
mainWindow.setMenuBarVisibility(false)

Reference: https://github.com/electron/electron/issues/1415

I tried mainWindow.setMenu(null), but it didn't work.

How to debug in Android Studio using adb over WiFi

You can find information relating to setting up a device over WiFi over by the Android ADB Docs.

For devices running Android 11+ see instructions.

For devices running Android 10- see instructions

Placeholder Mixin SCSS/CSS

To avoid 'Unclosed block: CssSyntaxError' errors being thrown from sass compilers add a ';' to the end of @content.

@mixin placeholder {
   ::-webkit-input-placeholder { @content;}
   :-moz-placeholder           { @content;}
   ::-moz-placeholder          { @content;}
   :-ms-input-placeholder      { @content;}
}

Android: how to create Switch case from this?

@Override
public void onClick(View v)
{
    switch (v.getId())
    {
        case R.id.:

            break;
        case R.id.:

            break;
        default:
            break;
    }
}

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

Try this.

public class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        var json = config.Formatters.JsonFormatter;
        json.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
        config.Formatters.Remove(config.Formatters.XmlFormatter);

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional , Action =RouteParameter.Optional }

        );
    }
}

Python threading. How do I lock a thread?

You can see that your locks are pretty much working as you are using them, if you slow down the process and make them block a bit more. You had the right idea, where you surround critical pieces of code with the lock. Here is a small adjustment to your example to show you how each waits on the other to release the lock.

import threading
import time
import inspect

class Thread(threading.Thread):
    def __init__(self, t, *args):
        threading.Thread.__init__(self, target=t, args=args)
        self.start()

count = 0
lock = threading.Lock()

def incre():
    global count
    caller = inspect.getouterframes(inspect.currentframe())[1][3]
    print "Inside %s()" % caller
    print "Acquiring lock"
    with lock:
        print "Lock Acquired"
        count += 1  
        time.sleep(2)  

def bye():
    while count < 5:
        incre()

def hello_there():
    while count < 5:
        incre()

def main():    
    hello = Thread(hello_there)
    goodbye = Thread(bye)


if __name__ == '__main__':
    main()

Sample output:

...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...

laravel Unable to prepare route ... for serialization. Uses Closure

If someone is still looking for an answer, for me the problem was in routes/web.php file. Example:

Route::get('/', function () {
    return view('welcome');
});

It is also Route, so yeah...Just remove it if not needed and you are good to go! You should also follow answers provided from above.

Can Json.NET serialize / deserialize to / from a stream?

public static void Serialize(object value, Stream s)
{
    using (StreamWriter writer = new StreamWriter(s))
    using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
    {
        JsonSerializer ser = new JsonSerializer();
        ser.Serialize(jsonWriter, value);
        jsonWriter.Flush();
    }
}

public static T Deserialize<T>(Stream s)
{
    using (StreamReader reader = new StreamReader(s))
    using (JsonTextReader jsonReader = new JsonTextReader(reader))
    {
        JsonSerializer ser = new JsonSerializer();
        return ser.Deserialize<T>(jsonReader);
    }
}

Could not find a part of the path ... bin\roslyn\csc.exe

Your build is trying to find \bin\roslyn\csc.exe because the following packages have been added to your project. Just review your packages.config file, you can have both of them there

Microsoft.CodeDom.Providers.DotNetCompilerPlatform
Microsoft.Net.Compilers

What is Roslyn and Who added them(packages) in the project : If you’re using .net Framework 4.5.2 to create projects using VS2015, you might have noticed that the project templates use Roslyn by default. Actually Roslyn is one of open-source compilers for .NET languages from Microsoft.

Why should we delete Roslyn : If your project has Roslyn references and you are interested to deploy it no server, you will get unwanted errors on the website as many hosting providers still have not upgraded their servers and hence do not support Roslyn. To resolve this issue, you will need to remove the Roslyn compiler from the project template.

if you are not interested in using Roslyn, follow steps bellow to delete it

1. Remove NuGet packages, use the following commands from Nuget Package Console

PM> Uninstall-package Microsoft.CodeDom.Providers.DotNetCompilerPlatform
PM> Uninstall-package Microsoft.Net.Compilers

2. After you do this, your web.config file should be auto-updated. In case it is not, look for the below code in web.config file and if it is found, delete this piece of code.

<system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"></compiler>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"></compiler>
    </compilers>
</system.codedom>

How to increment variable under DOS?

I built my answer thanks to previous contributors.

Not having time for a custom counter.exe, I downloaded sed for FREEDOS.

And then the batch code could be, emulating "wc -l" with the utility sed, something like this according to your loop (I just use it to increment through executions starting from "1" to n+1):

Just remember to manually create a file "test.txt" with written on the first row

0


sed -n '$=' test.txt > counter.txt
set /P Var=< counter.txt
echo 0 >> test.txt

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

Looks like you have a query that is taking longer than it should. From your stack trace and your code you should be able to determine exactly what query that is.

This type of timeout can have three causes;

  1. There's a deadlock somewhere
  2. The database's statistics and/or query plan cache are incorrect
  3. The query is too complex and needs to be tuned

A deadlock can be difficult to fix, but it's easy to determine whether that is the case. Connect to your database with Sql Server Management Studio. In the left pane right-click on the server node and select Activity Monitor. Take a look at the running processes. Normally most will be idle or running. When the problem occurs you can identify any blocked process by the process state. If you right-click on the process and select details it'll show you the last query executed by the process.

The second issue will cause the database to use a sub-optimal query plan. It can be resolved by clearing the statistics:

exec sp_updatestats

If that doesn't work you could also try

dbcc freeproccache

You should not do this when your server is under heavy load because it will temporarily incur a big performace hit as all stored procs and queries are recompiled when first executed. However, since you state the issue occurs sometimes, and the stack trace indicates your application is starting up, I think you're running a query that is only run on occasionally. You may be better off by forcing SQL Server not to reuse a previous query plan. See this answer for details on how to do that.

I've already touched on the third issue, but you can easily determine whether the query needs tuning by executing the query manually, for example using Sql Server Management Studio. If the query takes too long to complete, even after resetting the statistics you'll probably need to tune it. For help with that, you should post the exact query in a new question.

How to combine multiple inline style objects?

Need to merge the properties in object. For Example,

const boxStyle = {
  width : "50px",
  height : "50px"
};
const redBackground = {
  ...boxStyle,
  background: "red",
};
const blueBackground = {
  ...boxStyle,
  background: "blue",
}




 <div style={redBackground}></div>
 <div style={blueBackground}></div>

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

in my case, I got the same exception because the user that I configured in the app did not existed in the DB, creating the user and granting needed permissions solved the problem.

Setting focus on an HTML input box on page load

You could also use:

<body onload="focusOnInput()">
    <form name="passwordForm" action="verify.php" method="post">
        <input name="passwordInput" type="password" />
    </form>
</body>

And then in your JavaScript:

function focusOnInput() {
    document.forms["passwordForm"]["passwordInput"].focus();
}

How do you set the title color for the new Toolbar?

This worked for me

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:fitsSystemWindows="true"
    android:minHeight="?attr/actionBarSize"
    app:navigationIcon="@drawable/ic_back"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:subtitleTextColor="@color/white"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:title="This week stats"
    app:titleTextColor="@color/white">


    <ImageView
        android:id="@+id/submitEditNote"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_gravity="right"
        android:layout_marginRight="10dp"
        android:src="@android:drawable/ic_menu_manage" />
</android.support.v7.widget.Toolbar>

Regular Expression Validation For Indian Phone Number and Mobile number

For land Line Number

03595-259506
03592 245902
03598245785

you can use this

\d{5}([- ]*)\d{6}

NEW for all ;)

OLD: ((\+*)(0*|(0 )*|(0-)*|(91 )*)(\d{12}+|\d{10}+))|\d{5}([- ]*)\d{6}
NEW: ((\+*)((0[ -]+)*|(91 )*)(\d{12}+|\d{10}+))|\d{5}([- ]*)\d{6}

9775876662
0 9754845789
0-9778545896
+91 9456211568
91 9857842356
919578965389

03595-259506
03592 245902
03598245785

this site is useful for me, and maby for you .;)http://gskinner.com/RegExr/

SQL Server - Convert varchar to another collation (code page) to fix character encoding

I think SELECT CAST( CAST([field] AS VARBINARY(120)) AS varchar(120)) for your update

Disable LESS-CSS Overwriting calc()

Example for escaped string with variable:

@some-variable-height: 10px;

...

div {
    height: ~"calc(100vh - "@some-variable-height~")";
}

compiles to

div {
    height: calc(100vh - 10px );
}

Calling one Bash script from another Script passing it arguments with quotes and spaces

I found following program works for me

test1.sh 
a=xxx
test2.sh $a

in test2.sh you use $1 to refer variable a in test1.sh

echo $1

The output would be xxx

"Stack overflow in line 0" on Internet Explorer

You can turn off the "Disable Script Debugging" option inside of Internet Explorer and start debugging with Visual Studio if you happen to have that around.

I've found that it is one of few ways to diagnose some of those IE specific issues.

How to read file using NPOI

It might be helpful to rely on the Workbook factory to instantiate the workbook object since the factory method will do the detection of xls or xlsx for you. Reference: http://apache-poi.1045710.n5.nabble.com/How-to-check-for-valid-excel-files-using-POI-without-checking-the-file-extension-td2341055.html

IWorkbook workbook = WorkbookFactory.Create(inputStream);

If you're not sure of the Sheet's name but you are sure of the index (0 based), you can grab the sheet like this:

ISheet sheet = workbook.GetSheetAt(sheetIndex);

You can then iterate through the rows using code supplied by the accepted answer from mj82

How do I exit from a function?

return; // Prematurely return from the method (same keword works in VB, by the way)

Eclipse doesn't stop at breakpoints

I had all breakpoints enabled and configured as I should. But whenever I clicked "debug" it would only step through the program (press f5/f6) Turns out there was a rogue setting

Right Click project > debug configurations > "Debugger" tab > uncheck "Stop on startup at:" box

docker unauthorized: authentication required - upon push with successful login

Make sure your docker repositry name matches your local docker repo name. e.g lets say if you local repo name "kavashgar/nodjsapp"

then your should also have a repo names "kavashgar" in docker hub

Hibernate Criteria Restrictions AND / OR combination

For the new Criteria since version Hibernate 5.2:

CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);

Root<SomeClass> root = criteriaQuery.from(SomeClass.class);

Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");

Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);

Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);

Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);

criteriaQuery
        .select(root)
        .where(predicateResult);

List<SomeClass> list = getSession()
        .createQuery(criteriaQuery)
        .getResultList();  

Why std::cout instead of simply cout?

It seems possible your class may have been using pre-standard C++. An easy way to tell, is to look at your old programs and check, do you see:

#include <iostream.h>

or

#include <iostream>

The former is pre-standard, and you'll be able to just say cout as opposed to std::cout without anything additional. You can get the same behavior in standard C++ by adding

using std::cout;

or

using namespace std;

Just one idea, anyway.

ERROR 2006 (HY000): MySQL server has gone away

This is more of a rare issue but I have seen this if someone has copied the entire /var/lib/mysql directory as a way of migrating their DB to another server. The reason it doesn't work is because the database was running and using log files. It doesn't work sometimes if there are logs in /var/log/mysql. The solution is to copy the /var/log/mysql files as well.

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

Something I stumbled upon today for a DLL I knew was working fine with my VS2013 project, but not with VS2015:

Go to: Project -> XXXX Properties -> Build -> Uncheck "Prefer 32-bit"

This answer is way overdue and probably won't do any good, but if you. But I hope this will help somebody someday.

How to determine whether an object has a given property in JavaScript

ES6+:

There is a new feature on ES6+ that you can check it like below:

if (x?.y)

Actually, the interpretor checks the existence of x and then call the y and because of putting inside if parentheses the coercion happens and x?.y converted to boolean.

How do I make a newline after a twitter bootstrap element?

You're using span6 and span2. Both of these classes are "float:left" meaning, if possible they will always try to sit next to each other. Twitter bootstrap is based on a 12 grid system. So you should generally always get the span**#** to add up to 12.

E.g.: span4 + span4 + span4 OR span6 + span6 OR span4 + span3 + span5.

To force a span down though, without listening to the previous float you can use twitter bootstraps clearfix class. To do this, your code should look like this:

<ul class="nav nav-tabs span2">
  <li><a href="./index.html"><i class="icon-black icon-music"></i></a></li>
  <li><a href="./about.html"><i class="icon-black icon-eye-open"></i></a></li>
  <li><a href="./team.html"><i class="icon-black icon-user"></i></a></li>
  <li><a href="./contact.html"><i class="icon-black icon-envelope"></i></a></li>
</ul>
<!-- Notice this following line -->
<div class="clearfix"></div>
<div class="well span6">
  <h3>I wish this appeared on the next line without having to gratuitously use BR!</h3>
</div>

Git Push ERROR: Repository not found

git remote rm origin
git remote add origin <remote url>

Testing Private method using mockito

  1. By using reflection, private methods can be called from test classes. In this case,

    //test method will be like this ...

    public class TestA {
    
      @Test
        public void testMethod() {
    
        A a= new A();
        Method privateMethod = A.class.getDeclaredMethod("method1", null);
        privateMethod.setAccessible(true);
        // invoke the private method for test
        privateMethod.invoke(A, null);
    
        }
    }
    
  2. If the private method calls any other private method, then we need to spy the object and stub the another method.The test class will be like ...

    //test method will be like this ...

    public class TestA {
    
      @Test
        public void testMethod() {
    
        A a= new A();
        A spyA = spy(a);
        Method privateMethod = A.class.getDeclaredMethod("method1", null);
        privateMethod.setAccessible(true);
        doReturn("Test").when(spyA, "method2"); // if private method2 is returning string data
        // invoke the private method for test
        privateMethod.invoke(spyA , null);
    
        }
    }
    

**The approach is to combine reflection and spying the object. **method1 and **method2 are private methods and method1 calls method2.

HTML input arrays

As far as I know, there isn't anything on the HTML specs because browsers aren't supposed to do anything different for these fields. They just send them as they normally do and PHP is the one that does the parsing into an array, as do other languages.

Updating MySQL primary key

You can use the IGNORE keyword too, example:

 update IGNORE table set primary_field = 'value'...............

How to create an array from a CSV file using PHP and the fgetcsv function

This function will return array with Header values as array keys.

function csv_to_array($file_name) {
        $data =  $header = array();
        $i = 0;
        $file = fopen($file_name, 'r');
        while (($line = fgetcsv($file)) !== FALSE) {
            if( $i==0 ) {
                $header = $line;
            } else {
                $data[] = $line;        
            }
            $i++;
        }
        fclose($file);
        foreach ($data as $key => $_value) {
            $new_item = array();
            foreach ($_value as $key => $value) {
                $new_item[ $header[$key] ] =$value;
            }
            $_data[] = $new_item;
        }
        return $_data;
    }

How to view the contents of an Android APK file?

You can also use Jadx - https://github.com/skylot/jadx. I have used all the tools mentioned in this page and found that Jadx works the best. The manifest file and other class files are converted to readable format as much as possible by this tool.

PS - http://www.javadecompilers.com/apk also uses the jadx decompiler to do the same work online. Simpler if you want to unarchive a single apk.

Cheers!

Support for the experimental syntax 'classProperties' isn't currently enabled

I find the problem that my .babelrc was ignored, However I create babel.config.js and add the following:

module.exports = {
  plugins: [
    ['@babel/plugin-proposal-decorators', { legacy: true }],
    ['@babel/plugin-proposal-class-properties', { loose: true }],
    '@babel/plugin-syntax-dynamic-import',
    '@babel/plugin-transform-regenerator',
    [
      '@babel/plugin-transform-runtime',
      {
        helpers: false,
        regenerator: true,
      },
    ],
  ],
  presets: [
    "@babel/preset-flow",
    'module:metro-react-native-babel-preset',
  ],
};

And it works for me on React Native application, I think this also would help React apps as well.