Programs & Examples On #String matching

String matching is the problem of finding occurrences of one string (“pattern”, “needle”) in another (“text”, “haystack”).

PowerShell and the -contains operator

You can use like:

"12-18" -like "*-*"

Or split for contains:

"12-18" -split "" -contains "-"

Filter multiple values on a string column in dplyr

You need %in% instead of ==:

library(dplyr)
target <- c("Tom", "Lynn")
filter(dat, name %in% target)  # equivalently, dat %>% filter(name %in% target)

Produces

  days name
1   88 Lynn
2   11  Tom
3    1  Tom
4  222 Lynn
5    2 Lynn

To understand why, consider what happens here:

dat$name == target
# [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE

Basically, we're recycling the two length target vector four times to match the length of dat$name. In other words, we are doing:

 Lynn == Tom
  Tom == Lynn
Chris == Tom
 Lisa == Lynn
 ... continue repeating Tom and Lynn until end of data frame

In this case we don't get an error because I suspect your data frame actually has a different number of rows that don't allow recycling, but the sample you provide does (8 rows). If the sample had had an odd number of rows I would have gotten the same error as you. But even when recycling works, this is clearly not what you want. Basically, the statement dat$name == target is equivalent to saying:

return TRUE for every odd value that is equal to "Tom" or every even value that is equal to "Lynn".

It so happens that the last value in your sample data frame is even and equal to "Lynn", hence the one TRUE above.

To contrast, dat$name %in% target says:

for each value in dat$name, check that it exists in target.

Very different. Here is the result:

[1]  TRUE  TRUE FALSE FALSE FALSE  TRUE  TRUE  TRUE

Note your problem has nothing to do with dplyr, just the mis-use of ==.

Perl - If string contains text?

If you just need to search for one string within another, use the index function (or rindex if you want to start scanning from the end of the string):

if (index($string, $substring) != -1) {
   print "'$string' contains '$substring'\n";
}

To search a string for a pattern match, use the match operator m//:

if ($string =~ m/pattern/) {
    print "'$string' matches the pattern\n";       
}

Return positions of a regex match() in Javascript?

You can use the search method of the String object. This will only work for the first match, but will otherwise do what you describe. For example:

"How are you?".search(/are/);
// 4

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

Check whether a string contains a substring

To find out if a string contains substring you can use the index function:

if (index($str, $substr) != -1) {
    print "$str contains $substr\n";
} 

It will return the position of the first occurrence of $substr in $str, or -1 if the substring is not found.

javascript regular expression to check for IP addresses

And instead of

{1-3}

you should put

{1,3}

How do I check if a string contains a specific word?

I'm a bit impressed that none of the answers here that used strpos, strstr and similar functions mentioned Multibyte String Functions yet (2015-05-08).

Basically, if you're having trouble finding words with characters specific to some languages, such as German, French, Portuguese, Spanish, etc. (e.g.: ä, é, ô, ç, º, ñ), you may want to precede the functions with mb_. Therefore, the accepted answer would use mb_strpos or mb_stripos (for case-insensitive matching) instead:

if (mb_strpos($a,'are') !== false) {
    echo 'true';
}

If you cannot guarantee that all your data is 100% in UTF-8, you may want to use the mb_ functions.

A good article to understand why is The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky.

How to check whether a string contains a substring in JavaScript?

ECMAScript 6 introduced String.prototype.includes:

_x000D_
_x000D_
const string = "foo";_x000D_
const substring = "oo";_x000D_
_x000D_
console.log(string.includes(substring));
_x000D_
_x000D_
_x000D_

includes doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:

_x000D_
_x000D_
var string = "foo";_x000D_
var substring = "oo";_x000D_
_x000D_
console.log(string.indexOf(substring) !== -1);
_x000D_
_x000D_
_x000D_

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

A combination of both attempts is probably what you need:

^[0-9]{1,45}$

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

How about dumping the contents of the database, then using grep?

$ pg_dump --data-only --inserts -U postgres your-db-name > a.tmp
$ grep United a.tmp
INSERT INTO countries VALUES ('US', 'United States');
INSERT INTO countries VALUES ('GB', 'United Kingdom');

The same utility, pg_dump, can include column names in the output. Just change --inserts to --column-inserts. That way you can search for specific column names, too. But if I were looking for column names, I'd probably dump the schema instead of the data.

$ pg_dump --data-only --column-inserts -U postgres your-db-name > a.tmp
$ grep country_code a.tmp
INSERT INTO countries (iso_country_code, iso_country_name) VALUES ('US', 'United  States');
INSERT INTO countries (iso_country_code, iso_country_name) VALUES ('GB', 'United Kingdom');

Check if string matches pattern

regular expressions make this easy ...

[A-Z] will match exactly one character between A and Z

\d+ will match one or more digits

() group things (and also return things... but for now just think of them grouping)

+ selects 1 or more

Regular Expression Match to test for a valid year

you can go with sth like [^-]\d{4}$: you prevent the minus sign - to be before your 4 digits.
you can also use ^\d{4}$ with ^ to catch the beginning of the string. It depends on your scenario actually...

How to update data in one table from corresponding data in another table in SQL Server 2005

update test1 t1, test2 t2
set t2.deptid = t1.deptid
where t2.employeeid = t1.employeeid

you can not use from keyword for the mysql

Difference between /res and /assets directories

Following are some key points :

  1. Raw files Must have names that are valid Java identifiers , whereas files in Assets Have no location and name restrictions. In other words they can be grouped in whatever directories we wish
  2. Raw files Are easy to refer to from Java as well as from xml (i.e you can refer a file in raw from manifest or other xml file).
  3. Saving asset files here instead of in the assets/ directory only differs in the way that you access them as documented here http://developer.android.com/tools/projects/index.html.
  4. Resources defined in a library project are automatically imported to application projects that depend on the library. For assets, that doesn't happen; asset files must be present in the assets directory of the application project(s)
  5. The assets directory is more like a filesystem provides more freedom to put any file you would like in there. You then can access each of the files in that system as you would when accessing any file in any file system through Java . like Game data files , Fonts , textures etc.
  6. Unlike Resources, Assets can can be organized into subfolders in the assets directory However, the only thing you can do with an asset is get an input stream. Thus, it does not make much sense to store your strings or bitmaps in assets, but you can store custom-format data such as input correction dictionaries or game maps.
  7. Raw can give you a compile time check by generating your R.java file however If you want to copy your database to private directory you can use Assets which are made for streaming.

Conclusion

  1. Android API includes a very comfortable Resources framework that is also optimized for most typical use cases for various mobile apps. You should master Resources and try to use them wherever possible.
  2. However, if you need more flexibility for your special case, Assets are there to give you a lower level API that allows organizing and processing your resources with a higher degree of freedom.

How do I do a multi-line string in node.js?

Vanilla Javascipt does not support multi-line strings. Language pre-processors are turning out to be feasable these days.

CoffeeScript, the most popular of these has this feature, but it's not minimal, it's a new language. Google's traceur compiler adds new features to the language as a superset, but I don't think multi-line strings are one of the added features.

I'm looking to make a minimal superset of javascript that supports multiline strings and a couple other features. I started this little language a while back before writing the initial compiler for coffeescript. I plan to finish it this summer.

If pre-compilers aren't an option, there is also the script tag hack where you store your multi-line data in a script tag in the html, but give it a custom type so that it doesn't get evaled. Then later using javascript, you can extract the contents of the script tag.

Also, if you put a \ at the end of any line in source code, it will cause the the newline to be ignored as if it wasn't there. If you want the newline, then you have to end the line with "\n\".

Sending images using Http Post

Version 4.3.5 Updated Code

  • httpclient-4.3.5.jar
  • httpcore-4.3.2.jar
  • httpmime-4.3.5.jar

Since MultipartEntity has been deprecated. Please see the code below.

String responseBody = "failure";
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

String url = WWPApi.URL_USERS;
Map<String, String> map = new HashMap<String, String>();
map.put("user_id", String.valueOf(userId));
map.put("action", "update");
url = addQueryParams(map, url);

HttpPost post = new HttpPost(url);
post.addHeader("Accept", "application/json");

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(MIME.UTF8_CHARSET);

