Programs & Examples On #Unification

Unification, in computer science and logic, is an algorithmic process by which one attempts to solve the satisfiability problem. The goal of unification is to find a substitution which demonstrates that two seemingly different terms are in fact either identical or just equal.

Convert char array to single int?

I use :

int convertToInt(char a[1000]){
    int i = 0;
    int num = 0;
    while (a[i] != 0)
    {
        num =  (a[i] - '0')  + (num * 10);
        i++;
    }
    return num;;
}

ListView with Add and Delete Buttons in each Row in android

on delete button click event

public void delete(View v){                

    ListView listview1;
    ArrayList<E> datalist;

    final int position = listview1.getPositionForView((View) v.getParent());
    datalist.remove(position);
    myAdapter.notifyDataSetChanged();

}

Difference between timestamps with/without time zone in PostgreSQL

I try to explain it more understandably than the referred PostgreSQL documentation.

Neither TIMESTAMP variants store a time zone (or an offset), despite what the names suggest. The difference is in the interpretation of the stored data (and in the intended application), not in the storage format itself:

  • TIMESTAMP WITHOUT TIME ZONE stores local date-time (aka. wall calendar date and wall clock time). Its time zone is unspecified as far as PostgreSQL can tell (though your application may knows what it is). Hence, PostgreSQL does no time zone related conversion on input or output. If the value was entered into the database as '2011-07-01 06:30:30', then no mater in what time zone you display it later, it will still say year 2011, month 07, day 01, 06 hours, 30 minutes, and 30 seconds (in some format). Also, any offset or time zone you specify in the input is ignored by PostgreSQL, so '2011-07-01 06:30:30+00' and '2011-07-01 06:30:30+05' are the same as just '2011-07-01 06:30:30'. For Java developers: it's analogous to java.time.LocalDateTime.

  • TIMESTAMP WITH TIME ZONE stores a point on the UTC time line. How it looks (how many hours, minutes, etc.) depends on your time zone, but it always refers to the same "physical" instant (like the moment of an actual physical event). The input is internally converted to UTC, and that's how it's stored. For that, the offset of the input must be known, so when the input contains no explicit offset or time zone (like '2011-07-01 06:30:30') it's assumed to be in the current time zone of the PostgreSQL session, otherwise the explicitly specified offset or time zone is used (as in '2011-07-01 06:30:30+05'). The output is displayed converted to the current time zone of the PostgreSQL session. For Java developers: It's analogous to java.time.Instant (with lower resolution though), but with JDBC and JPA 2.2 you are supposed to map it to java.time.OffsetDateTime (or to java.util.Date or java.sql.Timestamp of course).

Some say that both TIMESTAMP variations store UTC date-time. Kind of, but it's confusing to put it that way in my opinion. TIMESTAMP WITHOUT TIME ZONE is stored like a TIMESTAMP WITH TIME ZONE, which rendered with UTC time zone happens to give the same year, month, day, hours, minutes, seconds, and microseconds as they are in the local date-time. But it's not meant to represent the point on the time line that the UTC interpretation says, it's just the way the local date-time fields are encoded. (It's some cluster of dots on the time line, as the real time zone is not UTC; we don't know what it is.)

How can I create my own comparator for a map?

Since C++11, you can also use a lambda expression instead of defining a comparator struct:

auto comp = [](const string& a, const string& b) { return a.length() < b.length(); };
map<string, string, decltype(comp)> my_map(comp);

my_map["1"]      = "a";
my_map["three"]  = "b";
my_map["two"]    = "c";
my_map["fouuur"] = "d";

for(auto const &kv : my_map)
    cout << kv.first << endl;

Output:

1
two
three
fouuur

I'd like to repeat the final note of Georg's answer: When comparing by length you can only have one string of each length in the map as a key.

Code on Ideone

gcc error: wrong ELF class: ELFCLASS64

It turns out the compiler version I was using did not match the compiled version done with the coreset.o.

One was 32bit the other was 64bit. I'll leave this up in case anyone else runs into a similar problem.

How do I vertically align text in a paragraph?

Try these styles:

_x000D_
_x000D_
p.event_desc {_x000D_
  font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;_x000D_
  line-height: 14px;_x000D_
  height:75px;_x000D_
  margin: 0px;_x000D_
  display: table-cell;_x000D_
  vertical-align: middle;_x000D_
  padding: 10px;_x000D_
  border: 1px solid #f00;_x000D_
}
_x000D_
<p class="event_desc">lorem ipsum</p>
_x000D_
_x000D_
_x000D_

android: stretch image in imageview to fit screen

Trying using :

imageview.setFitToScreen(true);
imageview.setScaleType(ScaleType.FIT_CENTER);

This will fit your imageview to the screen with the correct ratio.

Using a BOOL property

There's no benefit to using properties with primitive types. @property is used with heap allocated NSObjects like NSString*, NSNumber*, UIButton*, and etc, because memory managed accessors are created for free. When you create a BOOL, the value is always allocated on the stack and does not require any special accessors to prevent memory leakage. isWorking is simply the popular way of expressing the state of a boolean value.

In another OO language you would make a variable private bool working; and two accessors: SetWorking for the setter and IsWorking for the accessor.

Difference between fprintf, printf and sprintf?

In C, a "stream" is an abstraction; from the program's perspective it is simply a producer (input stream) or consumer (output stream) of bytes. It can correspond to a file on disk, to a pipe, to your terminal, or to some other device such as a printer or tty. The FILE type contains information about the stream. Normally, you don't mess with a FILE object's contents directly, you just pass a pointer to it to the various I/O routines.

There are three standard streams: stdin is a pointer to the standard input stream, stdout is a pointer to the standard output stream, and stderr is a pointer to the standard error output stream. In an interactive session, the three usually refer to your console, although you can redirect them to point to other files or devices:

$ myprog < inputfile.dat > output.txt 2> errors.txt

In this example, stdin now points to inputfile.dat, stdout points to output.txt, and stderr points to errors.txt.

fprintf writes formatted text to the output stream you specify.

printf is equivalent to writing fprintf(stdout, ...) and writes formatted text to wherever the standard output stream is currently pointing.

sprintf writes formatted text to an array of char, as opposed to a stream.

Using reCAPTCHA on localhost

You can write "localhost" or "127.0.0.1" but URL must be the same

Example : Google Domains Add-> localhost URL => localhost/login.php

Example : Google Domains Add-> 127.0.0.1 URL => 127.0.0.1/login.php

java.util.zip.ZipException: error in opening zip file

In my case SL4j-api.jar with multiple versions are conflicting in the maven repo. Than I deleted the entire SL4j-api folder in m2 maven repo and updated maven project, build maven project than ran the project in JBOSS server. issue got resolved.

How can I convert an Int to a CString?

If you want something more similar to your example try _itot_s. On Microsoft compilers _itot_s points to _itoa_s or _itow_s depending on your Unicode setting:

CString str;
_itot_s( 15, str.GetBufferSetLength( 40 ), 40, 10 );
str.ReleaseBuffer();

it should be slightly faster since it doesn't need to parse an input format.

Editing dictionary values in a foreach loop

You need to create a new Dictionary from the old rather than modifying in place. Somethine like (also iterate over the KeyValuePair<,> rather than using a key lookup:

int otherCount = 0;
int totalCounts = colStates.Values.Sum();
var newDict = new Dictionary<string,int>();
foreach (var kv in colStates) {
  if (kv.Value/(double)totalCounts < 0.05) {
    otherCount += kv.Value;
  } else {
    newDict.Add(kv.Key, kv.Value);
  }
}
if (otherCount > 0) {
  newDict.Add("Other", otherCount);
}

colStates = newDict;

How to make a JFrame button open another JFrame class in Netbeans?

This link works with me: video

The answer posted before didn't work for me until the second click

So what I did is Directly call:

        new NewForm().setVisible(true);

        this.dispose();//to close the current jframe

MySQL: Enable LOAD DATA LOCAL INFILE

This went a little weird for me, from one day to the next one the script that have been working since days just stop working. There wasn´t a newer version of mysql or any kind of upgrade but I was getting the same error, so I give a last try to the CSV file and notice that the end of lines were using \n instead of the expected ( per my script ) \r\n so I save it with the right EOL and run the script again without any trouble.

I think is kind of odd for mysql to tell me The used command is not allowed with this MySQL version since the reason was completely different.

My working command looks like this:

LOAD DATA LOCAL INFILE 'file-name' IGNORE INTO TABLE table-name CHARACTER SET latin1 FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES.

How to get changes from another branch

You can use rebase, for instance, git rebase our-team when you are on your branch featurex

It will move the start point of the branch at the end of your our-team branch, merging all changes in your featurex branch.

How to add and remove item from array in components in Vue 2

You can use Array.push() for appending elements to an array.

For deleting, it is best to use this.$delete(array, index) for reactive objects.

Vue.delete( target, key ): Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.

https://vuejs.org/v2/api/#Vue-delete

UIView's frame, bounds, center, origin, when to use what?

They are related values, and kept consistent by the property setter/getter methods (and using the fact that frame is a purely synthesized value, not backed by an actual instance variable).

The main equations are:

frame.origin = center - bounds.size / 2

(which is the same as)

center = frame.origin + bounds.size / 2

(and there’s also)

frame.size = bounds.size

That's not code, just equations to express the invariant between the three properties. These equations also assume your view's transform is the identity, which it is by default. If it's not, then bounds and center keep the same meaning, but frame can change. Unless you're doing non-right-angle rotations, the frame will always be the transformed view in terms of the superview's coordinates.

This stuff is all explained in more detail with a useful mini-library here:

http://bynomial.com/blog/?p=24

Adding rows dynamically with jQuery

Untested. Modify to suit:

$form = $('#my-form');

$rows = $form.find('.person-input-row');

$('button#add-new').click(function() {

    $rows.find(':first').clone().insertAfter($rows.find(':last'));

    $justInserted = $rows.find(':last');
    $justInserted.hide();
    $justInserted.find('input').val(''); // it may copy values from first one
    $justInserted.slideDown(500);


});

This is better than copying innerHTML because you will lose all attached events etc.

Address validation using Google Maps API

A great blog describing 14 address finders: https://www.conversion-uplift.co.uk/free-address-lookup-tools/

Many address autocomplete services, including Google's Places API, appears to offer international address support but it has limited accuracy.

For example, New Zealand address and geolocation data are free to download from Land Information New Zealand (LINZ). When a user search for an address such as 76 Francis St Hauraki from Google or Address Doctor, a positive match is returned. The land parcel was matched but not the postal/delivery address, which is either 76A or 76B. The problem is amplified with apartments and units on a single land parcel.

For 100% accuracy, use a country-specific address finder instead such as https://www.addy.co.nz for NZ address autocomplete.

Relational Database Design Patterns?

Design patterns aren't trivially reusable solutions.

Design patterns are reusable, by definition. They're patterns you detect in other good solutions.

A pattern is not trivially reusable. You can implement your down design following the pattern however.

Relational design patters include things like:

  1. One-to-Many relationships (master-detail, parent-child) relationships using a foreign key.

  2. Many-to-Many relationships with a bridge table.

  3. Optional one-to-one relationships managed with NULLs in the FK column.

  4. Star-Schema: Dimension and Fact, OLAP design.

  5. Fully normalized OLTP design.

  6. Multiple indexed search columns in a dimension.

  7. "Lookup table" that contains PK, description and code value(s) used by one or more applications. Why have code? I don't know, but when they have to be used, this is a way to manage the codes.

  8. Uni-table. [Some call this an anti-pattern; it's a pattern, sometimes it's bad, sometimes it's good.] This is a table with lots of pre-joined stuff that violates second and third normal form.

  9. Array table. This is a table that violates first normal form by having an array or sequence of values in the columns.

  10. Mixed-use database. This is a database normalized for transaction processing but with lots of extra indexes for reporting and analysis. It's an anti-pattern -- don't do this. People do it anyway, so it's still a pattern.

Most folks who design databases can easily rattle off a half-dozen "It's another one of those"; these are design patterns that they use on a regular basis.

And this doesn't include administrative and operational patterns of use and management.

Function vs. Stored Procedure in SQL Server

Stored procedure:

  • Is like a miniature program in SQL Server.
  • Can be as simple as a select statement, or as complex as a long script that adds, deletes, updates, and/or reads data from multiple tables in a database.
  • (Can implement loops and cursors, which both allow you to work with smaller results or row by row operations on data.)
  • Should be called using EXEC or EXECUTE statement.
  • Returns table variables, but we can't use OUT parameter.
  • Supports transactions.

Function:

  • Can not be used to update, delete, or add records to the database.
  • Simply returns a single value or a table value.
  • Can only be used to select records. However, it can be called very easily from within standard SQL, such as:

    SELECT dbo.functionname('Parameter1')
    

    or

    SELECT Name, dbo.Functionname('Parameter1') FROM sysObjects
    
  • For simple reusable select operations, functions can simplify code. Just be wary of using JOIN clauses in your functions. If your function has a JOIN clause and you call it from another select statement that returns multiple results, that function call will JOIN those tables together for each line returned in the result set. So though they can be helpful in simplifying some logic, they can also be a performance bottleneck if they're not used properly.

  • Returns the values using OUT parameter.
  • Does not support transactions.

Displaying unicode symbols in HTML

I know an answer has already been accepted, but wanted to point a few things out.

Setting the content-type and charset is obviously a good practice, doing it on the server is much better, because it ensures consistency across your application.

However, I would use UTF-8 only when the language of my application uses a lot of characters that are available only in the UTF-8 charset. If you want to show a unicode character or symbol in one of cases, you can do so without changing the charset of your page.

HTML renderers have always been able to display symbols which are not part of the encoding character set of the page, as long as you mention the symbol in its numeric character reference (NCR). Sounds weird but its true.

So, even if your html has a header that states it has an encoding of ansi or any of the iso charsets, you can display a check mark by using its html character reference, in decimal - &#10003; or in hex - &#x2713;

So its a little difficult to understand why you are facing this issue on your pages. Can you check if the NCR value is correct, this is a good reference http://www.fileformat.info/info/unicode/char/2713/index.htm

MongoDb query condition on comparing 2 fields

You can use a $where. Just be aware it will be fairly slow (has to execute Javascript code on every record) so combine with indexed queries if you can.

db.T.find( { $where: function() { return this.Grade1 > this.Grade2 } } );

or more compact:

db.T.find( { $where : "this.Grade1 > this.Grade2" } );

UPD for mongodb v.3.6+

you can use $expr as described in recent answer

'negative' pattern matching in python

Why dont you match the OK SYS row and not return it.

for item in output:
    matchObj = re.search("(OK SYS|\\.).*", item)
    if not matchObj:
        print "got item "  + item

Draw an X in CSS

_x000D_
_x000D_
#x{_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
    background-color:orange;_x000D_
    position:relative;_x000D_
    border-radius:2px;_x000D_
}_x000D_
#x::after,#x::before{_x000D_
    position:absolute;_x000D_
    top:9px;_x000D_
    left:0px;_x000D_
    content:'';_x000D_
    display:block;_x000D_
    width:20px;_x000D_
    height:2px;_x000D_
    background-color:red;_x000D_
    _x000D_
}_x000D_
#x::after{_x000D_
    -webkit-transform: rotate(45deg);_x000D_
    -moz-transform: rotate(45deg);_x000D_
    -ms-transform: rotate(45deg);_x000D_
    -o-transform: rotate(45deg);_x000D_
    transform: rotate(45deg);_x000D_
}_x000D_
#x::before{_x000D_
    -webkit-transform: rotate(-45deg);_x000D_
    -moz-transform: rotate(-45deg);_x000D_
    -ms-transform: rotate(-45deg);_x000D_
    -o-transform: rotate(-45deg);_x000D_
    transform: rotate(-45deg);_x000D_
}
_x000D_
<div id=x>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to add headers to OkHttp request interceptor?

Finally, I added the headers this way:

@Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request();
        Request newRequest;

        newRequest = request.newBuilder()
                .addHeader(HeadersContract.HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION)
                .addHeader(HeadersContract.HEADER_X_CLIENT_ID, CLIENT_ID)
                .build();
        return chain.proceed(newRequest);
    }

How to do a JUnit assert on a message in a logger

Effectively you are testing a side-effect of a dependent class. For unit testing you need only to verify that

logger.info()

was called with the correct parameter. Hence use a mocking framework to emulate logger and that will allow you to test your own class's behaviour.

how to convert rgb color to int in java

Use getRGB(), it helps ( no complicated programs )

Returns an array of integer pixels in the default RGB color model (TYPE_INT_ARGB) and default sRGB color space, from a portion of the image data.

Grouping into interval of 5 minutes within a time range

You should rather use GROUP BY UNIX_TIMESTAMP(time_stamp) DIV 300 instead of round(../300) because of the rounding I found that some records are counted into two grouped result sets.

Tensorflow import error: No module named 'tensorflow'

I had same issues on Windows 64-bit processor but manage to solve them. Check if your Python is for 32- or 64-bit installation. If it is for 32-bit, then you should download the executable installer (for e.g. you can choose latest Python version - for me is 3.7.3) https://www.python.org/downloads/release/python-373/ -> Scroll to the bottom in Files section and select “Windows x86-64 executable installer”. Download and install it.

The tensorflow installation steps check here : https://www.tensorflow.org/install/pip . I hope this helps somehow ...

What is the most effective way for float and double comparison?

