Programs & Examples On #Scala 2.8

Version 2.8 of the Scala language for the JVM. Use only if your question is specifically related to features of this version.

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

It seems necessary to state ones degree here: B.A. in Political Science and B.ed in Computer Science.

To the point:

Is this going to put people off coming to Scala?

Scala is difficult, because its underlying programming paradigm is difficult. Functional programming scares a lot of people. It is possible to build closures in PHP but people rarely do. So no, not this signature but all the rest will put people off, if they do not have the specific education to make them value the power of the underlying paradigm.

If this education is available, everyone can do it. Last year I build a chess computer with a bunch of school kids in SCALA! They had their problems but they did fine in the end.

If you're using Scala commercially, are you worried about this? Are you planning to adopt 2.8 immediately or wait to see what happens?

I would not be worried.

How to write to a file in Scala?

Starting Scala 2.13, the standard library provides a dedicated resource management utility: Using.

It can be used in this case with resources such as PrintWriter or BufferedWriter which extends AutoCloseable in order to write to a file and, no matter what, close the resource afterwards:

  • For instance, with java.io api:

    import scala.util.Using, java.io.{PrintWriter, File}
    
    // val lines = List("hello", "world")
    Using(new PrintWriter(new File("file.txt"))) {
      writer => lines.foreach(writer.println)
    }
    
  • Or with java.nio api:

    import scala.util.Using, java.nio.file.{Files, Paths}, java.nio.charset.Charset
    
    // val lines = List("hello", "world")
    Using(Files.newBufferedWriter(Paths.get("file.txt"), Charset.forName("UTF-8"))) {
      writer => lines.foreach(line => writer.write(line + "\n"))
    }
    

ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

First you need to specify in the Headers the Content-Type, for example, it can be application/json.

If you set application/json content type, then you need to send a json.

So in the body of your request you will send not form-data, not x-www-for-urlencoded but a raw json, for example {"Username": "user", "Password": "pass"}

You can adapt the example to various content types, including what you want to send.

You can use a tool like Postman or curl to play with this.

Read an Excel file directly from a R script

Another solution is the xlsReadWrite package, which doesn't require additional installs but does require you download the additional shlib before you use it the first time by :

require(xlsReadWrite)
xls.getshlib()

Forgetting this can cause utter frustration. Been there and all that...