if (career != null)
    builder.addTextBody("career", career, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (gender != null)
    builder.addTextBody("gender", gender, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (username != null)
    builder.addTextBody("username", username, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (email != null)
    builder.addTextBody("email", email, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (password != null)
    builder.addTextBody("password", password, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (country != null)
    builder.addTextBody("country", country, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (file != null)
    builder.addBinaryBody("Filedata", file, ContentType.MULTIPART_FORM_DATA, file.getName());

post.setEntity(builder.build());

try {
    responseBody = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
//  System.out.println("Response from Server ==> " + responseBody);

    JSONObject object = new JSONObject(responseBody);
    Boolean success = object.optBoolean("success");
    String message = object.optString("error");

    if (!success) {
        responseBody = message;
    } else {
        responseBody = "success";
    }

} catch (Exception e) {
    e.printStackTrace();
} finally {
    client.getConnectionManager().shutdown();
}

Chart creating dynamically. in .net, c#

Microsoft has a nice chart control. Download it here. Great video on this here. Example code is here. Happy coding!

How to change Bootstrap's global default font size?

In v4 change the SASS variable:

$font-size-base: 1rem !default;

Install Visual Studio 2013 on Windows 7

your log files shows it is stopping on error "0x8004C000"

From MS Website (http://social.technet.microsoft.com/wiki/contents/articles/15716.visual-studio-2012-and-the-error-code-2147205120.aspx):

Setup Status
Block

Restart not required
0x80044000 [-2147205120]

Restart required
0x8004C000 [-2147172352]

Description
If the only block to be reported is “Reboot Pending,” the returned value is the Incomplete-Reboot Required value (0x80048bc7).

using facebook sdk in Android studio

Scott Barta's solution worked for me, except I had to add these to the dependencies of my main project build.gradle file:

compile files('libs/android-support-v4.jar')
compile project(':libraries:facebook')

Also worth mentioning, you need to make sure:

android {
    compileSdkVersion 18
    buildToolsVersion "18.1.1"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 18
    }

Are the same in both build.gradle files...Once i did this it ran like a charm.

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

Uninstall your application from the emulator or device. Run the app again. (OnCreate() is not executed when the database already exists)

Allow Access-Control-Allow-Origin header using HTML5 fetch API

Solution to resolve issue in Local env's

I had my front-end code running in http://localhost:3000 and my API(Backend code) running at http://localhost:5000

Was using fetch API to call the API. Initially, it was throwing "cors" error. Then added this below code in my Backend API code, allowing origin and header from anywhere.

let allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', "*");
  res.header('Access-Control-Allow-Headers', "*");
  next();
}
app.use(allowCrossDomain);

However you must restrict origins in case of other environments like stage, prod.

Strictly NO for higher environments.

TypeError: unhashable type: 'dict'

A possible solution might be to use the JSON dumps() method, so you can convert the dictionary to a string ---

import json

a={"a":10, "b":20}
b={"b":20, "a":10}
c = [json.dumps(a), json.dumps(b)]


set(c)
json.dumps(a) in c

Output -

set(['{"a": 10, "b": 20}'])
True

How do I load the contents of a text file into a javascript variable?

Update 2020: Using Fetch with async/await

const response = await fetch('http://localhost/foo.txt');
const data = await response.text();
console.log(data);

Note that await can only be used in an async function. A longer example might be

_x000D_
_x000D_
async function loadFileAndPrintToConsole(url) {_x000D_
  try {_x000D_
    const response = await fetch(url);_x000D_
    const data = await response.text();_x000D_
    console.log(data);_x000D_
  } catch (err) {_x000D_
    console.error(err);_x000D_
  }_x000D_
}_x000D_
_x000D_
loadFileAndPrintToConsole('https://threejsfundamentals.org/LICENSE');
_x000D_
_x000D_
_x000D_

How to disable phone number linking in Mobile Safari?

To disable the phone parsing appearance for specific elements, this CSS seems to do the trick:

.element { pointer-events: none; }
.element > a { text-decoration:none; color:inherit; }

The first rule disables the click, the second takes care of the styling.

How to get name of the computer in VBA?

Looks like I'm late to the game, but this is a common question...

This is probably the code you want.

Please note that this code is in the public domain, from Usenet, MSDN, and the Excellerando blog.

Public Function ComputerName() As String
'' Returns the host name

'' Uses late-binding: bad for performance and stability, useful for 
'' code portability. The correct declaration is:

'   Dim objNetwork  As IWshRuntimeLibrary.WshNetwork
'   Set objNetwork = New IWshRuntimeLibrary.WshNetwork

    Dim objNetwork As Object
    Set objNetwork = CreateObject("WScript.Network")

    ComputerName = objNetwork.ComputerName
    
    Set objNetwork = Nothing

End Function

You'll probably need this, too:

Public Function UserName(Optional WithDomain As Boolean = False) As String
'' Returns the user's network name

'' Uses late-binding: bad for performance and stability, useful for
'' code portability. The correct declaration is:

'   Dim objNetwork  As IWshRuntimeLibrary.WshNetwork
'   Set objNetwork = New IWshRuntimeLibrary.WshNetwork


    Dim objNetwork As Object
    Set objNetwork = CreateObject("WScript.Network")

    If WithDomain Then
        UserName = objNetwork.UserDomain & "\" & objNetwork.UserName
    Else
        UserName = objNetwork.UserName
    End If
    
    Set objNetwork = Nothing

End Function

Making a triangle shape using xml definitions?

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <rotate
            android:fromDegrees="45"
            android:toDegrees="45"
            android:pivotX="-40%"
            android:pivotY="87%" >
            <shape
                android:shape="rectangle" >
                <stroke android:color="@android:color/transparent" android:width="0dp"/>
                <solid
                    android:color="#fff" />
            </shape>
        </rotate>
    </item>
</layer-list>

How to call a web service from jQuery

You can make an AJAX request like any other requests:

$.ajax( {
type:'Get',
url:'http://mysite.com/mywebservice',
success:function(data) {
 alert(data);
}

})

Delimiters in MySQL

The DELIMITER statement changes the standard delimiter which is semicolon ( ;) to another. The delimiter is changed from the semicolon( ;) to double-slashes //.

Why do we have to change the delimiter?

Because we want to pass the stored procedure, custom functions etc. to the server as a whole rather than letting mysql tool to interpret each statement at a time.

Cannot delete directory with Directory.Delete(path, true)

Editor's note: Although this answer contains some useful information, it is factually incorrect about the workings of Directory.Delete. Please read the comments for this answer, and other answers to this question.


I ran into this problem before.

The root of the problem is that this function does not delete files that are within the directory structure. So what you'll need to do is create a function that deletes all the files within the directory structure then all the directories before removing the directory itself. I know this goes against the second parameter but it's a much safer approach. In addition, you will probably want to remove READ-ONLY access attributes from the files right before you delete them. Otherwise that will raise an exception.

Just slap this code into your project.

public static void DeleteDirectory(string target_dir)
{
    string[] files = Directory.GetFiles(target_dir);
    string[] dirs = Directory.GetDirectories(target_dir);

    foreach (string file in files)
    {
        File.SetAttributes(file, FileAttributes.Normal);
        File.Delete(file);
    }

    foreach (string dir in dirs)
    {
        DeleteDirectory(dir);
    }

    Directory.Delete(target_dir, false);
}

Also, for me I personally add a restriction on areas of the machine that are allowed to be deleted because do you want someone to call this function on C:\WINDOWS (%WinDir%) or C:\.

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

You can prevent Safari from automatically zooming in on text fields during user input without disabling the user’s ability to pinch zoom. Just add maximum-scale=1 but leave out the user-scale attribute suggested in other answers.

It is a worthwhile option if you have a form in a layer that “floats” around if zoomed, which can cause important UI elements to move off screen.

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

While loop to test if a file exists in bash

I had the same problem, put the ! outside the brackets;

while ! [ -f /tmp/list.txt ];
do
    echo "#"
    sleep 1
done

Also, if you add an echo inside the loop it will tell you if you are getting into the loop or not.

Getting "type or namespace name could not be found" but everything seems ok?

To solve this issue it can also help to delete and recreate the *.sln.DotSettings file of the associated solution.

How to check if a value exists in an array in Ruby

How about this way?

['Cat', 'Dog', 'Bird'].index('Dog')

C++ sorting and keeping track of indexes

Are the items in the vector unique? If so, copy the vector, sort one of the copies with STL Sort then you can find which index each item had in the original vector.

If the vector is supposed to handle duplicate items, I think youre better of implementing your own sort routine.

How can I set a css border on one side only?

    div{
    border-left:solid red 3px;
    border-right:solid violet 4px;
    border-top:solid blue 4px;
    border-bottom:solid green 4px;
    background:grey;
    width:100px; height:50px
}

DEMO

How to compare if two structs, slices or maps are equal?

reflect.DeepEqual is often incorrectly used to compare two like structs, as in your question.

cmp.Equal is a better tool for comparing structs.

To see why reflection is ill-advised, let's look at the documentation:

Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal.

....

numbers, bools, strings, and channels - are deeply equal if they are equal using Go's == operator.

If we compare two time.Time values of the same UTC time, t1 == t2 will be false if their metadata timezone is different.

go-cmp looks for the Equal() method and uses that to correctly compare times.

Example:

m1 := map[string]int{
    "a": 1,
    "b": 2,
}
m2 := map[string]int{
    "a": 1,
    "b": 2,
}
fmt.Println(cmp.Equal(m1, m2)) // will result in true

What is "runtime"?

Run time exactly where your code comes into life and you can see lot of important thing your code do.

Runtime has a responsibility of allocating memory , freeing memory , using operating system's sub system like (File Services, IO Services.. Network Services etc.)

Your code will be called "WORKING IN THEORY" until you practically run your code. and Runtime is a friend which helps in achiving this.

Efficient way to add spaces between characters in a string

s = "BINGO"
print(s.replace("", " ")[1: -1])

Timings below

$ python -m timeit -s's = "BINGO"' 's.replace(""," ")[1:-1]'
1000000 loops, best of 3: 0.584 usec per loop
$ python -m timeit -s's = "BINGO"' '" ".join(s)'
100000 loops, best of 3: 1.54 usec per loop

An error has occured. Please see log file - eclipse juno

If nothing works, then try uninstalling and then reinstalling Eclipse. This is how i just fixed this problem after trying everything suggested on this forum.

Passing a URL with brackets to curl

I was getting this error though there were no (obvious) brackets in my URL, and in my situation the --globoff command will not solve the issue.

For example (doing this on on mac in iTerm2):

for endpoint in $(grep some_string output.txt); do curl "http://1.2.3.4/api/v1/${endpoint}" ; done

I have grep aliased to "grep --color=always". As a result, the above command will result in this error, with some_string highlighted in whatever colour you have grep set to:

curl: (3) bad range in URL position 31:
http://1.2.3.4/api/v1/lalalasome_stringlalala

The terminal was transparently translating the [colour\codes]some_string[colour\codes] into the expected no-special-characters URL when viewed in terminal, but behind the scenes the colour codes were being sent in the URL passed to curl, resulting in brackets in your URL.

Solution is to not use match highlighting.

iPad browser WIDTH & HEIGHT standard

You can try this:

    /*iPad landscape oriented styles */

    @media only screen and (device-width:768px)and (orientation:landscape){
        .yourstyle{

        }

    }

    /*iPad Portrait oriented styles */

    @media only screen and (device-width:768px)and (orientation:portrait){
        .yourstyle{

        }
    }

Unix's 'ls' sort by name

From the man page (for bash ls):

Sort entries alphabetically if none of -cftuSUX nor --sort.

CSS Printing: Avoiding cut-in-half DIVs between pages?

Only a partial solution: The only way I could get this to work for IE was to wrap each div in it's own table and set the page-break-inside on the table to avoid.

Example of Mockito's argumentCaptor

The steps in order to make a full check are:

Prepare the captor :

ArgumentCaptor<SomeArgumentClass> someArgumentCaptor = ArgumentCaptor.forClass(SomeArgumentClass.class);

verify the call to dependent on component (collaborator of subject under test). times(1) is the default value, so ne need to add it.

verify(dependentOnComponent, times(1)).send(someArgumentCaptor.capture());

Get the argument passed to collaborator

SomeArgumentClass someArgument = messageCaptor.getValue();

someArgument can be used for assertions

Convert xlsx to csv in Linux with command line

In bash, I used this libreoffice command to convert all my xlsx files in the current directory:

for i   in *.xlsx; do  libreoffice --headless --convert-to csv "$i" ; done

It takes care of spaces in the filename.

Tried again some years later, and it didn't work. This thread gives some tips, but the quickiest solution was to run as root (or running a sudo libreoffice). Not elegant, but quick.

Use the command scalc.exe in Windows

SQL query to find third highest salary in company

For me this query work fine in Mysql it will return third max salary from table

SELECT salary FROM users ORDER BY salary DESC LIMIT 1 OFFSET 2;

or

SELECT salary FROM users ORDER BY salary DESC LIMIT 2,1;

python-dev installation error: ImportError: No module named apt_pkg

The solution of @user8178061 worked well but I did it with some modifications for my version wich is python3.7 with Ubuntu

I replaced the apt_pkg.cpython-3m-i386-linux-gnu.so with apt_pkg.cpython-36m-x86_64-linux-gnu.so

Here the two commands to execute:

cd /usr/lib/python3/dist-packages

sudo cp apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

What is the Record type in typescript?

A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.

For example, say I have a Union like this:

type CatNames = "miffy" | "boris" | "mordred";

Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.

type CatList = Record<CatNames, {age: number}>

If I want to satisfy this CatList, I must create an object like this:

const cats:CatList = {
  miffy: { age:99 },
  boris: { age:16 },
  mordred: { age:600 }
}

You get very strong type safety:

  • If I forget a cat, I get an error.
  • If I add a cat that's not allowed, I get an error.
  • If I later change CatNames, I get an error. This is especially useful because CatNames is likely imported from another file, and likely used in many places.

Real-world React example.

I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes

I had a union like this:

type Statuses = "failed" | "complete";

I used this to create an object like this:

const icons: Record<
  Statuses,
  { iconType: IconTypes; iconColor: IconColors }
> = {
  failed: {
    iconType: "warning",
    iconColor: "red"
  },
  complete: {
    iconType: "check",
    iconColor: "green"
  };

I could then render by destructuring an element from the object into props, like so:

const Status = ({status}) => <Icon {...icons[status]} />

If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.

Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.

Align inline-block DIVs to top of container element

Add overflow: auto to the container div. http://www.quirksmode.org/css/clearing.html This website shows a few options when having this issue.

Python Pandas replicate rows in dataframe

Other way is using concat() function:

import pandas as pd

In [603]: df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))

In [604]: df
Out[604]: 
  col1  col2
0    a     0
1    b     1
2    c     2

In [605]: pd.concat([df]*3, ignore_index=True) # Ignores the index
Out[605]: 
  col1  col2
0    a     0
1    b     1
2    c     2
3    a     0
4    b     1
5    c     2
6    a     0
7    b     1
8    c     2

In [606]: pd.concat([df]*3)
Out[606]: 
  col1  col2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2

What is the difference between id and class in CSS, and when should I use them?

ID's have the functionality to work as links to particular sections within a webpage. a keyword after # tag will take you to a particular section of the webpage. e.g "http://exampleurl.com#chapter5" in the address bar will take you there when you have a "section5" id wrapped around the chapter 5 section of the page.

How to do tag wrapping in VS code?

imo there's a better answer for this using Snippets

Create a snippet with a definition like this:

"name_of_your_snippet": {
    "scope": "javascript,html",
    "prefix": "name_of_your_snippet",
    "body": "<${0:b}>$TM_SELECTED_TEXT</${0:b}>"
}

Then bind it to a key in keybindings.json E.g. like this:

{ 
    "key": "alt+w",
    "command": "editor.action.insertSnippet",
    "args": { "name": "name_of_your_snippet" }
}

I think this should give you exactly the same result as htmltagwrap but without having to install an extension.

It will insert tags around selected text, defaults to <b> tag & selects the tag so typing lets you change it.

If you want to use a different default tag just change the b in the body property of the snippet.

Find duplicate records in MySQL

To quickly see the duplicate rows you can run a single simple query

Here I am querying the table and listing all duplicate rows with same user_id, market_place and sku:

select user_id, market_place,sku, count(id)as totals from sku_analytics group by user_id, market_place,sku having count(id)>1;

To delete the duplicate row you have to decide which row you want to delete. Eg the one with lower id (usually older) or maybe some other date information. In my case I just want to delete the lower id since the newer id is latest information.

First double check if the right records will be deleted. Here I am selecting the record among duplicates which will be deleted (by unique id).

select a.user_id, a.market_place,a.sku from sku_analytics a inner join sku_analytics b where a.id< b.id and a.user_id= b.user_id and a.market_place= b.market_place and a.sku = b.sku;

Then I run the delete query to delete the dupes:

delete a from sku_analytics a inner join sku_analytics b where a.id< b.id and a.user_id= b.user_id and a.market_place= b.market_place and a.sku = b.sku;

Backup, Double check, verify, verify backup then execute.

How to linebreak an svg text within javascript?

I think this does what you want:

function ShowTooltip(evt, mouseovertext){
    // Make tooltip text        
    var tooltip_text = tt.childNodes.item(1);
    var words = mouseovertext.split("\\\n");
    var max_length = 0;

    for (var i=0; i<3; i++){
        tooltip_text.childNodes.item(i).firstChild.data = i<words.length ?  words[i] : " ";
        length = tooltip_text.childNodes.item(i).getComputedTextLength();
        if (length > max_length) {max_length = length;}
    }

    var x = evt.clientX + 14 + max_length/2;
    var y = evt.clientY + 29;
    tt.setAttributeNS(null,"transform", "translate(" + x + " " + y + ")")

    // Make tooltip background
    bg.setAttributeNS(null,"width", max_length+15);
    bg.setAttributeNS(null,"height", words.length*15+6);
    bg.setAttributeNS(null,"x",evt.clientX+8);
    bg.setAttributeNS(null,"y",evt.clientY+14);

    // Show everything
    tt.setAttributeNS(null,"visibility","visible");
    bg.setAttributeNS(null,"visibility","visible");
}

It splits the text on \\\n and for each puts each fragment in a tspan. Then it calculates the size of the box required based on the longest length of text and the number of lines. You will also need to change the tooltip text element to contain three tspans:

<g id="tooltip" visibility="hidden">
    <text><tspan>x</tspan><tspan x="0" dy="15">x</tspan><tspan x="0" dy="15">x</tspan></text>
</g>

This assumes that you never have more than three lines. If you want more than three lines you can add more tspans and increase the length of the for loop.

List of Java processes

Starting from Java 7, the simplest way and less error prone is to simply use the command jcmd that is part of the JDK such that it will work the same way on all OS.

Example:

> jcmd
5485 sun.tools.jcmd.JCmd
2125 MyProgram

jcmd allows to send diagnostic command requests to a running Java Virtual Machine (JVM).

More details about how to use jcmd.

See also the jcmd Utility

Hive ParseException - cannot recognize input near 'end' 'string'

The issue isn't actually a syntax error, the Hive ParseException is just caused by a reserved keyword in Hive (in this case, end).

The solution: use backticks around the offending column name:

CREATE EXTERNAL TABLE moveProjects (cid string, `end` string, category string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("dynamodb.table.name" = "Projects",
    "dynamodb.column.mapping" = "cid:cid,end:end,category:category");

With the added backticks around end, the query works as expected.

Reserved words in Amazon Hive (as of February 2013):

IF, HAVING, WHERE, SELECT, UNIQUEJOIN, JOIN, ON, TRANSFORM, MAP, REDUCE, TABLESAMPLE, CAST, FUNCTION, EXTENDED, CASE, WHEN, THEN, ELSE, END, DATABASE, CROSS

Source: This Hive ticket from the Facebook Phabricator tracker

How do I get into a non-password protected Java keystore or change the password?

Mac Mountain Lion has the same password now it uses Oracle.

Fetching distinct values on a column using Spark DataFrame

This solution demonstrates how to transform data with Spark native functions which are better than UDFs. It also demonstrates how dropDuplicates which is more suitable than distinct for certain queries.

Suppose you have this DataFrame:

+-------+-------------+
|country|    continent|
+-------+-------------+
|  china|         asia|
| brazil|south america|
| france|       europe|
|  china|         asia|
+-------+-------------+

Here's how to take all the distinct countries and run a transformation:

df
  .select("country")
  .distinct
  .withColumn("country", concat(col("country"), lit(" is fun!")))
  .show()
+--------------+
|       country|
+--------------+
|brazil is fun!|
|france is fun!|
| china is fun!|
+--------------+

You can use dropDuplicates instead of distinct if you don't want to lose the continent information:

df
  .dropDuplicates("country")
  .withColumn("description", concat(col("country"), lit(" is a country in "), col("continent")))
  .show(false)
+-------+-------------+------------------------------------+
|country|continent    |description                         |
+-------+-------------+------------------------------------+
|brazil |south america|brazil is a country in south america|
|france |europe       |france is a country in europe       |
|china  |asia         |china is a country in asia          |
+-------+-------------+------------------------------------+

See here for more information about filtering DataFrames and here for more information on dropping duplicates.

Ultimately, you'll want to wrap your transformation logic in custom transformations that can be chained with the Dataset#transform method.

How to open a PDF file in an <iframe>?

It also important to make sure that the web server sends the file with Content-Disposition = inline. this might not be the case if you are reading the file yourself and send it's content to the browser:

in php it will look like this...

...headers...
header("Content-Disposition: inline; filename=doc.pdf");
...headers...

readfile('localfilepath.pdf')

Delete multiple rows by selecting checkboxes using PHP

You should treat it as an array like this,

<input name="checkbox[]" type="checkbox" value="<?php echo $row['link_id']; ?>">

Then only, you can take its count and loop it for deletion.

You also need to pass the database connection to the query.

$result = mysqli_query($dbc, $sql);

Yours did not include it:

$result = mysqli_query($sql);

How to represent multiple conditions in a shell if statement?

In bash for string comparison, you can use the following technique.

if [ $var OP "val" ]; then
    echo "statements"
fi

Example:

var="something"
if [ $var != "otherthing" ] && [ $var != "everything" ] && [ $var != "allthings" ]; then
    echo "this will be printed"
else
    echo "this will not be printed"
fi

Encapsulation vs Abstraction?

Abstraction is a very general term, and abstraction in software is not limited to object-oriented languages. A dictionary definition: "the act of considering something as a general quality or characteristic, apart from concrete realities, specific objects, or actual instances".

Assembly language can be thought of as an abstraction of machine code -- assembly expresses the essential details and structure of the machine code, but frees you from having to think about the opcodes used, the layout of the code in memory, making jumps go to the right address, etc.

Your operating system's API is an abstraction of the underlying machine. Your compiler provides a layer of abstraction which shields you from the details of assembly language. The TCP/IP stack built into your operating system abstracts away the details of transmitting bits over a network. If you go down all the way to the raw silicon, the people who designed your CPU did so using circuit diagrams written in terms of "diodes" and "transistors", which are abstractions of how electrons travel through semiconductor crystals.

In software, everything is an abstraction. We build programs which simulate or model some aspect of reality, but by necessity our models always abstract away some details of the "real thing". We build layer on layer on layer of abstractions, because it is the only way we get anything done. (Imagine you were trying to make, say, a sudoku solver, and you had to design it using only semiconductor crystals. "OK, I need a piece of N-type silicon here...")

In comparison, "encapsulation" is a very specific and limited term. Some of the other answers to this question have already given good definitions for it.

regex to match a single character that is anything but a space

  • \s matches any white-space character
  • \S matches any non-white-space character
  • You can match a space character with just the space character;
  • [^ ] matches anything but a space character.

Pick whichever is most appropriate.

How can I get the max (or min) value in a vector?

In c++11, you can use some function like that:

int maxAt(std::vector<int>& vector_name) {
    int max = INT_MIN;
    for (auto val : vector_name) {
         if (max < val) max = val;
    }
    return max;
}

How to set a default row for a query that returns no rows?

*SQL solution

Suppose you have a review table which has primary key "id".

SELECT * FROM review WHERE id = 1555
UNION ALL
SELECT * FROM review WHERE NOT EXISTS ( SELECT * FROM review where id = 1555 ) AND id = 1

if table doesn't have review with 1555 id then this query will provide a review of id 1.

Java: getMinutes and getHours

One more way of getting minutes and hours is by using SimpleDateFormat.

SimpleDateFormat formatMinutes = new SimpleDateFormat("mm")
String getMinutes = formatMinutes.format(new Date())

SimpleDateFormat formatHours = new SimpleDateFormat("HH")
String getHours = formatHours.format(new Date())

CSS Equivalent of the "if" statement

CSS has become a very powerful tool over the years and it has hacks for a lot of things javaScript can do

There is a hack in CSS for using conditional statements/logic.

It involves using the symbol '~'

Let me further illustrate with an example.

Let's say you want a background to slide into the page when a button is clicked. All you need to do is use a radio checkbox. Style the label for the radio underneath the button so that when the button is pressed the checkbox is also pressed.

Then you use the code below

.checkbox:checked ~ .background{
opacity:1
width: 100%
}

This code simply states IF the checkbox is CHECKED then open up the background ELSE leave it as it is.

How to check visibility of software keyboard in Android?

The idea is, if you need to hide your keyboard and check soft input state at the same time, use the following solution:

public boolean hideSoftInput() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
    return imm.hideSoftInputFromWindow(mViewPager.getWindowToken(), 0);
}

This method returns true if keyboard was shown before hiding.

Socket send and receive byte array

You need to either have the message be a fixed size, or you need to send the size or you need to use some separator characters.

This is the easiest case for a known size (100 bytes):

in = new DataInputStream(server.getInputStream());
byte[] message = new byte[100]; // the well known size
in.readFully(message);

In this case DataInputStream makes sense as it offers readFully(). If you don't use it, you need to loop yourself until the expected number of bytes is read.

C# Linq Group By on multiple columns

Given a list:

var list = new List<Child>()
{
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "John"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Bob", Name = "Pete"},
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "Fred"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Fred", Name = "Bob"},
};

The query would look like:

var newList = list
    .GroupBy(x => new {x.School, x.Friend, x.FavoriteColor})
    .Select(y => new ConsolidatedChild()
        {
            FavoriteColor = y.Key.FavoriteColor,
            Friend = y.Key.Friend,
            School = y.Key.School,
            Children = y.ToList()
        }
    );

Test code:

foreach(var item in newList)
{
    Console.WriteLine("School: {0} FavouriteColor: {1} Friend: {2}", item.School,item.FavoriteColor,item.Friend);
    foreach(var child in item.Children)
    {
        Console.WriteLine("\t Name: {0}", child.Name);
    }
}

Result:

School: School1 FavouriteColor: blue Friend: Bob
    Name: John
    Name: Fred
School: School2 FavouriteColor: blue Friend: Bob
    Name: Pete
School: School2 FavouriteColor: blue Friend: Fred
    Name: Bob

PHP Constants Containing Arrays?

PHP 7+

As of PHP 7, you can just use the define() function to define a constant array :

define('ANIMALS', [
    'dog',
    'cat',
    'bird'
]);

echo ANIMALS[1]; // outputs "cat"

Get string after character

This should work:

your_str='GenFiltEff=7.092200e-01'
echo $your_str | cut -d "=" -f2

Bash: Strip trailing linebreak from output

One way:

wc -l < log.txt | xargs echo -n

Can not deserialize instance of java.lang.String out of START_OBJECT token

You're mapping this JSON

{
    "id": 2,
    "socket": "0c317829-69bf-43d6-b598-7c0c550635bb",
    "type": "getDashboard",
    "data": {
        "workstationUuid": "ddec1caa-a97f-4922-833f-632da07ffc11"
    },
    "reply": true
}

that contains an element named data that has a JSON object as its value. You are trying to deserialize the element named workstationUuid from that JSON object into this setter.

@JsonProperty("workstationUuid")
public void setWorkstation(String workstationUUID) {

This won't work directly because Jackson sees a JSON_OBJECT, not a String.

Try creating a class Data

public class Data { // the name doesn't matter 
    @JsonProperty("workstationUuid")
    private String workstationUuid;
    // getter and setter
}

the switch up your method

@JsonProperty("data")
public void setWorkstation(Data data) {
    // use getter to retrieve it

How to add element to C++ array?

Since I got so many negative feedback I realized my solution was wrong so i changed it.

int arr[20] = {1,2,3,4,5};
int index = 5;

void push(int n){
    arr[index] = n;
    index++;
}

push(6)

New array will contain value from 1 to 6 and you can make function for deletion like this as well.

Styling the last td in a table with css

Javascript is the only viable way to do this client side (that is, CSS won't help you). In jQuery:

$("table td:last").css("border", "none");

How to output git log with the first line only?

Does git log --oneline do what you want?

Redis: Show database size/size for keys

I usually prefer the key sampling method to troubleshoot such scenarios.

redis-cli -p 6379 -n db_number --bigkeys

Eg:-

redis-cli -p 6370 -n 0 --bigkeys

Ternary operator in AngularJS templates

  <body ng-app="app">
  <button type="button" ng-click="showme==true ? !showme :showme;message='Cancel Quiz'"  class="btn btn-default">{{showme==true ? 'Cancel Quiz': 'Take a Quiz'}}</button>
    <div ng-show="showme" class="panel panel-primary col-sm-4" style="margin-left:250px;">
      <div class="panel-heading">Take Quiz</div>
      <div class="form-group col-sm-8 form-inline" style="margin-top: 30px;margin-bottom: 30px;">

        <button type="button" class="btn btn-default">Start Quiz</button>
      </div>
    </div>
  </body>

Button toggle and change header of button and show/hide div panel. See the Plunkr

How can I avoid ResultSet is closed exception in Java?

make sure you have closed all your statments and resultsets before running rs.next. Finaly guarantees this

public boolean flowExists( Integer idStatusPrevious, Integer idStatus, Connection connection ) {
    LogUtil.logRequestMethod();

    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        ps = connection.prepareStatement( Constants.SCRIPT_SELECT_FIND_FLOW_STATUS_BY_STATUS );
        ps.setInt( 1, idStatusPrevious );
        ps.setInt( 2, idStatus );

        rs = ps.executeQuery();

        Long count = 0L;

        if ( rs != null ) {
            while ( rs.next() ) {
                count = rs.getLong( 1 );
                break;
            }
        }

        LogUtil.logSuccessMethod();

        return count > 0L;
    } catch ( Exception e ) {
        String errorMsg = String
            .format( Constants.ERROR_FINALIZED_METHOD, ( e.getMessage() != null ? e.getMessage() : "" ) );
        LogUtil.logError( errorMsg, e );

        throw new FatalException( errorMsg );
    } finally {
        rs.close();
        ps.close();
    }

Android button font size

Button butt= new Button(_context);
butt.setTextAppearance(_context, R.style.ButtonFontStyle);

and in res/values/style.xml

<resources>   
    <style name="ButtonFontStyle">
            <item name="android:textSize">12sp</item>
    </style>
</resources>

Activity transition in Android

I overwrite my default activity animation. I test it in api 15 that it work smoothly. Here is the solution that I use:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorPrimary</item>
    <item name="android:windowAnimationStyle">@style/CustomActivityAnimation</item>

</style>

<style name="CustomActivityAnimation" parent="@android:style/Animation.Activity">
    <item name="android:activityOpenEnterAnimation">@anim/slide_in_right</item>
    <item name="android:activityOpenExitAnimation">@anim/slide_out_left</item>
    <item name="android:activityCloseEnterAnimation">@anim/slide_in_left</item>
    <item name="android:activityCloseExitAnimation">@anim/slide_out_right</item>
</style>

Create anim folder under res folder and then create this four animation files:

slide_in_right.xml

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="100%p" android:toXDelta="0"
        android:duration="@android:integer/config_mediumAnimTime"/>
</set>

slide_out_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="-100%p"
        android:duration="@android:integer/config_mediumAnimTime"/>
</set>

slide_in_left.xml

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="-100%p" android:toXDelta="0"
        android:duration="@android:integer/config_mediumAnimTime"/>
</set>

slide_out_right.xml

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="100%p"
        android:duration="@android:integer/config_mediumAnimTime"/>
</set>

You can download my sample project.

That's all... :)

How to Execute SQL Server Stored Procedure in SQL Developer?

Select * from Table name ..i.e(are you save table name in sql(TEST) k.

Select * from TEST then you will execute your project.

"Sources directory is already netbeans project" error when opening a project from existing sources

In my case my project root directory consists ".project". This contain the XML reference of the project name.

By removing this, i am able to create a project.

Refresh Page C# ASP.NET

Careful with rewriting URLs, though. I'm using this, so it keeps URLs rewritten.

Response.Redirect(Request.RawUrl);

how to insert date and time in oracle?

create table Customer(
       CustId int primary key,
       CustName varchar(20),
       DOB date);

insert into Customer values(1,'kingle', TO_DATE('1994-12-16 12:00:00', 'yyyy-MM-dd hh:mi:ss'));

Remove duplicates from a dataframe in PySpark

It is not an import problem. You simply call .dropDuplicates() on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...) is pyspark.sql.dataframe.DataFrame, after you apply .collect() it is a plain Python list, and lists don't provide dropDuplicates method. What you want is something like this:

 (df1 = sqlContext
     .createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
     .dropDuplicates())

 df1.collect()

Why should I use core.autocrlf=true in Git?

I am a .NET developer, and have used Git and Visual Studio for years. My strong recommendation is set line endings to true. And do it as early as you can in the lifetime of your Repository.

That being said, I HATE that Git changes my line endings. A source control should only save and retrieve the work I do, it should NOT modify it. Ever. But it does.

What will happen if you don't have every developer set to true, is ONE developer eventually will set to true. This will begin to change the line endings of all of your files to LF in your repo. And when users set to false check those out, Visual Studio will warn you, and ask you to change them. You will have 2 things happen very quickly. One, you will get more and more of those warnings, the bigger your team the more you get. The second, and worse thing, is that it will show that every line of every modified file was changed(because the line endings of every line will be changed by the true guy). Eventually you won't be able to track changes in your repo reliably anymore. It is MUCH easier and cleaner to make everyone keep to true, than to try to keep everyone false. As horrible as it is to live with the fact that your trusted source control is doing something it should not. Ever.

How do I prevent people from doing XSS in Spring MVC?

I use Hibernate Validator via @Valid for all input objects (binding and @RequestBody json, see https://dzone.com/articles/spring-31-valid-requestbody). So @org.hibernate.validator.constraints.SafeHtml is a good solution for me.

Hibernate SafeHtmlValidator depends on org.jsoup, so it's needed to add one more project dependencies:

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.10.1</version>
</dependency>

For bean User with field

@NotEmpty
@SafeHtml
protected String name;

for update attempt with value <script>alert(123)</script> in controller

@PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
public void update(@Valid @RequestBody User user, @PathVariable("id") int id) 

or

@PostMapping
public void createOrUpdate(@Valid User user) {

is thrown BindException for binding and MethodArgumentNotValidException for @RequestBody with default message:

name may have unsafe html content

Validator works as well for binding, as before persisting. Apps could be tested at http://topjava.herokuapp.com/

UPDATE: see also comment from @GuyT

CVE-2019-10219 and status of @SafeHtml

We have been made aware of a CVE-2019-10219 related to the @SafeHtml constraint and it was fixed in both 6.0.18.Final and 6.1.0.Final....

However, we came to the conclusion that the @SafeHtml constraint was fragile, highly security-sensitive and depending on an external library that wasn’t designed for this purpose. Having it included in core Hibernate Validator was not a very good idea. That’s why we deprecated it and marked it for removal.There is no magic plan here so our users will have to maintain this constraint themselves

Resume for myself: it is safe and could be used, until solution better be found.

When should we implement Serializable interface?

The answer to this question is, perhaps surprisingly, never, or more realistically, only when you are forced to for interoperability with legacy code. This is the recommendation in Effective Java, 3rd Edition by Joshua Bloch:

There is no reason to use Java serialization in any new system you write

Oracle's chief architect, Mark Reinhold, is on record as saying removing the current Java serialization mechanism is a long-term goal.


Why Java serialization is flawed

Java provides as part of the language a serialization scheme you can opt in to, by using the Serializable interface. This scheme however has several intractable flaws and should be treated as a failed experiment by the Java language designers.

  • It fundamentally pretends that one can talk about the serialized form of an object. But there are infinitely many serialization schemes, resulting in infinitely many serialized forms. By imposing one scheme, without any way of changing the scheme, applications can not use a scheme most appropriate for them.
  • It is implemented as an additional means of constructing objects, which bypasses any precondition checks your constructors or factory methods perform. Unless tricky, error prone, and difficult to test extra deserialization code is written, your code probably has a gaping security weakness.
  • Testing interoperability of different versions of the serialized form is very difficult.
  • Handling of immutable objects is troublesome.

What to do instead

Instead, use a serialization scheme that you can explicitly control. Such as Protocol Buffers, JSON, XML, or your own custom scheme.

Template not provided using create-react-app

  1. npm install -g create-react-app in your pc
  2. create react project again with npx create-react-app my-app

.setAttribute("disabled", false); changes editable attribute to false

A disabled element is, (self-explaining) disabled and thereby logically not editable, so:

set the disabled attribute [...] changes the editable attribute too

Is an intended and well-defined behaviour.

The real problem here seems to be you're trying to set disabled to false via setAttribute() which doesn't do what you're expecting. an element is disabled if the disabled-attribute is set, independent of it's value (so, disabled="true", disabled="disabled" and disabled="false" all do the same: the element gets disabled). you should instead remove the complete attribute:

element.removeAttribute("disabled");

or set that property directly:

element.disabled = false;

How to use KeyListener

Here is an SSCCE,

package experiment;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class KeyListenerTester extends JFrame implements KeyListener {

    JLabel label;

    public KeyListenerTester(String s) {
        super(s);
        JPanel p = new JPanel();
        label = new JLabel("Key Listener!");
        p.add(label);
        add(p);
        addKeyListener(this);
        setSize(200, 100);
        setVisible(true);

    }

    @Override
    public void keyTyped(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key typed");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key typed");
        }

    }

    @Override
    public void keyPressed(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key pressed");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key pressed");
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key Released");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key Released");
        }
    }

    public static void main(String[] args) {
        new KeyListenerTester("Key Listener Tester");
    }
}

Additionally read upon these links : How to Write a Key Listener and How to Use Key Bindings

Xcode build failure "Undefined symbols for architecture x86_64"

I also encountered the same problem , the above methods will not work . I accidentally deleted the files in the following directory on it . enter image description here

Or

~/Library/Developer/Xcode/DerivedData/

enter image description here

Execute command without keeping it in history

As mentioned by Doodad in comments, unset HISTFILE does this nicely, but in case you also want to also delete some history, do echo $HISTFILE to get the history file location (usually ~/.bash_history), unset HISTFILE, and edit ~/.bash_history (or whatever HISTFILE was - of course it's now unset so you can't read it).

$ echo $HISTFILE       # E.g. ~/.bash_history
$ unset HISTFILE
$ vi ~/.bash_history   # Or your preferred editor

Then you've edited your history, and the fact that you edited it!

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

Say you let vmware use port 443, and use another ssl port in XAMPP Apache (httpd-ssl.conf) :

The red error will keep popping in XAMPP Control Panel. You also need to change the port in the XAMPP Control Panel configuration :

In XAMPP Control Panel, click the "Config" button (top-left). Then click "Service and Port Settings". There you can set the ports to match the ports used by Apache.

How to run sql script using SQL Server Management Studio?

Found this in another thread that helped me: Use xp_cmdshell and sqlcmd Is it possible to execute a text file from SQL query? - by Gulzar Nazim

EXEC xp_cmdshell  'sqlcmd -S ' + @DBServerName + ' -d  ' + @DBName + ' -i ' + @FilePathName

MySQL DELETE FROM with subquery as condition

You need to refer to the alias again in the delete statement, like:

DELETE th FROM term_hierarchy AS th
....

As outlined here in MySQL docs.

Crop image to specified size and picture location

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

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

How to change the Push and Pop animations in a navigation based app

Just use:

ViewController *viewController = [[ViewController alloc] init];

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
navController.navigationBarHidden = YES;

[self presentViewController:navController animated:YES completion: nil];
[viewController release];
[navController release];

How to use Utilities.sleep() function

Utilities.sleep(milliseconds) creates a 'pause' in program execution, meaning it does nothing during the number of milliseconds you ask. It surely slows down your whole process and you shouldn't use it between function calls. There are a few exceptions though, at least that one that I know : in SpreadsheetApp when you want to remove a number of sheets you can add a few hundreds of millisecs between each deletion to allow for normal script execution (but this is a workaround for a known issue with this specific method). I did have to use it also when creating many sheets in a spreadsheet to avoid the Browser needing to be 'refreshed' after execution.

Here is an example :

function delsheets(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var numbofsheet=ss.getNumSheets();// check how many sheets in the spreadsheet
  for (pa=numbofsheet-1;pa>0;--pa){ 
    ss.setActiveSheet(ss.getSheets()[pa]);
    var newSheet = ss.deleteActiveSheet(); // delete sheets begining with the last one
    Utilities.sleep(200);// pause in the loop for 200 milliseconds
  }
  ss.setActiveSheet(ss.getSheets()[0]);// return to first sheet as active sheet (useful in 'list' function)
}

Strange Jackson exception being thrown when serializing Hibernate object

I faced the same issue and It is really strange that the same code works in few case whereas it failed in some random cases.

I got it fixed by just making sure the proper setter/getter (Making sure the case sensitivity)

What is the "continue" keyword and how does it work in Java?

"continue" in Java means go to end of the current loop, means: if the compiler sees continue in a loop it will go to the next iteration

Example: This is a code to print the odd numbers from 1 to 10

the compiler will ignore the print code whenever it sees continue moving into the next iteration

for (int i = 0; i < 10; i++) { 
    if (i%2 == 0) continue;    
    System.out.println(i+"");
}

Ignore 'Security Warning' running script from command line

Assume that you need to launch ps script from shared folder

copy \\\server\script.ps1 c:\tmp.ps1 /y && PowerShell.exe -ExecutionPolicy Bypass -File c:\tmp.ps1 && del /f c:\tmp.ps1

P.S. Reduce googling)

How do you develop Java Servlets using Eclipse?

Alternatively you can use Jetty which is (now) part of the Eclipe Platform (the Help system is running Jetty). Besides Jetty is used by Android, Windows Mobile..

To get started check the Eclipse Wiki or if you prefer a Video And check out this related Post!

2 column div layout: right column with fixed width, left fluid

I have simplified it : I have edited jackjoe's answer. The height auto etc not required I think.

CSS:

#container {
position: relative;
margin:0 auto;
width: 1000px;
background: #C63;
padding: 10px;
}

#leftCol {
background: #e8f6fe;
width: auto;
}

#rightCol {
float:right;
width:30%;
background: #aafed6;
}

.box {
position:relative;
clear:both;
background:#F39;
 }
</style>

HTML:

<div id="container">

  <div id="rightCol"> 
   <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>

  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
 </div>

 <div id="leftCol">

   <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>

  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

</div>

</div>

<div class="box">
  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>

  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
</div>

Passing variables in remote ssh command

It is also possible to pass environment variables explicitly through ssh. It does require some server-side set-up through, so this this not a universal answer.

In my case, I wanted to pass a backup repository encryption key to a command on the backup storage server without having that key stored there, but note that any environment variable is visible in ps! The solution of passing the key on stdin would work as well, but I found it too cumbersome. In any case, here's how to pass an environment variable through ssh:

On the server, edit the sshd_config file, typically /etc/ssh/sshd_config and add an AcceptEnv directive matching the variables you want to pass. See man sshd_config. In my case, I want to pass variables to borg backup so I chose:

AcceptEnv BORG_*

Now, on the client use the -o SendEnv option to send environment variables. The following command line sets the environment variable BORG_SECRET and then flags it to be sent to the client machine (called backup). It then runs printenv there and filters the output for BORG variables:

$ BORG_SECRET=magic-happens ssh -o SendEnv=BORG_SECRET backup printenv | egrep BORG
BORG_SECRET=magic-happens

How to print all information from an HTTP request to the screen, in PHP

If you want actual HTTP Headers (both request and response), give hurl.it a try.

You can use the PHP command apache_request_headers() to get the request headers and apache_response_headers() to get the current response headers. Note that response can be changed later in the PHP script as long as content has not been served.

Facebook OAuth "The domain of this URL isn't included in the app's domain"

Most of the time its happen with not insert proper valid OAuth redirect URL in the product section of the FB dashboard.I suggest follow my bellow steps

01.Check the basic setting of the app is okay with bellow picture with you

enter image description here

02.check whether you have add a product

If not you can easily add log in product by clicking + sine as I show in the bellow.

If Yes just got to inside of the product setting. enter image description here

03.The check whether you have provide valid OAuth redirect URL

Its simple mean what should after login.It is not other than that your call back URl.You can see in my bellow picture I have added several redirect URLs. enter image description here

  1. have any problem further Watch my video-- > https://www.youtube.com/watch?v=mdhubrzV5y8&t=3s

How to select the first, second, or third element with a given class name?

use nth-child(item number) EX

<div class="parent_class">
    <div class="myclass">my text1</div>
    some other code+containers...

    <div class="myclass">my text2</div>
    some other code+containers...

    <div class="myclass">my text3</div>
    some other code+containers...
</div>
.parent_class:nth-child(1) { };
.parent_class:nth-child(2) { };
.parent_class:nth-child(3) { };

OR

:nth-of-type(item number) same your code

.myclass:nth-of-type(1) { };
.myclass:nth-of-type(2) { };
.myclass:nth-of-type(3) { };

codes for ADD,EDIT,DELETE,SEARCH in vb2010

Have you googled about it - insert update delete access vb.net, there are lots of reference about this.

Insert Update Delete Navigation & Searching In Access Database Using VB.NET

  • Create Visual Basic 2010 Project: VB-Access
  • Assume that, we have a database file named data.mdb
  • Place the data.mdb file into ..\bin\Debug\ folder (Where the project executable file (.exe) is placed)

what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB

is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.

it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:

Example code snippet:

Imports System
Imports System.Data
Imports System.Data.OleDb

Public Class DBUtil

 Private connectionString As String

 Public Sub New()

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=d:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource

 End Sub

 Public Function GetCategories() As DataSet

  Dim query As String = "SELECT * FROM Categories"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Categories")

 End Function

 Public SubUpdateCategories(ByVal name As String)
  Dim query As String = "update Categories set name = 'new2' where name = ?"
  Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
  Return FillDataSet(cmd, "Categories")

 End Sub

 Public Function GetItems() As DataSet

  Dim query As String = "SELECT * FROM Items"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Items")

 End Function

 Public Function GetItems(ByVal categoryID As Integer) As DataSet

  'Create the command.
  Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
  Dim cmd As New OleDbCommand(query)
  cmd.Parameters.AddWithValue("category_ID", categoryID)

  'Fill the dataset.
  Return FillDataSet(cmd, "Items")

 End Function

 Public Sub AddCategory(ByVal name As String)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Categories "
  insertSQL &= "VALUES(?)"
  Dim cmd As New OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Name", name)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Public Sub AddItem(ByVal title As String, ByVal description As String, _
    ByVal price As Decimal, ByVal categoryID As Integer)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Items "
  insertSQL &= "(Title, Description, Price, Category_ID)"
  insertSQL &= "VALUES (?, ?, ?, ?)"
  Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Title", title)
  cmd.Parameters.AddWithValue("Description", description)
  cmd.Parameters.AddWithValue("Price", price)
  cmd.Parameters.AddWithValue("CategoryID", categoryID)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=D:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource
  con.ConnectionString = connectionString
  cmd.Connection = con
  Dim adapter As New OleDbDataAdapter(cmd)
  Dim ds As New DataSet()

  Try
   con.Open()
   adapter.Fill(ds, tableName)
  Finally
   con.Close()
  End Try
  Return ds

 End Function