`return fabs(a - b) < EPSILON;

This is fine if:

  • the order of magnitude of your inputs don't change much
  • very small numbers of opposite signs can be treated as equal

But otherwise it'll lead you into trouble. Double precision numbers have a resolution of about 16 decimal places. If the two numbers you are comparing are larger in magnitude than EPSILON*1.0E16, then you might as well be saying:

return a==b;

I'll examine a different approach that assumes you need to worry about the first issue and assume the second is fine your application. A solution would be something like:

#define VERYSMALL  (1.0E-150)
#define EPSILON    (1.0E-8)
bool AreSame(double a, double b)
{
    double absDiff = fabs(a - b);
    if (absDiff < VERYSMALL)
    {
        return true;
    }

    double maxAbs  = max(fabs(a) - fabs(b));
    return (absDiff/maxAbs) < EPSILON;
}

This is expensive computationally, but it is sometimes what is called for. This is what we have to do at my company because we deal with an engineering library and inputs can vary by a few dozen orders of magnitude.

Anyway, the point is this (and applies to practically every programming problem): Evaluate what your needs are, then come up with a solution to address your needs -- don't assume the easy answer will address your needs. If after your evaluation you find that fabs(a-b) < EPSILON will suffice, perfect -- use it! But be aware of its shortcomings and other possible solutions too.

BadValue Invalid or no user locale set. Please ensure LANG and/or LC_* environment variables are set correctly

Generating locales

Missing locales are generated with locale-gen:

locale-gen en_US.UTF-8

Alternatively a locale file can be created manually with localedef:[1]

localedef -i en_US -f UTF-8 en_US.UTF-8

Setting Locale Settings

The locale settings can be set (to en_US.UTF-8 in the example) as follows:

export LANGUAGE=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
locale-gen en_US.UTF-8
dpkg-reconfigure locales

The dpkg-reconfigure locales command will open a dialog under Debian for selecting the desired locale. This dialog will not appear under Ubuntu. The Configure Locales in Ubuntu article shows how to find the information regarding Ubuntu.

C# list.Orderby descending

Sure:

var newList = list.OrderByDescending(x => x.Product.Name).ToList();

Doc: OrderByDescending(IEnumerable, Func).

In response to your comment:

var newList = list.OrderByDescending(x => x.Product.Name)
                  .ThenBy(x => x.Product.Price)
                  .ToList();

What does "static" mean in C?

It is important to note that static variables in functions get initialized at the first entry into that function and persist even after their call has been finished; in case of recursive functions the static variable gets initialized only once and persists as well over all recursive calls and even after the call of the function has been finished.

If the variable has been created outside a function, it means that the programmer is only able to use the variable in the source-file the variable has been declared.

Bootstrap alert in a fixed floating div at the top of page

The simplest approach would be to use any of these class utilities that Bootstrap provides:

<div class="position-fixed">...</div>
<div class="position-sticky">...</div>
<div class="fixed-top">...</div>
<div class="fixed-bottom">...</div>
<div class="sticky-top">...</div>

https://getbootstrap.com/docs/4.0/utilities/position

How to call a stored procedure (with parameters) from another stored procedure without temp table

You can create table variable instead of tamp table in procedure A and execute procedure B and insert into temp table by below query.

DECLARE @T TABLE
(
TABLE DEFINITION
)
.
.
.
INSERT INTO @T
EXEC B @MYDATE

and you continue operation.

Difference between "include" and "require" in php

The difference between include() and require() arises when the file being included cannot be found: include() will release a warning (E_WARNING) and the script will continue, whereas require() will release a fatal error (E_COMPILE_ERROR) and terminate the script. If the file being included is critical to the rest of the script running correctly then you need to use require().

For more details : Difference between Include and Require in PHP

How to open existing project in Eclipse

File > Import > General > Existing Projects into workspace. Select the root folder that has your project(s). It lists all the projects available in the selected folder. Select the ones you would like to import and click Finish. This should work just fine.

How can I calculate the number of lines changed between two commits in Git?

Another way to get all change log in a specified period of time

git log --author="Tri Nguyen" --oneline --shortstat --before="2017-03-20" --after="2017-03-10"

Output:

2637cc736 Revert changed code
 1 file changed, 5 insertions(+), 5 deletions(-)
ba8d29402 Fix review
 2 files changed, 4 insertions(+), 11 deletions(-)

With a long output content, you can export to file for more readable

git log --author="Tri Nguyen" --oneline --shortstat --before="2017-03-20" --after="2017-03-10" > /mnt/MyChangeLog.txt

What is content-type and datatype in an AJAX request?

See http://api.jquery.com/jQuery.ajax/, there's mention of datatype and contentType there.

They are both used in the request to the server so the server knows what kind of data to receive/send.

Node.js EACCES error when listening on most ports

Try authbind:

http://manpages.ubuntu.com/manpages/hardy/man1/authbind.1.html

After installing, you can add a file with the name of the port number you want to use in the following folder: /etc/authbind/byport/

Give it 500 permissions using chmod and change the ownership to the user you want to run the program under.

After that, do "authbind node ..." as that user in your project.

How do I create a comma delimited string from an ArrayList?

foo.ToArray().Aggregate((a, b) => (a + "," + b)).ToString()

or

string.Concat(foo.ToArray().Select(a => a += ",").ToArray())

Updating, as this is extremely old. You should, of course, use string.Join now. It didn't exist as an option at the time of writing.

Difference between two dates in years, months, days in JavaScript

Actually, there's a solution with a moment.js plugin and it's very easy.

You might use moment.js

Don't reinvent the wheel again.

Just plug Moment.js Date Range Plugin.


Example:

_x000D_
_x000D_
var starts = moment('2014-02-03 12:53:12');_x000D_
var ends   = moment();_x000D_
_x000D_
var duration = moment.duration(ends.diff(starts));_x000D_
_x000D_
// with ###moment precise date range plugin###_x000D_
// it will tell you the difference in human terms_x000D_
_x000D_
var diff = moment.preciseDiff(starts, ends, true); _x000D_
// example: { "years": 2, "months": 7, "days": 0, "hours": 6, "minutes": 29, "seconds": 17, "firstDateWasLater":  false }_x000D_
_x000D_
_x000D_
// or as string:_x000D_
var diffHuman = moment.preciseDiff(starts, ends);_x000D_
// example: 2 years 7 months 6 hours 29 minutes 17 seconds_x000D_
_x000D_
document.getElementById('output1').innerHTML = JSON.stringify(diff)_x000D_
document.getElementById('output2').innerHTML = diffHuman
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>_x000D_
_x000D_
  <script src="https://raw.githubusercontent.com/codebox/moment-precise-range/master/moment-precise-range.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
  _x000D_
  <h2>Difference between "NOW and 2014-02-03 12:53:12"</h2>_x000D_
  <span id="output1"></span>_x000D_
  <br />_x000D_
  <span id="output2"></span>_x000D_
  _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

I don't understand -Wl,-rpath -Wl,

The -Wl,xxx option for gcc passes a comma-separated list of tokens as a space-separated list of arguments to the linker. So

gcc -Wl,aaa,bbb,ccc

eventually becomes a linker call

ld aaa bbb ccc

In your case, you want to say "ld -rpath .", so you pass this to gcc as -Wl,-rpath,. Alternatively, you can specify repeat instances of -Wl:

gcc -Wl,aaa -Wl,bbb -Wl,ccc

Note that there is no comma between aaa and the second -Wl.

Or, in your case, -Wl,-rpath -Wl,..

SQL time difference between two dates result in hh:mm:ss

DECLARE  @StartDate datetime = '10/01/2012 08:40:18.000'
        ,@EndDate   datetime = '10/10/2012 09:52:48.000'
        ,@DaysDifferent int = 0
        ,@Sec BIGINT

select @Sec = DateDiff(s, @StartDate, @EndDate)

IF (DATEDIFF(day, @StartDate, @EndDate) > 0)
    BEGIN
        select @DaysDifferent = DATEDIFF(day, @StartDate, @EndDate)
        select @Sec = @Sec - ( @DaysDifferent * 86400 )
        SELECT LTRIM(STR(@DaysDifferent,3)) +'d '+ LTRIM(STR(@Sec/3600, 5)) + ':' + RIGHT('0' + LTRIM(@Sec%3600/60), 2) + ':' + RIGHT('0' + LTRIM(@Sec%60), 2) AS [dd hh:mm:ss]
    END
ELSE
    BEGIN
        SELECT LTRIM(STR(@DaysDifferent,3)) +'d '+ LTRIM(STR(@Sec/3600, 5)) + ':' + RIGHT('0' + LTRIM(@Sec%3600/60), 2) + ':' + RIGHT('0' + LTRIM(@Sec%60), 2) AS [dd hh:mm:ss]
    END

----------------------------------------------------------------------------------
dd HH:MM:SS
9d 1:12:30

How to get selected value of a dropdown menu in ReactJS

I was making a drop-down menu for a language selector - but I needed the dropdown menu to display the current language upon page load. I would either be getting my initial language from a URL param example.com?user_language=fr, or detecting it from the user’s browser settings. Then when the user interacted with the dropdown, the selected language would be updated and the language selector dropdown would display the currently selected language.

In the spirit of the other answers using food examples, I got all sorts of fruit goodness for you.

  • First up, answering the initially asked question with a basic React functional component - two examples with and without props, then how to import the component elsewhere.

  • Next up, the same example - but juiced up with Typescript.

  • Then a bonus finale - A language selector dropdown component using Typescript.


Basic React (16.13.1) Functional Component Example. Two examples of FruitSelectDropdown , one without props & one with accepting props fruitDetector

import React, { useState } from 'react'

export const FruitSelectDropdown = () => {
  const [currentFruit, setCurrentFruit] = useState('oranges')
  
  const changeFruit = (newFruit) => {
    setCurrentFruit(newFruit)
  }
  
  return (
    <form>
      <select 
        onChange={(event) => changeFruit(event.target.value)}
        value={currentFruit}
      >
        <option value="apples">Red Apples</option>
        <option value="oranges">Outrageous Oranges</option>
        <option value="tomatoes">Technically a Fruit Tomatoes</option>
        <option value="bananas">Bodacious Bananas</option>
      </select>
    </form>
  )
}

Or you can have FruitSelectDropdown accept props, maybe you have a function that outputs a string, you can pass it through using the fruitDetector prop

import React, { useState } from 'react'

export const FruitSelectDropdown = ({ fruitDetector }) => {
  const [currentFruit, setCurrentFruit] = useState(fruitDetector)
  
  const changeFruit = (newFruit) => {
    setCurrentFruit(newFruit)
  }
  
  return (
    <form>
      <select 
        onChange={(event) => changeFruit(event.target.value)}
        value={currentFruit}
      >
        <option value="apples">Red Apples</option>
        <option value="oranges">Outrageous Oranges</option>
        <option value="tomatoes">Technically a Fruit Tomatoes</option>
        <option value="bananas">Bodacious Bananas</option>
      </select>
    </form>
  )
}

Then import the FruitSelectDropdown elsewhere in your app

import React from 'react'
import { FruitSelectDropdown } from '../path/to/FruitSelectDropdown'

const App = () => {
  return (
    <div className="page-container">
      <h1 className="header">A webpage about fruit</h1>
      <div className="section-container">
        <h2>Pick your favorite fruit</h2>
        <FruitSelectDropdown fruitDetector='bananas' />

      </div>
    </div>
  )
}

export default App

FruitSelectDropdown with Typescript

import React, { FC, useState } from 'react'

type FruitProps = {
  fruitDetector: string;
}

export const FruitSelectDropdown: FC<FruitProps> = ({ fruitDetector }) => {
  const [currentFruit, setCurrentFruit] = useState(fruitDetector)
  
  const changeFruit = (newFruit: string): void => {
    setCurrentFruit(newFruit)
  }
  
  return (
    <form>
      <select 
        onChange={(event) => changeFruit(event.target.value)}
        value={currentFruit}
      >
        <option value="apples">Red Apples</option>
        <option value="oranges">Outrageous Oranges</option>
        <option value="tomatoes">Technically a Fruit Tomatoes</option>
        <option value="bananas">Bodacious Bananas</option>
      </select>
    </form>
  )
}

Then import the FruitSelectDropdown elsewhere in your app

import React, { FC } from 'react'
import { FruitSelectDropdown } from '../path/to/FruitSelectDropdown'

const App: FC = () => {
  return (
    <div className="page-container">
      <h1 className="header">A webpage about fruit</h1>
      <div className="section-container">
        <h2>Pick your favorite fruit</h2>
        <FruitSelectDropdown fruitDetector='bananas' />

      </div>
    </div>
  )
}

export default App

Bonus Round: Translation Dropdown with selected current value:

import React, { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'

export const LanguageSelectDropdown: FC = () => {
  const { i18n } = useTranslation()
  const i18nLanguage = i18n.language
  const [currentI18nLanguage, setCurrentI18nLanguage] = useState(i18nLanguage)
  
  const changeLanguage = (language: string): void => {
    i18n.changeLanguage(language)
    setCurrentI18nLanguage(language)
  }
  
  return (
    <form>
      <select 
        onChange={(event) => changeLanguage(event.target.value)}
        value={currentI18nLanguage}
      >
        <option value="en">English</option>
        <option value="de">Deutsch</option>
        <option value="es">Español</option>
        <option value="fr">Français</option>
      </select>
    </form>
  )
}

An invaluable resource for React/Typescript

How to set the opacity/alpha of a UIImage?

I realize this is quite late, but I needed something like this so I whipped up a quick and dirty method to do this.

+ (UIImage *) image:(UIImage *)image withAlpha:(CGFloat)alpha{

    // Create a pixel buffer in an easy to use format
    CGImageRef imageRef = [image CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    UInt8 * m_PixelBuf = malloc(sizeof(UInt8) * height * width * 4);

    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(m_PixelBuf, width, height,
                                                 bitsPerComponent, bytesPerRow, colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);

    //alter the alpha
    int length = height * width * 4;
    for (int i=0; i<length; i+=4)
    {
        m_PixelBuf[i+3] =  255*alpha;
    }


    //create a new image
    CGContextRef ctx = CGBitmapContextCreate(m_PixelBuf, width, height,
                                                 bitsPerComponent, bytesPerRow, colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

    CGImageRef newImgRef = CGBitmapContextCreateImage(ctx);  
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(ctx);  
    free(m_PixelBuf);

    UIImage *finalImage = [UIImage imageWithCGImage:newImgRef];
    CGImageRelease(newImgRef);  

    return finalImage;
}

Local and global temporary tables in SQL Server

1.) A local temporary table exists only for the duration of a connection or, if defined inside a compound statement, for the duration of the compound statement.

Local temp tables are only available to the SQL Server session or connection (means single user) that created the tables. These are automatically deleted when the session that created the tables has been closed. Local temporary table name is stared with single hash ("#") sign.

CREATE TABLE #LocalTemp
(
 UserID int,
 Name varchar(50), 
 Address varchar(150)
)
GO
insert into #LocalTemp values ( 1, 'Name','Address');
GO
Select * from #LocalTemp

The scope of Local temp table exist to the current session of current user means to the current query window. If you will close the current query window or open a new query window and will try to find above created temp table, it will give you the error.


2.) A global temporary table remains in the database permanently, but the rows exist only within a given connection. When connection is closed, the data in the global temporary table disappears. However, the table definition remains with the database for access when database is opened next time.

Global temp tables are available to all SQL Server sessions or connections (means all the user). These can be created by any SQL Server connection user and these are automatically deleted when all the SQL Server connections have been closed. Global temporary table name is stared with double hash ("##") sign.

CREATE TABLE ##GlobalTemp
(
 UserID int,
 Name varchar(50), 
 Address varchar(150)
)
GO
insert into ##GlobalTemp values ( 1, 'Name','Address');
GO
Select * from ##GlobalTemp

Global temporary tables are visible to all SQL Server connections while Local temporary tables are visible to only current SQL Server connection.

What is the precise meaning of "ours" and "theirs" in git?

I suspect you're confused here because it's fundamentally confusing. To make things worse, the whole ours/theirs stuff switches roles (becomes backwards) when you are doing a rebase.

Ultimately, during a git merge, the "ours" branch refers to the branch you're merging into:

git checkout merge-into-ours

and the "theirs" branch refers to the (single) branch you're merging:

git merge from-theirs

and here "ours" and "theirs" makes some sense, as even though "theirs" is probably yours anyway, "theirs" is not the one you were on when you ran git merge.

While using the actual branch name might be pretty cool, it falls apart in more complex cases. For instance, instead of the above, you might do:

git checkout ours
git merge 1234567

where you're merging by raw commit-ID. Worse, you can even do this:

git checkout 7777777    # detach HEAD
git merge 1234567       # do a test merge

in which case there are no branch names involved!

I think it's little help here, but in fact, in gitrevisions syntax, you can refer to an individual path in the index by number, during a conflicted merge

git show :1:README
git show :2:README
git show :3:README

Stage #1 is the common ancestor of the files, stage #2 is the target-branch version, and stage #3 is the version you are merging from.


The reason the "ours" and "theirs" notions get swapped around during rebase is that rebase works by doing a series of cherry-picks, into an anonymous branch (detached HEAD mode). The target branch is the anonymous branch, and the merge-from branch is your original (pre-rebase) branch: so "--ours" means the anonymous one rebase is building while "--theirs" means "our branch being rebased".


As for the gitattributes entry: it could have an effect: "ours" really means "use stage #2" internally. But as you note, it's not actually in place at the time, so it should not have an effect here ... well, not unless you copy it into the work tree before you start.

Also, by the way, this applies to all uses of ours and theirs, but some are on a whole file level (-s ours for a merge strategy; git checkout --ours during a merge conflict) and some are on a piece-by-piece basis (-X ours or -X theirs during a -s recursive merge). Which probably does not help with any of the confusion.

I've never come up with a better name for these, though. And: see VonC's answer to another question, where git mergetool introduces yet more names for these, calling them "local" and "remote"!

converting a base 64 string to an image and saving it

Here is working code for converting an image from a base64 string to an Image object and storing it in a folder with unique file name:

public void SaveImage()
{
    string strm = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; 

    //this is a simple white background image
    var myfilename= string.Format(@"{0}", Guid.NewGuid());

    //Generate unique filename
    string filepath= "~/UserImages/" + myfilename+ ".jpeg";
    var bytess = Convert.FromBase64String(strm);
    using (var imageFile = new FileStream(filepath, FileMode.Create))
    {
        imageFile.Write(bytess, 0, bytess.Length);
        imageFile.Flush();
    }
}

How do I display images from Google Drive on a website?

Use the 'Get Link' option in Google Drive to get the URL.

Use <img> tag in HTML and paste the link in there.

Change Open? in the URL to uc?.

What is "Signal 15 received"

This indicates the linux has delivered a SIGTERM to your process. This is usually at the request of some other process (via kill()) but could also be sent by your process to itself (using raise()). This signal requests an orderly shutdown of your process.

If you need a quick cheatsheet of signal numbers, open a bash shell and:

$ kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL
 5) SIGTRAP  6) SIGABRT  7) SIGBUS   8) SIGFPE
 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM   27) SIGPROF 28) SIGWINCH
29) SIGIO   30) SIGPWR  31) SIGSYS  34) SIGRTMIN
35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX    

You can determine the sender by using an appropriate signal handler like:

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

void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
  fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
      info->si_pid);
  exit(0);
}

int main (void)
{
  struct sigaction action = {
    .sa_handler = NULL,
    .sa_sigaction = sigterm_handler,
    .sa_mask = 0,
    .sa_flags = SA_SIGINFO,
    .sa_restorer = NULL
  };

  sigaction(SIGTERM, &action, NULL);
  sleep(60);

  return 0;
}

Notice that the signal handler also includes a call to exit(). It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).

Changing image sizes proportionally using CSS?

You can use object-fit css3 property, something like

_x000D_
_x000D_
<!doctype html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset='utf-8'>_x000D_
  <style>_x000D_
    .holder {_x000D_
      display: inline;_x000D_
    }_x000D_
    .holder img {_x000D_
      max-height: 200px;_x000D_
      max-width: 200px;_x000D_
      object-fit: cover;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class='holder'>_x000D_
    <img src='meld.png'>_x000D_
  </div>_x000D_
  <div class='holder'>_x000D_
    <img src='twiddla.png'>_x000D_
  </div>_x000D_
  <div class='holder'>_x000D_
    <img src='meld.png'>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

It is not exactly your answer, though, because of it doesn't stretch the container, but it behaves like the gallery and you can keep styling the img itself.

Another drawback of this solution is still a poor support of the css3 property. More details are available here: http://www.steveworkman.com/html5-2/javascript/2012/css3-object-fit-polyfill/. jQuery solution can be found there as well.

Adding author name in Eclipse automatically to existing files

Actually in Eclipse Indigo thru Oxygen, you have to go to the Types template Window -> Preferences -> Java -> Code Style -> Code templates -> (in right-hand pane) Comments -> double-click Types and make sure it has the following, which it should have by default:

/**
 * @author ${user}
 *
 * ${tags}
 */

and as far as I can tell, there is nothing in Eclipse to add the javadoc automatically to existing files in one batch. You could easily do it from the command line with sed & awk but that's another question.

If you are prepared to open each file individually, then selected the class / interface declaration line, e.g. public class AdamsClass { and then hit the key combo Shift + Alt + J and that will insert a new javadoc comment above, along with the author tag for your user. To experiment with other settings, go to Windows->Preferences->Java->Editor->Templates.

How do I simulate placeholder functionality on input date field?

As mentionned here, I've made it work with some ":before" pseudo-class and a small bit of javascript. Here is the idea :

 #myInput:before{ content:"Date of birth"; width:100%; color:#AAA; } 
 #myInput:focus:before,
 #myInput.not_empty:before{ content:none }

Then in javascript, add the "not_empty" class depending on the value in the onChange and onKeyUp events.

You can even add all of this dynamically on every date fields. Check my answer on the other thread for the code.

It's not perfect but it's working well in Chrome and iOS7 webviews. Maybe it could help you.

How to match a substring in a string, ignoring case

Try:

if haystackstr.lower().find(needlestr.lower()) != -1:
  # True

Permutation of array

Implementation via recursion (dynamic programming), in Java, with test case (TestNG).


Code

PrintPermutation.java

import java.util.Arrays;

/**
 * Print permutation of n elements.
 * 
 * @author eric
 * @date Oct 13, 2018 12:28:10 PM
 */
public class PrintPermutation {
    /**
     * Print permutation of array elements.
     * 
     * @param arr
     * @return count of permutation,
     */
    public static int permutation(int arr[]) {
        return permutation(arr, 0);
    }

    /**
     * Print permutation of part of array elements.
     * 
     * @param arr
     * @param n
     *            start index in array,
     * @return count of permutation,
     */
    private static int permutation(int arr[], int n) {
        int counter = 0;
        for (int i = n; i < arr.length; i++) {
            swapArrEle(arr, i, n);
            counter += permutation(arr, n + 1);
            swapArrEle(arr, n, i);
        }
        if (n == arr.length - 1) {
            counter++;
            System.out.println(Arrays.toString(arr));
        }

        return counter;
    }

    /**
     * swap 2 elements in array,
     * 
     * @param arr
     * @param i
     * @param k
     */
    private static void swapArrEle(int arr[], int i, int k) {
        int tmp = arr[i];
        arr[i] = arr[k];
        arr[k] = tmp;
    }
}

PrintPermutationTest.java (test case via TestNG)

import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * PrintPermutation test.
 * 
 * @author eric
 * @date Oct 14, 2018 3:02:23 AM
 */
public class PrintPermutationTest {
    @Test
    public void test() {
        int arr[] = new int[] { 0, 1, 2, 3 };
        Assert.assertEquals(PrintPermutation.permutation(arr), 24);

        int arrSingle[] = new int[] { 0 };
        Assert.assertEquals(PrintPermutation.permutation(arrSingle), 1);

        int arrEmpty[] = new int[] {};
        Assert.assertEquals(PrintPermutation.permutation(arrEmpty), 0);
    }
}

subquery in FROM must have an alias

In the case of nested tables, some DBMS require to use an alias like MySQL and Oracle but others do not have such a strict requirement, but still allow to add them to substitute the result of the inner query.

S3 limit to objects in a bucket

While you can store an unlimited number of files/objects in a single bucket, when you go to list a "directory" in a bucket, it will only give you the first 1000 files/objects in that bucket by default. To access all the files in a large "directory" like this, you need to make multiple calls to their API.

Creating a PDF from a RDLC Report in the Background

You can instanciate LocalReport

                FicheInscriptionBean fiche = new FicheInscriptionBean();
                fiche.ToFicheInscriptionBean(inscription);List<FicheInscriptionBean> list = new List<FicheInscriptionBean>();
                list.Add(fiche);
                ReportDataSource rds = new ReportDataSource();
                rds = new ReportDataSource("InscriptionDataSet", list);
                // attachement du QrCode.
                string stringToCode = numinscription + "," + inscription.Nom + "," + inscription.Prenom + "," + inscription.Cin;
                Bitmap BitmapCaptcha = PostulerFiche.GenerateQrCode(fiche.NumInscription + ":" + fiche.Cin, Brushes.Black, Brushes.White, 200);
                MemoryStream ms = new MemoryStream();
                BitmapCaptcha.Save(ms, ImageFormat.Gif);
                var base64Data = Convert.ToBase64String(ms.ToArray());
                string QR_IMG = base64Data;
                ReportParameter parameter = new ReportParameter("QR_IMG", QR_IMG, true);

                LocalReport report = new LocalReport();
                report.ReportPath = Page.Server.MapPath("~/rdlc/FicheInscription.rdlc");
                report.DataSources.Clear();
                report.SetParameters(new ReportParameter[] { parameter });
                report.DataSources.Add(rds);
                report.Refresh();

                string FileName = "FichePreinscription_" + numinscription + ".pdf";
                string extension;
                string encoding;
                string mimeType;
                string[] streams;
                Warning[] warnings;
                Byte[] mybytes = report.Render("PDF", null,
                              out extension, out encoding,
                              out mimeType, out streams, out warnings);
                using (FileStream fs = File.Create(Server.MapPath("~/rdlc/Reports/" + FileName)))
                {
                    fs.Write(mybytes, 0, mybytes.Length);
                }
                Response.ClearHeaders();
                Response.ClearContent();
                Response.Buffer = true;
                Response.Clear();
                Response.Charset = "";
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "attachment;filename=\"" + FileName + "\"");
                Response.WriteFile(Server.MapPath("~/rdlc/Reports/" + FileName));

                Response.Flush();
                File.Delete(Server.MapPath("~/rdlc/Reports/" + FileName));
                Response.Close();
                Response.End();

Android Studio - UNEXPECTED TOP-LEVEL EXCEPTION:

Like everyone else said here, the support library (com.android.support) is being included more than once in your project. Try adding this in your build.gradle at the root level and it should exclude the support library from being exported via other project dependencies.

configurations {
    all*.exclude group: 'com.android.support', module: 'support-v4'
}

If you have more then one support libs included in the dependencies like this, you may want to remove one of them:enter image description here

Trying to get property of non-object - Laravel 5

If you working with or loops (for, foreach, etc.) or relationships (one to many, many to many, etc.), this may mean that one of the queries is returning a null variable or a null relationship member.

For example: In a table, you may want to list users with their roles.

<table>
    <tr>
        <th>Name</th>
        <th>Role</th>
    </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ $user->name }}</td>
        <td>{{ $user->role->name }}</td>
    </tr>
    @endforeach
</table>

In the above case, you may receive this error if there is even one User who does not have a Role. You should replace {{ $user->role->name }} with {{ !empty($user->role) ? $user->role->name:'' }}, like this:

<table>
    <tr>
        <th>Name</th>
        <th>Role</th>
    </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ $user->name }}</td>
        <td>{{ !empty($user->role) ? $user->role->name:'' }}</td>
    </tr>
    @endforeach
</table>

Edit: You can use Laravel's the optional method to avoid errors (more information). For example:

<table>
    <tr>
        <th>Name</th>
        <th>Role</th>
    </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ $user->name }}</td>
        <td>{{ optional($user->role)->name }}</td>
    </tr>
    @endforeach
</table>

If you are using PHP 8, you can use the null safe operator:

<table>
    <tr>
        <th>Name</th>
        <th>Role</th>
    </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ $user?->name }}</td>
        <td>{{ $user?->role?->name }}</td>
    </tr>
    @endforeach
</table>

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

The 2nd option is the one you want.

In your web.config, make sure these keys exist:

<configuration>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
    </system.webServer>
</configuration>

How to permanently add a private key with ssh-add on Ubuntu?

A solution would be to force the key files to be kept permanently, by adding them in your ~/.ssh/config file:

IdentityFile ~/.ssh/gitHubKey
IdentityFile ~/.ssh/id_rsa_buhlServer

If you do not have a 'config' file in the ~/.ssh directory, then you should create one. It does not need root rights, so simply:

nano ~/.ssh/config

...and enter the lines above as per your requirements.

For this to work the file needs to have chmod 600. You can use the command chmod 600 ~/.ssh/config.

If you want all users on the computer to use the key put these lines into /etc/ssh/ssh_config and the key in a folder accessible to all.

Additionally if you want to set the key specific to one host, you can do the following in your ~/.ssh/config :

Host github.com
    User git
    IdentityFile ~/.ssh/githubKey

This has the advantage when you have many identities that a server doesn't reject you because you tried the wrong identities first. Only the specific identity will be tried.

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

ExecutorService, how to wait for all tasks to finish

You can use ExecutorService.invokeAll method, It will execute all task and wait till all threads finished their task.

Here is complete javadoc

You can also user overloaded version of this method to specify the timeout.

Here is sample code with ExecutorService.invokeAll

public class Test {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService service = Executors.newFixedThreadPool(3);
        List<Callable<String>> taskList = new ArrayList<>();
        taskList.add(new Task1());
        taskList.add(new Task2());
        List<Future<String>> results = service.invokeAll(taskList);
        for (Future<String> f : results) {
            System.out.println(f.get());
        }
    }

}

class Task1 implements Callable<String> {
    @Override
    public String call() throws Exception {
        try {
            Thread.sleep(2000);
            return "Task 1 done";
        } catch (Exception e) {
            e.printStackTrace();
            return " error in task1";
        }
    }
}

class Task2 implements Callable<String> {
    @Override
    public String call() throws Exception {
        try {
            Thread.sleep(3000);
            return "Task 2 done";
        } catch (Exception e) {
            e.printStackTrace();
            return " error in task2";
        }
    }
}

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

Since there is no programmatic way to mimic minimal-ui, we have come up with a different workaround, using calc() and known iOS address bar height to our advantage:

The following demo page (also available on gist, more technical details there) will prompt user to scroll, which then triggers a soft-fullscreen (hide address bar/menu), where header and content fills the new viewport.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scroll Test</title>

    <style>
        html, body {
            height: 100%;
        }

        html {
            background-color: red;
        }

        body {
            background-color: blue;
            margin: 0;
        }

        div.header {
            width: 100%;
            height: 40px;
            background-color: green;
            overflow: hidden;
        }

        div.content {
            height: 100%;
            height: calc(100% - 40px);
            width: 100%;
            background-color: purple;
            overflow: hidden;
        }

        div.cover {
            position: absolute;
            top: 0;
            left: 0;
            z-index: 100;
            width: 100%;
            height: 100%;
            overflow: hidden;
            background-color: rgba(0, 0, 0, 0.5);
            color: #fff;
            display: none;
        }

        @media screen and (width: 320px) {
            html {
                height: calc(100% + 72px);
            }

            div.cover {
                display: block;
            }
        }
    </style>
    <script>
        var timeout;

        window.addEventListener('scroll', function(ev) {

            if (timeout) {
                clearTimeout(timeout);
            }

            timeout = setTimeout(function() {

                if (window.scrollY > 0) {
                    var cover = document.querySelector('div.cover');
                    cover.style.display = 'none';
                }

            }, 200);

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

    <div class="header">
        <p>header</p>
    </div>
    <div class="content">
        <p>content</p>
    </div>
    <div class="cover">
        <p>scroll to soft fullscreen</p>
    </div>

</body>
</html>

'any' vs 'Object'

any is something specific to TypeScript is explained quite well by alex's answer.

Object refers to the JavaScript object type. Commonly used as {} or sometimes new Object. Most things in javascript are compatible with the object data type as they inherit from it. But any is TypeScript specific and compatible with everything in both directions (not inheritance based). e.g. :

var foo:Object; 
var bar:any;
var num:number;

foo = num; // Not an error
num = foo; // ERROR 

// Any is compatible both ways 
bar = num;
num = bar;  

How to use java.net.URLConnection to fire and handle HTTP requests?

I was also very inspired by this response.

I am often on projects where I need to do some HTTP, and I may not want to bring in a lot of 3rd party dependencies (which bring in others and so on and so on, etc.)

I started to write my own utilities based on some of this conversation (not any where done):

package org.boon.utils;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import static org.boon.utils.IO.read;

public class HTTP {

Then there are just a bunch or static methods.

public static String get(
        final String url) {

    Exceptions.tryIt(() -> {
        URLConnection connection;
        connection = doGet(url, null, null, null);
        return extractResponseString(connection);
    });
    return null;
}

public static String getWithHeaders(
        final String url,
        final Map<String, ? extends Object> headers) {
    URLConnection connection;
    try {
        connection = doGet(url, headers, null, null);
        return extractResponseString(connection);
    } catch (Exception ex) {
        Exceptions.handle(ex);
        return null;
    }
}

public static String getWithContentType(
        final String url,
        final Map<String, ? extends Object> headers,
        String contentType) {
    URLConnection connection;
    try {
        connection = doGet(url, headers, contentType, null);
        return extractResponseString(connection);
    } catch (Exception ex) {
        Exceptions.handle(ex);
        return null;
    }
}
public static String getWithCharSet(
        final String url,
        final Map<String, ? extends Object> headers,
        String contentType,
        String charSet) {
    URLConnection connection;
    try {
        connection = doGet(url, headers, contentType, charSet);
        return extractResponseString(connection);
    } catch (Exception ex) {
        Exceptions.handle(ex);
        return null;
    }
}

Then post...

public static String postBody(
        final String url,
        final String body) {
    URLConnection connection;
    try {
        connection = doPost(url, null, "text/plain", null, body);
        return extractResponseString(connection);
    } catch (Exception ex) {
        Exceptions.handle(ex);
        return null;
    }
}

public static String postBodyWithHeaders(
        final String url,
        final Map<String, ? extends Object> headers,
        final String body) {
    URLConnection connection;
    try {
        connection = doPost(url, headers, "text/plain", null, body);
        return extractResponseString(connection);
    } catch (Exception ex) {
        Exceptions.handle(ex);
        return null;
    }
}



public static String postBodyWithContentType(
        final String url,
        final Map<String, ? extends Object> headers,
        final String contentType,
        final String body) {

    URLConnection connection;
    try {
        connection = doPost(url, headers, contentType, null, body);


        return extractResponseString(connection);


    } catch (Exception ex) {
        Exceptions.handle(ex);
        return null;
    }


}


public static String postBodyWithCharset(
        final String url,
        final Map<String, ? extends Object> headers,
        final String contentType,
        final String charSet,
        final String body) {

    URLConnection connection;
    try {
        connection = doPost(url, headers, contentType, charSet, body);


        return extractResponseString(connection);


    } catch (Exception ex) {
        Exceptions.handle(ex);
        return null;
    }


}

private static URLConnection doPost(String url, Map<String, ? extends Object> headers,
                                    String contentType, String charset, String body
                                    ) throws IOException {
    URLConnection connection;/* Handle output. */
    connection = new URL(url).openConnection();
    connection.setDoOutput(true);
    manageContentTypeHeaders(contentType, charset, connection);

    manageHeaders(headers, connection);


    IO.write(connection.getOutputStream(), body, IO.CHARSET);
    return connection;
}

private static void manageHeaders(Map<String, ? extends Object> headers, URLConnection connection) {
    if (headers != null) {
        for (Map.Entry<String, ? extends Object> entry : headers.entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue().toString());
        }
    }
}

private static void manageContentTypeHeaders(String contentType, String charset, URLConnection connection) {
    connection.setRequestProperty("Accept-Charset", charset == null ? IO.CHARSET : charset);
    if (contentType!=null && !contentType.isEmpty()) {
        connection.setRequestProperty("Content-Type", contentType);
    }
}

private static URLConnection doGet(String url, Map<String, ? extends Object> headers,
                                    String contentType, String charset) throws IOException {
    URLConnection connection;/* Handle output. */
    connection = new URL(url).openConnection();
    manageContentTypeHeaders(contentType, charset, connection);

    manageHeaders(headers, connection);

    return connection;
}

private static String extractResponseString(URLConnection connection) throws IOException {
/* Handle input. */
    HttpURLConnection http = (HttpURLConnection)connection;
    int status = http.getResponseCode();
    String charset = getCharset(connection.getHeaderField("Content-Type"));

    if (status==200) {
        return readResponseBody(http, charset);
    } else {
        return readErrorResponseBody(http, status, charset);
    }
}

private static String readErrorResponseBody(HttpURLConnection http, int status, String charset) {
    InputStream errorStream = http.getErrorStream();
    if ( errorStream!=null ) {
        String error = charset== null ? read( errorStream ) :
            read( errorStream, charset );
        throw new RuntimeException("STATUS CODE =" + status + "\n\n" + error);
    } else {
        throw new RuntimeException("STATUS CODE =" + status);
    }
}

private static String readResponseBody(HttpURLConnection http, String charset) throws IOException {
    if (charset != null) {
        return read(http.getInputStream(), charset);
    } else {
        return read(http.getInputStream());
    }
}

private static String getCharset(String contentType) {
    if (contentType==null)  {
        return null;
    }
    String charset = null;
    for (String param : contentType.replace(" ", "").split(";")) {
        if (param.startsWith("charset=")) {
            charset = param.split("=", 2)[1];
            break;
        }
    }
    charset = charset == null ?  IO.CHARSET : charset;

    return charset;
}

Well you get the idea....

Here are the tests:

static class MyHandler implements HttpHandler {
    public void handle(HttpExchange t) throws IOException {

        InputStream requestBody = t.getRequestBody();
        String body = IO.read(requestBody);
        Headers requestHeaders = t.getRequestHeaders();
        body = body + "\n" + copy(requestHeaders).toString();
        t.sendResponseHeaders(200, body.length());
        OutputStream os = t.getResponseBody();
        os.write(body.getBytes());
        os.close();
    }
}


@Test
public void testHappy() throws Exception {

    HttpServer server = HttpServer.create(new InetSocketAddress(9212), 0);
    server.createContext("/test", new MyHandler());
    server.setExecutor(null); // creates a default executor
    server.start();

    Thread.sleep(10);


    Map<String,String> headers = map("foo", "bar", "fun", "sun");

    String response = HTTP.postBodyWithContentType("http://localhost:9212/test", headers, "text/plain", "hi mom");

    System.out.println(response);

    assertTrue(response.contains("hi mom"));
    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));


    response = HTTP.postBodyWithCharset("http://localhost:9212/test", headers, "text/plain", "UTF-8", "hi mom");

    System.out.println(response);

    assertTrue(response.contains("hi mom"));
    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));

    response = HTTP.postBodyWithHeaders("http://localhost:9212/test", headers, "hi mom");

    System.out.println(response);

    assertTrue(response.contains("hi mom"));
    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));


    response = HTTP.get("http://localhost:9212/test");

    System.out.println(response);


    response = HTTP.getWithHeaders("http://localhost:9212/test", headers);

    System.out.println(response);

    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));



    response = HTTP.getWithContentType("http://localhost:9212/test", headers, "text/plain");

    System.out.println(response);

    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));



    response = HTTP.getWithCharSet("http://localhost:9212/test", headers, "text/plain", "UTF-8");

    System.out.println(response);

    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));

    Thread.sleep(10);

    server.stop(0);


}

@Test
public void testPostBody() throws Exception {

    HttpServer server = HttpServer.create(new InetSocketAddress(9220), 0);
    server.createContext("/test", new MyHandler());
    server.setExecutor(null); // creates a default executor
    server.start();

    Thread.sleep(10);


    Map<String,String> headers = map("foo", "bar", "fun", "sun");

    String response = HTTP.postBody("http://localhost:9220/test", "hi mom");

    assertTrue(response.contains("hi mom"));


    Thread.sleep(10);

    server.stop(0);


}

@Test(expected = RuntimeException.class)
public void testSad() throws Exception {

    HttpServer server = HttpServer.create(new InetSocketAddress(9213), 0);
    server.createContext("/test", new MyHandler());
    server.setExecutor(null); // creates a default executor
    server.start();

    Thread.sleep(10);


    Map<String,String> headers = map("foo", "bar", "fun", "sun");

    String response = HTTP.postBodyWithContentType("http://localhost:9213/foo", headers, "text/plain", "hi mom");

    System.out.println(response);

    assertTrue(response.contains("hi mom"));
    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));

    Thread.sleep(10);

    server.stop(0);


}

You can find the rest here:

https://github.com/RichardHightower/boon

My goal is to provide the common things one would want to do in a bit more easier way then....

How to unzip gz file using Python

from sh import gunzip

gunzip('/tmp/file1.gz')

How to loop through a collection that supports IEnumerable?

Maybe you forgot the await before returning your collection

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

It needs you to add a Web Form, just go to add on properties -> new item -> Web Form. Then wen you run it, it will work. Simple

Running Jupyter via command line on Windows

I had the same problem, but

py -m notebook

worked for me.

Get google map link with latitude/longitude

The suggested answer no longer works after 2014. Now you have to use Google Maps Embed API for loading into iframe.

Here is the link for the question and solution.

If you are using Angular like me you won't be able to load the google maps in iframe because of XSS security issue. For that you need to sanitise the URL with Pipe from angular.

Here is the link to do so.

All the suggestions are tested and works 100% as of today.

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

You can run with PYTHONPATH in project root

PYTHONPATH=. py.test

Or use pip install as editable import

pip install -e .   # install package using setup.py in editable mode

Check synchronously if file/directory exists in Node.js

The answer to this question has changed over the years. The current answer is here at the top, followed by the various answers over the years in chronological order:

Current Answer

You can use fs.existsSync():

const fs = require("fs"); // Or `import fs from "fs";` with ESM
if (fs.existsSync(path)) {
    // Do something
}

It was deprecated for several years, but no longer is. From the docs:

Note that fs.exists() is deprecated, but fs.existsSync() is not. (The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.)

You've specifically asked for a synchronous check, but if you can use an asynchronous check instead (usually best with I/O), use fs.promises.access if you're using async functions or fs.access (since exists is deprecated) if not:

In an async function:

try {
    await fs.promises.access("somefile");
    // The check succeeded
} catch (error) {
    // The check failed
}

Or with a callback:

fs.access("somefile", error => {
    if (!error) {
        // The check succeeded
    } else {
        // The check failed
    }
});

Historical Answers

Here are the historical answers in chronological order:

  • Original answer from 2010
    (stat/statSync or lstat/lstatSync)
  • Update September 2012
    (exists/existsSync)
  • Update February 2015
    (Noting impending deprecation of exists/existsSync, so we're probably back to stat/statSync or lstat/lstatSync)
  • Update December 2015
    (There's also fs.access(path, fs.F_OK, function(){}) / fs.accessSync(path, fs.F_OK), but note that if the file/directory doesn't exist, it's an error; docs for fs.stat recommend using fs.access if you need to check for existence without opening)
  • Update December 2016
    fs.exists() is still deprecated but fs.existsSync() is no longer deprecated. So you can safely use it now.

Original answer from 2010:

You can use statSync or lstatSync (docs link), which give you an fs.Stats object. In general, if a synchronous version of a function is available, it will have the same name as the async version with Sync at the end. So statSync is the synchronous version of stat; lstatSync is the synchronous version of lstat, etc.

lstatSync tells you both whether something exists, and if so, whether it's a file or a directory (or in some file systems, a symbolic link, block device, character device, etc.), e.g. if you need to know if it exists and is a directory:

var fs = require('fs');
try {
    // Query the entry
    stats = fs.lstatSync('/the/path');

    // Is it a directory?
    if (stats.isDirectory()) {
        // Yes it is
    }
}
catch (e) {
    // ...
}

...and similarly, if it's a file, there's isFile; if it's a block device, there's isBlockDevice, etc., etc. Note the try/catch; it throws an error if the entry doesn't exist at all.

If you don't care what the entry is and only want to know whether it exists, you can use path.existsSync (or with latest, fs.existsSync) as noted by user618408:

var path = require('path');
if (path.existsSync("/the/path")) { // or fs.existsSync
    // ...
}

It doesn't require a try/catch but gives you no information about what the thing is, just that it's there. path.existsSync was deprecated long ago.


Side note: You've expressly asked how to check synchronously, so I've used the xyzSync versions of the functions above. But wherever possible, with I/O, it really is best to avoid synchronous calls. Calls into the I/O subsystem take significant time from a CPU's point of view. Note how easy it is to call lstat rather than lstatSync:

// Is it a directory?
lstat('/the/path', function(err, stats) {
    if (!err && stats.isDirectory()) {
        // Yes it is
    }
});

But if you need the synchronous version, it's there.

Update September 2012

The below answer from a couple of years ago is now a bit out of date. The current way is to use fs.existsSync to do a synchronous check for file/directory existence (or of course fs.exists for an asynchronous check), rather than the path versions below.

Example:

var fs = require('fs');

if (fs.existsSync(path)) {
    // Do something
}

// Or

fs.exists(path, function(exists) {
    if (exists) {
        // Do something
    }
});

Update February 2015

And here we are in 2015 and the Node docs now say that fs.existsSync (and fs.exists) "will be deprecated". (Because the Node folks think it's dumb to check whether something exists before opening it, which it is; but that's not the only reason for checking whether something exists!)

So we're probably back to the various stat methods... Until/unless this changes yet again, of course.

Update December 2015

Don't know how long it's been there, but there's also fs.access(path, fs.F_OK, ...) / fs.accessSync(path, fs.F_OK). And at least as of October 2016, the fs.stat documentation recommends using fs.access to do existence checks ("To check if a file exists without manipulating it afterwards, fs.access() is recommended."). But note that the access not being available is considered an error, so this would probably be best if you're expecting the file to be accessible:

var fs = require('fs');

try {
    fs.accessSync(path, fs.F_OK);
    // Do something
} catch (e) {
    // It isn't accessible
}

// Or

fs.access(path, fs.F_OK, function(err) {
    if (!err) {
        // Do something
    } else {
        // It isn't accessible
    }
});

Update December 2016

You can use fs.existsSync():

if (fs.existsSync(path)) {
    // Do something
}

It was deprecated for several years, but no longer is. From the docs:

Note that fs.exists() is deprecated, but fs.existsSync() is not. (The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.)

Which Java library provides base64 encoding/decoding?

Guava also has Base64 (among other encodings and incredibly useful stuff)

Downloading an entire S3 bucket?

  1. Windows User need to download S3EXPLORER from this link which also has installation instructions :- http://s3browser.com/download.aspx

  2. Then provide you AWS credentials like secretkey, accesskey and region to the s3explorer, this link contains configuration instruction for s3explorer:Copy Paste Link in brower: s3browser.com/s3browser-first-run.aspx

  3. Now your all s3 buckets would be visible on left panel of s3explorer.

  4. Simply select the bucket, and click on Buckets menu on top left corner, then select Download all files to option from the menu. Below is the screenshot for the same:

Bucket Selection Screen

  1. Then browse a folder to download the bucket at a particular place

  2. Click on OK and your download would begin.

How to insert pandas dataframe via mysqldb into database?

The to_sql method works for me.

However, keep in mind that the it looks like it's going to be deprecated in favor of SQLAlchemy:

FutureWarning: The 'mysql' flavor with DBAPI connection is deprecated and will be removed in future versions. MySQL will be further supported with SQLAlchemy connectables. chunksize=chunksize, dtype=dtype)

Best way to find the intersection of multiple sets?

Here I'm offering a generic function for multiple set intersection trying to take advantage of the best method available:

def multiple_set_intersection(*sets):
    """Return multiple set intersection."""
    try:
        return set.intersection(*sets)
    except TypeError: # this is Python < 2.6 or no arguments
        pass

    try: a_set= sets[0]
    except IndexError: # no arguments
        return set() # return empty set

    return reduce(a_set.intersection, sets[1:])

Guido might dislike reduce, but I'm kind of fond of it :)

How to find the nearest parent of a Git branch?

JoeChrysler's command-line magic can be simplified. Here's Joe's logic - for brevity I've introduced a parameter named cur_branch in place of the command substitution `git rev-parse --abbrev-ref HEAD` into both versions; that can be initialized like so:

cur_branch=$(git rev-parse --abbrev-ref HEAD)

Then, here's Joe's pipeline:

git show-branch -a           |
  grep '\*'                  | # we want only lines that contain an asterisk
  grep -v "$cur_branch"      | # but also don't contain the current branch
  head -n1                   | # and only the first such line
  sed 's/.*\[\(.*\)\].*/\1/' | # really, just the part of the line between []
  sed 's/[\^~].*//'            # and with any relative refs (^, ~n) removed

We can accomplish the same thing as all five of those individual command filters in a relatively simple awk command:

git show-branch -a |
  awk -F'[]^~[]' '/\*/ && !/'"$cur_branch"'/ {print $2;exit}'  

That breaks down like this:

-F'[]^~[]' 

split the line into fields at ], ^, ~, and [ characters.

/\*/                      

Find lines that contain an asterisk

&& !/'"$cur_branch"'/

...but not the current branch name

{ print $2;               

When you find such a line, print its second field (that is, the part between the first and second occurrences of our field separator characters). For simple branch names, that will be just what's between the brackets; for refs with relative jumps, it will be just the name without the modifier. So our set of field separators handles the intent of both sed commands.

  exit }

Then exit immediately. This means it only ever processes the first matching line, so we don't need to pipe the output through head -n 1.

How to comment and uncomment blocks of code in the Office VBA Editor

After adding the icon to the toolbar and when modifying the selected icon, the ampersand in the name input is specifying that the next character is the character used along with Alt for the shortcut. Since you must select a display option from the Modify Selection drop down menu that includes displaying the text, you could also write &C in the name field and get the same result as &Comment Block (without the lengthy text).

Parse DateTime string in JavaScript

We use this code to check if the string is a valid date

var dt = new Date(txtDate.value)
if (isNaN(dt))

What's is the difference between train, validation and test set, in neural networks?

We create a validation set to

  • Measure how well a model generalizes, during training
  • Tell us when to stop training a model;When the validation loss stops decreasing (and especially when the validation loss starts increasing and the training loss is still decreasing)

Why validation set used:

Why validation set used

How to set up tmux so that it starts up with specified windows opened?

:~$ tmux new-session "tmux source-file ~/session1"  

session1

neww
split-window -v 'ipython'  
split-window -h  
new-window 'mutt'  

create an alias in .bashrc

:~$ echo `alias tmux_s1='tmux new-session "tmux source-file ~/session1"'` >>~/.bashrc  
:~$ . ~/.bashrc  
:~$ tmux_s1  

How to get element's width/height within directives and component?

You can use ElementRef as shown below,

DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.

import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';

@Directive({
  selector:"[move]",
  host:{
    '(click)':"show()"
  }
})

export class GetEleDirective{

  constructor(private el:ElementRef){

  }
  show(){
    console.log(this.el.nativeElement);

    console.log('height---' + this.el.nativeElement.offsetHeight);  //<<<===here
    console.log('width---' + this.el.nativeElement.offsetWidth);    //<<<===here
  }
}

Same way you can use it within component itself wherever you need it.

Listview Scroll to the end of the list after updating the list

I use

setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);

to add entries at the bottom, and older entries scroll off the top, like a chat transcript

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

I had a similar issue on my controller and here is what worked for me:

model.DateSigned.HasValue ? model.DateSigned.Value.ToString("MM/dd/yyyy") : ""

"DateSigned" is the value from my model The line reads, if the model value has a value then format the value, otherwise show nothing.

Hope that helps

Redirect to Action by parameter mvc

return RedirectToAction("ProductImageManager","Index", new   { id=id   });

Here is an invalid parameters order, should be an action first
AND
ensure your routing table is correct

How to set locale in DatePipe in Angular 2?

Ok, I propose this solution, very simple, using ngx-translate

import { DatePipe } from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Pipe({
  name: 'localizedDate',
  pure: false
})
export class LocalizedDatePipe implements PipeTransform {

  constructor(private translateService: TranslateService) {
}

  transform(value: any): any {
    const date = new Date(value);

    const options = { weekday: 'long',
                  year: 'numeric',
                  month: 'long',
                  day: 'numeric',
                  hour: '2-digit',
                  minute: '2-digit',
                  second: '2-digit'
                    };

    return date.toLocaleString(this.translateService.currentLang, options);
  }

}

Python how to exit main function

You can use sys.exit() to exit from the middle of the main function.

However, I would recommend not doing any logic there. Instead, put everything in a function, and call that from __main__ - then you can use return as normal.

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

"Have you tried turning it off and on again?" (Roy of The IT crowd)

This happened to me today, which is why I ended up to this page. Seeing that error was weird since, recently, I have not made any changes in my Python environment. Interestingly, I observed that if I open a new notebook and import pandas I would not get the same error message. So, I did shutdown the troublesome notebook and started it again and voila it is working again!

Even though this solved the problem (at least for me), I cannot readily come up with an explanation as to why it happened in the first place!

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.

How to see the changes between two commits without commits in-between?

My alias settings in ~/.zshrc file for git diff:

alias gdf='git diff HEAD{'^',}' # diff between your recent tow commits

Thanks @Jinmiao Luo


git diff HEAD~2 HEAD

complete change between latest 2nd commit and current.

HEAD is convenient

How can I install an older version of a package via NuGet?

Try the following:

Uninstall-Package Newtonsoft.Json -Force

Followed by:

Install-Package Newtonsoft.Json -Version <press tab key for autocomplete>

No resource found that matches the given name '@style/ Theme.Holo.Light.DarkActionBar'

in addition,if you try to use CustomActionBarTheme,make sure there is

<application android:theme="@style/CustomActionBarTheme" ... />

in AndroidManifest.xml

not

<application android:theme="@android:style/CustomActionBarTheme" ... />

Increasing Google Chrome's max-connections-per-server limit to more than 6

I don't know that you can do it in Chrome outside of Windows -- some Googling shows that Chrome (and therefore possibly Chromium) might respond well to a certain registry hack.

However, if you're just looking for a simple solution without modifying your code base, have you considered Firefox? In the about:config you can search for "network.http.max" and there are a few values in there that are definitely worth looking at.

Also, for a device that will not be moving (i.e. it is mounted in a fixed location) you should consider not using Wi-Fi (even a Home-Plug would be a step up as far as latency / stability / dropped connections go).

How to get an Array with jQuery, multiple <input> with the same name

To catch the names array, i use that:

$("input[name*='task']")

Does C# have extension properties?

Because I recently needed this, I looked at the source of the answer in:

c# extend class by adding properties

and created a more dynamic version:

public static class ObjectExtenders
{
    static readonly ConditionalWeakTable<object, List<stringObject>> Flags = new ConditionalWeakTable<object, List<stringObject>>();

    public static string GetFlags(this object objectItem, string key)
    {
        return Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value;
    }

    public static void SetFlags(this object objectItem, string key, string value)
    {
        if (Flags.GetOrCreateValue(objectItem).Any(x => x.Key == key))
        {
            Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value = value;
        }
        else
        {
            Flags.GetOrCreateValue(objectItem).Add(new stringObject()
            {
                Key = key,
                Value = value
            });
        }
    }

    class stringObject
    {
        public string Key;
        public string Value;
    }
}

It can probably be improved a lot (naming, dynamic instead of string), I currently use this in CF 3.5 together with a hacky ConditionalWeakTable (https://gist.github.com/Jan-WillemdeBruyn/db79dd6fdef7b9845e217958db98c4d4)

https connection using CURL from command line

I had the same problem - I was fetching a page from my own site, which was served over HTTPS, but curl was giving the same "SSL certificate problem" message. I worked around it by adding a -k flag to the call to allow insecure connections.

curl -k https://whatever.com/script.php

Edit: I discovered the root of the problem. I was using an SSL certificate (from StartSSL, but I don't think that matters much) and hadn't set up the intermediate certificate properly. If you're having the same problem as user1270392 above, it's probably a good idea to test your SSL cert and fix any issues with it before resorting to the curl -k fix.

How do I get the last word in each line with bash

Try

$ awk 'NF>1{print $NF}' file
example.
line.
file.

To get the result in one line as in your example, try:

{
    sub(/\./, ",", $NF)
    str = str$NF
}
END { print str }

output:

$ awk -f script.awk file
example, line, file, 

Pure bash:

$ while read line; do [ -z "$line" ] && continue ;echo ${line##* }; done < file
example.
line.
file.

What causing this "Invalid length for a Base-64 char array"

This isn't an answer, sadly. After running into the intermittent error for some time and finally being annoyed enough to try to fix it, I have yet to find a fix. I have, however, determined a recipe for reproducing my problem, which might help others.

In my case it is SOLELY a localhost problem, on my dev machine that also has the app's DB. It's a .NET 2.0 app I'm editing with VS2005. The Win7 64 bit machine also has VS2008 and .NET 3.5 installed.

Here's what will generate the error, from a variety of forms:

  1. Load a fresh copy of the form.
  2. Enter some data, and/or postback with any of the form's controls. As long as there is no significant delay, repeat all you like, and no errors occur.
  3. Wait a little while (1 or 2 minutes maybe, not more than 5), and try another postback.

A minute or two delay "waiting for localhost" and then "Connection was reset" by the browser, and global.asax's application error trap logs:

Application_Error event: Invalid length for a Base-64 char array.
Stack Trace:
     at System.Convert.FromBase64String(String s)
     at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
     at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState)
     at System.Web.UI.HiddenFieldPageStatePersister.Load()

In this case, it is not the SIZE of the viewstate, but something to do with page and/or viewstate caching that seems to be biting me. Setting <pages> parameters enableEventValidation="false", and viewStateEncryption="Never" in the Web.config did not change the behavior. Neither did setting the maxPageStateFieldLength to something modest.

What does elementFormDefault do in XSD?

elementFormDefault="qualified" is used to control the usage of namespaces in XML instance documents (.xml file), rather than namespaces in the schema document itself (.xsd file).

By specifying elementFormDefault="qualified" we enforce namespace declaration to be used in documents validated with this schema.

It is common practice to specify this value to declare that the elements should be qualified rather than unqualified. However, since attributeFormDefault="unqualified" is the default value, it doesn't need to be specified in the schema document, if one does not want to qualify the namespaces.

python BeautifulSoup parsing table

Here you go:

data = []
table = soup.find('table', attrs={'class':'lineItemsTable'})
table_body = table.find('tbody')

rows = table_body.find_all('tr')
for row in rows:
    cols = row.find_all('td')
    cols = [ele.text.strip() for ele in cols]
    data.append([ele for ele in cols if ele]) # Get rid of empty values

This gives you:

[ [u'1359711259', u'SRF', u'08/05/2013', u'5310 4 AVE', u'K', u'19', u'125.00', u'$'], 
  [u'7086775850', u'PAS', u'12/14/2013', u'3908 6th Ave', u'K', u'40', u'125.00', u'$'], 
  [u'7355010165', u'OMT', u'12/14/2013', u'3908 6th Ave', u'K', u'40', u'145.00', u'$'], 
  [u'4002488755', u'OMT', u'02/12/2014', u'NB 1ST AVE @ E 23RD ST', u'5', u'115.00', u'$'], 
  [u'7913806837', u'OMT', u'03/03/2014', u'5015 4th Ave', u'K', u'46', u'115.00', u'$'], 
  [u'5080015366', u'OMT', u'03/10/2014', u'EB 65TH ST @ 16TH AV E', u'7', u'50.00', u'$'], 
  [u'7208770670', u'OMT', u'04/08/2014', u'333 15th St', u'K', u'70', u'65.00', u'$'], 
  [u'$0.00\n\n\nPayment Amount:']
]

Couple of things to note:

  • The last row in the output above, the Payment Amount is not a part of the table but that is how the table is laid out. You can filter it out by checking if the length of the list is less than 7.
  • The last column of every row will have to be handled separately since it is an input text box.

Update row with data from another row in the same table

Update MyTable
Set Value = (
                Select Min( T2.Value )
                From MyTable As T2
                Where T2.Id <> MyTable.Id
                    And T2.Name = MyTable.Name
                )
Where ( Value Is Null Or Value = '' )
    And Exists  (
                Select 1
                From MyTable As T3
                Where T3.Id <> MyTable.Id
                    And T3.Name = MyTable.Name
                )

DataTable: Hide the Show Entries dropdown but keep the Search box

This is key answer to this post "bLengthChange": false, will hide the Entries Dropdown

GenyMotion Unable to start the Genymotion virtual device

If all the other answers here fail (you can check that you have a correctly created host-only network in VirtualBox, which is basically what other answers here come down to):

https://stackoverflow.com/a/33733454/586754 (with screenshot) worked for me.

Basically, go to Windows network adapter settings for the "VirtualBox Host-Only Ethernet Adapter" and check "VirtualBox NDIS6 Bridged Networking Driver".

This made both Genymotion and Xamarin Android Player work again.

Reading NFC Tags with iPhone 6 / iOS 8

The ability to read an NFC tag has been added to iOS 11 which only support iPhone 7 and 7 plus

As a test drive I made this repo

First: We need to initiate NFCNDEFReaderSession class

var session: NFCNDEFReaderSession? 
session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false)

Then we need to start the session by:

session?.begin()

and when done:

session?.invalidate()

The delegate (which self should implement) has basically two functions:

func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage])
func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error)

here is my reference Apple docs

Execute a command line binary with Node.js

Node JS v15.8.0, LTS v14.15.4, and v12.20.1 --- Feb 2021

Async method (Unix):

'use strict';

const { spawn } = require( 'child_process' );
const ls = spawn( 'ls', [ '-lh', '/usr' ] );

ls.stdout.on( 'data', ( data ) => {
    console.log( `stdout: ${ data }` );
} );

ls.stderr.on( 'data', ( data ) => {
    console.log( `stderr: ${ data }` );
} );

ls.on( 'close', ( code ) => {
    console.log( `child process exited with code ${ code }` );
} );

Async method (Windows):

'use strict';

const { spawn } = require( 'child_process' );
// NOTE: Windows Users, this command appears to be differ for a few users.
// You can think of this as using Node to execute things in your Command Prompt.
// If `cmd` works there, it should work here.
// If you have an issue, try `dir`:
// const dir = spawn( 'dir', [ '.' ] );
const dir = spawn( 'cmd', [ '/c', 'dir' ] );

dir.stdout.on( 'data', ( data ) => console.log( `stdout: ${ data }` ) );
dir.stderr.on( 'data', ( data ) => console.log( `stderr: ${ data }` ) );
dir.on( 'close', ( code ) => console.log( `child process exited with code ${code}` ) );

Sync:

'use strict';

const { spawnSync } = require( 'child_process' );
const ls = spawnSync( 'ls', [ '-lh', '/usr' ] );

console.log( `stderr: ${ ls.stderr.toString() }` );
console.log( `stdout: ${ ls.stdout.toString() }` );

From Node.js v15.8.0 Documentation

The same goes for Node.js v14.15.4 Documentation and Node.js v12.20.1 Documentation

How to get status code from webclient?

Tried it out. ResponseHeaders do not include status code.

If I'm not mistaken, WebClient is capable of abstracting away multiple distinct requests in a single method call (e.g. correctly handling 100 Continue responses, redirects, and the like). I suspect that without using HttpWebRequest and HttpWebResponse, a distinct status code may not be available.

It occurs to me that, if you are not interested in intermediate status codes, you can safely assume the final status code is in the 2xx (successful) range, otherwise, the call would not be successful.

The status code unfortunately isn't present in the ResponseHeaders dictionary.

How to push a new folder (containing other folders and files) to an existing git repo?

You can directly go to Web IDE and upload your folder there.

Steps:

  1. Go to Web IDE(Mostly located below the clone option).
  2. Create new directory at your path
  3. Upload your files and folders

In some cases you may not be able to directly upload entire folder containing folders, In such cases, you will have to create directory structure yourself.

Visualizing decision tree in scikit-learn

sklearn.tree.export_graphviz doesn't return anything, and so by default returns None.

By doing dotfile = tree.export_graphviz(...) you overwrite your open file object, which had been previously assigned to dotfile, so you get an error when you try to close the file (as it's now None).

To fix it change your code to

...
dotfile = open("D:/dtree2.dot", 'w')
tree.export_graphviz(dtree, out_file = dotfile, feature_names = X.columns)
dotfile.close()
...

How do I make a C++ console program exit?

There are several ways to cause your program to terminate. Which one is appropriate depends on why you want your program to terminate. The vast majority of the time it should be by executing a return statement in your main function. As in the following.

int main()
{
     f();
     return 0;
}

As others have identified this allows all your stack variables to be properly destructed so as to clean up properly. This is very important.

If you have detected an error somewhere deep in your code and you need to exit out you should throw an exception to return to the main function. As in the following.

struct stop_now_t { };
void f()
{
      // ...
      if (some_condition())
           throw stop_now_t();
      // ...
}

int main()
{
     try {
          f();
     } catch (stop_now_t& stop) {
          return 1;
     }
     return 0;
 }

This causes the stack to be unwound an all your stack variables to be destructed. Still very important. Note that it is appropriate to indicate failure with a non-zero return value.

If in the unlikely case that your program detects a condition that indicates it is no longer safe to execute any more statements then you should use std::abort(). This will bring your program to a sudden stop with no further processing. std::exit() is similar but may call atexit handlers which could be bad if your program is sufficiently borked.

How can I change my Cygwin home folder after installation?

I did something quite simple. I did not want to change the windows 7 environment variable. So I directly edited the Cygwin.bat file.

@echo off
SETLOCAL
set HOME=C:\path\to\home
C:
chdir C:\apps\cygwin\bin
bash --login -i
ENDLOCAL

This just starts the local shell with this home directory; that is what I wanted. I am not going to remotely access this, so this worked for me.

Prevent Android activity dialog from closing on outside touch

This is the perfect answer to all your questions.... Hope you enjoy coding in Android

new AlertDialog.Builder(this)
            .setTitle("Akshat Rastogi Is Great")
            .setCancelable(false)
            .setMessage("I am the best Android Programmer")
            .setPositiveButton("I agree", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();

                }
            })
            .create().show();

Return Result from Select Query in stored procedure to a List

 SqlConnection connection = new SqlConnection(ConnectionString);

 command = new SqlCommand("TestProcedure", connection);
 command.CommandType = System.Data.CommandType.StoredProcedure;

 connection.Open();

 DataTable dt = new DataTable();

 dt.Load(command.ExecuteReader());

 gvGrid.DataSource = dt;
 gvGrid.DataBind();

What is the difference between Swing and AWT?

Java 8

Swing

  • It is a part of Java Foundation Classes
  • Swing is built on AWT
  • Swing components are lightweight
  • Swing supports pluggable look and feel
  • Platform independent
  • Uses MVC : Model-View-Controller architecture
  • package : javax.swing
  • Unlike Swing’s other components, which are lightweight, the top-level containers are heavyweight.

AWT - Abstract Window Toolkit

  • Platform dependent
  • AWT components are heavyweight
  • package java.awt

Concatenating Matrices in R

cbindX from the package gdata combines multiple columns of differing column and row lengths. Check out the page here:

http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/gdata/html/cbindX.html

It takes multiple comma separated matrices and data.frames as input :) You just need to

install.packages("gdata", dependencies=TRUE)

and then

library(gdata)
concat_data <- cbindX(df1, df2, df3) # or cbindX(matrix1, matrix2, matrix3, matrix4)

Reload content in modal (twitter bootstrap)

I wanted the AJAX loaded content removed when the modal closed, so I adjusted the line suggested by others (coffeescript syntax):

$('#my-modal').on 'hidden.bs.modal', (event) ->
  $(this).removeData('bs.modal').children().remove()

Rails 3.1 and Image Assets

http://railscasts.com/episodes/279-understanding-the-asset-pipeline

This railscast (Rails Tutorial video on asset pipeline) helps a lot to explain the paths in assets pipeline as well. I found it pretty useful, and actually watched it a few times.

The solution I chose is @Lee McAlilly's above, but this railscast helped me to understand why it works. Hope it helps!

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

  • Notepad++, Visual Studio, and some others: Alt + drag.
  • vim: Ctrl + v or (bizarrely enough) Quad-click-drag. In windows: Ctrl + Q (since Ctrl + V is the standard for paste)

Palindrome check in Javascript

function palindrome(str) {
// Good luck!
//convert the string into lowerCase.
 str = str.toLowerCase();
//this line remove all non=alphanumeric characters.
 strAlphaNum = str.replace(/[^a-z0-9]/g,"");
//this line create an array of the strAlphaNum string.
 strArray = strAlphaNum.split("");
//this line reverse the array
 strReversed = strArray.reverse();
//this line join the reversed array to make a string whithout space.
 strRevJoin = strReversed.join("");
//this condition check if the given string is a palindrome.
 if (strAlphaNum === strRevJoin){
 return true;}    
 else {return false;}
 }

Is there any sed like utility for cmd.exe?

sed (and its ilk) are contained within several packages of Unix commands.

If you don't want to install anything and your system ain't a Windows Server one, then you could use a scripting language (VBScript e.g.) for that. Below is a gross, off-the-cuff stab at it. Your command line would look like

cscript //NoLogo sed.vbs s/(oldpat)/(newpat)/ < inpfile.txt > outfile.txt

where oldpat and newpat are Microsoft vbscript regex patterns. Obviously I've only implemented the substitute command and assumed some things, but you could flesh it out to be smarter and understand more of the sed command-line.

Dim pat, patparts, rxp, inp
pat = WScript.Arguments(0)
patparts = Split(pat,"/")
Set rxp = new RegExp
rxp.Global = True
rxp.Multiline = False
rxp.Pattern = patparts(1)
Do While Not WScript.StdIn.AtEndOfStream
  inp = WScript.StdIn.ReadLine()
  WScript.Echo rxp.Replace(inp, patparts(2))
Loop

Getting rid of \n when using .readlines()

for each string in your list, use .strip() which removes whitespace from the beginning or end of the string:

for i in contents:
    alist.append(i.strip())

But depending on your use case, you might be better off using something like numpy.loadtxt or even numpy.genfromtxt if you need a nice array of the data you're reading from the file.

Entity Framework - Generating Classes

EDMX model won't work with EF7 but I've found a Community/Professional product which seems to be very powerfull : http://www.devart.com/entitydeveloper/editions.html

Filtering Pandas DataFrames on dates

If your datetime column have the Pandas datetime type (e.g. datetime64[ns]), for proper filtering you need the pd.Timestamp object, for example:

from datetime import date

import pandas as pd

value_to_check = pd.Timestamp(date.today().year, 1, 1)
filter_mask = df['date_column'] < value_to_check
filtered_df = df[filter_mask]

Android EditText Max Length

If you want to see a counter label you can use app:counterEnabled and android:maxLength, like:

<android.support.design.widget.TextInputLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  app:counterEnabled="true">

  <EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxLength="420" />

</android.support.design.widget.TextInputLayout>

DO NOT set app:counterMaxLength on TextInputLayout because it will conflict with android:maxLength resulting into the issue of invisible chars after the text hits the size limit.

Enum String Name from Value

Try this:

string m = Enum.GetName(typeof(MyEnumClass), value);

Python Pandas: Get index of rows which column matches certain value

I extended this question that is how to gets the row, columnand value of all matches value?

here is solution:

import pandas as pd
import numpy as np


def search_coordinate(df_data: pd.DataFrame, search_set: set) -> list:
    nda_values = df_data.values
    tuple_index = np.where(np.isin(nda_values, [e for e in search_set]))
    return [(row, col, nda_values[row][col]) for row, col in zip(tuple_index[0], tuple_index[1])]


if __name__ == '__main__':
    test_datas = [['cat', 'dog', ''],
                  ['goldfish', '', 'kitten'],
                  ['Puppy', 'hamster', 'mouse']
                  ]
    df_data = pd.DataFrame(test_datas)
    print(df_data)
    result_list = search_coordinate(df_data, {'dog', 'Puppy'})
    print(f"\n\n{'row':<4} {'col':<4} {'name':>10}")
    [print(f"{row:<4} {col:<4} {name:>10}") for row, col, name in result_list]

Output:

          0        1       2
0       cat      dog        
1  goldfish           kitten
2     Puppy  hamster   mouse


row  col        name
0    1           dog
2    0         Puppy

Visual Studio 2015 doesn't have cl.exe

In Visual Studio 2019 you can find cl.exe inside

32-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx86\x86
64-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx64\x64

Before trying to compile either run vcvars32 for 32-Bit compilation or vcvars64 for 64-Bit.

32-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars32.bat"
64-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"

If you can't find the file or the directory, try going to C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC and see if you can find a folder with a version number. If you can't, then you probably haven't installed C++ through the Visual Studio Installation yet.

Most efficient way to increment a Map value in Java

Now there is a shorter way with Java 8 using Map::merge.

myMap.merge(key, 1, Integer::sum)

What it does:

  • if key do not exists, put 1 as value
  • otherwise sum 1 to the value linked to key

More information here.

When to use EntityManager.find() vs EntityManager.getReference() with JPA

Sssuming you have a parent Post entity and a child PostComment as illustrated in the following diagram:

enter image description here

If you call find when you try to set the @ManyToOne post association:

PostComment comment = new PostComment();
comment.setReview("Just awesome!");
 
Post post = entityManager.find(Post.class, 1L);
comment.setPost(post);
 
entityManager.persist(comment);

Hibernate will execute the following statements:

SELECT p.id AS id1_0_0_,
       p.title AS title2_0_0_
FROM   post p
WHERE p.id = 1
 
INSERT INTO post_comment (post_id, review, id)
VALUES (1, 'Just awesome!', 1)

The SELECT query is useless this time because we don’t need the Post entity to be fetched. We only want to set the underlying post_id Foreign Key column.

Now, if you use getReference instead:

PostComment comment = new PostComment();
comment.setReview("Just awesome!");
 
Post post = entityManager.getReference(Post.class, 1L);
comment.setPost(post);
 
entityManager.persist(comment);

This time, Hibernate will issue just the INSERT statement:

INSERT INTO post_comment (post_id, review, id)
VALUES (1, 'Just awesome!', 1)

Unlike find, the getReference only returns an entity Proxy which only has the identifier set. If you access the Proxy, the associated SQL statement will be triggered as long as the EntityManager is still open.

However, in this case, we don’t need to access the entity Proxy. We only want to propagate the Foreign Key to the underlying table record so loading a Proxy is sufficient for this use case.

When loading a Proxy, you need to be aware that a LazyInitializationException can be thrown if you try to access the Proxy reference after the EntityManager is closed.

Remove the last character in a string in T-SQL?

Get the last character

Right(@string, len(@String) - (len(@String) - 1))

Running multiple commands with xargs

Another possible solution that works for me is something like -

cat a.txt | xargs bash -c 'command1 $@; command2 $@' bash

Note the 'bash' at the end - I assume it is passed as argv[0] to bash. Without it in this syntax the first parameter to each command is lost. It may be any word.

Example:

cat a.txt | xargs -n 5 bash -c 'echo -n `date +%Y%m%d-%H%M%S:` ; echo " data: " $@; echo "data again: " $@' bash

Measuring the distance between two coordinates in PHP

Quite old question, but for those interested in a PHP code that returns the same results as Google Maps, the following does the job:

/**
 * Computes the distance between two coordinates.
 *
 * Implementation based on reverse engineering of
 * <code>google.maps.geometry.spherical.computeDistanceBetween()</code>.
 *
 * @param float $lat1 Latitude from the first point.
 * @param float $lng1 Longitude from the first point.
 * @param float $lat2 Latitude from the second point.
 * @param float $lng2 Longitude from the second point.
 * @param float $radius (optional) Radius in meters.
 *
 * @return float Distance in meters.
 */
function computeDistance($lat1, $lng1, $lat2, $lng2, $radius = 6378137)
{
    static $x = M_PI / 180;
    $lat1 *= $x; $lng1 *= $x;
    $lat2 *= $x; $lng2 *= $x;
    $distance = 2 * asin(sqrt(pow(sin(($lat1 - $lat2) / 2), 2) + cos($lat1) * cos($lat2) * pow(sin(($lng1 - $lng2) / 2), 2)));

    return $distance * $radius;
}

I've tested with various coordinates and it works perfectly.

I think it should be faster then some alternatives too. But didn't test that.

Hint: Google Maps uses 6378137 as Earth radius. So using it with other algorithms might work as well.

Python Write bytes to file

If you want to write bytes then you should open the file in binary mode.

f = open('/tmp/output', 'wb')

Encoding Javascript Object to Json string

Unless the variable k is defined, that's probably what's causing your trouble. Something like this will do what you want:

var new_tweets = { };

new_tweets.k = { };

new_tweets.k.tweet_id = 98745521;
new_tweets.k.user_id = 54875;

new_tweets.k.data = { };

new_tweets.k.data.in_reply_to_screen_name = 'other_user';
new_tweets.k.data.text = 'tweet text';

// Will create the JSON string you're looking for.
var json = JSON.stringify(new_tweets);

You can also do it all at once:

var new_tweets = {
  k: {
    tweet_id: 98745521,
    user_id: 54875,
    data: {
      in_reply_to_screen_name: 'other_user',
      text: 'tweet_text'
    }
  }
}

Failed loading english.pickle with nltk.data.load

This is what worked for me just now:

# Do this in a separate python interpreter session, since you only have to do it once
import nltk
nltk.download('punkt')

# Do this in your ipython notebook or analysis script
from nltk.tokenize import word_tokenize

sentences = [
    "Mr. Green killed Colonel Mustard in the study with the candlestick. Mr. Green is not a very nice fellow.",
    "Professor Plum has a green plant in his study.",
    "Miss Scarlett watered Professor Plum's green plant while he was away from his office last week."
]

sentences_tokenized = []
for s in sentences:
    sentences_tokenized.append(word_tokenize(s))

sentences_tokenized is a list of a list of tokens:

[['Mr.', 'Green', 'killed', 'Colonel', 'Mustard', 'in', 'the', 'study', 'with', 'the', 'candlestick', '.', 'Mr.', 'Green', 'is', 'not', 'a', 'very', 'nice', 'fellow', '.'],
['Professor', 'Plum', 'has', 'a', 'green', 'plant', 'in', 'his', 'study', '.'],
['Miss', 'Scarlett', 'watered', 'Professor', 'Plum', "'s", 'green', 'plant', 'while', 'he', 'was', 'away', 'from', 'his', 'office', 'last', 'week', '.']]

The sentences were taken from the example ipython notebook accompanying the book "Mining the Social Web, 2nd Edition"

Create a new workspace in Eclipse

You can create multiple workspaces in Eclipse. You have to just specify the path of the workspace during Eclipse startup. You can even switch workspaces via File?Switch workspace.

You can then import project to your workspace, copy paste project to your new workspace folder, then

File?Import?Existing project in to workspace?select project.

Creating instance list of different objects

I believe your best shot is to declare the list as a list of objects:

List<Object> anything = new ArrayList<Object>();

Then you can put whatever you want in it, like:

anything.add(new Employee(..))

Evidently, you will not be able to read anything out of the list without a proper casting:

Employee mike = (Employee) anything.get(0);

I would discourage the use of raw types like:

List anything = new ArrayList()

Since the whole purpose of generics is precisely to avoid them, in the future Java may no longer suport raw types, the raw types are considered legacy and once you use a raw type you are not allowed to use generics at all in a given reference. For instance, take a look a this another question: Combining Raw Types and Generic Methods

Automatically start forever (node) on system restart

complete example crontab (located at /etc/crontab) ..

#!/bin/bash

# edit this file with .. crontab -u root -e
# view this file with .. crontab -u root -l

# put your path here if it differs
PATH=/root/bin:/root/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin

# * * * * * echo "executes once every minute" > /root/deleteme

@reboot cd /root/bible-api-dbt-server; npm run forever;
@reboot cd /root/database-api-server; npm run forever;
@reboot cd /root/mailer-api-server; npm run forever;

How to display errors for my MySQLi query?

Just simply add or die(mysqli_error($db)); at the end of your query, this will print the mysqli error.

 mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));

As a side note I'd say you are at risk of mysql injection, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.

PHP: Split a string in to an array foreach char

You can access characters in strings in the same way as you would access an array index, e.g.

$length = strlen($string);
$thisWordCodeVerdeeld = array();
for ($i=0; $i<$length; $i++) {
    $thisWordCodeVerdeeld[$i] = $string[$i];
}

You could also do:

$thisWordCodeVerdeeld = str_split($string);

However you might find it is easier to validate the string as a whole string, e.g. using regular expressions.

How to load images dynamically (or lazily) when users scrolls them into view

The Swiss Army knife of image lazy loading is YUI's ImageLoader.

Because there is more to this problem than simply watching the scroll position.

conflicting types error when compiling c program using gcc

You have to declare your functions before main()

(or declare the function prototypes before main())

As it is, the compiler sees my_print (my_string); in main() as a function declaration.

Move your functions above main() in the file, or put:

void my_print (char *);
void my_print2 (char *);

Above main() in the file.

How to read a list of files from a folder using PHP?

<html>
<head>
<title>Names</title>
</head>
<body style="background-color:powderblue;">

<form method='post' action='alex.php'>
 <input type='text' name='name'>
<input type='submit' value='name'>
</form>
Enter Name:
<?php

  if($_POST)
  {
  $Name = $_POST['name'];
  $count = 0;
  $fh=fopen("alex.txt",'a+') or die("failed to create");
  while(!feof($fh))
  {
    $line = chop(fgets($fh));
    if($line==$Name && $line!="")
    $count=1;
  }
  if($count==0 && $Name!="")
  {
    fwrite($fh, "\r\n$Name"); 
 }
  else if($count!=0 && $line!="") 
  { 
    echo '<font color="red">'.$Name.', the name you entered is already in the list.</font><br><br>';
  }
  $count=0;
  fseek($fh, 0);
  while(!feof($fh))
  {
    $a = chop(fgets($fh));
    echo $a.'<br>';
    $count++;
  }
  if($count<=1)
  echo '<br>There are no names in the list<br>';
  fclose($fh);
  }
?>
</body>
</html>

How to upload folders on GitHub

This is Web GUI of a GitHub repository:

enter image description here

Drag and drop your folder to the above area. When you upload too much folder/files, GitHub will notice you:

Yowza, that’s a lot of files. Try again with fewer than 100 files.

enter image description here

and add commit message

enter image description here

And press button Commit changes is the last step.

Get current category ID of the active page

If it is a category page,you can get id of current category by:

$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;

If you want to get category id of any particular category on any page, try using :

$category_id = get_cat_ID('Category Name');

How to read a string one letter at a time in python

I can't leave this question in this state with that final code in the question hanging over me...

dan: here's a much neater and shorter version of your code. It would be a good idea to look at how this is done and code more this way in future. I realise you probably have no further need of this code, but learning how you should do it is a good idea. Some things to note:

  • There are only two comments - and even the second is not really necessary for someone familiar with Python, they'll realise NL is being stripped. Only write comments where it adds value.

  • The with statement (recommended in another answer) removes the bother of closing the file through the context handler.

  • Use a dictionary instead of two lists.

  • A generator comprehension ((x for y in z)) is used to do the translation in one line.

  • Wrap as little code as you can in a try/except block to reduce the probability of catching an exception you didn't mean to.

  • Use the input() argument rather than print()ing first - Use '\n' to get the new line you want.

  • Don't write code across multiple lines or with intermediate variables like this just for the sake of it:

    a = a.b()
    a = a.c()
    b = a.x()
    c = b.y()
    

    Instead, write these constructs like this, chaining the calls as is perfectly valid:

    a = a.b().c()
    c = a.x().y()
    

code = {}
with open('morseCode.txt', 'r') as morse_code_file:
    # line format is <letter>:<morse code translation>
    for line in morse_code_file:
        line = line.rstrip()  # Remove NL
        code[line[0]] = line[2:]

user_input = input("Enter a string to convert to morse code or press <enter> to quit\n")
while user_input:
    try:
        print(''.join(code[x] for x in user_input.replace(' ', '').upper()))
    except KeyError:
        print("Error in input. Only alphanumeric characters, a comma, and period allowed")

    user_input = input("Try again or press <enter> to quit\n")

How to replace text in a column of a Pandas dataframe?

In addition, for those looking to replace more than one character in a column, you can do it using regular expressions:

import re
chars_to_remove = ['.', '-', '(', ')', '']
regular_expression = '[' + re.escape (''. join (chars_to_remove)) + ']'

df['string_col'].str.replace(regular_expression, '', regex=True)

What should main() return in C and C++?

The accepted answer appears to be targetted for C++, so I thought I'd add an answer that pertains to C, and this differs in a few ways. There were also some changes made between ISO/IEC 9899:1989 (C90) and ISO/IEC 9899:1999 (C99).

main() should be declared as either:

int main(void)
int main(int argc, char **argv)

Or equivalent. For example, int main(int argc, char *argv[]) is equivalent to the second one. In C90, the int return type can be omitted as it is a default, but in C99 and newer, the int return type may not be omitted.

If an implementation permits it, main() can be declared in other ways (e.g., int main(int argc, char *argv[], char *envp[])), but this makes the program implementation defined, and no longer strictly conforming.

The standard defines 3 values for returning that are strictly conforming (that is, does not rely on implementation defined behaviour): 0 and EXIT_SUCCESS for a successful termination, and EXIT_FAILURE for an unsuccessful termination. Any other values are non-standard and implementation defined. In C90, main() must have an explicit return statement at the end to avoid undefined behaviour. In C99 and newer, you may omit the return statement from main(). If you do, and main() finished, there is an implicit return 0.

Finally, there is nothing wrong from a standards point of view with calling main() recursively from a C program.

Why isn't Python very good for functional programming?

Scheme doesn't have algebraic data types or pattern matching but it's certainly a functional language. Annoying things about Python from a functional programming perspective:

  1. Crippled Lambdas. Since Lambdas can only contain an expression, and you can't do everything as easily in an expression context, this means that the functions you can define "on the fly" are limited.

  2. Ifs are statements, not expressions. This means, among other things, you can't have a lambda with an If inside it. (This is fixed by ternaries in Python 2.5, but it looks ugly.)

  3. Guido threatens to remove map, filter, and reduce every once in a while

On the other hand, python has lexical closures, Lambdas, and list comprehensions (which are really a "functional" concept whether or not Guido admits it). I do plenty of "functional-style" programming in Python, but I'd hardly say it's ideal.

How to convert existing non-empty directory into a Git working directory and push files to a remote repository

The simplest way of doing this which I find useful is the below.

This might not be the official way but it works well.

Suppose you have a project named "XYZ" on your PC. Now you want to make a git repo of this project on github and use its functionalities.

Step 1: go to "www.github.com"

Step 2: create a repository with a "README.md" file (name it as you like it)

Step 3: clone the repository to your PC.

Step 4: In the cloned folder you will get two things : ".git" folder and a "README.md" file. Copy these two in your project folder "XYZ".

Step 5: Delete the cloned repo.

Step 6: add, commit and push all the files and folders of your project.

Now, you can just use your project "XYZ" as a git repository.

Rounding Bigdecimal values with 2 Decimal Places

Add 0.001 first to the number and then call setScale(2, RoundingMode.ROUND_HALF_UP)

Code example:

public static void main(String[] args) {
    BigDecimal a = new BigDecimal("10.12445").add(new BigDecimal("0.001"));
    BigDecimal b = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println(b);
}

How can I use an ES6 import in Node.js?

Back to Jonathan002's original question about

"... what version supports the new ES6 import statements?"

based on the article by Dr. Axel Rauschmayer, there is a plan to have it supported by default (without the experimental command line flag) in Node.js 10.x LTS. According to node.js's release plan as it is on 3/29, 2018, it's likely to become available after Apr 2018, while LTS of it will begin on October 2018.

ASP.NET Identity reset password

string message = null;
//reset the password
var result = await IdentityManager.Passwords.ResetPasswordAsync(model.Token, model.Password);
if (result.Success)
{
    message = "The password has been reset.";
    return RedirectToAction("PasswordResetCompleted", new { message = message });
}
else
{
    AddErrors(result);
}

This snippet of code is taken out of the AspNetIdentitySample project available on github

SQL: IF clause within WHERE clause

You want the CASE statement

WHERE OrderNumber LIKE
CASE WHEN IsNumeric(@OrderNumber)=1 THEN @OrderNumber ELSE '%' + @OrderNumber END

MySQL GROUP BY two columns

Using Concat on the group by will work

SELECT clients.id, clients.name, portfolios.id, SUM ( portfolios.portfolio + portfolios.cash ) AS total
FROM clients, portfolios
WHERE clients.id = portfolios.client_id
GROUP BY CONCAT(portfolios.id, "-", clients.id)
ORDER BY total DESC
LIMIT 30

Deny direct access to all .php files except index.php

An easy solution is to rename all non-index.php files to .inc, then deny access to *.inc files. I use this in a lot of my projects and it works perfectly fine.

Show/hide div if checkbox selected

You would need to always consider the state of all checkboxes!

You could increase or decrease a number on checking or unchecking, but imagine the site loads with three of them checked.

So you always need to check all of them:

<script type="text/javascript">
<!--
function showMe (it, box) {
  // consider all checkboxes with same name
  var checked = amountChecked(box.name);

  var vis = (checked >= 3) ? "block" : "none";
  document.getElementById(it).style.display = vis;
}

function amountChecked(name) {
  var all = document.getElementsByName(name);

  // count checked
  var result = 0;
  all.forEach(function(el) {
    if (el.checked) result++;
  });

  return result;
}
//-->
</script>

Combining paste() and expression() functions in plot labels

Very nice example using paste and substitute to typeset both symbols (mathplot) and variables at http://vis.supstat.com/2013/04/mathematical-annotation-in-r/

Here is a ggplot adaptation

library(ggplot2)
x_mean <- 1.5
x_sd <- 1.2
N <- 500

n <- ggplot(data.frame(x <- rnorm(N, x_mean, x_sd)),aes(x=x)) +
    geom_bar() + stat_bin() +
    labs(title=substitute(paste(
             "Histogram of random data with ",
             mu,"=",m,", ",
             sigma^2,"=",s2,", ",
             "draws = ", numdraws,", ",
             bar(x),"=",xbar,", ",
             s^2,"=",sde),
             list(m=x_mean,xbar=mean(x),s2=x_sd^2,sde=var(x),numdraws=N)))

print(n)

No 'Access-Control-Allow-Origin' header is present on the requested resource error

If its calling spring boot service. you can handle it using below code.

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS")
                    .allowedHeaders("*", "Access-Control-Allow-Headers", "origin", "Content-type", "accept", "x-requested-with", "x-requested-by") //What is this for?
                    .allowCredentials(true);
        }
    };
}

htmlentities() vs. htmlspecialchars()

**HTML Character Entity Reference Chart at W3.org**

https://dev.w3.org/html5/html-author/charref

&Tab;
&NewLine;
!
&excl;
"
&quot; &QUOT;
#
&num;
$
&dollar;
%
&percnt;
&
&amp; &AMP;
'
&apos;
(
&lpar;
)
&rpar;
*
&ast; &midast;
+
&plus;
,
&comma;
.
&period;
/
&sol;
:
&colon;
;
&semi;
<
&lt; &LT;
=
&equals;
>
&gt; &GT;
?
&quest;
@
&commat;
[
&lsqb; &lbrack;
\
&bsol;
]
&rsqb; &rbrack;
^
&Hat;
_
&lowbar;
`
&grave; &DiacriticalGrave;
{
&lcub; &lbrace;
|
&verbar; &vert; &VerticalLine;
}
&rcub; &rbrace;