On a sidenote : You might want to consider converting to a text-based format (eg csv) and read in from there. This for a number of reasons :

  • whatever your solution (RODBC, gdata, xlsReadWrite) some strange things can happen when your data gets converted. Especially dates can be rather cumbersome. The HFWutils package has some tools to deal with EXCEL dates (per @Ben Bolker's comment).

  • if you have large sheets, reading in text files is faster than reading in from EXCEL.

  • for .xls and .xlsx files, different solutions might be necessary. EG the xlsReadWrite package currently does not support .xlsx AFAIK. gdata requires you to install additional perl libraries for .xlsx support. xlsx package can handle extensions of the same name.

Cannot get OpenCV to compile because of undefined references?

For me, this type of error:

mingw-w64-x86_64/lib/gcc/x86_64-w64-mingw32/8.2.0/../../../../x86_64-w64-mingw32/bin/ld: mingw-w64-x86_64/x86_64-w64-mingw32/lib/libTransform360.a(VideoFrameTransform.cpp.obj):VideoFrameTransform.cpp:(.text+0xc7c):
undefined reference to `cv::Mat::Mat(cv::Mat const&, cv::Rect_<int> const&)'

meant load order, I had to do -lTransform360 -lopencv_dnn345 -lopencv... just like that, that order. And putting them right next to each other helped too, don't put -lTransform360 all the way at the beginning...or you'll get, for some freaky reason:

undefined reference to `VideoFrameTransform_new'
undefined reference to `VideoFrameTransform_generateMapForPlane'

...

Import SQL file into mysql

Don't forget to use

charset utf8

If your sql file is in utf-8 :)

So you need to do:

cmd.exe

mysql -u root

mysql> charset utf8

mysql> use mydbname

mysql> source C:\myfolder\myfile.sql

Good luck ))

How to set <iframe src="..."> without causing `unsafe value` exception?

I usually add separate safe pipe reusable component as following

# Add Safe Pipe

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({name: 'mySafe'})
export class SafePipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) {
    }

    public transform(url) {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url);
    }
}
# then create shared pipe module as following 

import { NgModule } from '@angular/core'; 
import { SafePipe } from './safe.pipe';
@NgModule({
    declarations: [
        SafePipe
    ],
    exports: [
        SafePipe
    ]
})
export class SharedPipesModule {
}
# import shared pipe module in your native module

@NgModule({
    declarations: [],
    imports: [
        SharedPipesModule,
    ],
})
export class SupportModule {
}
<!-------------------
call your url (`trustedUrl` for me) and add `mySafe` as defined in Safe Pipe
---------------->
<div class="container-fluid" *ngIf="trustedUrl">
    <iframe [src]="trustedUrl | mySafe" align="middle" width="100%" height="800" frameborder="0"></iframe>
</div>

NameError: name 'reduce' is not defined in Python

You can add

from functools import reduce

before you use the reduce.

Exception in thread "main" java.lang.Error: Unresolved compilation problems

Your problem is in this line: Message messageObject = new Message ();
This error says that the Message class is not known at compile time.

So you need to import the Message class.

Something like this:

import package1.package2.Message;

Check this out.

http://docs.oracle.com/javase/tutorial/java/package/usepkgs.html

How can I set the default value for an HTML <select> element?

if you want to use the values from a Form and keep it dynamic try this with php

<form action="../<SamePage>/" method="post">


<?php
    $selected = $_POST['select'];
?>

<select name="select" size="1">

  <option <?php if($selected == '1'){echo("selected");}?>>1</option>
  <option <?php if($selected == '2'){echo("selected");}?>>2</option>

</select>
</form>

Convert int to a bit array in .NET

To convert your integer input to an array of bool of any size, just use LINQ.

bool[] ToBits(int input, int numberOfBits) {
    return Enumerable.Range(0, numberOfBits)
    .Select(bitIndex => 1 << bitIndex)
    .Select(bitMask => (input & bitMask) == bitMask)
    .ToArray();
}

So to convert an integer to a bool array of up to 32 bits, simply use it like so:

bool[] bits = ToBits(65, 8); // true, false, false, false, false, false, true, false

You may wish to reverse the array depending on your needs.

Array.Reverse(bits);

How do I create a new line in Javascript?

Use the \n for a newline character.

document.write("\n");

You can also have more than one:

document.write("\n\n\n"); // 3 new lines!  My oh my!

However, if this is rendering to HTML, you will want to use the HTML tag for a newline:

document.write("<br>");

The string Hello\n\nTest in your source will look like this:

Hello!

Test

The string Hello<br><br>Test will look like this in HTML source:

Hello<br><br>Test

The HTML one will render as line breaks for the person viewing the page, the \n just drops the text to the next line in the source (if it's on an HTML page).

Having links relative to root?

If you are creating the URL from the server side of an ASP.NET application, and deploying your website to a virtual directory (e.g. app2) in your website i.e. http://www.yourwebsite.com/app2/

then just insert

<base href="~/" />

just after the title tag.

so whenever you use root relative e.g.

<a href="/Accounts/Login"/> 

would resolve to "http://www.yourwebsite.com/app2/Accounts/Login"

This way you can always point to your files relatively-absolutely ;)

To me this is the most flexible solution.

HAX kernel module is not installed

Actual error

enter image description here

follow bellow two simple steps to fix.

Step 1:- update "Intel x86 Emulator Accelerator (HAXM installer)" Ref. bellow img enter image description here

Step2:-

After installing the installer, you have to run it to install it on your system. Open the directory where your Android SDK is located. Go inside the extras\Intel\Hardware_Accelerated_Execution_Manager directory and you should see the intelhaxm-android.exe file.

enter image description here

If you got the error "This computer meets requirements for HAXM, but VT-x is not turned on..." during installation try to turn it on in your BIOS and check your antivirus software settings also. (Check this stackoverflow post). Thats it! its working for me.

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

What are these new categories of expressions?

The FCD (n3092) has an excellent description:

— An lvalue (so called, historically, because lvalues could appear on the left-hand side of an assignment expression) designates a function or an object. [ Example: If E is an expression of pointer type, then *E is an lvalue expression referring to the object or function to which E points. As another example, the result of calling a function whose return type is an lvalue reference is an lvalue. —end example ]

— An xvalue (an “eXpiring” value) also refers to an object, usually near the end of its lifetime (so that its resources may be moved, for example). An xvalue is the result of certain kinds of expressions involving rvalue references (8.3.2). [ Example: The result of calling a function whose return type is an rvalue reference is an xvalue. —end example ]

— A glvalue (“generalized” lvalue) is an lvalue or an xvalue.

— An rvalue (so called, historically, because rvalues could appear on the right-hand side of an assignment expressions) is an xvalue, a temporary object (12.2) or subobject thereof, or a value that is not associated with an object.

— A prvalue (“pure” rvalue) is an rvalue that is not an xvalue. [ Example: The result of calling a function whose return type is not a reference is a prvalue. The value of a literal such as 12, 7.3e5, or true is also a prvalue. —end example ]

Every expression belongs to exactly one of the fundamental classifications in this taxonomy: lvalue, xvalue, or prvalue. This property of an expression is called its value category. [ Note: The discussion of each built-in operator in Clause 5 indicates the category of the value it yields and the value categories of the operands it expects. For example, the built-in assignment operators expect that the left operand is an lvalue and that the right operand is a prvalue and yield an lvalue as the result. User-defined operators are functions, and the categories of values they expect and yield are determined by their parameter and return types. —end note

I suggest you read the entire section 3.10 Lvalues and rvalues though.

How do these new categories relate to the existing rvalue and lvalue categories?

Again:

Taxonomy

Are the rvalue and lvalue categories in C++0x the same as they are in C++03?

The semantics of rvalues has evolved particularly with the introduction of move semantics.

Why are these new categories needed?

So that move construction/assignment could be defined and supported.

When is it acceptable to call GC.Collect?

This isn't that relevant to the question, but for XSLT transforms in .NET (XSLCompiledTranform) then you might have no choice. Another candidate is the MSHTML control.

How to include a Font Awesome icon in React's render()

If you are new to React JS and using create-react-app cli command to create the application, then run the following NPM command to include the latest version of font-awesome.

npm install --save font-awesome

import font-awesome to your index.js file. Just add below line to your index.js file

import '../node_modules/font-awesome/css/font-awesome.min.css'; 

or

import 'font-awesome/css/font-awesome.min.css';

Don't forget to use className as attribute

 render: function() {
    return <div><i className="fa fa-spinner fa-spin">no spinner but why</i></div>;
}

Best way to access web camera in Java

I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)

There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):

snapshot

The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.

API is really nice and easy to learn. Example how to capture single image and save it to PNG file:

Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));

Why can't non-default arguments follow default arguments?

SyntaxError: non-default argument follows default argument

If you were to allow this, the default arguments would be rendered useless because you would never be able to use their default values, since the non-default arguments come after.

In Python 3 however, you may do the following:

def fun1(a="who is you", b="True", *, x, y):
    pass

which makes x and y keyword only so you can do this:

fun1(x=2, y=2)

This works because there is no longer any ambiguity. Note you still can't do fun1(2, 2) (that would set the default arguments).

SQL: parse the first, middle and last name from a fullname field

It's difficult to answer without knowing how the "full name" is formatted.

It could be "Last Name, First Name Middle Name" or "First Name Middle Name Last Name", etc.

Basically you'll have to use the SUBSTRING function

SUBSTRING ( expression , start , length )

And probably the CHARINDEX function

CHARINDEX (substr, expression)

To figure out the start and length for each part you want to extract.

So let's say the format is "First Name Last Name" you could (untested.. but should be close) :

SELECT 
SUBSTRING(fullname, 1, CHARINDEX(' ', fullname) - 1) AS FirstName, 
SUBSTRING(fullname, CHARINDEX(' ', fullname) + 1, len(fullname)) AS LastName
FROM YourTable

Set Focus on EditText

If using requestFocus() in onCreate() introduces the issue of keyboard not showing on tap, use BindingAdapter using a SingleLiveEvent and request the focus inside that.

Here's how to do it:

BindingAdapter

@BindingAdapter("requestFocus")
fun bindRequestFocus(editText: EditText, event: Event<Boolean>?) {
    event?.getContentIfNotHandled()?.let {
        if (it) editText.requestFocus()
    }
}

What is the difference between List and ArrayList?

There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.

When you define your list as:

List myList = new ArrayList();

you can only call methods and reference members that are defined in the List interface. If you define it as:

ArrayList myList = new ArrayList();

you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.

Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).

That's called polymorphism. You can read up on it.

CSS background image to fit width, height should auto-scale in proportion

Try this,

element.style {
    background: rgba(0, 0, 0, 0) url("img/shopping_bgImg.jpg") no-repeat scroll center center / cover;
}

How to save and extract session data in codeigniter

First you have load session library.

$this->load->library("session");

You can load it in auto load, which I think is better.

To set session

$this->session->set_userdata("SESSION_NAME","VALUE");

To extract Data

$this->session->userdata("SESSION_NAME");

How to add number of days to today's date?

Here is a solution that worked for me.

function calduedate(ndays){

    var newdt = new Date(); var chrday; var chrmnth;
    newdt.setDate(newdt.getDate() + parseInt(ndays));

    var newdate = newdt.getFullYear();
    if(newdt.getMonth() < 10){
        newdate = newdate+'-'+'0'+newdt.getMonth();
    }else{
        newdate = newdate+'-'+newdt.getMonth();
    }
    if(newdt.getDate() < 10){
        newdate = newdate+'-'+'0'+newdt.getDate();
    }else{
        newdate = newdate+'-'+newdt.getDate();
    }

    alert("newdate="+newdate);

}

How to SHA1 hash a string in Android?

If you can get away with using Guava it is by far the simplest way to do it, and you don't have to reinvent the wheel:

final HashCode hashCode = Hashing.sha1().hashString(yourValue, Charset.defaultCharset());

You can then take the hashed value and get it as a byte[], as an int, or as a long.

No wrapping in a try catch, no shenanigans. And if you decide you want to use something other than SHA-1, Guava also supports sha256, sha 512, and a few I had never even heard about like adler32 and murmur3.

Check if a record exists in the database

I had a requirement to register user. In that case I need to check whether that username is already present in the database or not. I have tried the below in C# windows form application(EntityFramework) and it worked.

 var result = incomeExpenseManagementDB.Users.FirstOrDefault(x => x.userName == registerUserView.uNameText);
  if (result == null) {
      register.registerUser(registerUserView.fnameText, registerUserView.lnameText, registerUserView.eMailText, registerUserView.mobileText, registerUserView.bDateText, registerUserView.uNameText, registerUserView.pWordText);
  } else {
      MessageBox.Show("User Alreay Exist. Try with Different Username");
  }

Jackson JSON custom serialization for certain fields

In case you don't want to pollute your model with annotations and want to perform some custom operations, you could use mixins.

ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.setMixInAnnotation(Person.class, PersonMixin.class);
mapper.registerModule(simpleModule);

Override age:

public abstract class PersonMixin {
    @JsonSerialize(using = PersonAgeSerializer.class)
    public String age;
}

Do whatever you need with the age:

public class PersonAgeSerializer extends JsonSerializer<Integer> {
    @Override
    public void serialize(Integer integer, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(String.valueOf(integer * 52) + " months");
    }
}

Accessing value inside nested dictionaries

As always in python, there are of course several ways to do it, but there is one obvious way to do it.

tmpdict["ONE"]["TWO"]["THREE"] is the obvious way to do it.

When that does not fit well with your algorithm, that may be a hint that your structure is not the best for the problem.

If you just want to just save you repetative typing, you can of course alias a subset of the dict:

>>> two_dict = tmpdict['ONE']['TWO'] # now you can just write two_dict for tmpdict['ONE']['TWO']
>>> two_dict["spam"] = 23
>>> tmpdict
{'ONE': {'TWO': {'THREE': 10, 'spam': 23}}}

How to use comparison operators like >, =, < on BigDecimal

Use the compareTo method of BigDecimal :

public int compareTo(BigDecimal val) Compares this BigDecimal with the specified BigDecimal.

Returns:
-1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.

Vue equivalent of setTimeout?

please use setInterval like below:

    setInterval(()=>{this.checkOrder()},2000);

How to convert a NumPy array to PIL image applying matplotlib colormap

The method described in the accepted answer didn't work for me even after applying changes mentioned in its comments. But the below simple code worked:

import matplotlib.pyplot as plt
plt.imsave(filename, np_array, cmap='Greys')

np_array could be either a 2D array with values from 0..1 floats o2 0..255 uint8, and in that case it needs cmap. For 3D arrays, cmap will be ignored.

Easily measure elapsed time

#include<time.h> // for clock
#include<math.h> // for fmod
#include<cstdlib> //for system
#include <stdio.h> //for delay

using namespace std;

int main()
{


   clock_t t1,t2;

   t1=clock(); // first time capture

   // Now your time spanning loop or code goes here
   // i am first trying to display time elapsed every time loop runs

   int ddays=0; // d prefix is just to say that this variable will be used for display
   int dhh=0;
   int dmm=0;
   int dss=0;

   int loopcount = 1000 ; // just for demo your loop will be different of course

   for(float count=1;count<loopcount;count++)
   {

     t2=clock(); // we get the time now

     float difference= (((float)t2)-((float)t1)); // gives the time elapsed since t1 in milliseconds

    // now get the time elapsed in seconds

    float seconds = difference/1000; // float value of seconds
    if (seconds<(60*60*24)) // a day is not over
    {
        dss = fmod(seconds,60); // the remainder is seconds to be displayed
        float minutes= seconds/60;  // the total minutes in float
        dmm= fmod(minutes,60);  // the remainder are minutes to be displayed
        float hours= minutes/60; // the total hours in float
        dhh= hours;  // the hours to be displayed
        ddays=0;
    }
    else // we have reached the counting of days
    {
        float days = seconds/(24*60*60);
        ddays = (int)(days);
        float minutes= seconds/60;  // the total minutes in float
        dmm= fmod(minutes,60);  // the rmainder are minutes to be displayed
        float hours= minutes/60; // the total hours in float
        dhh= fmod (hours,24);  // the hours to be displayed

    }

    cout<<"Count Is : "<<count<<"Time Elapsed : "<<ddays<<" Days "<<dhh<<" hrs "<<dmm<<" mins "<<dss<<" secs";


    // the actual working code here,I have just put a delay function
    delay(1000);
    system("cls");

 } // end for loop

}// end of main 

How to filter a RecyclerView with a SearchView

With Android Architecture Components through the use of LiveData this can be easily implemented with any type of Adapter. You simply have to do the following steps:

1. Setup your data to return from the Room Database as LiveData as in the example below:

@Dao
public interface CustomDAO{

@Query("SELECT * FROM words_table WHERE column LIKE :searchquery")
    public LiveData<List<Word>> searchFor(String searchquery);
}

2. Create a ViewModel object to update your data live through a method that will connect your DAO and your UI

public class CustomViewModel extends AndroidViewModel {

    private final AppDatabase mAppDatabase;

    public WordListViewModel(@NonNull Application application) {
        super(application);
        this.mAppDatabase = AppDatabase.getInstance(application.getApplicationContext());
    }

    public LiveData<List<Word>> searchQuery(String query) {
        return mAppDatabase.mWordDAO().searchFor(query);
    }

}

3. Call your data from the ViewModel on the fly by passing in the query through onQueryTextListener as below:

Inside onCreateOptionsMenu set your listener as follows

searchView.setOnQueryTextListener(onQueryTextListener);

Setup your query listener somewhere in your SearchActivity class as follows

private android.support.v7.widget.SearchView.OnQueryTextListener onQueryTextListener =
            new android.support.v7.widget.SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    getResults(query);
                    return true;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    getResults(newText);
                    return true;
                }

                private void getResults(String newText) {
                    String queryText = "%" + newText + "%";
                    mCustomViewModel.searchQuery(queryText).observe(
                            SearchResultsActivity.this, new Observer<List<Word>>() {
                                @Override
                                public void onChanged(@Nullable List<Word> words) {
                                    if (words == null) return;
                                    searchAdapter.submitList(words);
                                }
                            });
                }
            };

Note: Steps (1.) and (2.) are standard AAC ViewModel and DAO implementation, the only real "magic" going on here is in the OnQueryTextListener which will update the results of your list dynamically as the query text changes.

If you need more clarification on the matter please don't hesitate to ask. I hope this helped :).

How to search all loaded scripts in Chrome Developer Tools?

In addition to Ctrl+Shift+F (Cmd+Option+F on Mac) as suggested in this answer, you can right click on the top tree node in the sources tab and select "Search in All Files":

enter image description here

What is the difference between PUT, POST and PATCH?

Think of it this way...

POST - create

PUT - replace

PATCH - update

GET - read

DELETE - delete

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

Did something like that once:

CREATE TABLE exclusions(excl VARCHAR(250));
INSERT INTO exclusions(excl)
VALUES
       ('%timeline%'),
       ('%Placeholders%'),
       ('%Stages%'),
       ('%master_stage_1205x465%'),
       ('%Accessories%'),
       ('%chosen-sprite.png'),
('%WebResource.axd');
GO
CREATE VIEW ToBeDeleted AS 
SELECT * FROM chunks
       WHERE chunks.file_id IN
       (
       SELECT DISTINCT
             lf.file_id
       FROM LargeFiles lf
       WHERE lf.file_id NOT IN
             (
             SELECT DISTINCT
                    lf.file_id
             FROM LargeFiles lf
                LEFT JOIN exclusions e ON(lf.URL LIKE e.excl)
                WHERE e.excl IS NULL
             )
       );
GO
CHECKPOINT
GO
SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;
WHILE @r>0

BEGIN
    DELETE TOP (10000) FROM ToBeDeleted;
    SET @r = @@ROWCOUNT  
END
GO

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

I know that it's an old question, but you can change the Response using a parameter (P):

public class Response<P> implements Serializable{

private static final long serialVersionUID = 1L;

public enum MessageCode {
    SUCCESS, ERROR, UNKNOWN
}

private MessageCode code;
private String message;
private P payload;

...
public P getPayload() {
    return payload;
}

public void setPayload(P payload) {
    this.payload = payload;
}

}

The method would be

public Response<Departments> getDepartments(){...}

I can't try it now but it should works.

Otherwise it's possible to extends Response

@XmlRootElement    
public class DepResponse extends Response<Department> {<no content>}

How to remove trailing whitespace in code, using another script?

fileinput seems to be for multiple input streams. This is what I would do:

with open("test.txt") as file:
    for line in file:
        line = line.rstrip()
        if line:
            print(line)

Getting all names in an enum as a String[]

Here`s an elegant solution using Apache Commons Lang 3:

EnumUtils.getEnumList(State.class)

Although it returns a List, you can convert the list easily with list.toArray()

TypeError: argument of type 'NoneType' is not iterable

If a function does not return anything, e.g.:

def test():
    pass

it has an implicit return value of None.

Thus, as your pick* methods do not return anything, e.g.:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")

the lines that call them, e.g.:

word = pickEasy()

set word to None, so wordInput in getInput is None. This means that:

if guess in wordInput:

is the equivalent of:

if guess in None:

and None is an instance of NoneType which does not provide iterator/iteration functionality, so you get that type error.

The fix is to add the return type:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

NULL values inside NOT IN clause

In A, 3 is tested for equality against each member of the set, yielding (FALSE, FALSE, TRUE, UNKNOWN). Since one of the elements is TRUE, the condition is TRUE. (It's also possible that some short-circuiting takes place here, so it actually stops as soon as it hits the first TRUE and never evaluates 3=NULL.)

In B, I think it is evaluating the condition as NOT (3 in (1,2,null)). Testing 3 for equality against the set yields (FALSE, FALSE, UNKNOWN), which is aggregated to UNKNOWN. NOT ( UNKNOWN ) yields UNKNOWN. So overall the truth of the condition is unknown, which at the end is essentially treated as FALSE.

Python Set Comprehension

primes = {x for x in range(2, 101) if all(x%y for y in range(2, min(x, 11)))}

I simplified the test a bit - if all(x%y instead of if not any(not x%y

I also limited y's range; there is no point in testing for divisors > sqrt(x). So max(x) == 100 implies max(y) == 10. For x <= 10, y must also be < x.

pairs = {(x, x+2) for x in primes if x+2 in primes}

Instead of generating pairs of primes and testing them, get one and see if the corresponding higher prime exists.

How to get an object's methods?

Get the Method Names:

var getMethodNames = function (obj) {
    return (Object.getOwnPropertyNames(obj).filter(function (key) {
        return obj[key] && (typeof obj[key] === "function");
    }));
};

Or, Get the Methods:

var getMethods     = function (obj) {
    return (Object.getOwnPropertyNames(obj).filter(function (key) {
        return obj[key] && (typeof obj[key] === "function");
    })).map(function (key) {
        return obj[key];
    });
};

excel formula to subtract number of days from a date

Here is what worked for me (Excel 14.0 - aka MS Office Pro Plus 2010):

=DATE(YEAR(A1), MONTH(A1), DAY(A1) - 16)

This takes the date (format mm/dd/yyyy) in cell A1 and subtracts 16 days with output in format of mm/dd/yyyy.

How to achieve pagination/table layout with Angular.js?

The simplest way is using slice. You pipe the slice and mention the start index and end index for the part of the data you wish to display. Here is the code:
HTML

<table>
  <thead>
     ...
  </thead>
  <tbody>
     <tr *ngFor="let row of rowData | slice:startIndex:endIndex">
        ...
     </tr>
  </tbody>
</table>
<nav *ngIf="rowData" aria-label="Page navigation example">
    <ul class="pagination">
        <li class="page-item">
            <a class="page-link" (click)="updateIndex(0)" aria-label="Previous">
                <span aria-hidden="true">First</span>
            </a>
        </li>
        <li *ngFor="let i of getArrayFromNumber(rowData.length)" class="page-item">
            <a class="page-link" (click)="updateIndex(i)">{{i+1}}</a></li>

        <li class="page-item">
            <a class="page-link" (click)="updateIndex(pageNumberArray.length-1)" aria-label="Next">
                <span aria-hidden="true">Last</span>
            </a>
        </li>
    </ul>
</nav>


TypeScript

...
public rowData = data // data you want to display in table
public paginationRowCount = 100 //number of records in a page
...
getArrayFromNumber(length) {
        if (length % this.paginationRowCount === 0) {
            this.pageNumberArray = Array.from(Array(Math.floor(length / this.paginationRowCount)).keys());
        } else {
            this.pageNumberArray = Array.from(Array(Math.floor(length / this.paginationRowCount) + 1).keys());
        }
        return this.pageNumberArray;
    }

    updateIndex(pageIndex) {
        this.startIndex = pageIndex * this.paginationRowCount;
        if (this.rowData.length > this.startIndex + this.paginationRowCount) {
            this.endIndex = this.startIndex + this.paginationRowCount;
        } else {
            this.endIndex = this.rowData.length;
        }
    }

Refence for tutorial: https://www.youtube.com/watch?v=Q0jPfb9iyE0

pip install mysql-python fails with EnvironmentError: mysql_config not found

For anyone that is using MariaDB instead of MySQL, the solution is to install the libmariadbclient-dev package and create a symbolic link to the config file with the correct name.

For example this worked for me:

ln -s /usr/bin/mariadb_config /usr/bin/mysql_config

how to set default main class in java?

You can set the Main-Class attribute in the jar file's manifest to point to which file you want to run automatically.

Create a unique number with javascript time

in reference to #Marcelo Lazaroni solution above

Date.now() + Math.random()

returns a number such as this 1567507511939.4558 (limited to 4 decimals), and will give non-unique numbers (or collisions) every 0.1%.

adding toString() fixes this

Date.now() + Math.random().toString()

returns '15675096840820.04510962122198503' (a string), and is further so 'slow' that you never get the 'same' millisecond, anyway.

How to reload / refresh model data from the server programmatically?

Before I show you how to reload / refresh model data from the server programmatically? I have to explain for you the concept of Data Binding. This is an extremely powerful concept that will truly revolutionize the way you develop. So may be you have to read about this concept from this link or this seconde link in order to unterstand how AngularjS work.

now I'll show you a sample example that exaplain how can you update your model from server.

HTML Code:

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="updateData()">Refresh Data</button>
</div>

So our controller named: PersonListCtrl and our Model named: persons. go to your Controller js in order to develop the function named: updateData() that will be invoked when we are need to update and refresh our Model persons.

Javascript Code:

app.controller('adsController', function($log,$scope,...){

.....

$scope.updateData = function(){
$http.get('/persons').success(function(data) {
       $scope.persons = data;// Update Model-- Line X
     });
}

});

Now I explain for you how it work: when user click on button Refresh Data, the server will call to function updateData() and inside this function we will invoke our web service by the function $http.get() and when we have the result from our ws we will affect it to our model (Line X).Dice that affects the results for our model, our View of this list will be changed with new Data.

maven... Failed to clean project: Failed to delete ..\org.ow2.util.asm-asm-tree-3.1.jar

If you run into this error in an IDE like Eclipse or IntelliJ, you may have one or more debug windows open and paused on a break-point. Terminate them.

Call Stored Procedure within Create Trigger in SQL Server

I think you will have to loop over the "inserted" table, which contains all rows that were updated. You can use a WHERE loop, or a WITH statement if your primary key is a GUID. This is the simpler (for me) to write, so here is my example. We use this approach, so I know for a fact it works fine.

ALTER TRIGGER [dbo].[RA2Newsletter] ON [dbo].[Reiseagent]
    AFTER INSERT
AS
        -- This is your primary key.  I assume INT, but initialize
        -- to minimum value for the type you are using.
        DECLARE @rAgent_ID INT = 0

        -- Looping variable.
        DECLARE @i INT = 0

        -- Count of rows affected for looping over
        DECLARE @count INT

        -- These are your old variables.
        DECLARE @rAgent_Name NVARCHAR(50)
        DECLARE @rAgent_Email NVARCHAR(50)
        DECLARE @rAgent_IP NVARCHAR(50)
        DECLARE @hotelID INT
        DECLARE @retval INT

    BEGIN 
        SET NOCOUNT ON ;

        -- Get count of affected rows
        SELECT  @Count = Count(rAgent_ID)
        FROM    inserted

        -- Loop over rows affected
        WHILE @i < @count
            BEGIN
                -- Get the next rAgent_ID
                SELECT TOP 1
                        @rAgent_ID = rAgent_ID
                FROM    inserted
                WHERE   rAgent_ID > @rAgent_ID
                ORDER BY rAgent_ID ASC

                -- Populate values for the current row
                SELECT  @rAgent_Name = rAgent_Name,
                        @rAgent_Email = rAgent_Email,
                        @rAgent_IP = rAgent_IP,
                        @hotelID = hotelID
                FROM    Inserted
                WHERE   rAgent_ID = @rAgent_ID

                -- Run your stored procedure
                EXEC insert2Newsletter '', '', @rAgent_Name, @rAgent_Email,
                    @rAgent_IP, @hotelID, 'RA', @retval 

                -- Set up next iteration
                SET @i = @i + 1
            END
    END 
GO

I sure hope this helps you out. Cheers!

Java JTable setting Column Width

fireTableStructureChanged();

will default the resize behavior ! If this method is called somewhere in your code AFTER you did set the column resize properties all your settings will be reset. This side effect can happen indirectly. F.e. as a consequence of the linked data model being changed in a way this method is called, after properties are set.

Spring MVC: Complex object as GET @RequestParam

I will add some short example from me.

The DTO class:

public class SearchDTO {
    private Long id[];

    public Long[] getId() {
        return id;
    }

    public void setId(Long[] id) {
        this.id = id;
    }
    // reflection toString from apache commons
    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
}

Request mapping inside controller class:

@RequestMapping(value="/handle", method=RequestMethod.GET)
@ResponseBody
public String handleRequest(SearchDTO search) {
    LOG.info("criteria: {}", search);
    return "OK";
}

Query:

http://localhost:8080/app/handle?id=353,234

Result:

[http-apr-8080-exec-7] INFO  c.g.g.r.f.w.ExampleController.handleRequest:59 - criteria: SearchDTO[id={353,234}]

I hope it helps :)

UPDATE / KOTLIN

Because currently I'm working a lot of with Kotlin if someone wants to define similar DTO the class in Kotlin should have the following form:

class SearchDTO {
    var id: Array<Long>? = arrayOf()

    override fun toString(): String {
        // to string implementation
    }
}

With the data class like this one:

data class SearchDTO(var id: Array<Long> = arrayOf())

the Spring (tested in Boot) returns the following error for request mentioned in answer:

"Failed to convert value of type 'java.lang.String[]' to required type 'java.lang.Long[]'; nested exception is java.lang.NumberFormatException: For input string: \"353,234\""

The data class will work only for the following request params form:

http://localhost:8080/handle?id=353&id=234

Be aware of this!

Java: Literal percent sign in printf statement

Escaped percent sign is double percent (%%):

System.out.printf("2 out of 10 is %d%%", 20);

Maven: Failed to retrieve plugin descriptor error

For me, the solution given on the page maven is not able to download anything from central because ssl don't work worked, when running Mint 19 in a VM:

sudo apt install ca-certificates-java
sudo update-ca-certificates -f

How to call a VbScript from a Batch File without opening an additional command prompt

rem This is the command line version
cscript "C:\Users\guest\Desktop\123\MyScript.vbs"

OR

rem This is the windowed version
wscript "C:\Users\guest\Desktop\123\MyScript.vbs"

You can also add the option //e:vbscript to make sure the scripting engine will recognize your script as a vbscript.

Windows/DOS batch files doesn't require escaping \ like *nix.

You can still use "C:\Users\guest\Desktop\123\MyScript.vbs", but this requires the user has *.vbs associated to wscript.

How to sort in-place using the merge sort algorithm?

This is my C version:

void mergesort(int *a, int len) {
  int temp, listsize, xsize;

  for (listsize = 1; listsize <= len; listsize*=2) {
    for (int i = 0, j = listsize; (j+listsize) <= len; i += (listsize*2), j += (listsize*2)) {
      merge(& a[i], listsize, listsize);
    }
  }

  listsize /= 2;

  xsize = len % listsize;
  if (xsize > 1)
    mergesort(& a[len-xsize], xsize);

  merge(a, listsize, xsize);
}

void merge(int *a, int sizei, int sizej) {
  int temp;
  int ii = 0;
  int ji = sizei;
  int flength = sizei+sizej;

  for (int f = 0; f < (flength-1); f++) {
    if (sizei == 0 || sizej == 0)
      break;

    if (a[ii] < a[ji]) {
      ii++;
      sizei--;
    }
    else {
      temp = a[ji];

      for (int z = (ji-1); z >= ii; z--)
        a[z+1] = a[z];  
      ii++;

      a[f] = temp;

      ji++;
      sizej--;
    }
  }
}

Back to previous page with header( "Location: " ); in PHP

Just try this in Javascript:

 $previous = "javascript:history.go(-1)";

Or you can try it in PHP:

if(isset($_SERVER['HTTP_REFERER'])) {
    $previous = $_SERVER['HTTP_REFERER'];
}

How do I make a batch file terminate upon encountering an error?

One minor update, you should change the checks for "if errorlevel 1" to the following...

IF %ERRORLEVEL% NEQ 0 

This is because on XP you can get negative numbers as errors. 0 = no problems, anything else is a problem.

And keep in mind the way that DOS handles the "IF ERRORLEVEL" tests. It will return true if the number you are checking for is that number or higher so if you are looking for specific error numbers you need to start with 255 and work down.

What is the difference between JavaScript and ECMAScript?

Javascript was the original name, meant to capitalize on the popularity of java. ECMA is the standards body that oversees the standard that was eventually put in place so the names are roughly equivalent.

Implementations have other names, like V8 or Rhino, etc.

How do I write a method to calculate total cost for all items in an array?

The total of 7 numbers in an array can be created as:

import java.util.*;
class Sum
{
   public static void main(String arg[])
   {
     int a[]=new int[7];
     int total=0;
     Scanner n=new Scanner(System.in);
     System.out.println("Enter the no. for total");

     for(int i=0;i<=6;i++) 
     {
       a[i]=n.nextInt();
       total=total+a[i];
      }
       System.out.println("The total is :"+total);
    }
}

error: ‘NULL’ was not declared in this scope

To complete the other answers: If you are using C++11, use nullptr, which is a keyword that means a void pointer pointing to null. (instead of NULL, which is not a pointer type)

ImportError: No module named 'selenium'

It's 2020 now, use python3 consistently

  • pip3 install selenium
  • python3 xxx.py

I meet the same problem when I install selenium using pip3, but run scripts using python.

How can I make space between two buttons in same div?

if use Bootstrap, you can change with style like: If you want only in one page, then betwen head tags add .btn-group btn{margin-right:1rem;}

If is for all the web site add to css file

How to get selected value of a dropdown menu in ReactJS

import React from 'react';
import Select from 'react-select';

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' },
];

class App extends React.Component {
  state = {
    selectedOption: null,
  };
  handleChange = selectedOption => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);
  };
  render() {
    const { selectedOption } = this.state;

    return (
      <Select
        value={selectedOption}
        onChange={this.handleChange}
        options={options}
      />
    );
  }
}