End Class

Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back

How set maximum date in datepicker dialog in android?

DatePicker dp = (DatePicker) findViewById(R.id.datePicker1);

dp.setMaxDate(new Date().getTime());

Removing all non-numeric characters from string in Python

Not sure if this is the most efficient way, but:

>>> ''.join(c for c in "abc123def456" if c.isdigit())
'123456'

The ''.join part means to combine all the resulting characters together without any characters in between. Then the rest of it is a list comprehension, where (as you can probably guess) we only take the parts of the string that match the condition isdigit.

How to parse an RSS feed using JavaScript?

Trying to find a good solution for this now, I happened upon the FeedEk jQuery RSS/ATOM Feed Plugin that does a great job of parsing and displaying RSS and Atom feeds via the jQuery Feed API. For a basic XML-based RSS feed, I've found it works like a charm and needs no server-side scripts or other CORS workarounds for it to run even locally.

How to change package name in flutter?

To change package name in flutter , you have to do it for all platforms.

To make it easier, I suggest you to use rename package .

Just run this command inside your flutter project root.

pub global run rename --bundleId com.onat.networkApp

Here, com.onat.networkApp is your package name

To target a specific platform use the "-t" option. e.g:

pub global run rename --bundleId com.example.android.app -t android

You can learn more about rename package here