&nbsp; &NonBreakingSpace;
¡
&iexcl;
¢
&cent;
£
&pound;
¤
&curren;
¥
&yen;
¦
&brvbar;
§
&sect;
¨
&Dot; &die; &DoubleDot; &uml;
©
&copy; &COPY;
ª
&ordf;
«
&laquo;
¬
&not;
&shy;
®
&reg; &circledR; &REG;
¯
&macr; &OverBar; &strns;
°
&deg;
±
&plusmn; &pm; &PlusMinus;
²
&sup2;
³
&sup3;
´
&acute; &DiacriticalAcute;
µ
&micro;
¶
&para;
·
&middot; &centerdot; &CenterDot;
¸
&cedil; &Cedilla;
¹
&sup1;
º
&ordm;
»
&raquo;
¼
&frac14;
½
&frac12; &half;
¾
&frac34;
¿
&iquest;
À
&Agrave;
Á
&Aacute;
Â
&Acirc;
Ã
&Atilde;
Ä
&Auml;
Å
&Aring;
Æ
&AElig;
Ç
&Ccedil;
È
&Egrave;
É
&Eacute;
Ê
&Ecirc;
Ë
&Euml;
Ì
&Igrave;
Í
&Iacute;
Î
&Icirc;
Ï
&Iuml;
Ð
&ETH;
Ñ
&Ntilde;
Ò
&Ograve;
Ó
&Oacute;
Ô
&Ocirc;
Õ
&Otilde;
Ö
&Ouml;
×
&times;
Ø
&Oslash;
Ù
&Ugrave;
Ú
&Uacute;
Û
&Ucirc;
Ü
&Uuml;
Ý
&Yacute;
Þ
&THORN;
ß
&szlig;
à
&agrave;
á
&aacute;
â
&acirc;
ã
&atilde;
ä
&auml;
å
&aring;
æ
&aelig;
ç
&ccedil;
è
&egrave;
é
&eacute;
ê
&ecirc;
ë
&euml;
ì
&igrave;
í
&iacute;
î
&icirc;
ï
&iuml;
ð
&eth;
ñ
&ntilde;
ò
&ograve;
ó
&oacute;
ô
&ocirc;
õ
&otilde;
ö
&ouml;
÷
&divide; &div;
ø
&oslash;
ù
&ugrave;
ú
&uacute;
û
&ucirc;
ü
&uuml;
ý
&yacute;
þ
&thorn;
ÿ
&yuml;
A
&Amacr;
a
&amacr;
A
&Abreve;
a
&abreve;
A
&Aogon;
a
&aogon;
C
&Cacute;
c
&cacute;
C
&Ccirc;
c
&ccirc;
C
&Cdot;
c
&cdot;
C
&Ccaron;
c
&ccaron;
D
&Dcaron;
d
&dcaron;
Ð
&Dstrok;
d
&dstrok;
E
&Emacr;
e
&emacr;
E
&Edot;
e
&edot;
E
&Eogon;
e
&eogon;
E
&Ecaron;
e
&ecaron;
G
&Gcirc;
g
&gcirc;
G
&Gbreve;
g
&gbreve;
G
&Gdot;
g
&gdot;
G
&Gcedil;
H
&Hcirc;
h
&hcirc;
H
&Hstrok;
h
&hstrok;
I
&Itilde;
i
&itilde;
I
&Imacr;
i
&imacr;
I
&Iogon;
i
&iogon;
I
&Idot;
i
&imath; &inodot;
?
&IJlig;
?
&ijlig;
J
&Jcirc;
j
&jcirc;
K
&Kcedil;
k
&kcedil;
?
&kgreen;
L
&Lacute;
l
&lacute;
L
&Lcedil;
l
&lcedil;
L
&Lcaron;
l
&lcaron;
?
&Lmidot;
?
&lmidot;
L
&Lstrok;
l
&lstrok;
N
&Nacute;
n
&nacute;
N
&Ncedil;
n
&ncedil;
N
&Ncaron;
n
&ncaron;
?
&napos;
?
&ENG;
?
&eng;
O
&Omacr;
o
&omacr;
O
&Odblac;
o
&odblac;
Œ
&OElig;
œ
&oelig;
R
&Racute;
r
&racute;
R
&Rcedil;
r
&rcedil;
R
&Rcaron;
r
&rcaron;
S
&Sacute;
s
&sacute;
S
&Scirc;
s
&scirc;
S
&Scedil;
s
&scedil;
Š
&Scaron;
š
&scaron;
T
&Tcedil;
t
&tcedil;
T
&Tcaron;
t
&tcaron;
T
&Tstrok;
t
&tstrok;
U
&Utilde;
u
&utilde;
U
&Umacr;
u
&umacr;
U
&Ubreve;
u
&ubreve;
U
&Uring;
u
&uring;
U
&Udblac;
u
&udblac;
U
&Uogon;
u
&uogon;
W
&Wcirc;
w
&wcirc;
Y
&Ycirc;
y
&ycirc;
Ÿ
&Yuml;
Z
&Zacute;
z
&zacute;
Z
&Zdot;
z
&zdot;
Ž
&Zcaron;
ž
&zcaron;
ƒ
&fnof;
?
&imped;
?
&gacute;
?
&jmath;
ˆ
&circ;
?
&caron; &Hacek;
?
&breve; &Breve;
?
&dot; &DiacriticalDot;
°
&ring;
?
&ogon;
˜
&tilde; &DiacriticalTilde;
?
&dblac; &DiacriticalDoubleAcute;
?
&DownBreve;
_
&UnderBar;
?
&Alpha;
?
&Beta;
G
&Gamma;
?
&Delta;
?
&Epsilon;
?
&Zeta;
?
&Eta;
T
&Theta;
?
&Iota;
?
&Kappa;
?
&Lambda;
?
&Mu;
?
&Nu;
?
&Xi;
?
&Omicron;
?
&Pi;
?
&Rho;
S
&Sigma;
?
&Tau;
?
&Upsilon;
F
&Phi;
?
&Chi;
?
&Psi;
O
&Omega;
a
&alpha;
ß
&beta;
?
&gamma;
d
&delta;
e
&epsiv; &varepsilon; &epsilon;
?
&zeta;
?
&eta;
?
&theta;
?
&iota;
?
&kappa;
?
&lambda;
µ
&mu;
?
&nu;
?
&xi;
?
&omicron;
p
&pi;
?
&rho;
?
&sigmav; &varsigma; &sigmaf;
s
&sigma;
t
&tau;
?
&upsi; &upsilon;
f
&phi; &phiv; &varphi;
?
&chi;
?
&psi;
?
&omega;
?
&thetav; &vartheta; &thetasym;
?
&Upsi; &upsih;
?
&straightphi;
?
&piv; &varpi;
?
&Gammad;
?
&gammad; &digamma;
?
&kappav; &varkappa;
?
&rhov; &varrho;
?
&epsi; &straightepsilon;
?
&bepsi; &backepsilon;
?
&IOcy;
?
&DJcy;
?
&GJcy;
?
&Jukcy;
?
&DScy;
?
&Iukcy;
?
&YIcy;
?
&Jsercy;
?
&LJcy;
?
&NJcy;
?
&TSHcy;
?
&KJcy;
?
&Ubrcy;
?
&DZcy;
?
&Acy;
?
&Bcy;
?
&Vcy;
?
&Gcy;
?
&Dcy;
?
&IEcy;
?
&ZHcy;
?
&Zcy;
?
&Icy;
?
&Jcy;
?
&Kcy;
?
&Lcy;
?
&Mcy;
?
&Ncy;
?
&Ocy;
?
&Pcy;
?
&Rcy;
?
&Scy;
?
&Tcy;
?
&Ucy;
?
&Fcy;
?
&KHcy;
?
&TScy;
?
&CHcy;
?
&SHcy;
?
&SHCHcy;
?
&HARDcy;
?
&Ycy;
?
&SOFTcy;
?
&Ecy;
?
&YUcy;
?
&YAcy;
?
&acy;
?
&bcy;
?
&vcy;
?
&gcy;
?
&dcy;
?
&iecy;
?
&zhcy;
?
&zcy;
?
&icy;
?
&jcy;
?
&kcy;
?
&lcy;
?
&mcy;
?
&ncy;
?
&ocy;
?
&pcy;
?
&rcy;
?
&scy;
?
&tcy;
?
&ucy;
?
&fcy;
?
&khcy;
?
&tscy;
?
&chcy;
?
&shcy;
?
&shchcy;
?
&hardcy;
?
&ycy;
?
&softcy;
?
&ecy;
?
&yucy;
?
&yacy;
?
&iocy;
?
&djcy;
?
&gjcy;
?
&jukcy;
?
&dscy;
?
&iukcy;
?
&yicy;
?
&jsercy;
?
&ljcy;
?
&njcy;
?
&tshcy;
?
&kjcy;
?
&ubrcy;
?
&dzcy;
 