And you can check it out on this site.

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

In my case, my custom http-client didn't support the gzip encoding. I was sending the "Accept-Encoding: gzip" header, and so the response was sent back as a gzip string and couldn't be decoded.

The solution was to not send that header.

How can I use an array of function pointers?

Here's how you can use it:

New_Fun.h

#ifndef NEW_FUN_H_
#define NEW_FUN_H_

#include <stdio.h>

typedef int speed;
speed fun(int x);

enum fp {
    f1, f2, f3, f4, f5
};

void F1();
void F2();
void F3();
void F4();
void F5();
#endif

New_Fun.c

#include "New_Fun.h"

speed fun(int x)
{
    int Vel;
    Vel = x;
    return Vel;
}

void F1()
{
    printf("From F1\n");
}

void F2()
{
    printf("From F2\n");
}

void F3()
{
    printf("From F3\n");
}

void F4()
{
    printf("From F4\n");
}

void F5()
{
    printf("From F5\n");
}

Main.c

#include <stdio.h>
#include "New_Fun.h"

int main()
{
    int (*F_P)(int y);
    void (*F_A[5])() = { F1, F2, F3, F4, F5 };    // if it is int the pointer incompatible is bound to happen
    int xyz, i;

    printf("Hello Function Pointer!\n");
    F_P = fun;
    xyz = F_P(5);
    printf("The Value is %d\n", xyz);
    //(*F_A[5]) = { F1, F2, F3, F4, F5 };
    for (i = 0; i < 5; i++)
    {
        F_A[i]();
    }
    printf("\n\n");
    F_A[f1]();
    F_A[f2]();
    F_A[f3]();
    F_A[f4]();
    return 0;
}

I hope this helps in understanding Function Pointer.

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

JavaScript: How to pass object by value?

With the ES6 syntax:

let obj = Object.assign({}, o);

How to dynamic filter options of <select > with jQuery?

I had a similar problem to this, so I altered the accepted answer to make a more generic version of the function. I thought I'd leave it here.

var filterSelectOptions = function($select, callback) {

    var options = null,
        dataOptions = $select.data('options');

    if (typeof dataOptions === 'undefined') {
        options = [];
        $select.children('option').each(function() {
            var $this = $(this);
            options.push({value: $this.val(), text: $this.text()});
        });
        $select.data('options', options);
    } else {
        options = dataOptions;
    }

    $select.empty();

    $.each(options, function(i) {
        var option = options[i];
        if(callback(option)) {
            $select.append(
                $('<option/>').text(option.text).val(option.value)
            );
        }
    });
};

Get the system date and split day, month and year

You should use DateTime.TryParseExcact if you know the format, or if not and want to use the system settings DateTime.TryParse. And to print the date,DateTime.ToString with the right format in the argument. To get the year, month or day you have DateTime.Year, DateTime.Month or DateTime.Day.

See DateTime Structures in MSDN for additional references.

How to execute a query in ms-access in VBA code?

How about something like this...

Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")

Do While Not rs.EOF
   Debug.Print rs("PictureLocation") & " - " & rs("ID")
   rs.MoveNext
Loop

Can regular expressions be used to match nested patterns?

YES

...assuming that there is some maximum number of nestings you'd be happy to stop at.

Let me explain.


@torsten-marek is right that a regular expression cannot check for nested patterns like this, BUT it is possible to define a nested regex pattern which will allow you to capture nested structures like this up to some maximum depth. I created one to capture EBNF-style comments (try it out here), like:

(* This is a comment (* this is nested inside (* another level! *) hey *) yo *)

The regex (for single-depth comments) is the following:

m{1} = \(+\*+(?:[^*(]|(?:\*+[^)*])|(?:\(+[^*(]))*\*+\)+

This could easily be adapted for your purposes by replacing the \(+\*+ and \*+\)+ with { and } and replacing everything in between with a simple [^{}]:

p{1} = \{(?:[^{}])*\}

(Here's the link to try that out.)

To nest, just allow this pattern within the block itself:

p{2} = \{(?:(?:p{1})|(?:[^{}]))*\}
  ...or...
p{2} = \{(?:(?:\{(?:[^{}])*\})|(?:[^{}]))*\}

To find triple-nested blocks, use:

p{3} = \{(?:(?:p{2})|(?:[^{}]))*\}
  ...or...
p{3} = \{(?:(?:\{(?:(?:\{(?:[^{}])*\})|(?:[^{}]))*\})|(?:[^{}]))*\}

A clear pattern has emerged. To find comments nested to a depth of N, simply use the regex:

p{N} = \{(?:(?:p{N-1})|(?:[^{}]))*\}

  where N > 1 and
  p{1} = \{(?:[^{}])*\}

A script could be written to recursively generate these regexes, but that's beyond the scope of what I need this for. (This is left as an exercise for the reader. )

Converting a double to an int in C#

ToInt32 rounds. Casting to int just throws away the non-integer component.

How to switch back to 'master' with git?

I'm trying to sort of get my head around what's going on over there. Is there anything IN your "example" folder? Git doesn't track empty folders.

If you branched and switched to your new branch then made a new folder and left it empty, and then did "git commit -a", you wouldn't get that new folder in the commit.

Which means it's untracked, which means checking out a different branch wouldn't remove it.

Maven: How to change path to target directory from command line?

You should use profiles.

<profiles>
    <profile>
        <id>otherOutputDir</id>
        <build>
            <directory>yourDirectory</directory>
        </build>
    </profile>
</profiles>

And start maven with your profile

mvn compile -PotherOutputDir

If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :

<properties>
    <buildDirectory>${project.basedir}/target</buildDirectory>
</properties>

<build>
    <directory>${buildDirectory}</directory>
</build>

And compile like this :

mvn compile -DbuildDirectory=test

That's because you can't change the target directory by using -Dproject.build.directory

jQuery disable a link

I always use this in jQuery for disabling links

$("form a").attr("disabled", "disabled");

Create a .csv file with values from a Python list

Use python's csv module for reading and writing comma or tab-delimited files. The csv module is preferred because it gives you good control over quoting.

For example, here is the worked example for you:

import csv
data = ["value %d" % i for i in range(1,4)]

out = csv.writer(open("myfile.csv","w"), delimiter=',',quoting=csv.QUOTE_ALL)
out.writerow(data)

Produces:

"value 1","value 2","value 3"

How to remove listview all items

An other approach after trying the solutions below. When you need it clear, just initialise your list to new clear new list.

List<ModelData> dataLists = new ArrayList<>();
                RaporAdapter adapter = new RaporAdapter(AyrintiliRapor.this, dataLists);
                listview.setAdapter(adapter);

Or set visibility to Gone / Invisible up to need

img_pdf.setVisibility(View.INVISIBLE);

ACCESS_FINE_LOCATION AndroidManifest Permissions Not Being Granted

Compatible with all SDK versions (android.permission.ACCESS_FINE_LOCATION became dangerous permission in Android M and requires user to manually grant it).

In Android versions below Android M ContextCompat.checkSelfPermission(...) always returns true if you add these permission(s) in AndroidManifest.xml)

public void onSomeButtonClick() {
    ...
    if (!permissionsGranted()) {
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 123);
    } else doLocationAccessRelatedJob();
    ...
}

private Boolean permissionsGranted() {
    return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);
}

@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 123) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission granted.
            doLocationAccessRelatedJob();
        } else {
            // User refused to grant permission. You can add AlertDialog here
            Toast.makeText(this, "You didn't give permission to access device location", Toast.LENGTH_LONG).show();
            startInstalledAppDetailsActivity();
        }
    }
}

private void startInstalledAppDetailsActivity() {
    Intent i = new Intent();
    i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    i.addCategory(Intent.CATEGORY_DEFAULT);
    i.setData(Uri.parse("package:" + getPackageName()));
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);
}

in AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

How does Git handle symbolic links?