@Media min-width & max-width

The underlying issue is using max-device-width vs plain old max-width.

Using the "device" keyword targets physical dimension of the screen, not the width of the browser window.

For example:

@media only screen and (max-device-width: 480px) {
    /* STYLES HERE for DEVICES with physical max-screen width of 480px */
}

Versus

@media only screen and (max-width: 480px) {
    /* STYLES HERE for BROWSER WINDOWS with a max-width of 480px. 
       This will work on desktops when the window is narrowed.  */
}

Why do I get an error instantiating an interface?

You can't instantiate interfaces or abstract classes.

That's because it wouldn't have any logic to it.

Interfaces provide a contract of the methods that should be in a class, without implementation. (So there's no actual logic in the interface).

Abstract classes provide basic logic of a class, but are not fully functional (not everything is implemented). So again, you won't be able to do anything with it.

How to style a checkbox using CSS

You can simply use appearance: none on modern browsers, so that there is no default styling and all your styles are applied properly:

input[type=checkbox] {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  display: inline-block;
  width: 2em;
  height: 2em;
  border: 1px solid gray;
  outline: none;
  vertical-align: middle;
}

input[type=checkbox]:checked {
  background-color: blue;
}

Sorting object property by values

let toSort = {a:2323, b: 14, c: 799} 
let sorted = Object.entries(toSort ).sort((a,b)=> a[1]-b[1]) 

Output:

[ [ "b", 14 ], [ "c", 799 ], [ "a", 2323 ] ]

Language Books/Tutorials for popular languages

For Javascript:

For PHP:

For OO design & programming, patterns:

For Refactoring:

For SQL/MySQL:

Proper way to assert type of variable in Python

You might want to try this example for version 2.6 of Python.

def my_print(text, begin, end):
    "Print text in UPPER between 'begin' and 'end' in lower."
    for obj in (text, begin, end):
        assert isinstance(obj, str), 'Argument of wrong type!'
    print begin.lower() + text.upper() + end.lower()

However, have you considered letting the function fail naturally instead?

What permission do I need to access Internet from an Android application?

just put above line like below

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.avocats.activeavocats"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="9"
    android:targetSdkVersion="16" />

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

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >


    <activity
        android:name="com.example.exp.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

Please run and re reconfigure your phpmyadmin

sudo dpkg-reconfigure phpmyadmin

Convert byte slice to io.Reader

r := strings(byteData)

This also works to turn []byte into io.Reader

PostgreSQL Crosstab Query

Solution with JSON aggregation:

CREATE TEMP TABLE t (
  section   text
, status    text
, ct        integer  -- don't use "count" as column name.
);

INSERT INTO t VALUES 
  ('A', 'Active', 1), ('A', 'Inactive', 2)
, ('B', 'Active', 4), ('B', 'Inactive', 5)
                   , ('C', 'Inactive', 7); 


SELECT section,
       (obj ->> 'Active')::int AS active,
       (obj ->> 'Inactive')::int AS inactive
FROM (SELECT section, json_object_agg(status,ct) AS obj
      FROM t
      GROUP BY section
     )X

What's the environment variable for the path to the desktop?

I found that the best solution is to use a vbscript together with the batch file.

Here is the batch file:

@ECHO OFF
FOR /F "usebackq delims=" %%i in (`cscript findDesktop.vbs`) DO SET DESKTOPDIR=%%i
ECHO %DESKTOPDIR%

Here is findDesktop.vbs file:

set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
wscript.echo(strDesktop)

There may be other solutions but I personally find this one less hackish.

I tested this on an English PC and also a French PC - it seems to work (Windows XP).

HTH,

Iulian Serbanoiu

The APK file does not exist on disk

The button is called "Sync Project with Gradle Files" and it looks alike: Gradle Sync... always need to click it, when updating the version number, which is resulting in another APK filename (unless the filename has not changed, installing the package always works, which hints for, that the filename is being cached). The equivalent Gradle CLI option appears to be --recompile-scripts.

@see Appendix D. Gradle Command Line.

PHP Undefined Index

if you use isset like the answer posted already by singles, just make sure there is a bracket at the end like so:
$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);

