Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Search - "string"
-
Public class UnnamedChild extends Person implements Mirziteh {
public UnamedChild(String fName){
super();
this.fName = fName;
}
//methods removed for brevity
}26 -
You know what really grinds my gears?
Seeing a 5-line comment, that have absolute no value, for a variable declaration.
Example:
/*
*
* String that holds a delivery address.
*
*/
public String deliveryAddress;8 -
Note to myself : Searching "String LaTeX" on google might give you something quite different from what you expected2
-
Apparently they'd never heard of bools. The best part is the case check given that they define the string.18
-
Working with a "senior frontend developer"
HIM: committed this code, and took him 2 weeks before his first commit on our project
var str = ''
if (string == 'String Here') {
str = 'stringhere'
} else if ( string == 'Another String Here') {
str = 'anotherstringhere'
} and so on ...
ME: WTF?
ME: can we do it like this?
ME: str = string.replace(/\s/g, '').toLowerCase()
Maybe he is senior by age :D10 -
C is a cool programming language where if you want to return a string from a function you have to set up an entire physical-universe human social system for adjudicating who is responsible for freeing it "In order to create a C string, you must first create civilization"
"In order to create a C string, you must first create civilization"10 -
Two strings walk into a bar and sit down. The bartender says, “So what’ll it be?”
The first string says, “I think I’ll have a beer quag fulk boorg jdk^CjfdLk jk3s d#f67howe%^U r89nvy~~owmc63^Dz x.xvcu”
“Please excuse my friend,” the second string says, “He isn’t null-terminated."2 -
These two strings walk into a bar and sit down. The bartender says, "So what'll it be?"
The first string says, "I think I'll have a beer quag fulk boorg jdk^CjfdLk jk3s d#f67howe%^U r89nvy owmc63^Dz x.xvcu"
"Please excuse my friend," the second string says, "He isn't null-terminated." -
Fun fact: if you send a string as response from a java Servlet to Ajax request. The string isn't null terminated.
wanna know how I found out. I didn't for 2 whole FUCKING days.1 -
Coworker: I give up! Please help me!
Me: What's up?
C: Take a look at this. I have this function here that gets the tab index and I'm passing it to the Tabs component over there. I'm logging the index and as you can see it's 3, but the Tabs component isn't working. However if I replace the function call with a 3 it works!
Coworker 2: While you were explaining all that, shellbug already thought about at least 3 reasons why that isn't working.
Me: **sighs** Of what type is the value that function is returning?
C: **stares at me for a few seconds** It's a number.
Me: Are you sure?
C: Well, it's returning 3.
Me: Please do a typeof.
It was string.8 -
Getting the nth character of a string.
Every other language:
string[n]
Swift:
string[index(string.startIndex, offsetBy: n)]8 -
I never make the same mistake twice, I make it eight or nine times just to be sure.
String name;
String number
String dob;5 -
Just looking at code, my colleague ("Senior Java Developer"), wrote...
if (process == "null") {...}
As you can guess, process is a String.
I just don't know what I can tell him. It's just so wrong, in every possible way...10 -
Looking into a helper class written by someone who was clearly not a master of their craft. The class deals with some string IDs...
public getIDPosition1(String id){
return id.substring(0,1);
}
So far so useless. But it gets better. What is declared immediately below the above method?
public getIDPosition2(String id){
return id.substring(1,2);
}
And below that? You guessed it:
public getIDPosition3(String id){
return id.substring(2,3);
}
This continues to position 10.... -.-7 -
Word of day:
Hellogrammer
Slang for person who can print "hello world", "hello", or some random string of character in multiple programming languages and whose knowledge is limited to printing string.
Synonyms: hypocrite, stupid, script Kidde....17 -
Recently saw a piece of code left by a former coworker where he converted an int to a long, by converting it to a string, then parsing the string.5
-
I programmed a random credit card generator at school and saved it to my :F drive which is the private drive for students to save stuff to. That night I tried accessing my account and it had notified me that it had been locked. I went into school the next day and was called into the office, the principal and Tech Administrator were there waiting for me and asked what the file was. The Tech Administrator tried to describe to me what he found
"This gen.html file seems to be malicious and puts our school at risk. It seems to be some sort of malware and stuff like that is prohibited at school."
Now me sitting in the chair listening to this, laughing in my head just said "okay" and nodded my head because he is the type of person to argue forever. They came to the conclusion to unlock my account by the end of the semester.
Just goes to show that it doesn't take much to get a Tech Admin position at a school.15 -
To all the programmers calling “ToString()” on variables that are already of type String....
Please stop.22 -
Unless you had a horrible accident where you lost most of your fingers, I don't understand why anyone would do this. I had to double check I wasn't looking at obfuscated code.
```
String a;
String flag;
String tp;
String n;
String chn;
String lt;
String lg;
String bid;
String d;
```11 -
public String getDbPasswd(){
try{
String dbPasswd = SomeInhouseEncryptionLib.getPasswd("/hard/coded/path/to/key");
return dbPasswd;
} catch(Exception e){
LOGGER.log(Level.SEVERE,e)
return "the-actual-password";
}
return null;
}
And this is now in production
FML3 -
Q : How do you generate random string?
A : Put my keyboard layout to Dvorak and write someone's name.3 -
Reverse the given string without using inbuilt java methods... 😭😭😭😭
Every time you will get this question even when you have more than 6 yrs of experience 😡11 -
Try this code in JS:
++[[]][+[]]+[+[]]
This is valid and returns the string "10" in JavaScript :)))
Source: in comment👇5 -
I've taken over a project with legacy code, this is one of the methods:
private bool areEqual(string value1, string value2)
{
return value1 == value2;
}
Also, the opening brackets are on a new line10 -
This guy who earns 20% more than me wrote a method to check which string of 2 is lexicographically smaller.
public boolean isSmaller(String s1, String s2) {
String [] temp = new String[2];
temp[0] = s1;
temp[1] = s2;
Collections.sort(temp);
if (temp[0].equalsIgnoreCase(s1)) {
return true;
}
else {
return false;
}
}5 -
i really love coding because in C# you write string, and in Arduino String( with a capital s). You mess this up and nothing works.
10/10 would rewrite the whole program again because of this.11 -
Found this gem yesterday...
function justNumber(BigDecimal n) {
string negative_sign = "-";
BigDecimal response = BigDecimal.valueOf(n.toString().replace(negative_sign, ""));
return response;
}11 -
As a developer, I'm sometimes accused of pulling strings out my arse.
As a dog owner, I've literally just had to pull a string out of my dog's arse.
I really wish she'd stop eating fabric.2 -
When one of your dev's can't keep his variable naming consistent, even within the same line. Throw in non-English comments, bad spelling and incorrect pluralization for good measure
string myVariable = THE_OTHER_VARABLE + AnotherDumbVariable
//This add the string for better working2 -
World's best random string generator
Open a vim session in front of a designer and tell him to exit 😂😂1 -
Two strings walk into a bar and sit down. The bartender says, “So what’ll it be?”
The first string says, “I think I’ll have a beer quag fulk boorg jdk^CjfdLk jk3s d#f67howe%^U r89nvy~~owmc63^Dz x.xvcu”
“Please excuse my friend,” the second string says. “He isn’t null-terminated.”
-
Not quite a rant, but if you came here for a cool way to reverse strings in python then I've got you covered:
backwardsString = string[::-1]
Don't know why you come to devRANT for tips on python string reversal but hey
I thought it was cool at the time ::)))3 -
String nullabity check duel...
null, isEmpty(), "", " ", '', ' ', " null", boolean, NaN, undefined, isNullOrEmpty and finally try-catch -
Writing a function to take a string of delimited entities, parse each character to find the separators, capture the characters in between separators, and return an array of entities.
I used this for about a year before I learned about String.split()
Yeah.1 -
I wrote a base converter in AssemblyScript that could take a numeric or string radix of 2-36. String options being binary, ternary, etc.
Then I couldn’t figure out how to color scheme it, so went about it the lazy way.
I present to you: Choose your own damned background and text colors.
https://baseconverterwebassembly.netlify.app/...6 -
"/path/to/my/file.swift:143:34: error: cannot convert return expression of type 'String.SubSequence' (aka 'Substring') to return type 'String'"
Ah yes, I love it when Substring isn't String5 -
public void 2016(){
if (badLuck = NOT_ENOUGH)
badLuck++;
else
badLuck++;
}
public String 2017(){
return HOPE_FOR_THE_BEST;
}
Happy new year fellow programmers!6 -
These two strings walk into a bar and sit down. The bartender says, "So what'll it be?"
The first string says, "I think I'll have a beer quag fulk boorg jdk^CjfdLk jk3s d#f67howe%^U r89nvy owmc63^Dz x.xvcu"
"Please excuse my friend," the second string says, "He isn't null-terminated." -
Java: String foo =“bar”;
C#: var foo = “bar”;
Go: var foo string = “bar”
I just started learning Go and I’ve been cringing since.19 -
Two C strings walk into a bar.
The bartender asks "What can I get ya?"
The first string says "I'll have a gin and tonic."
The second string thinks for a minute, then says "I'll take a tequila sunriseJF()#$JF(#)$(@J#()$@#())!*FNIN!OBN134ufh1ui34hf9813f8h8384h981h3984h5F!##@"
The first string apologizes, "You'll have to excuse my friend, he's not null-terminated."1 -
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
sorry for my messy code19 -
Ahhh yes Prof, because I really want to be doing more work than I need to be...
// Tedious string concatenation.
System.out.println("a: " + a + " b: " + b);
// Output using string formatting.
System.out.printf("a: %d b: %d\n", a, b);
But, hey that's just my opinion.3 -
String someStr = "your name";
// but i wanna capitalize it
someStr.capitalize(); // <-- operation has no effect
// ughh, fine 😒
String cappedStr = someStr.capitalise();
// wish I could just do this:
someStr .= capitalize(); // but it throws error 😩16 -
private String field;
public void setField(String field) {
field = field;
}
// I was wondering why didn't the value change3 -
Converting an int to a string for use in a switch statement... And nothing else.
Who the HELL wrote this crap?! -
I need someone standing behind me 24/7 making sure I don't try to String == "test"
Just wasted half an hour wondering why nothing was happening11 -
Idea for a next gen image compression method:
* Put your image into a reverse AI image generator to get the prompt for that image.
* store the text string as the compressed image
* Put the text string into to AI image generator to get back your compressed image.14 -
I'm curious...is there a practical application for reversing a string, other than for tutorials and interview questions?9
-
"How would you reverse a string?"
One of the best Java interview questions I ever had! (no kidding)8 -
Used a String as a Boolean
First sin of the year
😂😂😂
Ps:Android studio wont let me use int or boolean,it was suggesting to use respective arrays as it was inside a loop2 -
This jewel piece of code in Java:
if(String.valueOf(var1.toString( ) ).equalsIgnorecase(String.valueOf(var2.toString())){
//fuck something else here
}
String var1; //defined somewhere
String var2; //defined somewhere in the code
At this point I am not even mad 😂😂3 -
just quit my job, and the last push i do is changing all the literal string contained in variable and/or stdout to base64 encoded string. and change it to call my secretely placed decoder function.
Everything is working normally guys! *walks away into darkness*10 -
Unreal Engine adventures:
me: So ok, I need a map from int to String
Unreal: ya but it's called TMap, FCompactPoseBoneIndex and FName.
me: ..uhhh ok whatever
...
me: ok for debugging, please print this
Unreal: FName is not a string
me: k. Fname.toString().
Unreal: ya but it aint a TChar array now
...
IT'S A FKING STRING JUST PRINT IT. And the other guy is still an int with extra steps! Come the fuck on now....
I mean, honestly, a logging function that cannot print a fking FString? sigh...
Man, I miss python and blender...8 -
//Something great
try
{
//Some code.
}
catch(Exception ex)
{
string url = "http://stackoverflow.com/search?q=";
System.Diagnostics.Process.Start($"{url}{ex.Message}");
}1 -
Just had a discussion with a coworker. I noticed he was storing dates as string in mongodb, saying it was better for comparison and because he stored them in UTC. WTH, mongo already stores all dates in UTC and a string date is imposible to compare. I wasted 8 hours finding that last part out.6
-
Yes, php, it makes total sense that `array_diff` compares the string representation of the elements.1
-
These two strings walk into a bar and sit down. The bartender says, "So what'll it be?"
The first string says, "I think I'll have a beer quag fulk boorg jdk^CjfdLk jk3s d#f67howe%^U r89nvy owmc63^Dz x.xvcu"
"Please excuse my friend," the second string says, "He isn't null-terminated."1 -
Not sure why Microsoft named their string CString.
It's hard to find an appropriate result in Google about it.8 -
const abc: string = 'Hi';
Can we take a moment to appreciate how retarded it is that TSlint throws a warning here that the string type is inferred and unnecessary.
I want to put the type there because it looks more readable. Code looks better if every variable has a type, irrespective of whether it's a constant. I know the fucking type is inferred you braggart linter bitch. What the fuck does it expect? A fucking award because it inferred that a string constant is of the fucking type string? How the ever loving fuck does that warrant a squiggly ass yellow warning line, reminiscent of that smartass 10 year old in class who has to yell out every answer when the teacher never asked a question.5 -
When I was first learning Java I forgot to use If statements and made about a 600 systemoutprint lines. Don't be like me5
-
I created a class Log with a method d(String tag, String text) to replicate Android's log method in Flutter.
class Log {
static void d(String tag, String text) { print(tag + ": " + text); }
}
I replaced all 'print' into 'Log.d' in my project and I wondered why emulator kept crashing for the past two days.
Now I know..4 -
Get a DateTime. Convert to a string. Convert back to a DateTime. Use that DateTime to build a string.
WHY.
(it's red because I refactored it; snipped copied from our version control)3 -
package main
import (
"log"
"strings"
)
type Present struct {
from string
to string
}
type Santa struct {
presents []Present
}
type Person struct {
Name string
Nice bool
Presents []Present
}
func (santa *Santa) givePresents(person Person) []Present {
result := []Present{}
if person.Nice != true {
return result
}
for _, present := range santa.presents {
if strings.Compare(present.to, person.Name) == 0 {
result = append(result, present)
}
}
return result
}
func main() {
santa := Santa{
[]Present{
{"devRant", "Alex"},
{"Johanna", "Alex"},
{"Alex", "devRant"},
{"Alex", "Johanna"},
},
}
persons := []Person{
{"Alex", true, []Present{}},
{"Johanna", true, []Present{}},
{"devRant", false, []Present{}},
}
for idx, person := range persons {
persons[idx].Presents = santa.givePresents(person)
}
log.Println(persons)
}2 -
other dev changed constructor from
public A(String val){
this.val = val;
}
to
public A(String val){
this.setVal(val);
}
this feels bad in many ways, but need some arguments to convince him that its wrong11 -
Stop fucking with the numbers.
A number is a number, integer or float.
Just because you wanted your stupid decimal place doesn't mean you need to fuck things up and make the front-end break because now its sending a string the server instead of a float. For fuck sakes. How long have we been doing this?5 -
man, fuck php.
fuck fucking php fuckitily fucking hard.
basically every fuckin stdlib function it has is fucked in some way.
can't even remember it anymore properly, but...
for example:
explode(" ", "some string like this ");
function to "split a string into array of strings using the first param as the boundary marker.
the above one would return
["some", "string", "like", "this", ""]
BECAUSE I'M FUCKING FUCKITTY SURE THAT WHEN THE LAST CHARACTERS OF THE STRING ARE EQUAL TO THE SEPARATOR STRING, EVERYONE WANTS TO GET BACK ONE EXTRA FUCKING USELESS EMPTY ITEM IN THE ARRAY.
because beyond the last wall of my house, there's another room of my house, you stupid Lerdorf fuck.28 -
Helping out a friend how to code, and he said:
"Can't we just use a string? An array is just like a string anyway."
We were looking at some setting types in Visual Studio. -
This way of converting "string" to "s" (for example)
0) program reads the whole buffer, stores it as an array of instructions
1) program reverses the order of the instructions
2) parser makes standard token from an instruction ("asd" -> ASD)
3) parser2 assigns operands to instruction
4) parser 3 makes string from instruction token ?????
5) parser fucking 4 makeS A MUTABLE STRING INSTRUCTION
6) PARSER FIVE SUBSTITUES OPERANDS
7) AND THEN CUTS IT TO A REVERSED ARRAY OF COMMANDS
8) AND PUSHES IT UNTO THE STACK
WHAT1 -
Me, rueing typescript: "Dammit, Typescript!"
Typescript's cheeky response: Type 'string' is not assignable to type "Dammit"
ಠ_ಠ -
01000110 01110101 01100011 01101011 00100000 01011001 01101111 01110101 00100000 01000001 01101100 011011007
-
Pissed off:
Trying to write a date function that converts an Int (seconds) to days hours/minutes/seconds.
Get stuck when I build the output-string because I need to mix string and Int. I am used to C# and PHP, C++ just screws it up for me.3 -
Best conversation with non tech roommate ever:
Me: hey roomie, implement an algorithm to determine if a string has all unique characters
Roommate: like a string of code or a string of yarn?2 -
Rust ahahaah hhaahah ahah
the trait bound `std::result::Result<std::string::String, std::io::Error>: std::convert::AsRef<[u8]>` is not satisfied
the trait `std::convert::AsRef<[u8]>` is not implemented for `std::result::Result<std::string::String, std::io::Error>`16 -
Okay so I've written a string reverser in my own esoteric programming language.
Explanation: https://github.com/iAmGio/pikt/...5 -
Go home Dart, you're drunk
A value of type 'String' can't be returned from function 'myFunction' because it has a return type of 'String'. dart(return_of_invalid_type)
string.dart(102, 16): String is defined in C:\src\flutter\bin\cache\pkg\sky_engine\lib\core\string.dart
string.dart(102, 16): String is defined in C:\src\flutter\bin\cache\pkg\sky_engine\lib\core\string.dart2 -
Promise.resolve() in js. You have a string but need a promise? Just do a Promise.resolve(str) and boom! You can 'then' the shit out of your string...
-
I know that if something looks stupid but it works, it ain't stupid... but this is just plain borderline.
Basically, a cast from int to String to int to String from some legacy code I'm working with7 -
Not my worst but spent a few mins confused by this today:
private String str;
public myConstructor(String str){
str = this.str;
}2 -
Working with Microsoft.CodeAnalysis.CSharp
where I work with CSharpSyntaxTree
I can compile the code in code.
So basically,
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
using System;
namespace InAppCompiler
{
public class Writer
{
public void PrintText(string message)
{
Console.WriteLine(message);
}
public void ALLCAPS(string msg)
{
Console.WriteLine(msg);
}
}
}");
Freaking cool!3 -
I've been dreaming about an eat() method in, I guess, Javascript. It would accept a string as parameter and set the cursor position further by the width of that string in the current font and size without displaying the string. A bit like a span with FG == BG.
But the best was the debug mode: the characters would be printed, but a yellow duck would appear from the left and eat them in Pacman style.1 -
Just found the equivalent of this code living in a project that has been live for years.
String emailAddress = "";
String otherEmailAddresses = PopulateEmail();
if (emailAddress.Trim != "")
{
SendEmail(emailAddress);
if (otherEmailAddresses != "")
{
SendEmail(otherAddresses);
}
}
At least I didn't write this originally.2 -
You know what really bugs me? How movies show people hacking into something with the terminal and all the matrix code but its really not like that.6
-
When I forgot how everything works in c#.
Example:
var animalKey = 1;
Then I realize I needed it to be string.. and I couldn't figure out how to convert an int to a string... But all I needed was
var animalKey = "1";
I kicked myself pretty hard2 -
I spent 20 minutes looking at my Java if statement wondering why it's not working as intended:
if (word == "ABC")
I need some sleep/more coffee 🙃3 -
foreach(string language in LANGUAGES){
System.Console.writeLine(language.GetPhrase("Greeting"));
}2 -
Here are some of the variable types in java if someone needs it :)
-String myString = "Hello";
//integeres
- Byte myByte = 127; [It can hold up to 128
-Short myShort = 530; [up to 32767] -> 2 bytes
-int myInt = 8021; [up to 2,147,483,647] -> 4 bytes]
-long myLong = 213134; [ up to 9,223,372,036,854,755,807] -> 8bytes
//Decimal Numbers
-float myFloat = 3.14f;
-double myDouble = 23.45;
P.S.
I hate double... idk why
Bye12 -
Spring JPA might be annoying sometimes...
public MyResult findFirstByIdentities_CompanyIdAndIdentities_UserIdAndFromDateAndToDateAndFormatAndIdentities_SourceAndStatusInAndCreatedOnAfterOrderByCreatedOnDesc(String companyId, String userId, Date fromDate, Date toDate, String format, String source, Collection<String> status, Date createdOn) {...}
I know I know, efficiency is weeping in a dark corner. Will deal with it later2 -
Oh Shit! Here we go again!
print(request_permissions)
>> [ ]
if request_permissions:
//some if shit
else:
raise 404
It was supposed to raise 404 for empty array, but continue to exit if.
Me: What the fuck?
**printing request POST data**
**empty, nothing wrong here**
**double checked print statement output**
** still printing [ ] **
**restart server and again checking print statement**
**still same**
Getting mad over myself, for failing to debug simple if else.
Wait....
print(type(request_permissions))
>> <class 'str'>
Me: What the actual fuck??
Fucker literally dumped empty array to JSON causing array to convert into string "[ ]" and still using if else based on array instead of string length.
Thanks to our Product Manager who approved our request to revamp this part of code and also revamping the whole shitty project developed by 3rd party in upcoming quarter.22 -
Do you think my credit card company has a big bounty? String formatting really isn't that difficult.1
-
When you are dreaming about you being stuck in a never ending loop of string escape... Nightmares...1
-
Somehow I wrote some code that ended up comparing a string type object against a pointer of an unrelated class. There are NO functions to convert that class to any kind of string representation. Let alone ones that would allow that to happen in C++.
WhyTF did the compiler not pick up on this?5 -
C:
char greeting[] = "Hello world";
Developers: char array... What da f*CK!
C++
... Okay.
std::string,
std::string_view,
char*,
std::wstring,
hstring,
qstring...
How about now? ( ͡° ͜ʖ ͡°)5 -
I saw multiple attempts to convert an int to a String by concatenating it with an empty String...
String s = someInt +"";
(I'm guessing the compiler uses a StringBuilder here which still ends up calling Integer.toString())2 -
A TypeScript boolean/undefined Flag variable kept fucking up
true == true didnt hold true
checked the "typeof" in console and it's GOODDAMN STRING.
What's the point of TypeScript's "type safety" if a Boolean variable is holding a String type for whatever reason. URGHH I HATE JAVASCRIPT.23 -
Does anyone else get annoyed when your outside of a editor and you press the apostrophe/quote or parenthesis key only to outputs a single character and not a pair?
Drives me insane1 -
I'm trying to convert a legacy .NET Framework web api to .NET Core, the project and its supporting libraries are in awful conditions and to make things worse at a certain point someone has the genius idea of introducing Uncle Bob's "Clean" Architecture into a part of it so stuff which could simply look like this
public string doStuff(string input){
// Do the stuff
return output;
}
becomes a convoluted mess like this
public class StuffDoerRequest {
public string Input{get;set;}
}
public class StuffDoerResponse {
public string Output{get;set;}
}
public interface IStuffDoer {
public StuffDoerResponse Execute(StuffDoerRequest request);
}
public class StuffDoer {
public StuffDoerResponse Execute(StuffDoerRequest request) {
// Do the stuff
return new StuffDoerResponse() {
Output = actualFuckingOutput;
}
}
}
Edit: sorry for the lack of indentation, apparently DevRant trims leading whitespace7 -
I am trying to "invent" secure client-side authentication where all data are stored in browser encrypted and only accessible with the correct password. My question is, what is your opinion about my idea. If you think it is not secure or there is possible backdoor, let me know.
// INPUT:
- test string (hidden, random, random length)
- password
- password again
// THEN:
- hash test string with sha-512
- encrypt test string with password
- save hash of test string
// AUTH:
- decrypt test string
- hash decrypted string with sha-512
- compare hashes
- create password hash sha-512 (and delete password from memory, so you cannot get it somehow - possible hole here because hash is reversible with brute force)
// DATA PROCESSING
- encrypt/decrypt with password hash as secret (AES-256)
Thanks!
EDIT: Maybe some salt for test string would be nice8 -
Why is there no devDuck cape for Angular?
Well, If string length was the reason, "ng" would've sufficed.5 -
porting a script that supports barewords to something that doesn't....
string up = "up", down = "down";
if(position === up)
its all well and good until you find someone copyies and pwastes that to have in every function
string up = "up", down = "down";
if(position === up)
string up = "up", down = "down";
if(position === up)
string up = "up", down = "down";
if(position === up)
then imagine a much larger dictionary. Also there was a spelling mistake, several in fact.
also who rewrote the parser to try to support keywords as variables? -
string action = day == "Monday" ? "Go to work" : "Friday" ? "Netflix & chill" : "Saturday" ? "Sleep all day" : "Sunday" ? "Get ready again for Monday" : "Code from 9-5";
I wrote nested ternary operators before and I swear I'd only use shorter conditions like the one below. 😳
string action = isTired == true ? "Get some sleep" : "Drink more coffee";5 -
Found this in our Python codebase:
my_dict[key] = "%s" % str(my_dict[key])
Best way to convert a value to string xX -
public static void turnItUpTo(int val) {
this.setLevel(val);
}
public static void main(String[] args) {
turnItUpTo(11);
System.out.println("Rock out");
} -
When you tell your friend you're good at coding and they ask if you can hack into a Facebook account5
-
My boss writes code like this:
def someFunction (someArg: String) = ...
Who does that?! A space? Da fuck?! And it's all over the code base. Whenever another dev touches any of his stuff, we correct it:
def someFunction(someArg: String) = ...
The way god intended it!8 -
Do you need to escape string if you encode everything with base64 before it touches the database? 🤔
#BadPractise?6 -
Few years ago I was looking at legacy code that was developed by offshore team (what could go wrong,right) and I see small utility method that looks like this:
public boolean isEmptyNotEmpty(String s) {
boolean empty=false;
If(s==null) {
empty =true;
}
If(s.equals("")) {
empty = true;
}
return empty;
}
Thinking in myself: was he/she paid per line the line of code??!?!
Up to this date that was the worst part of the code that I encountered....2 -
Saw this in the Python project codebase today:
arg = '\"foo\"'
Which is funny, because '\"foo\"' == '"foo"' -
I dont know why but my team lead urges everyone to use empty string as a constant string variable from our utility class instead of just putting "" in our code... Its really cringe worthy... Why use Constants.NONE when you can put "" just to avoid null exception working with Strings..4
-
When you write print(string), which type of people are you:
A) 1. ( 2. string 3. )
B) 1. () 2. string
C) Autocomplete guys
D) hodor
*applies for echo, printf, println, etc.
** python2 and c++ are discriminated on purpose9 -
class smoking{
public static void main ( String []args){
int a = 2;
String c = "cigarettes";
if (a==2)
System.out.print ("go smoke "+ c);
else if (a <2)
System.out.println ("go buy some");
else
System.out.println ("error");
}
}10 -
I´m learning C # basic concepts and a question has come up after doing this exercise:
using System;
namespace exercise
{
class MainClass
{
public static void Main (string[] args)
{
console.WriteLine("Type your name");
String name = Console.ReadLine ();
console.WriteLine("Type one city");
String city = Console.ReadLine ();
console.WriteLine("Hello"+ name + "wellcome to " + city )
Console.ReadLine ();
}
}
}
Question: its necessary to put the last
Console.ReadLine ();?Why?8 -
Trying to learn c and I forgot the name of the string comparison function, so I googled "c string"
O boi....4 -
Wow, function overload is worst than garbage! Is more like toxic waste!
If you run out of names for functions just name them:
DoThatStuff1(int, string)
DoThatStuff2(object, int, string)
instead of:
DoThatStuff(int, string)
DoThatStuff(object, int, string)
Your coworkers and future you will thank you!8 -
Today I learned.
In php if you cast a string to array you get an array with one value: the string.20 -
So, in C#, are there any tips or guidelines as to how to write "clean" multiline strings? I mean, imo it doesn't look as neat when the code looks like:
static string kindOfLongVariableName = @"First line of string.
Second line of string...";
With the first line sort of hovering on the side. What I'm used to is with Python where you can just:
variable_name = """'\
First line.
Second line.
"""
And use the '\' to escape the newline, but that obviously doesn't work in C#. Can anyone point me in a direction to start looking? The docs are a bit confusing and not very beginner friendly. :/20 -
Emphasize secure implementations rather than just making something work...looking at you string concatenating sqli_query's.
-
{
"$schema": "http://json-schema.org/draft-04/...#",
"type": "object",
"id": "https://[URL_NAME]/forms/{id}/...#",
"properties": {
"title" : { "type": "string" },
"date" : { "type": "string" },
"content" : { "type": "string" },
"date_start": { "type": "string" },
"date_end" : { "type": "string" },
"status" : {
"type" : "string",
"enum" : ["1", "2", "3", "4", "5"]
}
},
required [
"title",
"date",
"content",
"date_start",
"date_end",
"status"
]
}
See if you can notice the error is this schema. Don't copy and paste it. I change some format to obsfucate the real data naming, but this schema error is still up there
Just wasted my 30 minutes staring at this10 -
We need a list of functions with an associated string, keyed by a sequential int. Neither can change between program versions. In fact, any changes align perfectly to program versions.
The datastructure: a list of string and func with statically known parameters
The solution my PO insists on: a class with static methods that have an attribute for specifying the number, and a database table of number to string. Whenever you need to pass around the list, you pass around a Type object of the class.6 -
The database dude: yeah it gets saved as a string.
*me sets up preg_match for a string*
Database 'guru': we tried entering the data in the form and we are getting an error. Fix it!
Turns out it's being saved by id.
Data wizards my ass -
String concatenation using + instead of StringBuilder....
Using prototype objects instead of singleton wherever required..1 -
Had a php float value that I needed to use as a string, so I typecasted it.
Later on in the code I need the value again but now it was a string.
Typecasted it back to a floating point.
My colleague almost killed me when he found out what caused the miscalculations.2 -
Just enrolled my Nexus 5x in the Android O beta.
I am very impressed so far with the differences between N and O -
Just firing up a new war which will be just as important in a few decades (if not today already) like Vim&Emacs.
So: Do you use 'string' or "string" in languages like JS, Python, ...?8 -
offending devs is easy -
String strName = " John";
String strGreet = Greet(strName.ToString());
return strGreet;11 -
var peanutButter = “creamy”;
var jelly = “strawberry”;
var bread = “Wonder”;
public string Lunch(peanutButter, jelly, bread, out satiation)
{
int stomach = 0;
string mouth = “”;
for (int hunger = 100; hunger > stomach; hunger--)
{
mouth += String.Format(peanutButter + jelly + bread);
stomach++;
}
return var satiation = “YAAASSSS”;
};4 -
I detest using `indexOf` to check if a string contains a substring so much I could write a rant about it.
Or is there a better way? One google search later: ES6 supports `string.prototype.includes`[1]
So moral of the story: Before ranting and using something, bother to look if it is still a problem. They might have fixed it.
[1] https://developer.mozilla.org/en/...4 -
Trying to encode human readable XML text in a HTML doc.
Sometimes you just give up, wrap the whole thing with a string, and set the value of an disabled input to the string. -
Looking for a way to generate an encrypted string (with salt) in C++ then send that string over to a java server and decrypt it on java as well. Any suggestions?9
-
Am I the only one who wants to be able to write functions in a human readable way, allowing for parameter in-between the words?
Instead of defining:
const enforceStringEndsWithChar(string: string, char: string) => {...}
I want to define it as:
const enforce(str: string)EndsWith(char: string) => {...}
.
.
.
I'll see myself out.6 -
public String findHappiness()
{
if(EverythingOk)
return “Drink Beer”;
else if(EverythingNotOk)
return “Drink Beer”;
else
return “Drink Beer”;
}1 -
Probably not worst but back when I was in graduate school I used '=' instead of '.equals()' for a string, by mistake. My professor was so pissed and taunted in front of whole class about how dumb people are here without taking any names(btw I didn't realize that guy was me until later) and gave me a low score
I told her later it really doesn't matter if I used either because '=' worked just fine in my case. She was a little more pissed after knowing that I wasn't wrong. 😜6 -
Wait, what am i missing? Learning java and got charSequence cannot be converted to string. Isn't a string a sequence of characters??? 🤔🤔🤔6
-
This actually exists in our code-base like this. I have no fucking clue what it does.
function combine(arg0: string, arg1: string): string {
return !arg0 ? arg1 : !arg1 ? arg0 : `${arg0} ${arg1}`;
}9 -
I once used try/catch the other way around. I tried to convert a string to an integer, and if it failed, I new that the string weren't a number (success)
-
Change my mind. Golang can be more difficult than it needs to be sometimes:
Find the first "non-null" value in an array:
Go:
Optional<String> result = Stream.<Supplier<String>> of(
() -> first(),
() -> second(),
() -> third() )
.map( x -> x.get() )
.filter( s -> s != null)
.findFirst();
Ruby:
@group_list.find { |x| !x["list"].blank? }16 -
The levenshtein function in PHP. Because the string function names have to kept as inconsistent as possible.2
-
I have a very basic question regarding strings in Java..I am not getting the clear explanation any where..
1. When the string is created with new operator, will it be stored only on heap or on both heap and string pool??
2. When I create a string like
s1="123";
s2=s1+"5";
What would happen at the second step??
a. will it put 1235 in the string literal pool??
b.Will it create a new string 5 in the literal pool??
please answer buddies.4 -
What is the best string comparison algorithm ?
Example Use case: group messages from your telco into groups of related messages.
I have gone through the various algos and implanted them. I just want your opinion if you have experience on this.15 -
When you can't login to your favouite game, because the games client can't handle your random string password :/
-
Difference between security threat and programming bug ?
Found a cool paper about format string attacks which mentioned buffer Overflow is a security threat while format string is a programming bug.
Had no idea what that really meant.
Tnx1 -
taking hours for string/object conversion to handle cookie based favourites depending on number of clicks left me considering being dumb, finally seeing just 15 lines of code.
-
Not a webdev so I don't care about how a website looks, but logical failures can really trigger me at times.
E.g. this German federal page you had a bunch of options to fill in your employment status. Though being incomplete it forced you to choose one from the list and then at the end you have to checkmark that you filled in everything correctly reminding you there might be legal consequences otherwise. Thanks.
Amusingly on the same page their enum to string converter seemed broken or they just didn't care. So options to choose from read like: Enum_marital_status_unwed_coupled
Fucked up the screen shot so I can't show, but made me chuckle.2 -
So I thought I had a basic, high level understanding of C++ STL strings, pointers, copy constructors and stuff. In comes a dirname, a -D_GLIBCXX_USE_CXX11_ABI=0 and... Toto, I've a feeling we're not in Kansas anymore.
So what is happening? I copy a string expecting a deep copy, but then I do the dirname or manipulation on the copy and it messes up *both* strings. gcc/C++ I know you're a beast, but what's going on there? Thing is only possible if I cast away const from c_str - which of course is a doubtful operation - but there also seems to be some strange copy on write logic that the data pointers initially point to same memory location and only with first manipulation on the copy they start to point to different addresses.
I had no clue. And still don't have.4 -
How can I be pro at string/json manipulations/regex etc?
I really suck at it and it really impacts my performance.3 -
Hit into NullPointerException on production then I saw this in the source code,
entity.getKey().getValue().contains("a string"):2 -
Why the fuck does B&R's find in string function return 0 when the search string was not found? The return type is not even unsigned?!5
-
StringUtils.isNumeric(String s)
From Apache commons-lang library will return TRUE for empty string. I learned that today the hard way...you don't need to make the same mistake... :)
Just update it to lang3 if you are working on legacy code and everyone will be happy... -
How to code a translator:
public string Translate(string input, string lang)
{
if (lang is string)
return input;
else throw new NotFoundException();
} -
<?php
// This is the demo code of a PHP gotcha which took me some hours to figure out
$hr = "\n<hr>\n";
$JSON = '{"2":"Element Foo","3":"Element Bar","Test":"Works"}';
$array = (array)json_decode($JSON);
echo "Version: " . phpversion() . $hr;
// Tested on: 5.5.35 and 7.0.15
var_dump($array);
// Prints: array(3) { '2' => string(11) "Element Foo" '3' => string(11) "Element Bar" 'Test' => string(5) "Works" }
echo $hr;
var_dump($array['Test']);
// Prints: string(5) "Works"
echo $hr;
var_dump($array[2]);
var_dump($array['2']);
var_dump($array["2"]);
var_dump($array[3]);
var_dump($array['3']);
var_dump($array["3"]);
// Prints: NULL + Notice: Undefined offset ... in ...
echo $hr;
$newArray = array();
foreach ($array as $key => $value) $newArray[$key] = $value;
var_dump($newArray[2]);
var_dump($newArray['2']);
var_dump($newArray["2"]);
// Prints three times: string(11) "Element Foo"
var_dump($newArray[3]);
var_dump($newArray['3']);
var_dump($newArray["3"]);
// Prints three times: string(11) "Element Bar"1 -
Where to start, maybe from string.
Empty string conditions and string comparison.
if “”: - python
“” == false - javascript
.equals() - java1 -
public class MyLife {
public static void main (String [] args) {
System.out.println ("My life sucks!");
}
} -
Another hours wasted on debugging, on what I hate most about programming: strings!
Don't get me started on C-strings, this abomination from hell. Inefficient, error prone. Memory corruption through off by one errors, BSOD by out of bound access, seen it all. No, it's strings in general. Just untyped junk of data, undocumented formats. Everything has to be parsed back and forth. And this is not limited to our stupid stupid code base, as I read about the security issues of using innerHTML or having to fight CMake again.
So back to the issue this rant is about. CMake like other scripting languages as bash have their peculiarities when dealing with the enemy (i.e. strings), e.g. all the escaping. The thing I fought against was getting CMake's fixup_bundle work on macOS. It was a bit pesky to debug. But in the end it turned out that my file path had one "//" instead of an "/" and the path comparison just did a string comparison without path normalization.
Stop giving us enough string to hang ourselves!rant debugging shit scripts of death fuck file paths fuck macos string to hang ourselves fuck strings cmake hell12 -
Terraform + helm-chart ... I really ned a break. Who the fuck invented this shit.
The HCL format sucks
The documentation sucks
The dev tools suck
The debug output sucks
But I'm ok with that, I can manage.
But today really it shot the bird ... I can't have a fucking comma in a string? Because idk why the fuck helm-release tries to parse that fucking string and wants to make an array or whatever out of it? Why, you fucking abomination?
Something in the docs? Nah, who reads them anyway.
Because you know it's totally not strange that a string is analyse and oh wait there's a comma in it, the dev surely wants me to make an array out of it, because you know ...
So now I have to escape my fucking comma to prevent it to parse my fucking string. I just want to have a fucking string you hideous monstrosity ....1 -
!Rant
If I'm validating a user input form should I use a hash or a encrypted string. I hope to include the user IP, header requested time plus a random number for the string.3 -
In python, is there a way to make this work?
----------
# list of people
people = ["Nick", "Sue", "Bob"]
# class instance
Bob.pockets = ["gum", "paperclip", "coins"]
# convert string to prefix of a class instance
Print(people[2].pockets())
----------
This is the simplest way to show what I'm needing to figure out.
I need to convert a string into the prefix of a class instance.
I'm having trouble figuring it out.7 -
String[] hidingPlaces = new String[1000000];
hidingPlaces[Math.rand()*1000000] = "bug";
findBug(hidingPlaces);
public int findBug(String [] are) {
// todo: return index of bug with complexity < O(1)
} -
Every programming tutorial:
Smh Smh(string smh)
{
String smh;
Smh smh;
Smh(string smh){this.smh = smh;}
Smh smH = new Smh(smh);
SmH = Smh.smh(smh);
return Smh(smh: smh);
}
This code doesn’t make any sense but the point is… WHY???
Meanwhile, they might say “I could name this something else but I’ll just give it the same fucking name” -
String sql = "DELETE FROM TABLE ";
conn.ExecUpd(sql + request.getParameter("recordNumberParam"), true); -
class post
{
public string type = "question";
public string info =
"I made a Notification Drawer for pc. It checks a file every 0.01 second. If that file contains a specific line of code, the notification drawer shows a notification. This way I can make other programs to be able to send notifications.";
public string question = "Is there an easier / better way to make 2 or more programs communicate?"
}8 -
String char replacement in C++ (according to SO):
Boost - replace_all(str1, str2);
C++ STL - 12 lines of code to iterate over the length of the string and store the result in a <char> vector.
Noooooooope. Thank God for Boost.1 -
How much trouble am I asking for in allowing for very large strings in attributes of json data?
I went and looked at the maximums for the string in json strings. I cannot see any real limitations. I did see if sending json data to a browser that it should not be more than 40MB. That seems excessive. I also checked my internal data types. The string can hold 2GB. Then there is a the server it will be served from in OPCUA. Which I saw discussion of strings in the 77KB range.
We are using a json file to configure what points to read from a modbus device. I am adding fields for name and notes. I could limit these fields, but part of me wants to see if some customer tries to make the world burn. For the most part we will be editing this file. But the customer may want to as well.2 -
I use Atom. It's a basic coding program similar to Notepad++ and Sublime Text but more minimalistic.
Link to it: http://atom.io -
so... self-referential arrays.
do you know any languages that have them? thoughts?
what I mean is (in pseudo-c# syntax) :
string[] r = new string[]{ "1", "2", self[0] + " and " + self[1] };
which would result in an array with items:
1
2
1 and 29 -
So I was playing around with JS inside of QML (Qt). I wanted to turn a number into a string and then modify individual chars based on certain criteria. Then I would convert back to a number. Should be simple right? Well JS would not let me write to the indexed element of the string. What the actual fuck? I need to drop to C++ to do actual string manipulation? I ended up looping the string and turning it into an array and then a join back to a string. There is probably a better way to do this in a more modern version of JS, but I am now starting to see why JS is a pariah on here. It has some quirks that make you question your devlife choices.
What was I working on? Some stupid crop circle thingy. I was trying to use the QML Canvas to draw some "simple" crop circles. So I started with this crop circle:
https://plus.maths.org/content/...
The result ended up being kind of a swirling crop circle thing. The static image was too boring:
https://imgur.com/gallery/900hogf
And yes, I was too lazy/cheap to license the screen capture program.7 -
Me and my friend were doing a discord bot using an extensions that allow us to collaborate.
We were making the bot with Node JS and. Something so horrible happened.
While making a purge function wich should remove the last messages of the discord we met a problem. When you do !purge 1
It were removing 11 messages.
The problem were that in my code i were adding 1 (int) to a string (my amount of message to remove) so it result 11 as string....
This is JAVASCRIPT
I don't know if this were a bug but being able to add 1 (int) to 1 (string) it's fucking dumb. It should result an error not making it as string!1 -
A usefull function, everyone should have near by. May requires some optimisations.
/// <summary>
/// DoEs tHiS To tHe pRoViDeD StRiNg. StArTs aLwAyS WiTh a cApItAl
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string DoThIsToThEtExT(string s)
{
var array = s.ToCharArray();
Parallel.For(0, s.Length, (index) =>
{
if (index % 2 == 0)
{
array[index] = array[index].ToString().ToUpper()[0];
}
else
{
array[index] = array[index].ToString().ToLower()[0];
}
});
return new string(array);
}3 -
Brain fart.
In Java and many other languages there are basic types, like char and String. So why does Java have char and String, but not a digit type?
A number is basically a series of digits. For modular arithmetic it is very useful to be able to extract the 3 in the number 1234, it's just the 3rd digit in a number.
Base 2, base 10, base anything could be supported easily too. E.g. a base 2 digit would be:
digit d = 0b2; // or 1b2, but 2b2 would be a compilation error
A number would then be some kind of string of digits.
Any thoughts on this?9 -
You know it's Friday afternoon when your interface is broken because you tried to set the type to the string 'string' instead of the keyword string.
Interface IEnvironment {
name: 'string',
...
} -
String apple = "ball";
Changes some code along with
String ball = "ball";
App crashes.
Tries debugging.
Undo everything
Back to
String apple = "ball"; -
class devRantPost
{
bool isRant = false;
string title = "Feature idea";
string content = "\n
If you try to buy something and the purchase fails, the error message should say this: Stop trying to use Lucky Patcher!";
bool isTried = totallyNot;
bool isWorked = false;
string purpose = "Research";
string content2 = "Pls don't ban me!";
}3 -
Can someone please explain me why the fuck the following doesn't work in C#?
Dictionary<string,object> mex=Json.Deserialize(data.ToString())as Dictionary<string,object>;
if(mex.ContainsKey("sessionId") && mex["sessionId"].ToString()!=tkn.GetSessionID())
the previous condition is NEVER true, but the following:
Dictionary<string,object> mex=Json.Deserialize(data.ToString())as Dictionary<string,object>;
if(mex.ContainsKey("sessionId") && mex["sessionId"]!=tkn.GetSessionID())
will actually work as expected.
tkn.GetSessionID() returns a string, of course
and mex["sessionId"] is always an object that contains a string in form of a number, like 152, 552, 6246 and so on and no, it won't ever contain any blank or other character
Fuck this fucking shit from C#8 -
A controller action taking a string input and directly accessing the file system with it, returning the file.
-
The moment you realize the .net Framework's String.TrimEnd() method will actually modify your String prior to returning it, and there seems to be no convenient way of getting a copy without declaring a new variable...
Just wanted to get rid of excess empty lines in the log caused by trailing <CR><LF> when receiving lines of serial data:
Console.WriteLine(DateTime.Now.ToString("H:m:s.fff") + " - serial data received on " + com_port + ": " + serial_data.TrimEnd())
But suddenly the parser could not find its termination characters anymore...
Resulting in probably the most disgusting parentheses I had ever added to any code:
Console.WriteLine(DateTime.Now.ToString("H:m:s.fff") + " - serial data received on " + com_port + (": " + serial_data).TrimEnd())
Yes, I feel bad about it, but then again is VB .net and it kinda "works for me". I promise I will (try to remember to) remove these as soon as debugging is done...4 -
I need help in this?
Create a function name divisers/Divisers that makes an inter n>1 and returns an array with all of the interger’s divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string ‘(interger) is prime’ (null in C#)(use Either string a in Haskell and Result<Vec<u32>, String> in Rust)5 -
Argh
Help
If you know, a specific string is always going to be the same, and theres no way any other value could be passed to this statement. Is it still ok to use string.substring(0, string.IndexOf(&$&$))?
I feel dirty every time....1 -
Help? I would like to create a Search delegate with Edit Text (Because Search View is weird) for a custom adapter List View (not String Array).... anyone know how?
I search over the Internet all I found is Search Delegate for String Array. -
I have a function that receives 2 parameters: a string and a max numer of characters.
It returns an array with the partitioned string.
Example:
function name("hi, I love devRant", 10);
//return:
array(2){
[0] ->"hi, I love"
[1] ->" devRant"
}
Now.... what would be the appropriate name for that function?10 -
Design question for y'all
Context: python lambda
Better to make classes for dictionary objects holding strings between methods
Throw strings around separately
Throw the dictionary around6 -
Why is Lua such a pain to install? Like seriously there are so many hoops to jump through, why can't it be like java or python? -_-3
-
Been working on some meta code.
Inspired by flatted, I made a JSON serializer that exports to either an evalable string or a string that can be written to a file and used as a standard module.
It's part of a bigger project
https://twitter.com/ThingtimeCorp/...
Hope you like -
WHAT IS WRONG?
public class Person {
String name;
public Person (String personName) {
name = personName;
}
public String greet (String yourName ) {
return String.format ("Hi %s, my name is %s" + name+yourName);
}
}3 -
Hey senior programmer out there. Please give one good reason to continue using JSON.
(When i'm dealing with AJAX, i insert a specific symbol in the string returned by the server and later on the front end , i just split that string to separate my data.
And JSON has become useless to me since16