&ensp;
 
&emsp;
 
&emsp13;
 
&emsp14;
 
&numsp;
 
&puncsp;
 
&thinsp; &ThinSpace;
 
&hairsp; &VeryThinSpace;
?
&ZeroWidthSpace; &NegativeVeryThinSpace; &NegativeThinSpace; &NegativeMediumSpace; &NegativeThickSpace;
?
&zwnj;
?
&zwj;
?
&lrm;
?
&rlm;
-
&hyphen; &dash;
–
&ndash;
—
&mdash;
-
&horbar;
?
&Verbar; &Vert;
‘
&lsquo; &OpenCurlyQuote;
’
&rsquo; &rsquor; &CloseCurlyQuote;
‚
&lsquor; &sbquo;
“
&ldquo; &OpenCurlyDoubleQuote;
”
&rdquo; &rdquor; &CloseCurlyDoubleQuote;
„
&ldquor; &bdquo;
†
&dagger;
‡
&Dagger; &ddagger;
•
&bull; &bullet;
?
&nldr;
…
&hellip; &mldr;
‰
&permil;
?
&pertenk;
'
&prime;
"
&Prime;
?
&tprime;
`
&bprime; &backprime;
‹
&lsaquo;
›
&rsaquo;
?
&oline;
?
&caret;
?
&hybull;
/
&frasl;
?
&bsemi;
?
&qprime;
?
&MediumSpace;
?
&NoBreak;
?
&ApplyFunction; &af;
?
&InvisibleTimes; &it;
?
&InvisibleComma; &ic;
€
&euro;
?
&tdot; &TripleDot;
?
&DotDot;
C
&Copf; &complexes;
?
&incare;
g
&gscr;
H
&hamilt; &HilbertSpace; &Hscr;
H
&Hfr; &Poincareplane;
H
&quaternions; &Hopf;
h
&planckh;
?
&planck; &hbar; &plankv; &hslash;
I
&Iscr; &imagline;
I
&image; &Im; &imagpart; &Ifr;
L
&Lscr; &lagran; &Laplacetrf;
l
&ell;
N
&Nopf; &naturals;
?
&numero;
?
&copysr;
P
&weierp; &wp;
P
&Popf; &primes;
Q
&rationals; &Qopf;
R
&Rscr; &realine;
R
&real; &Re; &realpart; &Rfr;
R
&reals; &Ropf;
?
&rx;
™
&trade; &TRADE;
Z
&integers; &Zopf;
?
&ohm;
?
&mho;
Z
&Zfr; &zeetrf;
?
&iiota;
Å
&angst;
B
&bernou; &Bernoullis; &Bscr;
C
&Cfr; &Cayleys;
e
&escr;
E
&Escr; &expectation;
F
&Fscr; &Fouriertrf;
M
&phmmat; &Mellintrf; &Mscr;
o
&order; &orderof; &oscr;
?
&alefsym; &aleph;
?
&beth;
?
&gimel;
?
&daleth;
?
&CapitalDifferentialD; &DD;
?
&DifferentialD; &dd;
?
&ExponentialE; &exponentiale; &ee;
?
&ImaginaryI; &ii;
?
&frac13;
?
&frac23;
?
&frac15;
?
&frac25;
?
&frac35;
?
&frac45;
?
&frac16;
?
&frac56;
?
&frac18;
?
&frac38;
?
&frac58;
?
&frac78;
?
&larr; &leftarrow; &LeftArrow; &slarr; &ShortLeftArrow;
?
&uarr; &uparrow; &UpArrow; &ShortUpArrow;
?
&rarr; &rightarrow; &RightArrow; &srarr; &ShortRightArrow;
?
&darr; &downarrow; &DownArrow; &ShortDownArrow;
?
&harr; &leftrightarrow; &LeftRightArrow;
?
&varr; &updownarrow; &UpDownArrow;
?
&nwarr; &UpperLeftArrow; &nwarrow;
?
&nearr; &UpperRightArrow; &nearrow;
?
&searr; &searrow; &LowerRightArrow;
?
&swarr; &swarrow; &LowerLeftArrow;
?
&nlarr; &nleftarrow;
?
&nrarr; &nrightarrow;
?
&rarrw; &rightsquigarrow;
?
&Larr; &twoheadleftarrow;
?
&Uarr;
?
&Rarr; &twoheadrightarrow;
?
&Darr;
?
&larrtl; &leftarrowtail;
?
&rarrtl; &rightarrowtail;
?
&LeftTeeArrow; &mapstoleft;
?
&UpTeeArrow; &mapstoup;
?
&map; &RightTeeArrow; &mapsto;
?
&DownTeeArrow; &mapstodown;
?
&larrhk; &hookleftarrow;
?
&rarrhk; &hookrightarrow;
?
&larrlp; &looparrowleft;
?
&rarrlp; &looparrowright;
?
&harrw; &leftrightsquigarrow;
?
&nharr; &nleftrightarrow;
?
&lsh; &Lsh;
?
&rsh; &Rsh;
?
&ldsh;
?
&rdsh;
?
&crarr;
?
&cularr; &curvearrowleft;
?
&curarr; &curvearrowright;
?
&olarr; &circlearrowleft;
?
&orarr; &circlearrowright;
?
&lharu; &LeftVector; &leftharpoonup;
?
&lhard; &leftharpoondown; &DownLeftVector;
?
&uharr; &upharpoonright; &RightUpVector;
?
&uharl; &upharpoonleft; &LeftUpVector;
?
&rharu; &RightVector; &rightharpoonup;
?
&rhard; &rightharpoondown; &DownRightVector;
?
&dharr; &RightDownVector; &downharpoonright;
?
&dharl; &LeftDownVector; &downharpoonleft;
?
&rlarr; &rightleftarrows; &RightArrowLeftArrow;
?
&udarr; &UpArrowDownArrow;
?
&lrarr; &leftrightarrows; &LeftArrowRightArrow;
?
&llarr; &leftleftarrows;
?
&uuarr; &upuparrows;
?
&rrarr; &rightrightarrows;
?
&ddarr; &downdownarrows;
?
&lrhar; &ReverseEquilibrium; &leftrightharpoons;
?
&rlhar; &rightleftharpoons; &Equilibrium;
?
&nlArr; &nLeftarrow;
?
&nhArr; &nLeftrightarrow;
?
&nrArr; &nRightarrow;
?
&lArr; &Leftarrow; &DoubleLeftArrow;
?
&uArr; &Uparrow; &DoubleUpArrow;
?
&rArr; &Rightarrow; &Implies; &DoubleRightArrow;
?
&dArr; &Downarrow; &DoubleDownArrow;
?
&hArr; &Leftrightarrow; &DoubleLeftRightArrow; &iff;
?
&vArr; &Updownarrow; &DoubleUpDownArrow;
?
&nwArr;
?
&neArr;
?
&seArr;
?
&swArr;
?
&lAarr; &Lleftarrow;
?
&rAarr; &Rrightarrow;
?
&zigrarr;
?
&larrb; &LeftArrowBar;
?
&rarrb; &RightArrowBar;
?
&duarr; &DownArrowUpArrow;
?
&loarr;
?
&roarr;
?
&hoarr;
?
&forall; &ForAll;
?
&comp; &complement;
?
&part; &PartialD;
?
&exist; &Exists;
?
&nexist; &NotExists; &nexists;
Ø
&empty; &emptyset; &emptyv; &varnothing;
?
&nabla; &Del;
?
&isin; &isinv; &Element; &in;
?
&notin; &NotElement; &notinva;
?
&niv; &ReverseElement; &ni; &SuchThat;
?
&notni; &notniva; &NotReverseElement;
?
&prod; &Product;
?
&coprod; &Coproduct;
?
&sum; &Sum;
-
&minus;
±
&mnplus; &mp; &MinusPlus;
?
&plusdo; &dotplus;
\
&setmn; &setminus; &Backslash; &ssetmn; &smallsetminus;
*
&lowast;
°
&compfn; &SmallCircle;
v
&radic; &Sqrt;
?
&prop; &propto; &Proportional; &vprop; &varpropto;
8
&infin;
?
&angrt;
?
&ang; &angle;
?
&angmsd; &measuredangle;
?
&angsph;
|
&mid; &VerticalBar; &smid; &shortmid;
?
&nmid; &NotVerticalBar; &nsmid; &nshortmid;
?
&par; &parallel; &DoubleVerticalBar; &spar; &shortparallel;
?
&npar; &nparallel; &NotDoubleVerticalBar; &nspar; &nshortparallel;
?
&and; &wedge;
?
&or; &vee;
n
&cap;
?
&cup;
?
&int; &Integral;
?
&Int;
?
&tint; &iiint;
?
&conint; &oint; &ContourIntegral;
?
&Conint; &DoubleContourIntegral;
?
&Cconint;
?
&cwint;
?
&cwconint; &ClockwiseContourIntegral;
?
&awconint; &CounterClockwiseContourIntegral;
?
&there4; &therefore; &Therefore;
?
&becaus; &because; &Because;
:
&ratio;
?
&Colon; &Proportion;
?
&minusd; &dotminus;
?
&mDDot;
?
&homtht;
~
&sim; &Tilde; &thksim; &thicksim;
?
&bsim; &backsim;
?
&ac; &mstpos;
?
&acd;
?
&wreath; &VerticalTilde; &wr;
?
&nsim; &NotTilde;
?
&esim; &EqualTilde; &eqsim;
?
&sime; &TildeEqual; &simeq;
?
&nsime; &nsimeq; &NotTildeEqual;
?
&cong; &TildeFullEqual;
?
&simne;
?
&ncong; &NotTildeFullEqual;
˜
&asymp; &ap; &TildeTilde; &approx; &thkap; &thickapprox;
?
&nap; &NotTildeTilde; &napprox;
?
&ape; &approxeq;
?
&apid;
?
&bcong; &backcong;
?
&asympeq; &CupCap;
?
&bump; &HumpDownHump; &Bumpeq;
?
&bumpe; &HumpEqual; &bumpeq;
?
&esdot; &DotEqual; &doteq;
?
&eDot; &doteqdot;
?
&efDot; &fallingdotseq;
?
&erDot; &risingdotseq;
?
&colone; &coloneq; &Assign;
?
&ecolon; &eqcolon;
?
&ecir; &eqcirc;
?
&cire; &circeq;
?
&wedgeq;
?
&veeeq;
?
&trie; &triangleq;
?
&equest; &questeq;
?
&ne; &NotEqual;
=
&equiv; &Congruent;
?
&nequiv; &NotCongruent;
=
&le; &leq;
=
&ge; &GreaterEqual; &geq;
?
&lE; &LessFullEqual; &leqq;
?
&gE; &GreaterFullEqual; &geqq;
?
&lnE; &lneqq;
?
&gnE; &gneqq;
«
&Lt; &NestedLessLess; &ll;
»
&Gt; &NestedGreaterGreater; &gg;
?
&twixt; &between;
?
&NotCupCap;
?
&nlt; &NotLess; &nless;
?
&ngt; &NotGreater; &ngtr;
?
&nle; &NotLessEqual; &nleq;
?
&nge; &NotGreaterEqual; &ngeq;
?
&lsim; &LessTilde; &lesssim;
?
&gsim; &gtrsim; &GreaterTilde;
?
&nlsim; &NotLessTilde;
?
&ngsim; &NotGreaterTilde;
?
&lg; &lessgtr; &LessGreater;
?
&gl; &gtrless; &GreaterLess;
?
&ntlg; &NotLessGreater;
?
&ntgl; &NotGreaterLess;
?
&pr; &Precedes; &prec;
?
&sc; &Succeeds; &succ;
?
&prcue; &PrecedesSlantEqual; &preccurlyeq;
?
&sccue; &SucceedsSlantEqual; &succcurlyeq;
?
&prsim; &precsim; &PrecedesTilde;
?
&scsim; &succsim; &SucceedsTilde;
?
&npr; &nprec; &NotPrecedes;
?
&nsc; &nsucc; &NotSucceeds;
?
&sub; &subset;
?
&sup; &supset; &Superset;
?
&nsub;
?
&nsup;
?
&sube; &SubsetEqual; &subseteq;
?
&supe; &supseteq; &SupersetEqual;
?
&nsube; &nsubseteq; &NotSubsetEqual;
?
&nsupe; &nsupseteq; &NotSupersetEqual;
?
&subne; &subsetneq;
?
&supne; &supsetneq;
?
&cupdot;
?
&uplus; &UnionPlus;
?
&sqsub; &SquareSubset; &sqsubset;
?
&sqsup; &SquareSuperset; &sqsupset;
?
&sqsube; &SquareSubsetEqual; &sqsubseteq;
?
&sqsupe; &SquareSupersetEqual; &sqsupseteq;
?
&sqcap; &SquareIntersection;
?
&sqcup; &SquareUnion;
?
&oplus; &CirclePlus;
?
&ominus; &CircleMinus;
?
&otimes; &CircleTimes;
?
&osol;
?
&odot; &CircleDot;
?
&ocir; &circledcirc;
?
&oast; &circledast;
?
&odash; &circleddash;
?
&plusb; &boxplus;
?
&minusb; &boxminus;
?
&timesb; &boxtimes;
?
&sdotb; &dotsquare;
?
&vdash; &RightTee;
?
&dashv; &LeftTee;
?
&top; &DownTee;
?
&bottom; &bot; &perp; &UpTee;
?
&models;
?
&vDash; &DoubleRightTee;
?
&Vdash;
?
&Vvdash;
?
&VDash;
?
&nvdash;
?
&nvDash;
?
&nVdash;
?
&nVDash;
?
&prurel;
?
&vltri; &vartriangleleft; &LeftTriangle;
?
&vrtri; &vartriangleright; &RightTriangle;
?
&ltrie; &trianglelefteq; &LeftTriangleEqual;
?
&rtrie; &trianglerighteq; &RightTriangleEqual;
?
&origof;
?
&imof;
?
&mumap; &multimap;
?
&hercon;
?
&intcal; &intercal;
?
&veebar;
?
&barvee;
?
&angrtvb;
?
&lrtri;
?
&xwedge; &Wedge; &bigwedge;
?
&xvee; &Vee; &bigvee;
?
&xcap; &Intersection; &bigcap;
?
&xcup; &Union; &bigcup;
?
&diam; &diamond; &Diamond;
·
&sdot;
?
&sstarf; &Star;
?
&divonx; &divideontimes;
?
&bowtie;
?
&ltimes;
?
&rtimes;
?
&lthree; &leftthreetimes;
?
&rthree; &rightthreetimes;
?
&bsime; &backsimeq;
?
&cuvee; &curlyvee;
?
&cuwed; &curlywedge;
?
&Sub; &Subset;
?
&Sup; &Supset;
?
&Cap;
?
&Cup;
?
&fork; &pitchfork;
?
&epar;
?
&ltdot; &lessdot;
?
&gtdot; &gtrdot;
?
&Ll;
?
&Gg; &ggg;
?
&leg; &LessEqualGreater; &lesseqgtr;
?
&gel; &gtreqless; &GreaterEqualLess;
?
&cuepr; &curlyeqprec;
?
&cuesc; &curlyeqsucc;
?
&nprcue; &NotPrecedesSlantEqual;
?
&nsccue; &NotSucceedsSlantEqual;
?
&nsqsube; &NotSquareSubsetEqual;
?
&nsqsupe; &NotSquareSupersetEqual;
?
&lnsim;
?
&gnsim;
?
&prnsim; &precnsim;
?
&scnsim; &succnsim;
?
&nltri; &ntriangleleft; &NotLeftTriangle;
?
&nrtri; &ntriangleright; &NotRightTriangle;
?
&nltrie; &ntrianglelefteq; &NotLeftTriangleEqual;
?
&nrtrie; &ntrianglerighteq; &NotRightTriangleEqual;
?
&vellip;
?
&ctdot;
?
&utdot;
?
&dtdot;
?
&disin;
?
&isinsv;
?
&isins;
?
&isindot;
?
&notinvc;
?
&notinvb;
?
&isinE;
?
&nisd;
?
&xnis;
?
&nis;
?
&notnivc;
?
&notnivb;
?
&barwed; &barwedge;
?
&Barwed; &doublebarwedge;
?
&lceil; &LeftCeiling;
?
&rceil; &RightCeiling;
?
&lfloor; &LeftFloor;
?
&rfloor; &RightFloor;
?
&drcrop;
?
&dlcrop;
?
&urcrop;
?
&ulcrop;
¬
&bnot;
?
&profline;
?
&profsurf;
?
&telrec;
?
&target;
?
&ulcorn; &ulcorner;
?
&urcorn; &urcorner;
?
&dlcorn; &llcorner;
?
&drcorn; &lrcorner;
?
&frown; &sfrown;
?
&smile; &ssmile;
?
&cylcty;
?
&profalar;
?
&topbot;
?
&ovbar;
?
&solbar;
?
&angzarr;
?
&lmoust; &lmoustache;
?
&rmoust; &rmoustache;
?
&tbrk; &OverBracket;
?
&bbrk; &UnderBracket;
?
&bbrktbrk;
?
&OverParenthesis;
?
&UnderParenthesis;
?
&OverBrace;
?
&UnderBrace;
?
&trpezium;
?
&elinters;
?
&blank;
?
&oS; &circledS;
-
&boxh; &HorizontalLine;
¦
&boxv;
+
&boxdr;
+
&boxdl;
+
&boxur;
+
&boxul;
+
&boxvr;
¦
&boxvl;
-
&boxhd;
-
&boxhu;
+
&boxvh;
-
&boxH;
¦
&boxV;
+
&boxdR;
+
&boxDr;
+
&boxDR;
+
&boxdL;
+
&boxDl;
+
&boxDL;
+
&boxuR;
+
&boxUr;
+
&boxUR;
+
&boxuL;
+
&boxUl;
+
&boxUL;
¦
&boxvR;
¦
&boxVr;
¦
&boxVR;
¦
&boxvL;
¦
&boxVl;
¦
&boxVL;
-
&boxHd;
-
&boxhD;
-
&boxHD;
-
&boxHu;
-
&boxhU;
-
&boxHU;
+
&boxvH;
+
&boxVh;
+
&boxVH;
¯
&uhblk;
_
&lhblk;
¦
&block;
¦
&blk14;
¦
&blk12;
¦
&blk34;
?
&squ; &square; &Square;
?
&squf; &squarf; &blacksquare; &FilledVerySmallSquare;
?
&EmptyVerySmallSquare;
?
&rect;
?
&marker;
?
&fltns;
?
&xutri; &bigtriangleup;
?
&utrif; &blacktriangle;
?
&utri; &triangle;
?
&rtrif; &blacktriangleright;
?
&rtri; &triangleright;
?
&xdtri; &bigtriangledown;
?
&dtrif; &blacktriangledown;
?
&dtri; &triangledown;
?
&ltrif; &blacktriangleleft;
?
&ltri; &triangleleft;
?
&loz; &lozenge;
?
&cir;
?
&tridot;
?
&xcirc; &bigcirc;
?
&ultri;
?
&urtri;
?
&lltri;
?
&EmptySmallSquare;
?
&FilledSmallSquare;
?
&starf; &bigstar;
?
&star;
?
&phone;
?
&female;
?
&male;
?
&spades; &spadesuit;
?
&clubs; &clubsuit;
?
&hearts; &heartsuit;
?
&diams; &diamondsuit;
?
&sung;
?
&flat;
?
&natur; &natural;
?
&sharp;
?
&check; &checkmark;
?
&cross;
?
&malt; &maltese;
?
&sext;
|
&VerticalSeparator;
?
&lbbrk;
?
&rbbrk;
?
&lobrk; &LeftDoubleBracket;
?
&robrk; &RightDoubleBracket;
?
&lang; &LeftAngleBracket; &langle;
?
&rang; &RightAngleBracket; &rangle;
?
&Lang;
?
&Rang;
?
&loang;
?
&roang;
?
&xlarr; &longleftarrow; &LongLeftArrow;
?
&xrarr; &longrightarrow; &LongRightArrow;
?
&xharr; &longleftrightarrow; &LongLeftRightArrow;
?
&xlArr; &Longleftarrow; &DoubleLongLeftArrow;
?
&xrArr; &Longrightarrow; &DoubleLongRightArrow;
?
&xhArr; &Longleftrightarrow; &DoubleLongLeftRightArrow;
?
&xmap; &longmapsto;
?
&dzigrarr;
?
&nvlArr;
?
&nvrArr;
?
&nvHarr;
?
&Map;
?
&lbarr;
?
&rbarr; &bkarow;
?
&lBarr;
?
&rBarr; &dbkarow;
?
&RBarr; &drbkarow;
?
&DDotrahd;
?
&UpArrowBar;
?
&DownArrowBar;
?
&Rarrtl;
?
&latail;
?
&ratail;
?
&lAtail;
?
&rAtail;
?
&larrfs;
?
&rarrfs;
?
&larrbfs;
?
&rarrbfs;
?
&nwarhk;
?
&nearhk;
?
&searhk; &hksearow;
?
&swarhk; &hkswarow;
?
&nwnear;
?
&nesear; &toea;
?
&seswar; &tosa;
?
&swnwar;
?
&rarrc;
?
&cudarrr;
?
&ldca;
?
&rdca;
?
&cudarrl;
?
&larrpl;
?
&curarrm;
?
&cularrp;
?
&rarrpl;
?
&harrcir;
?
&Uarrocir;
?
&lurdshar;
?
&ldrushar;
?
&LeftRightVector;
?
&RightUpDownVector;
?
&DownLeftRightVector;
?
&LeftUpDownVector;
?
&LeftVectorBar;
?
&RightVectorBar;
?
&RightUpVectorBar;
?
&RightDownVectorBar;
?
&DownLeftVectorBar;
?
&DownRightVectorBar;
?
&LeftUpVectorBar;
?
&LeftDownVectorBar;
?
&LeftTeeVector;
?
&RightTeeVector;
?
&RightUpTeeVector;
?
&RightDownTeeVector;
?
&DownLeftTeeVector;
?
&DownRightTeeVector;
?
&LeftUpTeeVector;
?
&LeftDownTeeVector;
?
&lHar;
?
&uHar;
?
&rHar;
?
&dHar;
?
&luruhar;
?
&ldrdhar;
?
&ruluhar;
?
&rdldhar;
?
&lharul;
?
&llhard;
?
&rharul;
?
&lrhard;
?
&udhar; &UpEquilibrium;
?
&duhar; &ReverseUpEquilibrium;
?
&RoundImplies;
?
&erarr;
?
&simrarr;
?
&larrsim;
?
&rarrsim;
?
&rarrap;
?
&ltlarr;
?
&gtrarr;
?
&subrarr;
?
&suplarr;
?
&lfisht;
?
&rfisht;
?
&ufisht;
?
&dfisht;
?
&lopar;
?
&ropar;
?
&lbrke;
?
&rbrke;
?
&lbrkslu;
?
&rbrksld;
?
&lbrksld;
?
&rbrkslu;
?
&langd;
?

Not fully, pls track the link for fully document.

SQL get the last date time record

Considering that max(dates) can be different for each filename, my solution :

select filename, dates, status
from yt a
where a.dates = (
  select max(dates)
    from yt b
    where a.filename = b.filename
)
;

http://sqlfiddle.com/#!18/fdf8d/1/0

HTH

How do I separate an integer into separate digits in an array in JavaScript?

var n = 38679;
var digits = n.toString().split("");
console.log(digits);

Now the number n is divided to its digits and they are presented in an array, and each element of that array is in string format. To transform them to number format do this:

var digitsNum = digits.map(Number);
console.log(digitsNum);

Or get an array with all elements in number format from the beginning:

var n = 38679;
var digits = n.toString().split("").map(Number);
console.log(digits);

What is the proper way to check and uncheck a checkbox in HTML5?

<input type="checkbox" checked="checked" />

or simply

<input type="checkbox" checked />

for checked checkbox. No checked attribute (<input type="checkbox" />) for unchecked checkbox.

reference: http://www.w3.org/TR/html-markup/input.checkbox.html#input.checkbox.attrs.checked

Read all contacts' phone numbers in android

In the same way just get their other numbers using the other "People" references

People.TYPE_HOME
People.TYPE_MOBILE
People.TYPE_OTHER
People.TYPE_WORK

Set EditText cursor color

Use this

android:textCursorDrawable="@color/white"

iReport not starting using JRE 8

It works only with JRE 1.7 just download it and extract to your prefered location

and use the following command to open the iReport

ireport --jdkhome Path To JDK Home

Reading file using fscanf() in C

In your code:

while(fscanf(fp,"%s %c",item,&status) == 1)  

why 1 and not 2? The scanf functions return the number of objects read.

Placing an image to the top right corner - CSS

While looking at the same problem, I found an example

<style type="text/css">
#topright {
    position: absolute;
    right: 0;
    top: 0;
    display: block;
    height: 125px;
    width: 125px;
    background: url(TRbanner.gif) no-repeat;
    text-indent: -999em;
    text-decoration: none;
}
</style>

<a id="topright" href="#" title="TopRight">Top Right Link Text</a>

The trick here is to create a small, (I used GIMP) a PNG (or GIF) that has a transparent background, (and then just delete the opposite bottom corner.)

CSS Layout - Dynamic width DIV

try

<div style="width:100%;">
    <div style="width:50px; float: left;"><img src="myleftimage" /></div>
    <div style="width:50px; float: right;"><img src="myrightimage" /></div>
    <div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
</div>

or

<div style="width:100%; border:2px solid #dadada;">
    <div style="width:50px; float: left;"><img src="myleftimage" /></div>
    <div style="width:50px; float: right;"><img src="myrightimage" /></div>
    <div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
<div style="clear:both"></div>    
</div>

Bootstrap how to get text to vertical align in a div container

h2.text-left{
  position:relative;
  top:50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
}

Explanation:

The top:50% style essentially pushes the header element down 50% from the top of the parent element. The translateY stylings also act in a similar manner by moving then element down 50% from the top.

Please note that this works well for headers with 1 (maybe 2) lines of text as this simply moves the top of the header element down 50% and then the rest of the content fills in below that, which means that with multiple lines of text it would appear to be slightly below vertically aligned.

A possible fix for multiple lines would be to use a percentage slightly less than 50%.

Extracting jar to specified directory

Current working version as of Oct 2020, updated to use maven-antrun-plugin 3.0.0.

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>3.0.0</version>
            <executions>
                <execution>
                    <id>prepare</id>
                    <phase>package</phase>
                    <configuration>
                        <target>
                            <unzip src="target/shaded-jar/shade-test.jar"
                                   dest="target/unpacked-shade/"/>
                        </target>
                    </configuration>
                    <goals>
                        <goal>run</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

Using python's mock patch.object to change the return value of a method called within another method

To add to Silfheed's answer, which was useful, I needed to patch multiple methods of the object in question. I found it more elegant to do it this way:

Given the following function to test, located in module.a_function.to_test.py:

from some_other.module import SomeOtherClass

def add_results():
    my_object = SomeOtherClass('some_contextual_parameters')
    result_a = my_object.method_a()
    result_b = my_object.method_b()
    
    return result_a + result_b

To test this function (or class method, it doesn't matter), one can patch multiple methods of the class SomeOtherClass by using patch.object() in combination with sys.modules:

@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
  mocked_other_class().method_a.return_value = 4
  mocked_other_class().method_b.return_value = 7

  self.assertEqual(add_results(), 11)

This works no matter the number of methods of SomeOtherClass you need to patch, with independent results.

Also, using the same patching method, an actual instance of SomeOtherClass can be returned if need be:

@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
  other_class_instance = SomeOtherClass('some_controlled_parameters')
  mocked_other_class.return_value = other_class_instance 
  ...

How to remove word wrap from textarea?

Textareas shouldn't wrap by default, but you can set wrap="soft" to explicitly disable wrap:

<textarea name="nowrap" cols="30" rows="3" wrap="soft"></textarea>

EDIT: The "wrap" attribute is not officially supported. I got it from the german SELFHTML page (an english source is here) that says IE 4.0 and Netscape 2.0 support it. I also tested it in FF 3.0.7 where it works as supposed. Things have changed here, SELFHTML is now a wiki and the english source link is dead.

EDIT2: If you want to be sure every browser supports it, you can use CSS to change wrap behaviour:

Using Cascading Style Sheets (CSS), you can achieve the same effect with white-space: nowrap; overflow: auto;. Thus, the wrap attribute can be regarded as outdated.

From here (seems to be an excellent page with information about textarea).

EDIT3: I'm not sure when it changed (according to the comments, must've been around 2014), but wrap is now an official HTML5 attribute, see w3schools. Changed the answer to match this.

Android view layout_width - how to change programmatically?

You can set height and width like this also:

viewinstance.setLayoutParams(new LayoutParams(width, height));

Easier way to create circle div than using an image?

basically this uses div's position absolute to place a character at the given coordinates. so using the parametric equation for a circle, you can draw a circle. if you were to change div's position to relative, it'll result in a sine wave...

in essence we are graphing equations by abusing the position property. i'm not versed well in css, so someone can surely make this more elegant. enjoy.

this works on all browsers and mobile devices (that i'm aware of). i use it on my own website to draw sine waves of text (www.cpixel.com). the original source of this code is found here: www.mathopenref.com/coordcirclealgorithm.html

    <html>
    <head></head>
    <body>
    <script language="Javascript">

    var x_center = 50; //0 in both x_center and y_center will place the center
    var y_center = 50; // at the top left of the browser
    var resolution_step = 360; //how many times to stop along the circle to plot your character.
    var radius = 50; //how big ya want your circle?
    var plot_character = "·"; //could use any character here, try letters/words for cool effects
    var div_top_offset=10;
    var div_left_offset=10;
    var x,y;

    for ( var angle_theta = 0;  angle_theta < 2 * Math.PI;  angle_theta += 2 * Math.PI/resolution_step ){
        x = x_center + radius * Math.cos(angle_theta);
        y = y_center - radius * Math.sin(angle_theta);
        document.write("<div style='position:absolute;top:" + (y+div_top_offset) + ";left:"+ (x+div_left_offset) + "'>" + plot_character + "</div>");
    }

    </script>
    </body>
    </html>

Angularjs how to upload multipart form data and a file?

It is more efficient to send the files directly.

The base64 encoding of Content-Type: multipart/form-data adds an extra 33% overhead. If the server supports it, it is more efficient to send the files directly:

Doing Multiple $http.post Requests Directly from a FileList

$scope.upload = function(url, fileList) {
    var config = {
      headers: { 'Content-Type': undefined },
      transformResponse: angular.identity
    };
    var promises = fileList.map(function(file) {
      return $http.post(url, file, config);
    });
    return $q.all(promises);
};

When sending a POST with a File object, it is important to set 'Content-Type': undefined. The XHR send method will then detect the File object and automatically set the content type.


Working Demo of "select-ng-files" Directive that Works with ng-model1

The <input type=file> element does not by default work with the ng-model directive. It needs a custom directive:

_x000D_
_x000D_
angular.module("app",[]);

angular.module("app").directive("selectNgFiles", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
        ngModel.$setViewValue(files);
      })
    }
  }
});
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app">
    <h1>AngularJS Input `type=file` Demo</h1>
    
    <input type="file" select-ng-files ng-model="fileList" multiple>
    
    <h2>Files</h2>
    <div ng-repeat="file in fileList">
      {{file.name}}
    </div>
  </body>
_x000D_
_x000D_
_x000D_

Does List<T> guarantee insertion order?

This is the code I have for moving an item down one place in a list:

if (this.folderImages.SelectedIndex > -1 && this.folderImages.SelectedIndex < this.folderImages.Items.Count - 1)
{
    string imageName = this.folderImages.SelectedItem as string;
    int index = this.folderImages.SelectedIndex;

    this.folderImages.Items.RemoveAt(index);
    this.folderImages.Items.Insert(index + 1, imageName);
    this.folderImages.SelectedIndex = index + 1;
 }

and this for moving it one place up:

if (this.folderImages.SelectedIndex > 0)
{
    string imageName = this.folderImages.SelectedItem as string;
    int index = this.folderImages.SelectedIndex;

    this.folderImages.Items.RemoveAt(index);
    this.folderImages.Items.Insert(index - 1, imageName);
    this.folderImages.SelectedIndex = index - 1;
}

folderImages is a ListBox of course so the list is a ListBox.ObjectCollection, not a List<T>, but it does inherit from IList so it should behave the same. Does this help?

Of course the former only works if the selected item is not the last item in the list and the latter if the selected item is not the first item.

How do you divide each element in a list by an int?

The idiomatic way would be to use list comprehension:

myList = [10,20,30,40,50,60,70,80,90]
myInt = 10
newList = [x / myInt for x in myList]

or, if you need to maintain the reference to the original list:

myList[:] = [x / myInt for x in myList]

UITextField text change event

  1. KVO solutions do not work

KVO does NOT work in iOS for controls: http://stackoverflow.com/a/6352525/1402846 https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/KVO.html

  1. In the observing class, you do this:

Given that you know the text view you want to watch:

var watchedTextView: UITextView!

Do this:

NotificationCenter.default.addObserver(
    self,
    selector: #selector(changed),
    name: UITextView.textDidChangeNotification,
    object: watchedTextView)

However, be careful with that:

  • it's likely you only want to call that once, so do not call it in, for example, layoutSubviews

  • it's quite difficult to know when to best call it during your bring-up process. It will depend on your situation. Unfortunately there is no standard, locked-in solution

  • for example you usually certainly can not call it at init time, since of course watchedTextView may not exist yet

.

  1. the next problem is that ...

None of the notifications are called when text is changed programmatically.

This is a huge, age-old, and stupid, nuisance in iOS engineering.

Controls simply do not - end of story - call the notifcations when the .text property is changed programmatically.

This is insanely annoying because of course - obviously - every app ever made sets the text programmatically, such as clearing the field after the user posts, etc.

You have to subclass the text view (or similar control) like this:

class NonIdioticTextView: UIITextView {

    override var text: String! {
        // boilerplate code needed to make watchers work properly:
        get {
            return super.text
        }
        set {
            super.text = newValue
            NotificationCenter.default.post(
                name: UITextView.textDidChangeNotification,
                object: self)
        }

    }

}

(Tip - don't forget the super call has to come before ! the post call.)

There is no solution available, unless, you fix the control by subclassing as shown just above. That is the only solution.

Note that the notification

UITextView.textDidChangeNotification

results in

func textViewDidChangeSelection(_ textView: UITextView) 

being called.

(Not textViewDidChange .)

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

I got this same error when installing to an actual device. More information and a solution to loading the missing libraries to the device can be found at the following site:

Fixing the INSTALL_FAILED_MISSING_SHARED_LIBRARY Error

To set this up correctly, there are 2 key files that need to be copied to the system:

com.google.android.maps.xml

com.google.android.maps.jar

These files are located in the any of these google app packs:

http://android.d3xt3...0120-signed.zip

http://goo-inside.me...0120-signed.zip

http://android.local...0120-signed.zip

These links no longer work, but you can find the files in the android sdk if you have Google Maps API v1

After unzipping any of these files, you want to copy the files to your system, like-ah-so:

adb remount

adb push system/etc/permissions/com.google.android.maps.xml /system/etc/permissions

adb push system/framework/com.google.android.maps.jar /system/framework

adb reboot

JavaScript backslash (\) in variables is causing an error

You may want to try the following, which is more or less the standard way to escape user input:

function stringEscape(s) {
    return s ? s.replace(/\\/g,'\\\\').replace(/\n/g,'\\n').replace(/\t/g,'\\t').replace(/\v/g,'\\v').replace(/'/g,"\\'").replace(/"/g,'\\"').replace(/[\x00-\x1F\x80-\x9F]/g,hex) : s;
    function hex(c) { var v = '0'+c.charCodeAt(0).toString(16); return '\\x'+v.substr(v.length-2); }
}

This replaces all backslashes with an escaped backslash, and then proceeds to escape other non-printable characters to their escaped form. It also escapes single and double quotes, so you can use the output as a string constructor even in eval (which is a bad idea by itself, considering that you are using user input). But in any case, it should do the job you want.

hexadecimal string to byte array in python

You can use the Codecs module in the Python Standard Library, i.e.

import codecs

codecs.decode(hexstring, 'hex_codec')

Execute PHP function with onclick

Try to do something like this:

<!--Include jQuery-->
<script type="text/javascript" src="jquery.min.js"></script> 

<script type="text/javascript"> 
function doSomething() { 
    $.get("somepage.php"); 
    return false; 
} 
</script>

<a href="#" onclick="doSomething();">Click Me!</a>

Possible to extend types in Typescript?

You can also do:

export type UserEvent = Event & { UserId: string; };

Download history stock prices automatically from yahoo finance in python

You can check out the yahoo_fin package. It was initially created after Yahoo Finance changed their API (documentation is here: http://theautomatic.net/yahoo_fin-documentation).

from yahoo_fin import stock_info as si

aapl_data = si.get_data("aapl")

nflx_data = si.get_data("nflx")

aapl_data.head()

nflx_data.head()

aapl.to_csv("aapl_data.csv")

nflx_data.to_csv("nflx_data.csv")

Easy way to turn JavaScript array into comma-separated list?

Here's an implementation that converts a two-dimensional array or an array of columns into a properly escaped CSV string. The functions do not check for valid string/number input or column counts (ensure your array is valid to begin with). The cells can contain commas and quotes!

Here's a script for decoding CSV strings.

Here's my script for encoding CSV strings:

// Example
var csv = new csvWriter();
csv.del = '\t';
csv.enc = "'";

var nullVar;
var testStr = "The comma (,) pipe (|) single quote (') double quote (\") and tab (\t) are commonly used to tabulate data in plain-text formats.";
var testArr = [
    false,
    0,
    nullVar,
    // undefinedVar,
    '',
    {key:'value'},
];

console.log(csv.escapeCol(testStr));
console.log(csv.arrayToRow(testArr));
console.log(csv.arrayToCSV([testArr, testArr, testArr]));

/**
 * Class for creating csv strings
 * Handles multiple data types
 * Objects are cast to Strings
 **/

function csvWriter(del, enc) {
    this.del = del || ','; // CSV Delimiter
    this.enc = enc || '"'; // CSV Enclosure

    // Convert Object to CSV column
    this.escapeCol = function (col) {
        if(isNaN(col)) {
            // is not boolean or numeric
            if (!col) {
                // is null or undefined
                col = '';
            } else {
                // is string or object
                col = String(col);
                if (col.length > 0) {
                    // use regex to test for del, enc, \r or \n
                    // if(new RegExp( '[' + this.del + this.enc + '\r\n]' ).test(col)) {

                    // escape inline enclosure
                    col = col.split( this.enc ).join( this.enc + this.enc );

                    // wrap with enclosure
                    col = this.enc + col + this.enc;
                }
            }
        }
        return col;
    };

    // Convert an Array of columns into an escaped CSV row
    this.arrayToRow = function (arr) {
        var arr2 = arr.slice(0);

        var i, ii = arr2.length;
        for(i = 0; i < ii; i++) {
            arr2[i] = this.escapeCol(arr2[i]);
        }
        return arr2.join(this.del);
    };

    // Convert a two-dimensional Array into an escaped multi-row CSV 
    this.arrayToCSV = function (arr) {
        var arr2 = arr.slice(0);

        var i, ii = arr2.length;
        for(i = 0; i < ii; i++) {
            arr2[i] = this.arrayToRow(arr2[i]);
        }
        return arr2.join("\r\n");
    };
}

C - Convert an uppercase letter to lowercase

#include <stdio.h>
#include <string.h>

int main()
{
    char string[] = "Strlwr in C";

    printf("%s\n",strlwr(string));

    return  0;
}

use strlwr for lowering the case

Change CSS properties on click

Firstly, using on* attributes to add event handlers is a very outdated way of achieving what you want. As you've tagged your question with jQuery, here's a jQuery implementation:

<div id="foo">hello world!</div>
<img src="zoom.png" id="image" />
$('#image').click(function() {
    $('#foo').css({
        'background-color': 'red',
        'color': 'white',
        'font-size': '44px'
    });
});

A more efficient method is to put those styles into a class, and then add that class onclick, like this:

_x000D_
_x000D_
$('#image').click(function() {
  $('#foo').addClass('myClass');
});
_x000D_
.myClass {
  background-color: red;
  color: white;
  font-size: 44px;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="foo">hello world!</div>
<img src="https://i.imgur.com/9zbkKVz.png?1" id="image" />
_x000D_
_x000D_
_x000D_

Here's a plain Javascript implementation of the above for those who require it:

_x000D_
_x000D_
document.querySelector('#image').addEventListener('click', () => {
  document.querySelector('#foo').classList.add('myClass');
}); 
_x000D_
.myClass {
  background-color: red;
  color: white;
  font-size: 44px;
}
_x000D_
<div id="foo">hello world!</div>
<img src="https://i.imgur.com/9zbkKVz.png?1" id="image" />
_x000D_
_x000D_
_x000D_

Click event on select option element in chrome

I know that this code snippet works for recognizing an option click (at least in Chrome and FF). Furthermore, it works if the element wasn't there on DOM load. I usually use this when I input sections of inputs into a single select element and I don't want the section title to be clicked.

$(document).on('click', 'option[value="disableme"]', function(){
    $('option[value="disableme"]').prop("selected", false);
});

Java : Comparable vs Comparator

Comparator provides a way for you to provide custom comparison logic for types that you have no control over.

Comparable allows you to specify how objects that you are implementing get compared.

Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator.

Otherwise you can use Comparable.

Filtering a spark dataframe based on date

Don't use this as suggested in other answers

.filter(f.col("dateColumn") < f.lit('2017-11-01'))

But use this instead

.filter(f.col("dateColumn") < f.unix_timestamp(f.lit('2017-11-01 00:00:00')).cast('timestamp'))

This will use the TimestampType instead of the StringType, which will be more performant in some cases. For example Parquet predicate pushdown will only work with the latter.

Returning an empty array

In a single line you could do:

private static File[] bar(){
    return new File[]{};
}

Enable UTF-8 encoding for JavaScript

Same problem here, solved with this: In Eclipse (with .js file open and on focus), go to, "File", "Properties", "Resource", "Text file encoding" choose "Other:" UTF-8, put correct characters code inside the code save your file and you are done!

OpenMP set_num_threads() is not working

Besides calling omp_get_num_threads() outside of the parallel region in your case, calling omp_set_num_threads() still doesn't guarantee that the OpenMP runtime will use exactly the specified number of threads. omp_set_num_threads() is used to override the value of the environment variable OMP_NUM_THREADS and they both control the upper limit of the size of the thread team that OpenMP would spawn for all parallel regions (in the case of OMP_NUM_THREADS) or for any consequent parallel region (after a call to omp_set_num_threads()). There is something called dynamic teams that could still pick smaller number of threads if the run-time system deems it more appropriate. You can disable dynamic teams by calling omp_set_dynamic(0) or by setting the environment variable OMP_DYNAMIC to false.

To enforce a given number of threads you should disable dynamic teams and specify the desired number of threads with either omp_set_num_threads():

omp_set_dynamic(0);     // Explicitly disable dynamic teams
omp_set_num_threads(4); // Use 4 threads for all consecutive parallel regions
#pragma omp parallel ...
{
    ... 4 threads used here ...
}

or with the num_threads OpenMP clause:

omp_set_dynamic(0);     // Explicitly disable dynamic teams
// Spawn 4 threads for this parallel region only
#pragma omp parallel ... num_threads(4)
{
    ... 4 threads used here ...
}