Capture keyboardinterrupt in Python without try-except

I know this is an old question but I came here first and then discovered the atexit module. I do not know about its cross-platform track record or a full list of caveats yet, but so far it is exactly what I was looking for in trying to handle post-KeyboardInterrupt cleanup on Linux. Just wanted to throw in another way of approaching the problem.

I want to do post-exit clean-up in the context of Fabric operations, so wrapping everything in try/except wasn't an option for me either. I feel like atexit may be a good fit in such a situation, where your code is not at the top level of control flow.

atexit is very capable and readable out of the box, for example:

import atexit

def goodbye():
    print "You are now leaving the Python sector."

atexit.register(goodbye)

You can also use it as a decorator (as of 2.6; this example is from the docs):

import atexit

@atexit.register
def goodbye():
    print "You are now leaving the Python sector."

If you wanted to make it specific to KeyboardInterrupt only, another person's answer to this question is probably better.

But note that the atexit module is only ~70 lines of code and it would not be hard to create a similar version that treats exceptions differently, for example passing the exceptions as arguments to the callback functions. (The limitation of atexit that would warrant a modified version: currently I can't conceive of a way for the exit-callback-functions to know about the exceptions; the atexit handler catches the exception, calls your callback(s), then re-raises that exception. But you could do this differently.)

For more info see:

How can I change image source on click with jQuery?

You can use jQuery's attr() function, like $("#id").attr('src',"source").

How to read a CSV file from a URL with Python?

You could do it with the requests module as well:

url = 'http://winterolympicsmedals.com/medals.csv'
r = requests.get(url)
text = r.iter_lines()
reader = csv.reader(text, delimiter=',')

Action bar navigation modes are deprecated in Android L

The new Toolbar cannot be used for inflating multiple line objects, so it is impossible to add Tabs to it.
If you want to use a Toolbar like a TabWidget you can insert some Tab Objects to it, but only with the old Holo style.

Here there is a custom Library that uses v7 Toolbar like TabWidget with the new Material Design animations, but it uses the same methods from the old ActionBar Tabs, so you can attach your ViewPager to it.

Add a string of text into an input field when user clicks a button

this will do it with just javascript - you can also put the function in a .js file and call it with onclick

//button
<div onclick="
   document.forms['name_of_the_form']['name_of_the_input'].value += 'text you want to add to it'"
>button</div>

How to print to console in pytest?

Using -s option will print output of all functions, which may be too much.

If you need particular output, the doc page you mentioned offers few suggestions:

  1. Insert assert False, "dumb assert to make PyTest print my stuff" at the end of your function, and you will see your output due to failed test.

  2. You have special object passed to you by PyTest, and you can write the output into a file to inspect it later, like

    def test_good1(capsys):
        for i in range(5):
            print i
        out, err = capsys.readouterr()
        open("err.txt", "w").write(err)
        open("out.txt", "w").write(out)
    

    You can open the out and err files in a separate tab and let editor automatically refresh it for you, or do a simple py.test; cat out.txt shell command to run your test.

That is rather hackish way to do stuff, but may be it is the stuff you need: after all, TDD means you mess with stuff and leave it clean and silent when it's ready :-).

Is it possible to get element from HashMap by its position?

HashMaps don't allow access by position, it only knows about the hash code and and it can retrieve the value if it can calculate the hash code of the key. TreeMaps have a notion of ordering. Linkedhas maps preserve the order in which they entered the map.

Why do this() and super() have to be the first statement in a constructor?

Because the JLS says so. Could the JLS be changed in a compatible manner to allow it? Yup.

However, it would complicate the language spec, which is already more than complicated enough. It wouldn't be a highly useful thing to do and there are ways around it (call another constructor with the result of a static method or lambda expression this(fn()) - the method is called before the other constructor, and hence also the super constructor). So the power to weight ratio of doing the change is unfavourable.

Note that this rule alone does not prevent use of fields before the super class has completed construction.

Consider these illegal examples.

super(this.x = 5);

super(this.fn());

super(fn());

super(x);

super(this instanceof SubClass);
// this.getClass() would be /really/ useful sometimes.

This example is legal, but "wrong".

class MyBase {
    MyBase() {
        fn();
    }
    abstract void fn();
}
class MyDerived extends MyBase {
    void fn() {
       // ???
    }
}

In the above example, if MyDerived.fn required arguments from the MyDerived constructor they would need to be sleazed through with a ThreadLocal. ;(

Incidentally, since Java 1.4, the synthetic field that contains the outer this is assigned before inner classes super constructor is called. This caused peculiar NullPointerException events in code compiled to target earlier versions.

Note also, in the presence of unsafe publication, construction can be viewed reordered by other threads, unless precautions are made.

Edit March 2018: In message Records: construction and validation Oracle is suggesting this restriction be removed (but unlike C#, this will be definitely unassigned (DU) before constructor chaining).

Historically, this() or super() must be first in a constructor. This restriction was never popular, and perceived as arbitrary. There were a number of subtle reasons, including the verification of invokespecial, that contributed to this restriction. Over the years, we've addressed these at the VM level, to the point where it becomes practical to consider lifting this restriction, not just for records, but for all constructors.

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

Android SDK Build Tools are exactly what the name says they are; tools for building Android Applications.It is very important to use the latest build tools version (selected automatically by your IDE via the Android SDK) but the reason the old versions are left there is to support backward compatibility, that is If your projects depend on older versions of the Build Tools.

Beamer: How to show images as step-by-step images

This is what I did:

\begin{frame}{series of images}
\begin{center}
\begin{overprint}

\only<2>{\includegraphics[scale=0.40]{image1.pdf}}
\hspace{-0.17em}\only<3>{\includegraphics[scale=0.40]{image2.pdf}}
\hspace{-0.34em}\only<4>{\includegraphics[scale=0.40]{image3.pdf}}
\hspace{-0.17em}\only<5>{\includegraphics[scale=0.40]{image4.pdf}}

\only<2-5>{\mbox{\structure{Figure:} something}}

\end{overprint}
\end{center}
\end{frame}

Bootstrap 4 responsive tables won't take up 100% width

The following WON'T WORK. It causes another issue. It will now do the 100% width but it won't be responsive on smaller devices:

.table-responsive {
    display: table;
}

All these answers introduced another problem by recommending display: table;. The only solution as of right now is to use it as a wrapper:

<div class="table-responsive">
  <table class="table">
...
 </table>
</div>

How to increase Bootstrap Modal Width?

In Bootstrap 3 you need to change the modal-dialog. So, in this case, you can add the class modal-admin in the place where modal-dialog stands.

@media (min-width: 768px) {
  .modal-dialog {
    width: 600;
    margin: 30px auto;
  }
  .modal-content {
    -webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
            box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
  }
  .modal-sm {
    width: 300px;
  }
}

Configure Nginx with proxy_pass

Nginx prefers prefix-based location matches (not involving regular expression), that's why in your code block, /stash redirects are going to /.

The algorithm used by Nginx to select which location to use is described thoroughly here: https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms#matching-location-blocks

HTML Form: Select-Option vs Datalist-Option

From a technical point of view they're completely different. <datalist> is an abstract container of options for other elements. In your case you've used it with <input type="text" but you can also use it with ranges, colors, dates etc. http://demo.agektmr.com/datalist/

If using it with text input, as a type of autocomplete, then the question really is: Is it better to use a free-form text input, or a predetermined list of options? In that case I think the answer is a bit more obvious.

If we focus on the use of <datalist> as a list of options for a text field then here are some specific differences between that and a select box:

  • A <datalist> fed text box has a single string for both display label and submit. A select box can have a different submit value vs. display label <option value='ie'>Internet Explorer</option>.
  • A <datalist> fed text box does not support the <optgroup> tag to organize the display.
  • You can not restrict a user to the list of options in a <datalist> like you can with a <select>.
  • The onchange event works differently. On a <select> element, the onchange event is fired immediately upon change, whereas with <input type="text" the event is fired after the element loses focus or the user presses enter.
  • <datalist> has really spotty support across browsers. The way to show all available options is inconsistent, and things only get worse from there.

The last point is really the big one in my opinion. Since you will HAVE to have a more universal autocomplete fallback, then there is almost no reason to go through the trouble of configuring a <datalist>. Plus any decent autocomplete pluging will allow for ways to style the display of your options, which <datalist> does not do. If <datalist> accepted <li> elements that you could manipulate however you want, it would have been really great! But NO.

Also insofar as i can tell, the <datalist> search is an exact match from the beginning of the string. So if you had <option value="internet explorer"> and you searched for 'explorer' you would get no results. Most autocomplete plugins will search anywhere in the text.

I've only used <datalist> as a quick and lazy convenience helper for some internal pages where I know with a 100% certainty that the users have the latest Chrome or Firefox, and will not try to submit bogus values. For any other case, it's hard to recommend the use of <datalist> due to very poor browser support.

View HTTP headers in Google Chrome?

For Version 78.0.3904.87, OS = Windows 7, 64 bit PC

Steps:

  1. Press F12
  2. Select Network Tab
  3. Select XHR
  4. Under Name --> you can see all the XHR requests made.
  5. To view Request Headers of a particular XHR request, click on that request. All details about that XHR request will appear on right hand side.

Creating a triangle with for loops

First think of a solution without code. The idea is to print an odd number of *, increasing by line. Then center the * by using spaces. Knowing the max number of * in the last line, will give you the initial number of spaces to center the first *. Now write it in code.

Remove the legend on a matplotlib figure

According to the information from @naitsirhc, I wanted to find the official API documentation. Here are my finding and some sample code.

  1. I created a matplotlib.Axes object by seaborn.scatterplot().
  2. The ax.get_legend() will return a matplotlib.legned.Legend instance.
  3. Finally, you call .remove() function to remove the legend from your plot.
ax = sns.scatterplot(......)
_lg = ax.get_legend()
_lg.remove()

If you check the matplotlib.legned.Legend API document, you won't see the .remove() function.

The reason is that the matplotlib.legned.Legend inherited the matplotlib.artist.Artist. Therefore, when you call ax.get_legend().remove() that basically call matplotlib.artist.Artist.remove().

In the end, you could even simplify the code into two lines.

ax = sns.scatterplot(......)
ax.get_legend().remove()

How do I print the percent sign(%) in c

Use "%%". The man page describes this requirement:

% A '%' is written. No argument is converted. The complete conversion specification is '%%'.

How do I get formatted JSON in .NET using C#?

For UTF8 encoded JSON file using .NET Core 3.1, I was finally able to use JsonDocument based upon this information from Microsoft: https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to#utf8jsonreader-utf8jsonwriter-and-jsondocument

string allLinesAsOneString = string.Empty;
string [] lines = File.ReadAllLines(filename, Encoding.UTF8);
foreach(var line in lines)
    allLinesAsOneString += line;

JsonDocument jd = JsonDocument.Parse(Encoding.UTF8.GetBytes(allLinesAsOneString));
var writer = new Utf8JsonWriter(Console.OpenStandardOutput(), new JsonWriterOptions
{
    Indented = true
});
JsonElement root = jd.RootElement;
if( root.ValueKind == JsonValueKind.Object )
{
    writer.WriteStartObject();
}
foreach (var jp in root.EnumerateObject())
    jp.WriteTo(writer);
writer.WriteEndObject();

writer.Flush();

IntelliJ Organize Imports

Just move your mouse over the missing view and hit keys on windows ALT + ENTER

Why do multiple-table joins produce duplicate rows?

This might sound like a really basic "DUH" answer, but make sure that the column you're using to Lookup from on the merging file is actually full of unique values!

I noticed earlier today that PowerQuery won't throw you an error (like in PowerPivot) and will happily allow you to run a Many-Many merge. This will result in multiple rows being produced for each record that matches with a non-unique value.

How to add time to DateTime in SQL

DECLARE @DDate      date        -- To store the current date
DECLARE @DTime      time        -- To store the current time
DECLARE @DateTime   datetime    -- To store the result of the concatenation
;
SET @DDate      =   GETDATE()   -- Getting the current date
SET @DTime      =   GETDATE()   -- Getting the current time



SET @DateTime   =   CONVERT(datetime, CONVERT(varchar(19), LTRIM(@DDate) + ' ' + LTRIM(@DTime) ));
;
/*
    1. LTRIM the date and time do an automatic conversion of both types to string.
    2. The inside CONVERT to varchar(19) is needed, because you cannot do a direct conversion to datetime
    3. Once the inside conversion is done, the second do the final conversion to datetime.
*/  

-- The following select shows the initial variables and the result of the concatenation
SELECT @DDate, @DTime, @DateTime

How do I `jsonify` a list in Flask?

josonify works..but if you intend to just pass an array without the 'results' key, you can use json library from python. The following conversion works for me..

 import json

 @app.route('/test/json')
 def test_json():
 list = [
        {'a': 1, 'b': 2},
        {'a': 5, 'b': 10}
       ]
 return json.dumps(list))

How to escape a while loop in C#

"break" is a command that breaks out of the "closest" loop.

While there are many good uses for break, you shouldn't use it if you don't have to -- it can be seen as just another way to use goto, which is considered bad.

For example, why not:

while (!(the condition you're using to break))
        {
         //Your code here.
        }

If the reason you're using "break" is because you don't want to continue execution of that iteration of the loop, you may want to use the "continue" keyword, which immediately jumps to the next iteration of the loop, whether it be while or for.

while (!condition) {
   //Some code
   if (condition) continue;
   //More code that will be skipped over if the condition was true
}

Convert number to month name in PHP

To do the conversion in respect of the current locale, you can use the strftime function:

setlocale(LC_TIME, 'fr_FR.UTF-8');                                              
$monthName = strftime('%B', mktime(0, 0, 0, $monthNumber));

date doesn't respect the locale, strftime does.

How would I create a UIAlertView in Swift?

// Custom Class For UIAlertView

//MARK:- MODULES
import Foundation
import UIKit

//MARK:- CLASS
class Alert  : NSObject{

static let shared = Alert()

var okAction : AlertSuccess?
typealias AlertSuccess = (()->())?
var alert: UIAlertController?

/** show */
public func show(title : String?, message : String?, viewController : UIViewController?, okAction : AlertSuccess = nil) {

    let version : NSString = UIDevice.current.systemVersion as NSString
    if  version.doubleValue >= 8 {
        alert = UIAlertController(title: title, message: message, preferredStyle:.alert)
        alert?.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction) in

            if let okAction = okAction {
                okAction()
            }
        }))
        viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil);
    }
}