Git just stores the contents of the link (i.e. the path of the file system object that it links to) in a 'blob' just like it would for a normal file. It then stores the name, mode and type (including the fact that it is a symlink) in the tree object that represents its containing directory.

When you checkout a tree containing the link, it restores the object as a symlink regardless of whether the target file system object exists or not.

If you delete the file that the symlink references it doesn't affect the Git-controlled symlink in any way. You will have a dangling reference. It is up to the user to either remove or change the link to point to something valid if needed.

check if a std::vector contains a certain object?

See question: How to find an item in a std::vector?

You'll also need to ensure you've implemented a suitable operator==() for your object, if the default one isn't sufficient for a "deep" equality test.

How to get the current time in milliseconds in C Programming

There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX function gettimeofday().

Structs data type in php?

You can use an array

$something = array(
   'key' => 'value',
   'key2' => 'value2'
);

or with standard object.

$something = new StdClass();

$something->key = 'value';
$something->key2 = 'value2';

Difference between h:button and h:commandButton

This is taken from the book - The Complete Reference by Ed Burns & Chris Schalk

h:commandButton vs h:button

What’s the difference between h:commandButton|h:commandLink and h:button|h:link ?

The latter two components were introduced in 2.0 to enable bookmarkable JSF pages, when used in concert with the View Parameters feature.

There are 3 main differences between h:button|h:link and h:commandButton|h:commandLink.

First, h:button|h:link causes the browser to issue an HTTP GET request, while h:commandButton|h:commandLink does a form POST. This means that any components in the page that have values entered by the user, such as text fields, checkboxes, etc., will not automatically be submitted to the server when using h:button|h:link. To cause values to be submitted with h:button|h:link, extra action has to be taken, using the “View Parameters” feature.

The second main difference between the two kinds of components is that h:button|h:link has an outcome attribute to describe where to go next while h:commandButton|h:commandLink uses an action attribute for this purpose. This is because the former does not result in an ActionEvent in the event system, while the latter does.

Finally, and most important to the complete understanding of this feature, the h:button|h:link components cause the navigation system to be asked to derive the outcome during the rendering of the page, and the answer to this question is encoded in the markup of the page. In contrast, the h:commandButton|h:commandLink components cause the navigation system to be asked to derive the outcome on the POSTBACK from the page. This is a difference in timing. Rendering always happens before POSTBACK.

system("pause"); - Why is it wrong?

system("pause");  

is wrong because it's part of Windows API and so it won't work in other operation systems.

You should try to use just objects from C++ standard library. A better solution will be to write:

cin.get();
return 0;

But it will also cause problems if you have other cins in your code. Because after each cin, you'll tap an Enter or \n which is a white space character. cin ignores this character and leaves it in the buffer zone but cin.get(), gets this remained character. So the control of the program reaches the line return 0 and the console gets closed before letting you see the results.
To solve this, we write the code as follows:

cin.ignore();  
cin.get();  
return 0;

What in layman's terms is a Recursive Function using PHP

Laymens terms:

A recursive function is a function that calls itself

A bit more in depth:

If the function keeps calling itself, how does it know when to stop? You set up a condition, known as a base case. Base cases tell our recursive call when to stop, otherwise it will loop infinitely.

What was a good learning example for me, since I have a strong background in math, was factorial. By the comments below, it seems the factorial function may be a bit too much, I'll leave it here just in case you wanted it.

function fact($n) {
  if ($n === 0) { // our base case
     return 1;
  }
  else {
     return $n * fact($n-1); // <--calling itself.
  }
}

In regards to using recursive functions in web development, I do not personally resort to using recursive calls. Not that I would consider it bad practice to rely on recursion, but they shouldn't be your first option. They can be deadly if not used properly.

Although I cannot compete with the directory example, I hope this helps somewhat.

(4/20/10) Update:

It would also be helpful to check out this question, where the accepted answer demonstrates in laymen terms how a recursive function works. Even though the OP's question dealt with Java, the concept is the same,

Exporting functions from a DLL with dllexport

For C++ :

I just faced the same issue and I think it is worth mentioning a problem comes up when one use both __stdcall (or WINAPI) and extern "C":

As you know extern "C" removes the decoration so that instead of :

__declspec(dllexport) int Test(void)                        --> dumpbin : ?Test@@YaHXZ

you obtain a symbol name undecorated:

extern "C" __declspec(dllexport) int Test(void)             --> dumpbin : Test

However the _stdcall ( = macro WINAPI, that changes the calling convention) also decorates names so that if we use both we obtain :

   extern "C" __declspec(dllexport) int WINAPI Test(void)   --> dumpbin : _Test@0

and the benefit of extern "C" is lost because the symbol is decorated (with _ @bytes)

Note that this only occurs for x86 architecture because the __stdcall convention is ignored on x64 (msdn : on x64 architectures, by convention, arguments are passed in registers when possible, and subsequent arguments are passed on the stack.).

This is particularly tricky if you are targeting both x86 and x64 platforms.


Two solutions

  1. Use a definition file. But this forces you to maintain the state of the def file.

  2. the simplest way : define the macro (see msdn) :

#define EXPORT comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)

and then include the following pragma in the function body:

#pragma EXPORT

Full Example :

 int WINAPI Test(void)
{
    #pragma EXPORT
    return 1;
}

This will export the function undecorated for both x86 and x64 targets while preserving the __stdcall convention for x86. The __declspec(dllexport) is not required in this case.

How to download a file over HTTP?

An improved version of the PabloG code for Python 2/3:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import ( division, absolute_import, print_function, unicode_literals )

import sys, os, tempfile, logging

if sys.version_info >= (3,):
    import urllib.request as urllib2
    import urllib.parse as urlparse
else:
    import urllib2
    import urlparse

def download_file(url, dest=None):
    """ 
    Download and save a file specified by url to dest directory,
    """
    u = urllib2.urlopen(url)

    scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
    filename = os.path.basename(path)
    if not filename:
        filename = 'downloaded.file'
    if dest:
        filename = os.path.join(dest, filename)

    with open(filename, 'wb') as f:
        meta = u.info()
        meta_func = meta.getheaders if hasattr(meta, 'getheaders') else meta.get_all
        meta_length = meta_func("Content-Length")
        file_size = None
        if meta_length:
            file_size = int(meta_length[0])
        print("Downloading: {0} Bytes: {1}".format(url, file_size))

        file_size_dl = 0
        block_sz = 8192
        while True:
            buffer = u.read(block_sz)
            if not buffer:
                break

            file_size_dl += len(buffer)
            f.write(buffer)

            status = "{0:16}".format(file_size_dl)
            if file_size:
                status += "   [{0:6.2f}%]".format(file_size_dl * 100 / file_size)
            status += chr(13)
            print(status, end="")
        print()

    return filename

if __name__ == "__main__":  # Only run if this file is called directly
    print("Testing with 10MB download")
    url = "http://download.thinkbroadband.com/10MB.zip"
    filename = download_file(url)
    print(filename)

How to prevent text in a table cell from wrapping

<th nowrap="nowrap">

or

<th style="white-space:nowrap;">

or

<th class="nowrap">
<style type="text/css">
.nowrap { white-space: nowrap; }
</style>

PHP: how can I get file creation date?

This is the example code taken from the PHP documentation here: https://www.php.net/manual/en/function.filemtime.php

// outputs e.g.  somefile.txt was last changed: December 29 2002 22:16:23.

$filename = 'somefile.txt';

if (file_exists($filename)) {

    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}

The code specifies the filename, then checks if it exists and then displays the modification time using filemtime().

filemtime() takes 1 parameter which is the path to the file, this can be relative or absolute.

Access images inside public folder in laravel

Just use public_path() it will find public folder and address it itself.

<img src=public_path().'/images/imagename.jpg' >

How to set an environment variable from a Gradle build?

You can also "prepend" the environment variable setting by using 'environment' command:

run.doFirst { environment 'SPARK_LOCAL_IP', 'localhost' }

Embed image in a <button> element

The topic is 'Embed image in a button element', and the question using plain HTML. I do this using the span tag in the same way that glyphicons are used in bootstrap. My image is 16 x 16px and can be any format.

Here's the plain HTML that answers the question:

<button type="button"><span><img src="images/xxx.png" /></span>&nbsp;Click Me</button>

Break promise chain and call a function based on the step in the chain where it is broken (rejected)

Use a SequentialPromise Module

Intention

Provide a module whose responsibility is to execute requests sequentially, while tracking the current index of each operation in an ordinal manner. Define the operation in a Command Pattern for flexibility.

Participants

  • Context: The object whose member method performs an operation.
  • SequentialPromise: Defines an execute method to chain & track each operation. SequentialPromise returns a Promise-Chain from all operations performed.
  • Invoker: Creates a SequentialPromise instance, providing it context & action, and calls its execute method while passing in an ordinal list of options for each operation.

Consequences

Use SequentialPromise when ordinal behavior of Promise resolution is needed. SequentialPromise will track the index for which a Promise was rejected.

Implementation

clear();

var http = {
    get(url) {
        var delay = Math.floor( Math.random() * 10 ), even = !(delay % 2);
        var xhr = new Promise(exe);

        console.log(`REQUEST`, url, delay);
        xhr.then( (data) => console.log(`SUCCESS: `, data) ).catch( (data) => console.log(`FAILURE: `, data) );

        function exe(resolve, reject) {
            var action = { 'true': reject, 'false': resolve }[ even ];
            setTimeout( () => action({ url, delay }), (1000 * delay) );
        }

        return xhr;
    }
};

var SequentialPromise = new (function SequentialPromise() {
    var PRIVATE = this;

    return class SequentialPromise {

        constructor(context, action) {
            this.index = 0;
            this.requests = [ ];
            this.context = context;
            this.action = action;

            return this;
        }

        log() {}

        execute(url, ...more) {
            var { context, action, requests } = this;
            var chain = context[action](url);

            requests.push(chain);
            chain.then( (data) => this.index += 1 );

            if (more.length) return chain.then( () => this.execute(...more) );
            return chain;
        }

    };
})();

var sequence = new SequentialPromise(http, 'get');
var urls = [
    'url/name/space/0',
    'url/name/space/1',
    'url/name/space/2',
    'url/name/space/3',
    'url/name/space/4',
    'url/name/space/5',
    'url/name/space/6',
    'url/name/space/7',
    'url/name/space/8',
    'url/name/space/9'
];
var chain = sequence.execute(...urls);
var promises = sequence.requests;

chain.catch( () => console.warn(`EXECUTION STOPPED at ${sequence.index} for ${urls[sequence.index]}`) );

// console.log('>', chain, promises);

Gist

SequentialPromise

Run function from the command line

We can write something like this. I have used with python-3.7.x

import sys

def print_fn():
    print("Hi")

def sum_fn(a, b):
    print(a + b)

if __name__ == "__main__":
    args = sys.argv
    # args[0] = current file
    # args[1] = function name
    # args[2:] = function args : (*unpacked)
    globals()[args[1]](*args[2:])

python demo.py print_fn
python demo.py sum_fn 5 8

How should I edit an Entity Framework connection string?

If you remove the connection string from the app.config file, re-running the entity Data Model wizard will guide you to build a new connection.

Regular cast vs. static_cast vs. dynamic_cast

dynamic_cast only supports pointer and reference types. It returns NULL if the cast is impossible if the type is a pointer or throws an exception if the type is a reference type. Hence, dynamic_cast can be used to check if an object is of a given type, static_cast cannot (you will simply end up with an invalid value).

C-style (and other) casts have been covered in the other answers.

How to remove the first Item from a list?

You can find a short collection of useful list functions here.

list.pop(index)

>>> l = ['a', 'b', 'c', 'd']
>>> l.pop(0)
'a'
>>> l
['b', 'c', 'd']
>>> 

del list[index]

>>> l = ['a', 'b', 'c', 'd']
>>> del l[0]
>>> l
['b', 'c', 'd']
>>> 

These both modify your original list.

Others have suggested using slicing:

  • Copies the list
  • Can return a subset

Also, if you are performing many pop(0), you should look at collections.deque

from collections import deque
>>> l = deque(['a', 'b', 'c', 'd'])
>>> l.popleft()
'a'
>>> l
deque(['b', 'c', 'd'])
  • Provides higher performance popping from left end of the list

Fastest way to check if a file exist using standard C++/C++11/C?

there is only one faster way to check if the file exists and if you have permission to read it the way is using C language wish is faster and can be used also in any version in C++

solution: in C there is a library errno.h which has an external (global) integer variable called errno which contains a number that can be used to recognize the type of error

    #include <stdio.h>
    #include <stdbool.h>
    #include <errno.h>

    bool isFileExist(char fileName[]) {
        FILE *fp = fopen(fileName, "r");
        if (fp) {
            fclose(fp);
            return true;
        }
        return errno != ENOENT;
    }

    bool isFileCanBeRead(char fileName[]) {
        FILE *fp = fopen(fileName, "r");
        if (fp) {
            fclose(fp);
            return true;
        }
        return errno != ENOENT && errno != EPERM;
    }

Setting selection to Nothing when programming Excel

If using a button to call the paste procedure,

try activating the button after the operation. this successfully clears the selection

without

  • having to mess around with hidden things
  • selecting another cell (which is exactly the opposite of what was asked)
  • affecting the clipboard mode
  • having the hacky method of pressing escape which doesn't always work

HTH

Sub BtnCopypasta_Worksheet_Click()
   range.copy
   range.paste
BtnCopypasta.Activate
End sub

HTH

How to make popup look at the centre of the screen?

/*--------  Bootstrap Modal Popup in Center of Screen --------------*/
/*---------------extra css------*/
.modal {
    text-align: center;
    padding: 0 !important;
}
.modal:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
    margin-right: -4px;
}
.modal-dialog {
    display: inline-block;
    text-align: left;
    vertical-align: middle;
}
/*----- Modal Popup -------*/
<div class="modal fade" role="dialog">
    <div class="modal-dialog" >
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
                <h5 class="modal-title">Header</h5>
            </div>
            <div class="modal-body">
               body here     
             </div>
        <div class="modal-footer">            
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        </div>
    </div>
</div>
</div>

Detect Browser Language in PHP

Try this one:

#########################################################
# Copyright © 2008 Darrin Yeager                        #
# https://www.dyeager.org/                               #
# Licensed under BSD license.                           #
#   https://www.dyeager.org/downloads/license-bsd.txt    #
#########################################################

function getDefaultLanguage() {
   if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"]))
      return parseDefaultLanguage($_SERVER["HTTP_ACCEPT_LANGUAGE"]);
   else
      return parseDefaultLanguage(NULL);
   }

function parseDefaultLanguage($http_accept, $deflang = "en") {
   if(isset($http_accept) && strlen($http_accept) > 1)  {
      # Split possible languages into array
      $x = explode(",",$http_accept);
      foreach ($x as $val) {
         #check for q-value and create associative array. No q-value means 1 by rule
         if(preg_match("/(.*);q=([0-1]{0,1}.\d{0,4})/i",$val,$matches))
            $lang[$matches[1]] = (float)$matches[2];
         else
            $lang[$val] = 1.0;
      }

      #return default language (highest q-value)
      $qval = 0.0;
      foreach ($lang as $key => $value) {
         if ($value > $qval) {
            $qval = (float)$value;
            $deflang = $key;
         }
      }
   }
   return strtolower($deflang);
}