/** showWithCancelAndOk */
public func showWithCancelAndOk(title : String, okTitle : String, cancelTitle : String, message : String, viewController : UIViewController?, okAction : AlertSuccess = nil, cancelAction : AlertSuccess = nil) {
    let version:NSString = UIDevice.current.systemVersion as NSString;

    if  version.doubleValue >= 8 {
        alert = UIAlertController(title: title, message: message, preferredStyle:.alert)

        alert?.addAction(UIAlertAction(title: cancelTitle, style: .default, handler: { (action: UIAlertAction) in

            if let cancelAction = cancelAction {
                cancelAction()
            }
        }))
        alert?.addAction(UIAlertAction(title: okTitle, style: .default, handler: { (action: UIAlertAction) in

            if let okAction = okAction {
                okAction()
            }
        }))
        viewController?.present(alert!, animated:true, completion:nil);
    }
}

/** showWithTimer */
public func showWithTimer(message : String?, viewController : UIViewController?) {

    let version : NSString = UIDevice.current.systemVersion as NSString
    if  version.doubleValue >= 8 {
        alert = UIAlertController(title: "", message: message, preferredStyle:.alert)
        viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil)
        let when = DispatchTime.now() + 1
        DispatchQueue.main.asyncAfter(deadline: when){
            self.alert?.dismiss(animated: true, completion: nil)
        }
    }
}
}

Use:-

Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self) //without ok action

Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
                            //ok action
                        }) // with ok action

Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
                            //ok action 
}, cancelAction: {
 //cancel action
}) //with cancel and ok action

Alert.shared.showWithTimer(message : "This is an alert with timer", viewController : self) //with timer

font-weight is not working properly?

I removed the text-transform: uppercase; and then set it to bold/bolder, and this seemed to work.

Reference member variables as class members

Is there a name to describe this idiom?

In UML it is called aggregation. It differs from composition in that the member object is not owned by the referring class. In C++ you can implement aggregation in two different ways, through references or pointers.

I am assuming it is to prevent the possibly large overhead of copying a big complex object?

No, that would be a really bad reason to use this. The main reason for aggregation is that the contained object is not owned by the containing object and thus their lifetimes are not bound. In particular the referenced object lifetime must outlive the referring one. It might have been created much earlier and might live beyond the end of the lifetime of the container. Besides that, the state of the referenced object is not controlled by the class, but can change externally. If the reference is not const, then the class can change the state of an object that lives outside of it.

Is this generally good practice? Are there any pitfalls to this approach?

It is a design tool. In some cases it will be a good idea, in some it won't. The most common pitfall is that the lifetime of the object holding the reference must never exceed the lifetime of the referenced object. If the enclosing object uses the reference after the referenced object was destroyed, you will have undefined behavior. In general it is better to prefer composition to aggregation, but if you need it, it is as good a tool as any other.

gpg decryption fails with no secret key error

Looks like the secret key isn't on the other machine, so even with the right passphrase (read from a file) it wouldn't work.

These options should work, to

  • Either copy the keyrings (maybe only secret keyring required, but public ring is public anyway) over to the other machine
  • Or export the secret key & then import it on the other machine

A few useful looking options from man gpg:

--export
Either export all keys from all keyrings (default keyrings and those registered via option --keyring), or if at least one name is given, those of the given name. The new keyring is written to STDOUT or to the file given with option --output. Use together with --armor to mail those keys.

--export-secret-keys
Same as --export, but exports the secret keys instead.

--import
--fast-import
Import/merge keys. This adds the given keys to the keyring. The fast version is currently just a synonym.

And maybe

--keyring file
Add file to the current list of keyrings. If file begins with a tilde and a slash, these are replaced by the $HOME directory. If the file- name does not contain a slash, it is assumed to be in the GnuPG home directory ("~/.gnupg" if --homedir or $GNUPGHOME is not used).

Note that this adds a keyring to the current list. If the intent is to use the specified keyring alone, use --keyring along with --no-default-keyring.

--secret-keyring file
Same as --keyring but for the secret keyrings.

Java integer list

If you want to rewrite a line on console, print a control character \r (carriage return).

List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
Iterator<Integer> myListIterator = myCoords.iterator(); 
while (myListIterator.hasNext()) {
    Integer coord = myListIterator.next();     
    System.out.print("\r");
    System.out.print(coord);
    Thread.sleep(2000);
}

How to commit changes to a new branch

git checkout -b your-new-branch

git add <files>

git commit -m <message>

First, checkout your new branch. Then add all the files you want to commit to staging. Lastly, commit all the files you just added. You might want to do a git push origin your-new-branch afterward so your changes show up on the remote.

Adding an item to an associative array

before for loop :

$data = array();

then in your loop:

$data[] = array($catagory => $question);

ld cannot find an existing library

Unless I'm badly mistaken libmagic or -lmagic is not the same library as ImageMagick. You state that you want ImageMagick.

ImageMagick comes with a utility to supply all appropriate options to the compiler.

Ex:

g++ program.cpp `Magick++-config --cppflags --cxxflags --ldflags --libs` -o "prog"

What is REST call and how to send a REST call?

REST is somewhat of a revival of old-school HTTP, where the actual HTTP verbs (commands) have semantic meaning. Til recently, apps that wanted to update stuff on the server would supply a form containing an 'action' variable and a bunch of data. The HTTP command would almost always be GET or POST, and would be almost irrelevant. (Though there's almost always been a proscription against using GET for operations that have side effects, in reality a lot of apps don't care about the command used.)

With REST, you might instead PUT /profiles/cHao and send an XML or JSON representation of the profile info. (Or rather, I would -- you would have to update your own profile. :) That'd involve logging in, usually through HTTP's built-in authentication mechanisms.) In the latter case, what you want to do is specified by the URL, and the request body is just the guts of the resource involved.

http://en.wikipedia.org/wiki/Representational_State_Transfer has some details.

What's the difference between compiled and interpreted language?

Here is the Basic Difference between Compiler vs Interpreter Language.

Compiler Language

  • Takes entire program as single input and converts it into object code which is stored in the file.
  • Intermediate Object code is generated
  • e.g: C,C++
  • Compiled programs run faster because compilation is done before execution.
  • Memory requirement is more due to the creation of object code.
  • Error are displayed after the entire program is compiled
  • Source code ---Compiler ---Machine Code ---Output

Interpreter Language:

  • Takes single instruction as single input and executes instructions.
  • Intermediate Object code is NOT generated
  • e.g: Perl, Python, Matlab
  • Interpreted programs run slower because compilation and execution take place simultaneously.
  • Memory requirement is less.
  • Error are displayed for every single instruction.
  • Source Code ---Interpreter ---Output

How do I fix "The expression of type List needs unchecked conversion...'?

Even easier

return new ArrayList<?>(getResultOfHibernateCallback(...))

Implement a loading indicator for a jQuery AJAX call

This is how I realised the loading indicator by an Glyphicon:

<!DOCTYPE html>
<html>

<head>
    <title>Demo</title>

    <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/bootstrap.min.js"></script>

    <style>
        .gly-ani {
          animation: ani 2s infinite linear;
        }
        @keyframes ani {
          0% {
            transform: rotate(0deg);
          }
          100% {
            transform: rotate(359deg);
          }
        }
    </style>  
</head>

<body>
<div class="container">

    <span class="glyphicon glyphicon-refresh gly-ani" style="font-size:40px;"></span>

</div>
</body>

</html>

How can I keep Bootstrap popovers alive while being hovered?

I found the mouseleave will not fire when weird things happen, like the window focus changes suddenly, then the user comes back to the browser. In cases like that, mouseleave will never fire until the cursor goes over and leaves the element again.

This solution I came up with relies on mouseenter on the window object, so it disappears when the mouse is moved anywhere else on the page.

This was designed to work with having multiple elements on the page that will trigger it (like in a table).

var allMenus = $(".menus");
allMenus.popover({
    html: true,
    trigger: "manual",
    placement: "bottom",
    content: $("#menuContent")[0].outerHTML
}).on("mouseenter", (e) => {
    allMenus.not(e.target).popover("hide");
    $(e.target).popover("show");
    e.stopPropagation();
}).on("shown.bs.popover", () => {
    $(window).on("mouseenter.hidepopover", (e) => {
        if ($(e.target).parents(".popover").length === 0) {
            allMenus.popover("hide");
            $(window).off("mouseenter.hidepopover");
        }
    });
});

A non well formed numeric value encountered

This helped me a lot -

$new_date = date_format(date_create($old_date), 'Y-m-d');

Here, date_create() provides you a date object for a given date & date_format() will set it in a given format.

for example,

<?php
    $date = date_create("13-02-2013");  // DateTime Object ( [date] => 2013-02-13 00:00:00.000000 [timezone_type] => 3 [timezone] => America/New_York )
    echo date_format($date,"Y-m-d");    // 2013-02-13
?>

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

Towards the second half of Create REST API using ASP.NET MVC that speaks both JSON and plain XML, to quote:

Now we need to accept JSON and XML payload, delivered via HTTP POST. Sometimes your client might want to upload a collection of objects in one shot for batch processing. So, they can upload objects using either JSON or XML format. There's no native support in ASP.NET MVC to automatically parse posted JSON or XML and automatically map to Action parameters. So, I wrote a filter that does it."

He then implements an action filter that maps the JSON to C# objects with code shown.

PHP json_encode json_decode UTF-8

Try sending the UTF-8 Charset header:

<?php header ('Content-type: text/html; charset=utf-8'); ?>

And the HTML meta:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

React.js: Wrapping one component into another

Try:

var Wrapper = React.createClass({
  render: function() {
    return (
      <div className="wrapper">
        before
          {this.props.children}
        after
      </div>
    );
  }
});

See Multiple Components: Children and Type of the Children props in the docs for more info.

How to center links in HTML

p is not how you put text in a. That is the problem. The only solution is to put the text between <a> and </a>. For example:

<a href="https://stackoverflow.com/posts/64201994/edit" style="text-align:center;">Stack Overflow</a>

Left Join With Where Clause

When making OUTER JOINs (ANSI-89 or ANSI-92), filtration location matters because criteria specified in the ON clause is applied before the JOIN is made. Criteria against an OUTER JOINed table provided in the WHERE clause is applied after the JOIN is made. This can produce very different result sets. In comparison, it doesn't matter for INNER JOINs if the criteria is provided in the ON or WHERE clauses -- the result will be the same.

  SELECT  s.*, 
          cs.`value`
     FROM SETTINGS s
LEFT JOIN CHARACTER_SETTINGS cs ON cs.setting_id = s.id
                               AND cs.character_id = 1

NavigationBar bar, tint, and title text color in iOS 8

In Swift5 and Xcode 10

self.navigationItem.title = "your name"
let textAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white]
navigationController?.navigationBar.titleTextAttributes = textAttributes

.htaccess file to allow access to images folder to view pictures?

Give permission in .htaccess as follows:

<Directory "Your directory path/uploads/">
Allow from all
</Directory>

Laravel Pagination links not including other GET parameters

I think you should use this code in Laravel version 5+. Also this will work not only with parameter page but also with any other parameter(s):

$users->appends(request()->input())->links();

Personally, I try to avoid using Facades as much as I can. Using global helper functions is less code and much elegant.

UPDATE:

Do not use Input Facade as it is deprecated in Laravel v6+

How can I force clients to refresh JavaScript files?

The jQuery function getScript can also be used to ensure that a js file is indeed loaded every time the page is loaded.

This is how I did it:

$(document).ready(function(){
    $.getScript("../data/playlist.js", function(data, textStatus, jqxhr){
         startProgram();
    });
});

Check the function at http://api.jquery.com/jQuery.getScript/

By default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested.

How can I set a custom baud rate on Linux?

There is an serial I/O chip on your motherboard's CPU (16650 UART). This chip uses 8-bit port as control and data bus, and thus you can issue a command to it through writing to this chip through the control and data bus.

Usually, an application did the following steps on the serial port

  1. Set baud rate, parity, encoding, flow control, and starting / ending sequence length during program start. This setup can be done via ioctl to the serial device or 'stty' command. In fact, the stty command uses ioctl to that serial device.
  2. Write characters of data to the serial device and the driver will be writing data charaters to the UART chip through its 8-bit data bus.

In short, you can specify the baud rate only in the STTY command, and then all other options would be kept as default, and it should enough to connect to ohter devices.

How do I display a decimal value to 2 decimal places?

Mike M.'s answer was perfect for me on .NET, but .NET Core doesn't have a decimal.Round method at the time of writing.

In .NET Core, I had to use:

decimal roundedValue = Math.Round(rawNumber, 2, MidpointRounding.AwayFromZero);

A hacky method, including conversion to string, is:

public string FormatTo2Dp(decimal myNumber)
{
    // Use schoolboy rounding, not bankers.
    myNumber = Math.Round(myNumber, 2, MidpointRounding.AwayFromZero);

    return string.Format("{0:0.00}", myNumber);
}

Performance of Java matrix math libraries?

You may want to check out the jblas project. It's a relatively new Java library that uses BLAS, LAPACK and ATLAS for high-performance matrix operations.

The developer has posted some benchmarks in which jblas comes off favourably against MTJ and Colt.

Convert a timedelta to days, hours and minutes

I don't understand

days, hours, minutes = td.days, td.seconds // 3600, td.seconds // 60 % 60

how about this

days, hours, minutes = td.days, td.seconds // 3600, td.seconds % 3600 / 60.0

You get minutes and seconds of a minute as a float.

What do Clustered and Non clustered index actually mean?

Clustered Index - A clustered index defines the order in which data is physically stored in a table. Table data can be sorted in only way, therefore, there can be only one clustered index per table. In SQL Server, the primary key constraint automatically creates a clustered index on that particular column.