How to calculate the angle between a line and the horizontal axis?

Sorry, but I'm pretty sure Peter's answer is wrong. Note that the y axis goes down the page (common in graphics). As such the deltaY calculation has to be reversed, or you get the wrong answer.

Consider:

System.out.println (Math.toDegrees(Math.atan2(1,1)));
System.out.println (Math.toDegrees(Math.atan2(-1,1)));
System.out.println (Math.toDegrees(Math.atan2(1,-1)));
System.out.println (Math.toDegrees(Math.atan2(-1,-1)));

gives

45.0
-45.0
135.0
-135.0

So if in the example above, P1 is (1,1) and P2 is (2,2) [because Y increases down the page], the code above will give 45.0 degrees for the example shown, which is wrong. Change the order of the deltaY calculation and it works properly.

How to order results with findBy() in Doctrine

$ens = $em->getRepository('AcmeBinBundle:Marks')
              ->findBy(
                 array(), 
                 array('id' => 'ASC')
               );

Unable to start MySQL server

In my case I had to go to the MySQL installer, then configuration button for the MySQL server, then next until the option to "create the server as a windows service" ticked that, gave it a service name as MySQL8.0, next and then finish, that solved the issue and started a new service

How can I change the text color with jQuery?

Or you may do the following

$(this).animate({color:'black'},1000);

But you need to download the color plugin from here.

How to send and receive JSON data from a restful webservice using Jersey API

Your use of @PathParam is incorrect. It does not follow these requirements as documented in the javadoc here. I believe you just want to POST the JSON entity. You can fix this in your resource method to accept JSON entity.

@Path("/hello")
public class Hello {

  @POST
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public JSONObject sayPlainTextHello(JSONObject inputJsonObj) throws Exception {

    String input = (String) inputJsonObj.get("input");
    String output = "The input you sent is :" + input;
    JSONObject outputJsonObj = new JSONObject();
    outputJsonObj.put("output", output);

    return outputJsonObj;
  }
}

And, your client code should look like this:

  ClientConfig config = new DefaultClientConfig();
  Client client = Client.create(config);
  client.addFilter(new LoggingFilter());
  WebResource service = client.resource(getBaseURI());
  JSONObject inputJsonObj = new JSONObject();
  inputJsonObj.put("input", "Value");
  System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).post(JSONObject.class, inputJsonObj));

Find character position and update file name

The string is a .NET string so you can use .NET methods. In your case:

$index = "The string".IndexOf(" ")

will return 3, which is the first occurrence of space in the string. For more information see: http://msdn.microsoft.com/en-us/library/system.string.aspx

For your need try something like:

$s.SubString($s.IndexOf("_") + 1, $s.LastIndexOf(".") - $s.IndexOf("_") - 1)

Or you could use regexps:

if ($s -Match '(_)(.*)(\.)[^.]*$') {  $matches[2] }

(has to be adjusted depending on exactly what you need).

How to access JSON Object name/value?

If you response is like {'customer':{'first_name':'John','last_name':'Cena'}}

var d = JSON.parse(response);
alert(d.customer.first_name); // contains "John"

Thanks,

How can I update my ADT in Eclipse?

I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).

Solution is: First Update ADT to 22.0.4 and then Update SDK Tool to 22.0.4

The above link says,

ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so

What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).

How to Update your ADT to Latest Version

  1. In Eclipse go to Help

  2. Install New Software ---> Add

  3. inside Add Repository write the Name: ADT (or whatever you want)

  4. Location: https://dl-ssl.google.com/android/eclipse/

  5. after loading you should get Developer Tools and NDK Plugins

  6. check both if you want to use the Native Developer Kit (NDK) in the future or check

  7. Developer Tool only

  8. click Next

  9. Finish

Create an ArrayList of unique values

You can read from file to map, where the key is the date and skip if the the whole row if the date is already in map

        Map<String, List<String>> map = new HashMap<String, List<String>>();

        int i = 0;
        String lastData = null;
        while (s.hasNext()) {
            String str = s.next();
            if (i % 13 == 0) {
                if (map.containsKey(str)) {
                    //skip the whole row
                    lastData = null;
                } else {
                    lastData = str;
                    map.put(lastData, new ArrayList<String>());
                }
            } else if (lastData != null) {
                map.get(lastData).add(str);
            }


            i++;
        }

How do I set up access control in SVN?

Although I would suggest the Apache approach is better, SVN Serve works fine and is pretty straightforward.

Assuming your repository is called "my_repo", and it is stored in C:\svn_repos:

  1. Create a file called "passwd" in "C:\svn_repos\my_repo\conf". This file should look like:

    [Users]
    username = password
    john = johns_password
    steve = steves_password
    
  2. In C:\svn_repos\my_repo\conf\svnserve.conf set:

    [general]
    password-db = passwd
    auth-access=read
    auth-access=write
    

This will force users to log in to read or write to this repository.

Follow these steps for each repository, only including the appropriate users in the passwd file for each repository.

Executing Batch File in C#

I wanted something that was more directly usable without organization-specific hard-coded string values in it. I offer the following as a directly reusable chunk of code. The minor downside is needing to determine and pass the working folder when making the call.

public static void ExecuteCommand(string command, string workingFolder)
        {
            int ExitCode;
            ProcessStartInfo ProcessInfo;
            Process process;

            ProcessInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
            ProcessInfo.CreateNoWindow = true;
            ProcessInfo.UseShellExecute = false;
            ProcessInfo.WorkingDirectory = workingFolder;
            // *** Redirect the output ***
            ProcessInfo.RedirectStandardError = true;
            ProcessInfo.RedirectStandardOutput = true;

            process = Process.Start(ProcessInfo);
            process.WaitForExit();

            // *** Read the streams ***
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();

            ExitCode = process.ExitCode;

            MessageBox.Show("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
            MessageBox.Show("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
            MessageBox.Show("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
            process.Close();
        }

Called like this:

    // This will get the current WORKING directory (i.e. \bin\Debug)
    string workingDirectory = Environment.CurrentDirectory;
    // This will get the current PROJECT directory
    string projectDirectory = Directory.GetParent(workingDirectory).Parent.FullName;
    string commandToExecute = Path.Combine(projectDirectory, "TestSetup", "WreckersTestSetupQA.bat");
    string workingFolder = Path.GetDirectoryName(commandToExecute);
    commandToExecute = QuotesAround(commandToExecute);
    ExecuteCommand(commandToExecute, workingFolder);

In this example, from within Visual Studio 2017, as part of a test run, I want to run an environment reset batch file before executing some tests. (SpecFlow+xUnit). I got tired of extra steps for manually running the bat file separately, and wanted to just run the bat file as part of the C# test setup code. The environment reset batch file moves test case files back into the input folder, cleans up output folders, etc. to get to the proper test starting state for testing. The QuotesAround method simply puts quotes around the command line in case there are spaces in folder names ("Program Files", anyone?). All that's in it is this: private string QuotesAround(string input) {return "\"" + input + "\"";}

Hope some find this useful and save a few minutes if your scenario is similar to mine.

PHP mPDF save file as PDF

This can be done like this. It worked fine for me. And also set the directory permissions to 777 or 775 if not set.

ob_clean();
$mpdf->Output('directory_name/pdf_file_name.pdf', 'F');

How to validate array in Laravel?

Asterisk symbol (*) is used to check values in the array, not the array itself.

$validator = Validator::make($request->all(), [
    "names"    => "required|array|min:3",
    "names.*"  => "required|string|distinct|min:3",
]);

In the example above:

  • "names" must be an array with at least 3 elements,
  • values in the "names" array must be distinct (unique) strings, at least 3 characters long.

EDIT: Since Laravel 5.5 you can call validate() method directly on Request object like so:

$data = $request->validate([
    "name"    => "required|array|min:3",
    "name.*"  => "required|string|distinct|min:3",
]);

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded

I find that the "solution" of just increasing the timeouts obscures what's really going on here, which is either

  1. Your code and/or network calls are way too slow (should be sub 100 ms for a good user experience)
  2. The assertions (tests) are failing and something is swallowing the errors before Mocha is able to act on them.

You usually encounter #2 when Mocha doesn't receive assertion errors from a callback. This is caused by some other code swallowing the exception further up the stack. The right way of dealing with this is to fix the code and not swallow the error.

When external code swallows your errors

In case it's a library function that you are unable to modify, you need to catch the assertion error and pass it onto Mocha yourself. You do this by wrapping your assertion callback in a try/catch block and pass any exceptions to the done handler.

it('should not fail', function (done) { // Pass reference here!

  i_swallow_errors(function (err, result) {
    try { // boilerplate to be able to get the assert failures
      assert.ok(true);
      assert.equal(result, 'bar');
      done();
    } catch (error) {
      done(error);
    }
  });
});

This boilerplate can of course be extracted into some utility function to make the test a little more pleasing to the eye:

it('should not fail', function (done) { // Pass reference here!
    i_swallow_errors(handleError(done, function (err, result) {
        assert.equal(result, 'bar');
    }));
});

// reusable boilerplate to be able to get the assert failures
function handleError(done, fn) {
    try { 
        fn();
        done();
    } catch (error) {
        done(error);
    }
}

Speeding up network tests

Other than that I suggest you pick up the advice on starting to use test stubs for network calls to make tests pass without having to rely on a functioning network. Using Mocha, Chai and Sinon the tests might look something like this

describe('api tests normally involving network calls', function() {

    beforeEach: function () {
        this.xhr = sinon.useFakeXMLHttpRequest();
        var requests = this.requests = [];

        this.xhr.onCreate = function (xhr) {
            requests.push(xhr);
        };
    },

    afterEach: function () {
        this.xhr.restore();
    }


    it("should fetch comments from server", function () {
        var callback = sinon.spy();
        myLib.getCommentsFor("/some/article", callback);
        assertEquals(1, this.requests.length);

        this.requests[0].respond(200, { "Content-Type": "application/json" },
                                 '[{ "id": 12, "comment": "Hey there" }]');
        expect(callback.calledWith([{ id: 12, comment: "Hey there" }])).to.be.true;
    });

});

See Sinon's nise docs for more info.

Duplicate line in Visual Studio Code

Mac:

Duplicate Line Down :shift + option + ?

Duplicate Line Up:shift + option + ?

Can't connect to local MySQL server through socket homebrew

You'll need to run mysql_install_db - easiest way is if you're in the install directory:

$ cd /usr/local/Cellar/mysql/<version>/ 
$ mysql_install_db

Alternatively, you can feed mysql_install_db a basedir parameter like the following:

$ mysql_install_db --basedir="$(brew --prefix mysql)"

How can I get a specific parameter from location.search?

A non-regex approach, you can simply split by the character '&' and iterate through the key/value pair:

function getParameter(paramName) {
  var searchString = window.location.search.substring(1),
      i, val, params = searchString.split("&");

  for (i=0;i<params.length;i++) {
    val = params[i].split("=");
    if (val[0] == paramName) {
      return val[1];
    }
  }
  return null;
}

2020 EDIT:

Nowadays, in modern browsers you can use the URLSearchParams constructor:

_x000D_
_x000D_
const params = new URLSearchParams('?year=2020&month=02&day=01')_x000D_
_x000D_
// You can access specific parameters:_x000D_
console.log(params.get('year'))_x000D_
console.log(params.get('month'))_x000D_
_x000D_
// And you can iterate over all parameters_x000D_
for (const [key, value] of params) {_x000D_
  console.log(`Key: ${key}, Value: ${value}`);_x000D_
}
_x000D_
_x000D_
_x000D_

Restful API service

Robby provides a great answer, though I can see you still looking for more information. I implemented REST api calls the easy BUT wrong way. It wasn't until watching this Google I/O video that I understood where I went wrong. It's not as simple as putting together an AsyncTask with a HttpUrlConnection get/put call.

Select top 2 rows in Hive

Yes, here you can use LIMIT.

You can try it by the below query:

SELECT * FROM employee_list SORT BY salary DESC LIMIT 2

Unix command-line JSON parser?

Checkout TickTick.

It's a true Bash JSON parser.

#!/bin/bash
. /path/to/ticktick.sh

# File
DATA=`cat data.json`
# cURL
#DATA=`curl http://foobar3000.com/echo/request.json`

tickParse "$DATA"

echo ``pathname``
echo ``headers["user-agent"]``

foreach loop in angularjs

Questions 1 & 2

So basically, first parameter is the object to iterate on. It can be an array or an object. If it is an object like this :

var values = {name: 'misko', gender: 'male'};

Angular will take each value one by one the first one is name, the second is gender.

If your object to iterate on is an array (also possible), like this :

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
 { "Name" : "Linda", "Password" : "lindatheQueen" }]

Angular.forEach will take one by one starting by the first object, then the second object.

For each of this object, it will so take them one by one and execute a specific code for each value. This code is called the iterator function. forEach is smart and behave differently if you are using an array of a collection. Here is some exemple :

var obj = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(obj, function(value, key) {
  console.log(key + ': ' + value);
});
// it will log two iteration like this
// name: misko
// gender: male

So key is the string value of your key and value is ... the value. You can use the key to access your value like this : obj['name'] = 'John'

If this time you display an array, like this :

var values = [{ "Name" : "Thomas", "Password" : "thomasTheKing" },
           { "Name" : "Linda", "Password" : "lindatheQueen" }];
angular.forEach(values, function(value, key){
     console.log(key + ': ' + value);
});
// it will log two iteration like this
// 0: [object Object]
// 1: [object Object]

So then value is your object (collection), and key is the index of your array since :

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
 { "Name" : "Linda", "Password" : "lindatheQueen" }]
// is equal to
{0: { "Name" : "Thomas", "Password" : "thomasTheKing" },
 1: { "Name" : "Linda", "Password" : "lindatheQueen" }}

I hope it answer your question. Here is a JSFiddle to run some code and test if you want : http://jsfiddle.net/ygahqdge/

Debugging your code

The problem seems to come from the fact $http.get() is an asynchronous request.

You send a query on your son, THEN when you browser end downloading it it execute success. BUT just after sending your request your perform a loop using angular.forEach without waiting the answer of your JSON.

You need to include the loop in the success function

var app = angular.module('testModule', [])
    .controller('testController', ['$scope', '$http', function($scope, $http){
    $http.get('Data/info.json').then(function(data){
         $scope.data = data;

         angular.forEach($scope.data, function(value, key){
         if(value.Password == "thomasTheKing")
           console.log("username is thomas");
         });
    });

});

This should work.

Going more deeply

The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.

You can give a look at deferred/promise APIs, it is an important concept of Angular to make smooth asynchronous actions.

finding multiples of a number in Python

If this is what you are looking for -

To find all the multiples between a given number and a limit

def find_multiples(integer, limit):
    return list(range(integer,limit+1, integer))

This should return -

Test.assert_equals(find_multiples(5, 25), [5, 10, 15, 20, 25])

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at

  1. session_start() must be at the top of your source, no html or other output befor!
  2. your can only send session_start() one time
  3. by this way if(session_status()!=PHP_SESSION_ACTIVE) session_start()

Regular expression to match numbers with or without commas and decimals in text

Here's a regex:

(?:\d+)((\d{1,3})*([\,\ ]\d{3})*)(\.\d+)?

that accepts numbers:

  • without spaces and/or decimals, eg. 123456789, 123.123
  • with commas or spaces as thousands separator and/or decimals, eg. 123 456 789, 123 456 789.100, 123,456, 3,232,300,000.00

Tests: http://regexr.com/3h1a2

How do you truncate all tables in a database using TSQL?

It is a little late but it might help someone. I created a procedure sometimes back which does the following using T-SQL:

  1. Store all constraints in a Temporary table
  2. Drop All Constraints
  3. Truncate all tables with exception of some tables, which does not need truncation
  4. Recreate all Constraints.

I have listed it on my blog here

How do I put an already-running process under nohup?

This worked for me on Ubuntu linux while in tcshell.

  1. CtrlZ to pause it

  2. bg to run in background

  3. jobs to get its job number

  4. nohup %n where n is the job number

How can I refresh or reload the JFrame?

Try this code. I also faced the same problem, but some how I solved it.

public class KitchenUserInterface {

    private JFrame frame;
    private JPanel main_panel, northpanel , southpanel;
    private JLabel label;
    private JButton nextOrder;
    private JList list;

    private static KitchenUserInterface kitchenRunner ;

    public void setList(String[] order){
        kitchenRunner.frame.dispose();
        kitchenRunner.frame.setVisible(false);
        kitchenRunner= new KitchenUserInterface(order);

    }

    public KitchenUserInterface getInstance() {
        if(kitchenRunner == null) {
            synchronized(KitchenUserInterface.class) {
                if(kitchenRunner == null) {
                    kitchenRunner = new KitchenUserInterface();
                }
            }
        }


        return this.kitchenRunner;
    }

    private KitchenUserInterface() {


        frame = new JFrame("Lullaby's Kitchen");
        main_panel = new JPanel();
        main_panel.setLayout(new BorderLayout());
        frame.setContentPane(main_panel);



        northpanel = new JPanel();
        northpanel.setLayout(new FlowLayout());


        label = new JLabel("Kitchen");

        northpanel.add(label);


        main_panel.add(northpanel , BorderLayout.NORTH);


        frame.setSize(500 , 500 );
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private KitchenUserInterface (String[] order){
        this();
        list = new JList<String>(order);
        main_panel.add(list , BorderLayout.CENTER);

        southpanel = new JPanel();
         southpanel.setLayout(new FlowLayout());

         nextOrder = new JButton("Next Order Set");
         nextOrder.addActionListener(new OrderUpListener(list));
         southpanel.add(nextOrder);
         main_panel.add(southpanel, BorderLayout.SOUTH);



    }

    public static void main(String[] args) {
        KitchenUserInterface dat = kitchenRunner.getInstance();
        try{

        Thread.sleep(1500);
        System.out.println("Ready");
        dat.setList(OrderArray.getInstance().getOrders());
        }
        catch(Exception event) {
            System.out.println("Error sleep");
            System.out.println(event);
        }


        }

}

is inaccessible due to its protection level

myClub.distance = Console.ReadLine();

should be

myClub.mydistance = Console.ReadLine(); 

use your public properties that you have defined for others as well instead of the protected field members.

How to add and get Header values in WebApi

In case someone is using ASP.NET Core for model binding,

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

There's is built in support for retrieving values from the header using the [FromHeader] attribute

public string Test([FromHeader]string Host, [FromHeader]string Content-Type )
{
     return $"Host: {Host} Content-Type: {Content-Type}";
}

How to fix nginx throws 400 bad request headers on any header testing tools?

Just to clearify, in /etc/nginx/nginx.conf, you can put at the beginning of the file the line

error_log /var/log/nginx/error.log debug;

And then restart nginx:

sudo service nginx restart

That way you can detail what nginx is doing and why it is returning the status code 400.

Programmatically get height of navigation bar

The light bulb started to come on. Unfortunately, I have not discovered a uniform way to correct the problem, as described below.

I believe that my whole problem centers on my autoresizingMasks. And the reason I have concluded that is the same symptoms exist, with or without a UIWebView. And that symptom is that everything is peachy for Portrait. For Landscape, the bottom-most UIButton pops down behind the TabBar.

For example, on one UIView, I have, from top to bottom:

UIView – both springs set (default case) and no struts

UIScrollView - If I set the two springs, and clear everything else (like the UIView), then the UIButton intrudes on the object immediately above it. If I clear everything, then UIButton is OK, but the stuff at the very top hides behind the StatusBar Setting only the top strut, the UIButton pops down behind the Tab Bar.

UILabel and UIImage next vertically – top strut set, flexible everywhere else

Just to complete the picture for the few that have a UIWebView:

UIWebView - Struts: top, left, right Springs: both

UIButton – nothing set, i.e., flexible everywhere

Although my light bulb is dim, there appears to be hope.

Is "delete this" allowed in C++?

Well, in Component Object Model (COM) delete this construction can be a part of Release method that is called whenever you want to release aquisited object:

void IMyInterface::Release()
{
    --instanceCount;
    if(instanceCount == 0)
        delete this;
}

Fetch frame count with ffmpeg

In Unix, this works like a charm:

ffmpeg -i 00000.avi -vcodec copy -acodec copy -f null /dev/null 2>&1 \
                                          | grep 'frame=' | cut -f 2 -d ' '

Android Lint contentDescription warning

Non textual widgets need a content description in some ways to describe textually the image so that screens readers to be able to describe the user interface. You can ignore the property xmlns:tools="http://schemas.android.com/tools"
tools:ignore="contentDescription"
or define the property android:contentDescription="your description"

How can I run a windows batch file but hide the command window?

To self-hide already running script you'll need getCmdPid.bat and windowoMode.bat

@echo off

echo self minimizing
call getCmdPid.bat
call windowMode.bat -pid %errorlevel% -mode hidden

echo --other commands--
pause

Here I've compiled all ways that I know to start a hidden process with batch without external tools.With a ready to use scripts (some of them rich on options) , and all of them form command line.Where is possible also the PID is returned .Used tools are IEXPRESS,SCHTASKS,WScript.Shell,Win32_Process and JScript.Net - but all of them wrapped in a .bat files.

Deep copy an array in Angular 2 + TypeScript

Here is my own. Doesn't work for complex cases, but for a simple array of Objects, it's good enough.

  deepClone(oldArray: Object[]) {
    let newArray: any = [];
    oldArray.forEach((item) => {
      newArray.push(Object.assign({}, item));
    });
    return newArray;
  }

How do you make Vim unhighlight what you searched for?

Append the following line to the end of your .vimrc to prevent highlighting altogether:

set nohlsearch

Skipping error in for-loop

One (dirty) way to do it is to use tryCatch with an empty function for error handling. For example, the following code raises an error and breaks the loop :

for (i in 1:10) {
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
Erreur : Urgh, the iphone is in the blender !

But you can wrap your instructions into a tryCatch with an error handling function that does nothing, for example :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

But I think you should at least print the error message to know if something bad happened while letting your code continue to run :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
ERROR : Urgh, the iphone is in the blender ! 
[1] 8
[1] 9
[1] 10

EDIT : So to apply tryCatch in your case would be something like :

for (v in 2:180){
    tryCatch({
        mypath=file.path("C:", "file1", (paste("graph",names(mydata[columnname]), ".pdf", sep="-")))
        pdf(file=mypath)
        mytitle = paste("anything")
        myplotfunction(mydata[,columnnumber]) ## this function is defined previously in the program
        dev.off()
    }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

How to get the size of a file in MB (Megabytes)?

Try following code:

File file = new File("infilename");

// Get the number of bytes in the file
long sizeInBytes = file.length();
//transform in MB
long sizeInMb = sizeInBytes / (1024 * 1024);

Is there a way to avoid null check before the for-each loop iteration starts?

How much shorter do you want it to be? It is only an extra 2 lines AND it is clear and concise logic.

I think the more important thing you need to decide is if null is a valid value or not. If they are not valid, you should write you code to prevent it from happening. Then you would not need this kind of check. If you go get an exception while doing a foreach loop, that is a sign that there is a bug somewhere else in your code.

ModuleNotFoundError: What does it mean __main__ is not a package?

I have the same issue as you did. I think the problem is that you used relative import in in-package import. There is no __init__.py in your directory. So just import as Moses answered above.

The core issue I think is when you import with a dot:

from .p_02_paying_debt_off_in_a_year import compute_balance_after

It is equivalent to:

from __main__.p_02_paying_debt_off_in_a_year import compute_balance_after

where __main__ refers to your current module p_03_using_bisection_search.py.


Briefly, the interpreter does not know your directory architecture.

When the interpreter get in p_03.py, the script equals:

from p_03_using_bisection_search.p_02_paying_debt_off_in_a_year import compute_balance_after

and p_03_using_bisection_search does not contain any modules or instances called p_02_paying_debt_off_in_a_year.


So I came up with a cleaner solution without changing python environment valuables (after looking up how requests do in relative import):

The main architecture of the directory is:

main.py
setup.py
problem_set_02/
   __init__.py
   p01.py
   p02.py
   p03.py

Then write in __init__.py:

from .p_02_paying_debt_off_in_a_year import compute_balance_after

Here __main__ is __init__ , it exactly refers to the module problem_set_02.

Then go to main.py:

import problem_set_02

You can also write a setup.py to add specific module to the environment.

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

How to calculate an age based on a birthday?

Stackoverflow uses such function to determine the age of a user.

Calculate age in C#

The given answer is

DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age)) age--;

So your helper method would look like

public static string Age(this HtmlHelper helper, DateTime birthday)
{
    DateTime now = DateTime.Today;
    int age = now.Year - birthday.Year;
    if (now < birthday.AddYears(age)) age--;

    return age.ToString();
}

Today, I use a different version of this function to include a date of reference. This allow me to get the age of someone at a future date or in the past. This is used for our reservation system, where the age in the future is needed.

public static int GetAge(DateTime reference, DateTime birthday)
{
    int age = reference.Year - birthday.Year;
    if (reference < birthday.AddYears(age)) age--;

    return age;
}

How do I strip all spaces out of a string in PHP?

Do you just mean spaces or all whitespace?

For just spaces, use str_replace:

$string = str_replace(' ', '', $string);

For all whitespace (including tabs and line ends), use preg_replace:

$string = preg_replace('/\s+/', '', $string);

(From here).

How to use a filter in a controller?

Using following sample code we can filter array in angular controller by name. this is based on following description. http://docs.angularjs.org/guide/filter

this.filteredArray = filterFilter(this.array, {name:'Igor'});

JS:

 angular.module('FilterInControllerModule', []).
    controller('FilterController', ['filterFilter', function(filterFilter) {
      this.array = [
        {name: 'Tobias'},
        {name: 'Jeff'},
        {name: 'Brian'},
        {name: 'Igor'},
        {name: 'James'},
        {name: 'Brad'}
      ];
      this.filteredArray = filterFilter(this.array, {name:'Igor'});
    }]);

HTML

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example96-production</title>
  

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.3/angular.min.js"></script>
  <script src="script.js"></script>
  

  
</head>
<body ng-app="FilterInControllerModule">
    <div ng-controller="FilterController as ctrl">
    <div>
      All entries:
      <span ng-repeat="entry in ctrl.array">{{entry.name}} </span>
    </div>
    <div>
      Filter By Name in angular controller
      <span ng-repeat="entry in ctrl.filteredArray">{{entry.name}} </span>
    </div>
  </div>
</body>
</html>

Unique random string generation

Get Unique Key using GUID Hash code

public static string GetUniqueKey(int length)
{
    string guidResult = string.Empty;

    while (guidResult.Length < length)
    {
        // Get the GUID.
        guidResult += Guid.NewGuid().ToString().GetHashCode().ToString("x");
    }

    // Make sure length is valid.
    if (length <= 0 || length > guidResult.Length)
        throw new ArgumentException("Length must be between 1 and " + guidResult.Length);

    // Return the first length bytes.
    return guidResult.Substring(0, length);
}

How can I get client information such as OS and browser

There are two not bad libs for parsing user agent strings:

Module 'tensorflow' has no attribute 'contrib'

This issue might be helpful for you, it explains how to achieve TPUStrategy, a popular functionality of tf.contrib in TF<2.0.

So, in TF 1.X you could do the following:

resolver = tf.contrib.cluster_resolver.TPUClusterResolver('grpc://' + os.environ['COLAB_TPU_ADDR'])
tf.contrib.distribute.initialize_tpu_system(resolver)
strategy = tf.contrib.distribute.TPUStrategy(resolver)

And in TF>2.0, where tf.contrib is deprecated, you achieve the same by:

tf.config.experimental_connect_to_host('grpc://' + os.environ['COLAB_TPU_ADDR'])
resolver = tf.distribute.cluster_resolver.TPUClusterResolver('grpc://' + os.environ['COLAB_TPU_ADDR'])
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.experimental.TPUStrategy(resolver) 

C#: Assign same value to multiple variables in single statement

It's as simple as:

num1 = num2 = 5;

When using an object property instead of variable, it is interesting to know that the get accessor of the intermediate value is not called. Only the set accessor is invoked for all property accessed in the assignation sequence.

Take for example a class that write to the console everytime the get and set accessor are invoked.

static void Main(string[] args)
{
    var accessorSource = new AccessorTest(5);
    var accessor1 = new AccessorTest();
    var accessor2 = new AccessorTest();

    accessor1.Value = accessor2.Value = accessorSource.Value;

    Console.ReadLine();
}

public class AccessorTest
{
    public AccessorTest(int value = default(int))
    {
        _Value = value;
    }

    private int _Value;

    public int Value
    {
        get
        {
            Console.WriteLine("AccessorTest.Value.get {0}", _Value);
            return _Value;
        }
        set
        {
            Console.WriteLine("AccessorTest.Value.set {0}", value);
            _Value = value;
        }
    }
}

This will output

AccessorTest.Value.get 5
AccessorTest.Value.set 5
AccessorTest.Value.set 5

Meaning that the compiler will assign the value to all properties and it will not re-read the value every time it is assigned.

What is "not assignable to parameter of type never" error in typescript?

One more reason for the error.

if you are exporting after wrapping component with connect()() then props may give typescript error
Solution: I didn't explore much as I had the option of replacing connect function with useSelector hook
for example

/* Comp.tsx */
interface IComp {
 a: number
}

const Comp = ({a}:IComp) => <div>{a}</div>

/* ** 

below line is culprit, you are exporting default the return 
value of Connect and there is no types added to that return
value of that connect()(Comp) 

** */

export default connect()(Comp)


--
/* App.tsx */
const App = () => {
/**  below line gives same error 
[ts] Argument of type 'number' is not assignable to 
parameter of type 'never' */
 return <Comp a={3} />
}

Get the year from specified date php

  public function getYear($pdate) {
    $date = DateTime::createFromFormat("Y-m-d", $pdate);
    return $date->format("Y");
}

public function getMonth($pdate) {
    $date = DateTime::createFromFormat("Y-m-d", $pdate);
    return $date->format("m");
}

public function getDay($pdate) {
    $date = DateTime::createFromFormat("Y-m-d", $pdate);
    return $date->format("d");
}

How to get all key in JSON object (javascript)

var input = {"document":
  {"people":[
    {"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
    {"name":["hermione granger"],"age":["18"],"gender":["Female"]},
  ]}
}

var keys = [];
for(var i = 0;i<input.document.people.length;i++)
{
    Object.keys(input.document.people[i]).forEach(function(key){
        if(keys.indexOf(key) == -1)
        {
            keys.push(key);
        }
    });
}
console.log(keys);

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

Lumen: get URL parameter in a Blade view

Laravel 5.6:

{{ Request::query('parameter') }}

What does the variable $this mean in PHP?

It's a reference to the current object, it's most commonly used in object oriented code.

Example:

<?php
class Person {
    public $name;

    function __construct( $name ) {
        $this->name = $name;
    }
};

$jack = new Person('Jack');
echo $jack->name;

This stores the 'Jack' string as a property of the object created.

How can I query for null values in entity framework?

I'm not able to comment divega's post, but among the different solutions presented here, divega's solution produces the best SQL. Both performance wise and length wise. I just checked with SQL Server Profiler and by looking at the execution plan (with "SET STATISTICS PROFILE ON").

Find a value in DataTable

Maybe you can filter rows by possible columns like this :

DataRow[] filteredRows = 
  datatable.Select(string.Format("{0} LIKE '%{1}%'", columnName, value));

Convert a String representation of a Dictionary to a dictionary?

using json.loads:

>>> import json
>>> h = '{"foo":"bar", "foo2":"bar2"}'
>>> d = json.loads(h)
>>> d
{u'foo': u'bar', u'foo2': u'bar2'}
>>> type(d)
<type 'dict'>

The tilde operator in Python

The only time I've ever used this in practice is with numpy/pandas. For example, with the .isin() dataframe method.

In the docs they show this basic example

>>> df.isin([0, 2])
        num_legs  num_wings
falcon      True       True
dog        False       True

But what if instead you wanted all the rows not in [0, 2]?

>>> ~df.isin([0, 2])
        num_legs  num_wings
falcon     False       False
dog        True        False

convert string to char*

There are many ways. Here are at least five:

/*
 * An example of converting std::string to (const)char* using five
 * different methods. Error checking is emitted for simplicity.
 *
 * Compile and run example (using gcc on Unix-like systems):
 *
 *  $ g++ -Wall -pedantic -o test ./test.cpp
 *  $ ./test
 *  Original string (0x7fe3294039f8): hello
 *  s1 (0x7fe3294039f8): hello
 *  s2 (0x7fff5dce3a10): hello
 *  s3 (0x7fe3294000e0): hello
 *  s4 (0x7fe329403a00): hello
 *  s5 (0x7fe329403a10): hello
 */

#include <alloca.h>
#include <string>
#include <cstring>

int main()
{
    std::string s0;
    const char *s1;
    char *s2;
    char *s3;
    char *s4;
    char *s5;

    // This is the initial C++ string.
    s0 = "hello";

    // Method #1: Just use "c_str()" method to obtain a pointer to a
    // null-terminated C string stored in std::string object.
    // Be careful though because when `s0` goes out of scope, s1 points
    // to a non-valid memory.
    s1 = s0.c_str();

    // Method #2: Allocate memory on stack and copy the contents of the
    // original string. Keep in mind that once a current function returns,
    // the memory is invalidated.
    s2 = (char *)alloca(s0.size() + 1);
    memcpy(s2, s0.c_str(), s0.size() + 1);

    // Method #3: Allocate memory dynamically and copy the content of the
    // original string. The memory will be valid until you explicitly
    // release it using "free". Forgetting to release it results in memory
    // leak.
    s3 = (char *)malloc(s0.size() + 1);
    memcpy(s3, s0.c_str(), s0.size() + 1);

    // Method #4: Same as method #3, but using C++ new/delete operators.
    s4 = new char[s0.size() + 1];
    memcpy(s4, s0.c_str(), s0.size() + 1);

    // Method #5: Same as 3 but a bit less efficient..
    s5 = strdup(s0.c_str());

    // Print those strings.
    printf("Original string (%p): %s\n", s0.c_str(), s0.c_str());
    printf("s1 (%p): %s\n", s1, s1);
    printf("s2 (%p): %s\n", s2, s2);
    printf("s3 (%p): %s\n", s3, s3);
    printf("s4 (%p): %s\n", s4, s4);
    printf("s5 (%p): %s\n", s5, s5);

    // Release memory...
    free(s3);
    delete [] s4;
    free(s5);
}

SQL: How to properly check if a record exists

You can use:

SELECT COUNT(1) FROM MyTable WHERE ... 

or

WHERE [NOT] EXISTS 
( SELECT 1 FROM MyTable WHERE ... )

This will be more efficient than SELECT * since you're simply selecting the value 1 for each row, rather than all the fields.

There's also a subtle difference between COUNT(*) and COUNT(column name):

  • COUNT(*) will count all rows, including nulls
  • COUNT(column name) will only count non null occurrences of column name

Simple proof that GUID is not unique

  1. Go to the cryogenics lab in the New York City.
  2. Freeze yourself for (roughly) 1990 years.
  3. Get a job at Planet Express.
  4. Buy a brand-new CPU. Build a computer, run the program, and place it in the safe place with an pseudo-perpetual motion machine like the doomsday machine.
  5. Wait until the time machine is invented.
  6. Jump to the future using the time machine. If you bought 1YHz 128bit CPU, go to 3,938,453,320 days 20 hours 15 minutes 38 seconds 463 ms 463 µs 374 ns 607 ps after when you started to run the program.
  7. ...?
  8. PROFIT!!!

... It takes at least 10,783,127 years even if you had 1YHz CPU which is 1,000,000,000,000,000 (or 1,125,899,906,842,624 if you prefer to use binary prefix) times faster than 1GHz CPU.

So rather than waiting for the compute finished, it would be better to feed pigeons which lost their home because other n pigeons took their home. :(

Or, you can wait until 128-bit quantum computer is invented. Then you may prove that GUID is not unique, by using your program in reasonable time(maybe).

How to get main window handle from process id?

Just to make sure you are not confusing the tid (thread id) and the pid (process id):

DWORD pid;
DWORD tid = GetWindowThreadProcessId( this->m_hWnd, &pid);

Locate Git installation folder on Mac OS X

On most of UNIX based sys, its at /usr/bin/git (if installed with default options)
all git related scripts are at /usr/libexec/git-core

bash: mkvirtualenv: command not found

Use this procedure to create virtual env in ubuntu

Step 1

Install pip

   sudo apt-get install python-pip

step 2

Install virtualenv

   sudo pip install virtualenv

step 3

Create a dir to store your virtualenvs (I use ~/.virtualenvs)

   mkdir ~/.virtualenvs

or use this command to install specific version of python in env

virtualenv -p /usr/bin/python3.6 venv

step 4

   sudo pip install virtualenvwrapper

step 5

   sudo nano ~/.bashrc

step 6

Add this two line code at the end of the bashrc file

  export WORKON_HOME=~/.virtualenvs
  source /usr/local/bin/virtualenvwrapper.sh

step 7

Open new terminal (recommended)

step 8

Create a new virtualenv

  mkvirtualenv myawesomeproject

step 9

To load or switch between virtualenvs, use the workon command:

  workon myawesomeproject

step 10

To exit your new virtualenv, use

 deactivate

and make sure using pip vs pip3

OR follow the steps below to install virtual environment using python3

Install env

python3 -m venv my-project-env

and activate your virtual environment using the following command:

source my-project-env/bin/activate

or if you want particular python version

virtualenv --python=python3.7.5 myenv

Print: Entry, ":CFBundleIdentifier", Does Not Exist

My terminal pops out the same message due to deleting some simulators I don't use in Xcode.

If you run react-native run-ios with no specific parameters, react-native will run the default simulator which is iPhone 6 with iOS 10.3.1 in my case and I deleted this simulator by chance.

Here comes my error messages:

xcodebuild: error: Unable to find a destination matching the provided destination specifier:
        { id:F3A7BF54-B827-4517-A30D-8B3241C8EBF8 }

Available destinations for the "albums" scheme:
    { platform:iOS Simulator, id:CD64F26B-045A-4E27-B05A-5255924095FB, OS:10.3.1, name:iPad Pro (9.7 inch) }
    { platform:iOS Simulator, id:8FC41950-9E60-4264-B8B6-20E62FAB3BD0, OS:10.3.1, name:iPad Pro (10.5-inch) }
    { platform:iOS Simulator, id:991C8B5F-49E2-4BB7-BBB6-2F5D1776F8D2, OS:10.3.1, name:iPad Pro (12.9 inch) }
    { platform:iOS Simulator, id:B9A80D04-E43F-43E3-9CA5-21137F7C673D, OS:10.3.1, name:iPhone 7 }
    { platform:iOS Simulator, id:58F6514E-185B-4B12-9336-B8A1D4E901F8, OS:10.3.1, name:iPhone 7 Plus }

. . .

Installing build/Build/Products/Debug-iphonesimulator/myapp.app
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist

Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/myapp.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist

In order to get rid of these, open up your Xcode and check for available simulators (as same as terminal listed) and run react-native run-ios --simulator="your device name"

For my case, I run react-native run-ios --simulator="iPhone 7", the problem solved.

C# Ignore certificate errors?

Add a certificate validation handler. Returning true will allow ignoring the validation error:

ServicePointManager
    .ServerCertificateValidationCallback += 
    (sender, cert, chain, sslPolicyErrors) => true;

How can I unstage my files again after making a local commit?

git reset --soft HEAD~1 should do what you want. After this, you'll have the first changes in the index (visible with git diff --cached), and your newest changes not staged. git status will then look like this:

# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       modified:   foo.java
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   foo.java
#

You can then do git add foo.java and commit both changes at once.

Get each line from textarea

Use PHP DOM to parse and add <br/> in it. Like this:

$html = '<textarea> put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
quote by placing > at start of line
</textarea>';

//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('textarea');

//get text and add <br/> then remove last <br/>
$lines = $nodes->item(0)->nodeValue;

//split it by newlines
$lines = explode("\n", $lines);

//add <br/> at end of each line
foreach($lines as $line)
    $output .= $line . "<br/>";

//remove last <br/>
$output = rtrim($output, "<br/>");

//display it
var_dump($output);

This outputs:

string ' put returns between paragraphs
<br/>for linebreak add 2 spaces at end
<br/>indent code by 4 spaces
<br/>quote by placing > at start of line
' (length=141)

How do I configure different environments in Angular.js?

Very late to the thread, but a technique I've used, pre-Angular, is to take advantage of JSON and the flexibility of JS to dynamically reference collection keys, and use inalienable facts of the environment (host server name, current browser language, etc.) as inputs to selectively discriminate/prefer suffixed key names within a JSON data structure.

This provides not merely deploy-environment context (per OP) but any arbitrary context (such as language) to provide i18n or any other variance required simultaneously, and (ideally) within a single configuration manifest, without duplication, and readably obvious.

IN ABOUT 10 LINES VANILLA JS

Overly-simplified but classic example: An API endpoint base URL in a JSON-formatted properties file that varies per environment where (natch) the host server will also vary:

    ...
    'svcs': {
        'VER': '2.3',
        'API@localhost': 'http://localhost:9090/',
        '[email protected]': 'https://www.uat.productionwebsite.com:9090/res/',
        '[email protected]': 'https://www.productionwebsite.com:9090/api/res/'
    },
    ...

A key to the discrimination function is simply the server hostname in the request.

This, naturally, can be combined with an additional key based on the user's language settings:

    ...
    'app': {
        'NAME': 'Ferry Reservations',
        'NAME@fr': 'Réservations de ferry',
        'NAME@de': 'Fähren Reservierungen'
    },
    ...

The scope of the discrimination/preference can be confined to individual keys (as above) where the "base" key is only overwritten if there's a matching key+suffix for the inputs to the function -- or an entire structure, and that structure itself recursively parsed for matching discrimination/preference suffixes:

    'help': {
        'BLURB': 'This pre-production environment is not supported. Contact Development Team with questions.',
        'PHONE': '808-867-5309',
        'EMAIL': '[email protected]'
    },
    '[email protected]': {
        'BLURB': 'Please contact Customer Service Center',
        'BLURB@fr': 'S\'il vous plaît communiquer avec notre Centre de service à la clientèle',
        'BLURB@de': 'Bitte kontaktieren Sie unseren Kundendienst!!1!',
        'PHONE': '1-800-CUS-TOMR',
        'EMAIL': '[email protected]'
    },

SO, if a visiting user to the production website has German (de) language preference setting, the above configuration would collapse to:

    'help': {
        'BLURB': 'Bitte kontaktieren Sie unseren Kundendienst!!1!',
        'PHONE': '1-800-CUS-TOMR',
        'EMAIL': '[email protected]'
    },

What does such a magical preference/discrimination JSON-rewriting function look like? Not much:

// prefer(object,suffix|[suffixes]) by/par/durch storsoc
// prefer({ a: 'apple', a@env: 'banana', b: 'carrot' },'env') -> { a: 'banana', b: 'carrot' }
function prefer(o,sufs) {
    for (var key in o) {
        if (!o.hasOwnProperty(key)) continue; // skip non-instance props
        if(key.split('@')[1]) { // suffixed!
            // replace root prop with the suffixed prop if among prefs
            if(o[key] && sufs.indexOf(key.split('@')[1]) > -1) o[key.split('@')[0]] = JSON.parse(JSON.stringify(o[key]));

            // and nuke the suffixed prop to tidy up
            delete o[key];

            // continue with root key ...
            key = key.split('@')[0];
        }

        // ... in case it's a collection itself, recurse it!
        if(o[key] && typeof o[key] === 'object') prefer(o[key],sufs);

    };
};

In our implementations, which include Angular and pre-Angular websites, we simply bootstrap the configuration well ahead of other resource calls by placing the JSON within a self-executing JS closure, including the prefer() function, and fed basic properties of hostname and language-code (and accepts any additional arbitrary suffixes you might need):

(function(prefs){ var props = {
    'svcs': {
        'VER': '2.3',
        'API@localhost': 'http://localhost:9090/',
        '[email protected]': 'https://www.uat.productionwebsite.com:9090/res/',
        '[email protected]': 'https://www.productionwebsite.com:9090/api/res/'
    },
    ...
    /* yadda yadda moar JSON und bisque */

    function prefer(o,sufs) {
        // body of prefer function, broken for e.g.
    };

    // convert string and comma-separated-string to array .. and process it
    prefs = [].concat( ( prefs.split ? prefs.split(',') : prefs ) || []);
    prefer(props,prefs);
    window.app_props = JSON.parse(JSON.stringify(props));
})([location.hostname, ((window.navigator.userLanguage || window.navigator.language).split('-')[0])  ] );

A pre-Angular site would now have a collapsed (no @ suffixed keys) window.app_props to refer to.

An Angular site, as a bootstrap/init step, simply copies the dead-dropped props object into $rootScope, and (optionally) destroys it from global/window scope

app.constant('props',angular.copy(window.app_props || {})).run( function ($rootScope,props) { $rootScope.props = props; delete window.app_props;} );

to be subsequently injected into controllers:

app.controller('CtrlApp',function($log,props){ ... } );

or referred to from bindings in views:

<span>{{ props.help.blurb }} {{ props.help.email }}</span>

Caveats? The @ character is not valid JS/JSON variable/key naming, but so far accepted. If that's a deal-breaker, substitute for any convention you like, such as "__" (double underscore) as long as you stick to it.

The technique could be applied server-side, ported to Java or C# but your efficiency/compactness may vary.

Alternately, the function/convention could be part of your front-end compile script, so that the full gory all-environment/all-language JSON is never transmitted over the wire.

UPDATE

We've evolved usage of this technique to allow multiple suffixes to a key, to avoid being forced to use collections (you still can, as deeply as you want), and as well to honor the order of the preferred suffixes.

Example (also see working jsFiddle):

var o = { 'a':'apple', 'a@dev':'apple-dev', 'a@fr':'pomme',
          'b':'banana', 'b@fr':'banane', 'b@dev&fr':'banane-dev',
          'c':{ 'o':'c-dot-oh', 'o@fr':'c-point-oh' }, 'c@dev': { 'o':'c-dot-oh-dev', 'o@fr':'c-point-oh-dev' } };

/*1*/ prefer(o,'dev');        // { a:'apple-dev', b:'banana',     c:{o:'c-dot-oh-dev'}   }
/*2*/ prefer(o,'fr');         // { a:'pomme',     b:'banane',     c:{o:'c-point-oh'}     }
/*3*/ prefer(o,'dev,fr');     // { a:'apple-dev', b:'banane-dev', c:{o:'c-point-oh-dev'} }
/*4*/ prefer(o,['fr','dev']); // { a:'pomme',     b:'banane-dev', c:{o:'c-point-oh-dev'} }
/*5*/ prefer(o);              // { a:'apple',     b:'banana',     c:{o:'c-dot-oh'}       }

1/2 (basic usage) prefers '@dev' keys, discards all other suffixed keys

3 prefers '@dev' over '@fr', prefers '@dev&fr' over all others

4 (same as 3 but prefers '@fr' over '@dev')

5 no preferred suffixes, drops ALL suffixed properties

It accomplishes this by scoring each suffixed property and promoting the value of a suffixed property to the non-suffixed property when iterating over the properties and finding a higher-scored suffix.

Some efficiencies in this version, including removing dependence on JSON to deep-copy, and only recursing into objects that survive the scoring round at their depth:

function prefer(obj,suf) {
    function pr(o,s) {
        for (var p in o) {
            if (!o.hasOwnProperty(p) || !p.split('@')[1] || p.split('@@')[1] ) continue; // ignore: proto-prop OR not-suffixed OR temp prop score
            var b = p.split('@')[0]; // base prop name
            if(!!!o['@@'+b]) o['@@'+b] = 0; // +score placeholder
            var ps = p.split('@')[1].split('&'); // array of property suffixes
            var sc = 0; var v = 0; // reset (running)score and value
            while(ps.length) {
                // suffix value: index(of found suffix in prefs)^10
                v = Math.floor(Math.pow(10,s.indexOf(ps.pop())));
                if(!v) { sc = 0; break; } // found suf NOT in prefs, zero score (delete later)
                sc += v;
            }
            if(sc > o['@@'+b]) { o['@@'+b] = sc; o[b] = o[p]; } // hi-score! promote to base prop
            delete o[p];
        }
        for (var p in o) if(p.split('@@')[1]) delete o[p]; // remove scores
        for (var p in o) if(typeof o[p] === 'object') pr(o[p],s); // recurse surviving objs
    }
    if( typeof obj !== 'object' ) return; // validate
    suf = ( (suf || suf === 0 ) && ( suf.length || suf === parseFloat(suf) ) ? suf.toString().split(',') : []); // array|string|number|comma-separated-string -> array-of-strings
    pr(obj,suf.reverse());
}

What is the cleanest way to disable CSS transition effects temporarily?

Add an additional CSS class that blocks the transition, and then remove it to return to the previous state. This make both CSS and JQuery code short, simple and well understandable.

CSS:

.notransition {
  -webkit-transition: none !important;
  -moz-transition: none !important;
  -o-transition: none !important;
  -ms-transition: none !important;
  transition: none !important;
}

!important was added to be sure that this rule will have more "weight", because ID is normally more specific than class.

JQuery:

$('#elem').addClass('notransition'); // to remove transition
$('#elem').removeClass('notransition'); // to return to previouse transition

The APK file does not exist on disk

In my case, executing "Sync Project with Gradle Files" helped. Neither restarting Andoid Studio nor clearing the cache did anything.

Could not create the Java virtual machine

Set the JVM memory:

export _JAVA_OPTIONS=-Xmx512M

How can I make my match non greedy in vim?

G'day,

Vim's regexp processing is not too brilliant. I've found that the regexp syntax for sed is about the right match for vim's capabilities.

I usually set the search highlighting on (:set hlsearch) and then play with the regexp after entering a slash to enter search mode.

Edit: Mark, that trick to minimise greedy matching is also covered in Dale Dougherty's excellent book "Sed & Awk" (sanitised Amazon link).

Chapter Three "Understanding Regular Expression Syntax" is an excellent intro to the more primitive regexp capabilities involved with sed and awk. Only a short read and highly recommended.

HTH

cheers,

How do I move files in node.js?

Shelljs is a very handy solution.

command: mv([options ,] source, destination)

Available options:

-f: force (default behaviour)

-n: to prevent overwriting

const shell = require('shelljs');
const status = shell.mv('README.md', '/home/my-dir');
if(status.stderr)  console.log(status.stderr);
else console.log('File moved!');

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

In Python, what happens when you import inside of a function?

Does it re-import every time the function is run?

No; or rather, Python modules are essentially cached every time they are imported, so importing a second (or third, or fourth...) time doesn't actually force them to go through the whole import process again. 1

Does it import once at the beginning whether or not the function is run?

No, it is only imported if and when the function is executed. 2, 3

As for the benefits: it depends, I guess. If you may only run a function very rarely and don't need the module imported anywhere else, it may be beneficial to only import it in that function. Or if there is a name clash or other reason you don't want the module or symbols from the module available everywhere, you may only want to import it in a specific function. (Of course, there's always from my_module import my_function as f for those cases.)

In general practice, it's probably not that beneficial. In fact, most Python style guides encourage programmers to place all imports at the beginning of the module file.

How to get a specific output iterating a hash in Ruby?

The most basic way to iterate over a hash is as follows:

hash.each do |key, value|
  puts key
  puts value
end

Cannot find Microsoft.Office.Interop Visual Studio

I had the same issue with Visual Studio Community 2013, I fixed it downloading and installing the latest update of Office Developer Tools for Visual Studio 2013. Now I am able to see the whole Microsoft.Office.Interop.* list when I go to

Add References > Assemblies > Extensions

you can download it from here:

https://www.visualstudio.com/en-us/news/vs2013-update4-rtm-vs.aspx#Office
http://aka.ms/OfficeDevToolsForVS2013

After installation of Gulp: “no command 'gulp' found”

I'm on lubuntu 19.10

I've used combination of previous answers, and didn't tweak the $PATH.

  1. npm uninstall --global gulp gulp-cli This removes any package if they are already there.
  2. sudo npm install --global gulp-cli Reinstall it as root user.

If you want to do copy and paste

npm uninstall --global gulp gulp-cli && sudo npm install --global gulp-cli 

should work

I guess --global is unnecessary here as it's installed using sudo, but I've used it just in case.

Android toolbar center title and custom font

Typeface face= Typeface.createFromAsset(getAssets(), "font/font.ttf"); // your custom font
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTypeface(face);
setSupportActionBar(toolbar);

Other Tutorial:

  1. Android Toolbar Example
  2. Using Custom Font in Android
  3. ActionBar Tutorial with Example

How to destroy JWT Tokens on logout?

While other answers provide detailed solutions for various setups, this might help someone who is just looking for a general answer.

There are three general options, pick one or more:

  1. On the client side, delete the cookie from the browser using javascript.

  2. On the server side, set the cookie value to an empty string or something useless (for example "deleted"), and set the cookie expiration time to a time in the past.

  3. On the server side, update the refreshtoken stored in your database. Use this option to log out the user from all devices where they are logged in (their refreshtokens will become invalid and they have to log in again).

Python setup.py develop vs install

python setup.py install is used to install (typically third party) packages that you're not going to develop/modify/debug yourself.

For your own stuff, you want to first install your package and then be able to frequently edit the code without having to re-install the package every time — and that is exactly what python setup.py develop does: it installs the package (typically just a source folder) in a way that allows you to conveniently edit your code after it’s installed to the (virtual) environment, and have the changes take effect immediately.

Note that it is highly recommended to use pip install . (install) and pip install -e . (developer install) to install packages, as invoking setup.py directly will do the wrong things for many dependencies, such as pull prereleases and incompatible package versions, or make the package hard to uninstall with pip.

Fatal error: Call to undefined function curl_init()

For Ubuntu

Install Curl extension for PHP & restart apache server.

sudo apt-get install php5-curl
sudo service apache2 restart

For Windows

Problem arises because of not including the lib_curl.dll to PHP. also load following extension if not working,so those extension in php.ini or remove comment if already exist in php.ini file then remove comment.

extension=php_bz2.dll
extension=php_curl.dll
extension=php_dba.dll

Now restart apache server. If you get an error "Unable to Load php_curl.dll", copy SSLEAY32.PHP, libEAY32.dll (OpenSSL) Libraries to the System32 folder.

Could not find any resources appropriate for the specified culture or the neutral culture

I solved the problem like this:

  1. Right click on your ResourceFile
  2. Change the "Build Action" property Compile to "Embedded Resource"
  3. Then build and run

It works perfectly.

How to access single elements in a table in R

?"[" pretty much covers the various ways of accessing elements of things.

Under usage it lists these:

x[i]
x[i, j, ... , drop = TRUE]
x[[i, exact = TRUE]]
x[[i, j, ..., exact = TRUE]]
x$name
getElement(object, name)

x[i] <- value
x[i, j, ...] <- value
x[[i]] <- value
x$i <- value

The second item is sufficient for your purpose

Under Arguments it points out that with [ the arguments i and j can be numeric, character or logical

So these work:

data[1,1]
data[1,"V1"]

As does this:

data$V1[1]

and keeping in mind a data frame is a list of vectors:

data[[1]][1]
data[["V1"]][1]

will also both work.

So that's a few things to be going on with. I suggest you type in the examples at the bottom of the help page one line at a time (yes, actually type the whole thing in one line at a time and see what they all do, you'll pick up stuff very quickly and the typing rather than copypasting is an important part of helping to commit it to memory.)

Is there a decent wait function in C++?

the equivalent to the batch program would be

#include<iostream>
int main()
{
    std::cout<<"Hello, World!\n";
    std::cin.get();
    return 0;
}

The additional line does exactly what PAUSE does, waits for a single character input

Appending the same string to a list of strings in Python

The simplest way to do this is with a list comprehension:

[s + mystring for s in mylist]

Notice that I avoided using builtin names like list because that shadows or hides the builtin names, which is very much not good.

Also, if you do not actually need a list, but just need an iterator, a generator expression can be more efficient (although it does not likely matter on short lists):

(s + mystring for s in mylist)

These are very powerful, flexible, and concise. Every good python programmer should learn to wield them.

Generate Java class from JSON?

If you're using Jackson (the most popular library there), try

https://github.com/astav/JsonToJava

Its open source (last updated on Jun 7, 2013 as of year 2020) and anyone should be able to contribute.

Summary

A JsonToJava source class file generator that deduces the schema based on supplied sample json data and generates the necessary java data structures.

It encourages teams to think in Json first, before writing actual code.

Features

  • Can generate classes for an arbitrarily complex hierarchy (recursively)
  • Can read your existing Java classes and if it can deserialize into those structures, will do so
  • Will prompt for user input when ambiguous cases exist

How to assign a NULL value to a pointer in python?

All objects in python are implemented via references so the distinction between objects and pointers to objects does not exist in source code.

The python equivalent of NULL is called None (good info here). As all objects in python are implemented via references, you can re-write your struct to look like this:

class Node:
    def __init__(self): #object initializer to set attributes (fields)
        self.val = 0
        self.right = None
        self.left = None

And then it works pretty much like you would expect:

node = Node()
node.val = some_val #always use . as everything is a reference and -> is not used
node.left = Node()

Note that unlike in NULL in C, None is not a "pointer to nowhere": it is actually the only instance of class NoneType. Therefore, as None is a regular object, you can test for it just like any other object:

if node.left == None:
   print("The left node is None/Null.")

Although since None is a singleton instance, it is considered more idiomatic to use is and compare for reference equality:

if node.left is None:
   print("The left node is None/Null.")

Extract a substring from a string in Ruby using a regular expression

String1.scan(/<([^>]*)>/).last.first

scan creates an array which, for each <item> in String1 contains the text between the < and the > in a one-element array (because when used with a regex containing capturing groups, scan creates an array containing the captures for each match). last gives you the last of those arrays and first then gives you the string in it.

Clear the entire history stack and start a new activity on Android

Case 1:Only two activity A and B:

Here Activity flow is A->B .On clicking backbutton from B we need to close the application then while starting Activity B from A just call finish() this will prevent android from storing Activity A in to the Backstack.eg for activity A is Loding/Splash screen of application.

Intent newIntent = new Intent(A.this, B.class);
startActivity(newIntent);
finish();

Case 2:More than two activitiy:

If there is a flow like A->B->C->D->B and on clicking back button in Activity B while coming from Activity D.In that case we should use.

Intent newIntent = new Intent(D.this,B.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(newIntent);

Here Activity B will be started from the backstack rather than a new instance because of Intent.FLAG_ACTIVITY_CLEAR_TOP and Intent.FLAG_ACTIVITY_NEW_TASK clears the stack and makes it the top one.So when we press back button the whole application will be terminated.

HTML text-overflow ellipsis detection

All the solutions did not really work for me, what did work was compare the elements scrollWidth to the scrollWidth of its parent (or child, depending on which element has the trigger).

When the child's scrollWidth is higher than its parents, it means .text-ellipsis is active.


When event is the parent element

function isEllipsisActive(event) {
    let el          = event.currentTarget;
    let width       = el.offsetWidth;
    let widthChild  = el.firstChild.offsetWidth;
    return (widthChild >= width);
}

When event is the child element

function isEllipsisActive(event) {
    let el          = event.currentTarget;
    let width       = el.offsetWidth;
    let widthParent = el.parentElement.scrollWidth;
    return (width >= widthParent);
}

Change language of Visual Studio 2017 RC

  1. Go to Tools -> Options
  2. Select International Settings in Environment and on the right side of a screen you should see a combo with the list of installed language packages. (so in my case Czech, English and same as on MS Windows )
  3. Click on Ok

You have to restart Visual Studio to see the change...

If you are polish (and got polish language settings)

  1. Narzedzia -> Opcje
  2. Ustawienia miedzynarodowe in Srodowisko

Hope this helps! Have a great time in Poland!