Non-Clustered Index - A non-clustered index doesn’t sort the physical data inside the table. In fact, a non-clustered index is stored at one place and table data is stored in another place. This is similar to a textbook where the book content is located in one place and the index is located in another. This allows for more than one non-clustered index per table.It is important to mention here that inside the table the data will be sorted by a clustered index. However, inside the non-clustered index data is stored in the specified order. The index contains column values on which the index is created and the address of the record that the column value belongs to.When a query is issued against a column on which the index is created, the database will first go to the index and look for the address of the corresponding row in the table. It will then go to that row address and fetch other column values. It is due to this additional step that non-clustered indexes are slower than clustered indexes

Differences between clustered and Non-clustered index

  1. There can be only one clustered index per table. However, you can create multiple non-clustered indexes on a single table.
  2. Clustered indexes only sort tables. Therefore, they do not consume extra storage. Non-clustered indexes are stored in a separate place from the actual table claiming more storage space.
  3. Clustered indexes are faster than non-clustered indexes since they don’t involve any extra lookup step.

For more information refer to this article.

Convert an object to an XML string

    public static string Serialize(object dataToSerialize)
    {
        if(dataToSerialize==null) return null;

        using (StringWriter stringwriter = new System.IO.StringWriter())
        {
            var serializer = new XmlSerializer(dataToSerialize.GetType());
            serializer.Serialize(stringwriter, dataToSerialize);
            return stringwriter.ToString();
        }
    }

    public static T Deserialize<T>(string xmlText)
    {
        if(String.IsNullOrWhiteSpace(xmlText)) return default(T);

        using (StringReader stringReader = new System.IO.StringReader(xmlText))
        {
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stringReader);
        }
    }

change values in array when doing foreach

Javascript is pass by value, and which essentially means part is a copy of the value in the array.

To change the value, access the array itself in your loop.

arr[index] = 'new value';

How to remove application from app listings on Android Developer Console

Note: Adding a new answer as the publish/unpublish option is moved to different location.

As mentioned in other answers you cannot delete the app. With updated Google Play Console (Beta), the Unpublish option is moved to different location:

Setup -> Advanced Settings -> App Availability

Enable Published / Unpublished accordingly!

enter image description here

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

You can use fall-through:

switch (pageid)
{
    case "listing-page":
    case "home-page":
        alert("hello");
        break;
    case "details-page":
        alert("goodbye");
        break;
}

LINQ: Select where object does not contain items from list

dump this into a more specific collection of just the ids you don't want

var notTheseBarIds = filterBars.Select(fb => fb.BarId);

then try this:

fooSelect = (from f in fooBunch
             where !notTheseBarIds.Contains(f.BarId)
             select f).ToList();

or this:

fooSelect = fooBunch.Where(f => !notTheseBarIds.Contains(f.BarId)).ToList();

How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?

This seemed to work for me:

LocationManager locMan = (LocationManager) activity.getSystemService(activity.LOCATION_SERVICE);
long networkTS = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getTime();

Working on Android 2.2 API (Level 8)

Android - how to make a scrollable constraintlayout?

For completing the previous answers I am adding the following example, which also takes into account the use of the AppBar. With this code, the Android Studio design editor seems to work fine with the ConstraintLayout.

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:background="@drawable/bg"
    android:orientation="vertical">

<android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.ActionBar.AppOverlayTheme">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/AppTheme.PopupOverlay"/>
</android.support.design.widget.AppBarLayout>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/image_id"
            android:layout_width="match_parent"
            android:layout_height="@dimen/app_bar_height"
            android:fitsSystemWindows="true"
            android:scaleType="centerCrop"
            android:src="@drawable/intro"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="parent" />

        <TextView
            android:id="@+id/desc_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/text_margin"
            android:text="@string/intro_desc"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/image_id" />

        <Button
            android:id="@+id/button_scan"
            style="?android:textAppearanceSmall"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:backgroundTint="@color/colorAccent"
            android:padding="8dp"
            android:text="@string/intro_button_scan"
            android:textStyle="bold"
            app:layout_constraintTop_toBottomOf="@+id/desc_id" />

        <Button
            android:id="@+id/button_return"
            style="?android:textAppearanceSmall"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginTop="8dp"
            android:backgroundTint="@color/colorAccent"
            android:padding="8dp"
            android:text="@string/intro_button_return"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/button_recycle" />

        <Button
            android:id="@+id/button_recycle"
            style="?android:textAppearanceSmall"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:backgroundTint="@color/colorAccent"
            android:padding="8dp"
            android:text="@string/intro_button_recycle"
            android:textStyle="bold"
            app:layout_constraintTop_toBottomOf="@+id/button_scan" />
    </android.support.constraint.ConstraintLayout>
</ScrollView>
</LinearLayout>

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

Solved 403: Forbidden when visiting localhost. Using ports 80,443,3308 (the later to handle conflict with MySQL Server installation) Windows 10, XAMPP 7.4.1, Apache 2.4.x My web files are in a separate folder.

httpd.conf - look for these lines and set it up where you have your files, mine is web folder.

DocumentRoot "C:/web"
<Directory "C:/web">

Changed these 2 lines.

<VirtualHost *:80>
 ServerAdmin [email protected]
 DocumentRoot "C:/web/project1"
 ServerName project1.localhost
 <Directory "C:/web/project1">
  Order allow,deny
  allow from all
 </Directory>
</VirtualHost>

to this

<VirtualHost *:80>
 ServerAdmin [email protected]
 DocumentRoot "C:/web/project1"
 ServerName project1.localhost
 <Directory "C:/web/project1">
  Require all granted
 </Directory>
</VirtualHost>

Add your details in your hosts file C:\Windows\System32\drivers\etc\hosts file

127.0.0.1 localhost
127.0.0.1 project1.localhost

Stop start XAMPP, and click Apache admin (or localhost) and the wonderful XAMPP dashboard now displays! And visit your project at project1.localhost

jQuery equivalent of JavaScript's addEventListener method

One thing to note is that jQuery event methods do not fire/trap load on embed tags that contain SVG DOM which loads as a separate document in the embed tag. The only way I found to trap a load event on these were to use raw JavaScript.

This will not work (I've tried on/bind/load methods):

$img.on('load', function () {
    console.log('FOO!');
});

However, this works:

$img[0].addEventListener('load', function () {
    console.log('FOO!');
}, false);

.NET Console Application Exit Event

If you are using a console application and you are pumping messages, can't you use the WM_QUIT message?

what is the difference between const_iterator and iterator?

Performance wise there is no difference. The only purpose of having const_iterator over iterator is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:

std::vector<int> integers{ 3, 4, 56, 6, 778 };

If we were to read & write the members of a container we will use iterator:

for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
       {*it = 4;  std::cout << *it << std::endl; }

If we were to only read the members of the container integers you might wanna use const_iterator which doesn't allow to write or modify members of container.

for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
       { cout << *it << endl; }

NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.

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

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

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

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

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

How to import a Python class that is in a directory above?

from ..subpkg2 import mod

Per the Python docs: When inside a package hierarchy, use two dots, as the import statement doc says:

When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after from you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod. If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod. The specification for relative imports is contained within PEP 328.

PEP 328 deals with absolute/relative imports.

git rebase fatal: Needed a single revision

Check that you spelled the branch name correctly. I was rebasing a story branch (i.e. branch_name) and forgot the story part. (i.e. story/branch_name) and then git spit this error at me which didn't make much sense in this context.

How to fix the "508 Resource Limit is reached" error in WordPress?

I faced to this problem a lot when developing my company's website using WordPress. Finally I found that it happened because me and my colleague update the website at the same time as well as we installed and activated many plugins that we did not use them. The solution for me was we update the website in different time and deactivated and uninstalled those plugins.

"Debug certificate expired" error in Eclipse Android plugins

H-m-m-m. Interesting how so many people have had slightly different experiences with this. I remember the days when this was considered a sign that the software was not ready for release, and the team would actually fix it BEFORE users started seeing these problems:(

My own experience was just a little different. I had already tried Project>Clean, but still got the same build failure. Then I deleted the debug.keystore (under .android) just as the first answer said. Still got the same problem. Then I did a clean again, and wonder of wonders, it worked!

Now don't get me wrong, I am glad that I got it working thanks to the hints in this thread. But clearly clean isn't working right, and how did it find an expired key after I deleted the keystore??? Clearly something is wrong with Eclipse or the ADT -- not so sure which.

Create normal zip file programmatically

.NET has a built functionality for compressing files in the System.IO.Compression namespace. Using this you do not have to take an extra library as a dependency. This functionality is available from .NET 2.0.

Here is the way to do the compressing from the MSDN page I linked:

    public static void Compress(FileInfo fi)
    {
        // Get the stream of the source file.
        using (FileStream inFile = fi.OpenRead())
        {
            // Prevent compressing hidden and already compressed files.
            if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden)
                    != FileAttributes.Hidden & fi.Extension != ".gz")
            {
                // Create the compressed file.
                using (FileStream outFile = File.Create(fi.FullName + ".gz"))
                {
                    using (GZipStream Compress = new GZipStream(outFile,
                            CompressionMode.Compress))
                    {
                        // Copy the source file into the compression stream.
                        byte[] buffer = new byte[4096];
                        int numRead;
                        while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            Compress.Write(buffer, 0, numRead);
                        }
                        Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
                            fi.Name, fi.Length.ToString(), outFile.Length.ToString());
                    }
                }
            }
        }

How to enable named/bind/DNS full logging?

Run command rndc querylog on or add querylog yes; to options{}; section in named.conf to activate that channel.

Also make sure you’re checking correct directory if your bind is chrooted.

Catching exceptions from Guzzle

In my case I was throwing Exception on a namespaced file, so php tried to catch My\Namespace\Exception therefore not catching any exceptions at all.

Worth checking if catch (Exception $e) is finding the right Exception class.

Just try catch (\Exception $e) (with that \ there) and see if it works.

load iframe in bootstrap modal

It seems that your

$(".modal").on('shown.bs.modal')   // One way Or

You can do this in a slight different way, like this

$('.btn').click(function(){
    // Send the src on click of button to the iframe. Which will make it load.
    $(".openifrmahere").find('iframe').attr("src","http://www.hf-dev.info");
    $('.modal').modal({show:true});
    // Hide the loading message
    $(".openifrmahere").find('iframe').load(function() {
        $('.loading').hide();
    });
})

How to reload .bashrc settings without logging out and back in again?

Depending on your environment, just typing

bash

may also work.

How to extract HTTP response body from a Python requests call?


import requests

site_request = requests.get("https://abhiunix.in")

site_response = str(site_request.content)

print(site_response)

You can do it either way.

Is it possible to get only the first character of a String?

Use ld.charAt(0). It will return the first char of the String.

With ld.substring(0, 1), you can get the first character as String.

How do I download a file from the internet to my linux server with Bash

I guess you could use curl and wget, but since Oracle requires you to check of some checkmarks this will be painfull to emulate with the tools mentioned. You would have to download the page with the license agreement and from looking at it figure out what request is needed to get to the actual download.

Of course you could simply start a browser, but this might not qualify as 'from the command line'. So you might want to look into lynx, a text based browser.

How do you post to the wall on a facebook page (not profile)

You can not post to Facebook walls automatically without creating an application and using the templated feed publisher as Frank pointed out.

The only thing you can do is use the 'share' widgets that they provide, which require user interaction.

EXCEL VBA, inserting blank row and shifting cells

Sub Addrisk()

Dim rActive As Range
Dim Count_Id_Column as long

Set rActive = ActiveCell

Application.ScreenUpdating = False

with thisworkbook.sheets(1) 'change to "sheetname" or sheetindex
    for i = 1 to .range("A1045783").end(xlup).row
        if 'something'  = 'something' then
            .range("A" & i).EntireRow.Copy 'add thisworkbook.sheets(index_of_sheet) if you copy from another sheet
            .range("A" & i).entirerow.insert shift:= xldown 'insert and shift down, can also use xlup
            .range("A" & i + 1).EntireRow.paste 'paste is all, all other defs are less.
            'change I to move on to next row (will get + 1 end of iteration)
            i = i + 1
        end if

            On Error Resume Next
                .SpecialCells(xlCellTypeConstants).ClearContents
            On Error GoTo 0

        End With
    next i
End With

Application.CutCopyMode = False
Application.ScreenUpdating = True 're-enable screen updates

End Sub

How to convert an int array to String with toString method in Java

Using the utility I describe here, you can have a more control over the string representation you get for your array.

String[] s = { "hello", "world" };
RichIterable<String> r = RichIterable.from(s);
r.mkString();                 // gives "hello, world"
r.mkString(" | ");            // gives "hello | world"
r.mkString("< ", ", ", " >"); // gives "< hello, world >"

Draw a connecting line between two elements

jsPlumb is an option available that supports drag and drop, as seen by its numerous demos, including the Flowchart demo.

It is available in a free Community edition, and a paid Toolkit edition.

The Toolkit edition wraps the Community edition with a comprehensive data binding layer, as well as several UI widgets for building applications and integrations for popular libraries, and is commercially licensed.