Datasets:
id stringlengths 5 33 | instruction stringlengths 32 49.4k | output stringlengths 25 48.6k | system stringclasses 1
value | technology stringclasses 9
values | quality_score float64 5 10 | source stringclasses 2
values | meta dict |
|---|---|---|---|---|---|---|---|
so_3954927 | How to replace captured groups only?
I have HTML code before and after the string: I would like to replace the `0` with something like : `!NEW_ID!` So I made a simple regex : But I don't see how to replace exclusively the captured block. Is there a way to replace a captured result like ($1) with some other string ? Th... | A solution is to add captures for the preceding and following text: Explanation The parentheses are used to create "groups", which then get assigned a base-1 index, accessible in a replace with a `$`. the first word `(\w+)` is in a group, and becomes `$1` the middle part `(\d+)` is the second group (but gets ignored in... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 282
} | |
so_12797118 | How can I declare optional function parameters in JavaScript?
Can I declare default parameter like in JavaScript? | With ES6: This is now part of the language : Please keep in mind that ES6 checks the values against `undefined` and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default). With ES5: This works as long as all values you explicitly pass in are truthy . Valu... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 214
} | |
so_30280370 | How does Content Security Policy (CSP) work?
I'm getting a bunch of errors in the developer console: Refused to evaluate a string Refused to execute inline script because it violates the following Content Security Policy directive Refused to load the script Refused to load the stylesheet What's this all about? How doe... | The `Content-Security-Policy` meta-tag allows you to reduce the risk of XSS attacks by allowing you to define where resources can be loaded from, preventing browsers from loading data from any other locations. This makes it harder for an attacker to inject malicious code into your site. I banged my head against a brick... | javascript | 10 | stackoverflow | {
"tier": "deep_reasoning",
"total_tokens": 1555
} | |
so_7862233 | Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink
I'm developing a web page in which I'm using Twitter's Bootstrap Framework and their Bootstrap Tabs JS . It works great except for a few minor issues, one of which is I do not know how go directly to a specific tab from an external link. For exampl... | Here is my solution to the problem, a bit late perhaps. But it could maybe help others:
```
// Javascript to enable link to tab
var hash = location.hash.replace(/^#/, ''); // ^ means starting, meaning only match the first hash
if (hash) {
$('.nav-tabs a[href="#' + hash + '"]').tab('show');
}
// Change hash for ... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 214
} | |
so_9298839 | Is it possible to stop JavaScript execution?
Is it possible in some way to stop or terminate JavaScript in a way that it prevents any further JavaScript-based execution from occuring, without reloading the browser? I am thinking of a JavaScript equivalent of `exit()` in PHP. | Short answer: If you want to know more, keep reading. Do you want to stop JavaScript's execution for developing/debugging? The expression `debugger;` in your code, will halt the page execution, and then your browser's developer tools will allow you to review the state of your page at the moment it was frozen. Do you wa... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 554
} | |
so_10270351 | How to write an inline IF statement in JavaScript?
How can I use an inline `if` statement in JavaScript? Is there an inline `else` statement too? Something like this: | You don't necessarily need jQuery. JavaScript alone will do this. The `c` variable will be `minor` if the value is `true`, and `major` if the value is `false`. This is known as a Conditional (ternary) Operator. https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator
```
var a = 2;
... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 152
} | |
so_17037524 | orderBy multiple fields in Angular
How to sort by using multiple fields at same time in angular? fist by group and then by sub-group for Example I wanted to display this as group : Sub-group 1 - 1 1 - 2 1 - 20 2 - 1 2 - 10 2 - 11 | Please see this: http://jsfiddle.net/JSWorld/Hp4W7/32/
```
<div ng-repeat="division in divisions | orderBy:['group','sub']">{{division.group}}-{{division.sub}}</div>
``` | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 100
} | |
so_2087370 | Decode HTML entities in Python string?
I'm parsing some HTML with Beautiful Soup 3, but it contains HTML entities which Beautiful Soup 3 doesn't automatically decode for me: How can I decode the HTML entities in `text` to get `"£682m"` instead of `"£682m"`. | Python 3.4+ Use `html.unescape()` : FYI `html.parser.HTMLParser.unescape` is deprecated, and was supposed to be removed in 3.5 , although it was left in by mistake. It will be removed from the language soon. Python 2.6-3.3 You can use `HTMLParser.unescape()` from the standard library: For Python 2.6-2.7 it's in `HTMLPa... | python | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 318
} | |
so_3411771 | Best way to replace multiple characters in a string?
I need to replace some characters as follows: `&` ➔ `\&`, `#` ➔ `\#`, ... I coded as follows, but I guess there should be some better way. Any hints? | Replacing two characters I timed all the methods in the current answers along with one extra. With an input string of `abc&def#ghi` and replacing & -> \& and # -> \#, the fastest way was to chain together the replacements like this: `text.replace('&', '\&').replace('#', '\#')`. Timings for each function: a) 1000000 loo... | python | 10 | stackoverflow | {
"tier": "deep_reasoning",
"total_tokens": 2064
} | |
so_11277989 | How to get the focused element with jQuery?
Using jQuery, how can I get the input element that has the caret's (cursor's) focus? Or in other words, how to determine if an input has the caret's focus? | Which one should you use? quoting the jQuery docs : As with other pseudo-class selectors (those that begin with a ":"), it is recommended to precede :focus with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare `$(':focus')` is equivalent to `$('*:focus')`. ... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 261
} | |
so_30610523 | Reverse an array in JavaScript without mutating the original array
Array.prototype.reverse reverses the contents of an array in place (with mutation)... Is there a similarly simple strategy for reversing an array without altering the contents of the original array (without mutation)? | You can use slice() to make a copy then reverse() it
```
var newarray = array.slice().reverse();
```
```
var array = ['a', 'b', 'c', 'd', 'e'];
var newarray = array.slice().reverse();
console.log('a', array);
console.log('na', newarray);
``` | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 133
} | |
so_9575790 | How to get time in milliseconds since the unix epoch in Javascript?
Possible Duplicate: How do you get a timestamp in JavaScript? Calculating milliseconds from epoch How can I get the current `epoch` time in Javascript? Basically the number of milliseconds since midnight, 1970-01-01. | Date.now() returns a unix timestamp in milliseconds. Prior to ECMAScript5 (I.E. Internet Explorer 8 and older) you needed to construct a Date object, from which there are several ways to get a unix timestamp in milliseconds:
```
const now = Date.now(); // Unix timestamp in milliseconds
console.log( now );
```
```
co... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 177
} | |
so_1894792 | How to determine whether an object has a given property in JavaScript
How can I determine whether an object `x` has a defined property `y`, regardless of the value of `x.y`? I'm currently using but that seems a bit clunky. Is there a better way? | Object has property: If you are testing for properties that are on the object itself (not a part of its prototype chain) you can use `.hasOwnProperty()` : Object or its prototype has a property: You can use the `in` operator to test for properties that are inherited as well.
```
if (typeof(x.y) !== 'undefined')
```
`... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 163
} | |
so_16873323 | JavaScript sleep/wait before continuing
I have a JavaScript code that I need to add a sleep/wait function to. The code I am running is already in a function, eg: I have heard that a possible solution might include but I am not sure how to use it in this case. I can't use PHP, as my server does not support it, although... | JS does not have a sleep function, it has setTimeout() or setInterval() functions. If you can move the code that you need to run after the pause into the `setTimeout()` callback, you can do something like this: see example here : http://jsfiddle.net/9LZQp/ This won't halt the execution of your script, but due to the fa... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 482
} | |
so_41407414 | Convert string to Enum in Python
What's the correct way to convert a string to a corresponding instance of an `Enum` subclass? Seems like `getattr(YourEnumType, str)` does the job, but I'm not sure if it's safe enough. As an example, suppose I have an enum like Given the string `'debug'`, how can I get `BuildType.debu... | This functionality is already built in to `Enum` : The member names are case sensitive, so if user-input is being converted you need to make sure case matches:
```
class BuildType(Enum):
debug = 200
release = 400
```
```
>>> from enum import Enum
>>> class Build(Enum):
... debug = 200
... build = 400
... ... | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 195
} | |
so_798854 | All combinations of a list of lists
I'm basically looking for a python version of Combination of `List >` Given a list of lists, I need a new list that gives all the possible combinations of items between the lists. The number of lists is unknown, so I need something that works for all cases. Bonus points for elegance... | you need `itertools.product` :
```
>>> import itertools
>>> a = [[1,2,3],[4,5,6],[7,8,9,10]]
>>> list(itertools.product(*a))
[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 4, 10), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 5, 10), (1, 6, 7), (1, 6, 8), (1, 6, 9), (1, 6, 10), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 4, 10), (2, 5, 7), (2... | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 214
} | |
so_12572362 | How can I get a string after a specific substring?
How can I get a string after a specific substring? For example, I want to get the string after `"world"` in ...which in this case is: `". I'm a beginner"`) | The easiest way is probably just to split on your target word: split takes the word (or character) to split on and optionally a limit to the number of splits. In this example, split on "world" and limit it to only one split.
```
my_string = "Hello, Python world. I'm a beginner"
```
```
my_string = "Hello, Python worl... | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 146
} | |
so_17192158 | NameError: global name 'xrange' is not defined in Python 3
I am getting an error when running a python program: The game is from here . What causes this error? | You are trying to run a Python 2 codebase with Python 3. `xrange()` was renamed to `range()` in Python 3. Run the game with Python 2 instead. Don't try to port it unless you know what you are doing, most likely there will be more problems beyond `xrange()` vs. `range()`. For the record, what you are seeing is not a syn... | python | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 510
} | |
so_15993913 | Format date with Moment.js
I have a string in this format: I would like to use Moment.js get it in this format `mm/dd/yyyy : 04/12/2013` for display. I tried to do it using this method, Which errors and says `there is no such method called replace`? Am I approaching this in the wrong way? Edit I should also mention th... | The 2nd argument to `moment()` is a parsing format rather than a display format. To format a date, you want the `.format()` method : Also note that case does matter. For Month, Day of Month, and Year, the format should be uppercase.
```
var testDate = "Fri Apr 12 2013 19:08:55 GMT-0500 (CDT)"
```
```
moment(testDate,... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 533
} | |
so_929103 | Convert a number range to another range, maintaining ratio
I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point. I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these ... | Or a little more readable: Or if you want to protect for the case where the old range is 0 ( OldMin = OldMax ): Note that in this case we're forced to pick one of the possible new range values arbitrarily. Depending on context, sensible choices could be: `NewMin` ( see sample ), `NewMax` or `(NewMin + NewMax) / 2`
```... | python | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 370
} | |
so_1801668 | Convert a list with strings all to lowercase or uppercase
I have a Python list variable that contains strings. Is there a function that can convert all the strings in one pass to lowercase and vice versa, uppercase? | It can be done with list comprehensions or with the `map` function
```
>>> [x.lower() for x in ["A", "B", "C"]]
['a', 'b', 'c']
>>> [x.upper() for x in ["a", "b", "c"]]
['A', 'B', 'C']
```
```
>>> list(map(lambda x: x.lower(), ["A", "B", "C"]))
['a', 'b', 'c']
>>> list(map(lambda x: x.upper(), ["a", "b", "c"]))
['A',... | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 137
} | |
so_7409780 | Does reading an entire file leave the file handle open?
If you read an entire file with `content = open('Path/to/file', 'r').read()` is the file handle left open until the script exits? Is there a more concise method to read a whole file? | The answer to that question depends somewhat on the particular Python implementation. To understand what this is all about, pay particular attention to the actual `file` object. In your code, that object is mentioned only once, in an expression, and becomes inaccessible immediately after the `read()` call returns. This... | python | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 627
} | |
so_15115328 | Python Requests - No connection adapters
I'm using the Requests: HTTP for Humans library and I got this error: No connection adapters were found for '192.168.1.61:8080/api/call' What does this mean, and how can I fix it? | You need to include the protocol scheme: Without the `http://` part, Requests doesn’t have any idea how to connect to the remote server. Note that the protocol scheme must be all lowercase; if your URL starts with `HTTP://` for example, it won’t find the `http://` connection adapter either.
```
'http://192.168.1.61:80... | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 139
} | |
so_2013255 | How to get year/month/day from a date object?
`alert(dateObj)` gives `Wed Dec 30 2009 00:00:00 GMT+0800` How to get date in format `2009/12/30`? | or you can set new date and give the above values
```
const dateObj = new Date();
const month = dateObj.getUTCMonth() + 1; // months from 1-12
const day = dateObj.getUTCDate();
const year = dateObj.getUTCFullYear();
const newDate = year + "/" + month + "/" + day;
// Using template literals:
const newDate = ... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 179
} | |
so_3262605 | How to check whether a Storage item is set?
How can I check if an item is set in `localStorage`? Currently I am using | The `getItem` method in the WebStorage specification, explicitly returns `null` if the item does not exist: ... If the given key does not exist in the list associated with the object then this method must return null. ... So, you can: See this related question: Storing Objects in HTML5 localStorage
```
if (!(localStor... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 184
} | |
so_13943471 | What is the correct syntax of ng-include?
I’m trying to include an HTML snippet inside of an `ng-repeat`, but I can’t get the include to work. It seems the current syntax of `ng-include` is different than what it was previously: I see many examples using But in the official docs , it says to use But then down the page... | You have to single quote your `src` string inside of the double quotes: Source
```
<div ng-include src="'views/sidepanel.html'"></div>
``` | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 299
} | |
so_9133102 | How to grab substring before a specified character in JavaScript?
I am trying to extract everything before the ',' comma. How do I do this in JavaScript or jQuery? I tried this and not working.. I just want to grab the street address. | While it’s not the best place for definitive information on what each method does ( MDN Web Docs are better for that) W3Schools.com is good for introducing you to syntax.
```
1345 albany street, Bellevue WA 42344
```
```
var streetaddress= substr(addy, 0, index(addy, '.'));
```
```
const streetAddress = addy.substri... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 146
} | |
so_19304574 | Center/Set Zoom of Map to cover all visible Markers?
I am setting multiple markers on my map and I can set statically the zoom levels and the center but what I want is, to cover all the markers and zoom as much as possible having all markets visible Available methods are following `setZoom(zoom:number)` and `setCenter... | You need to use the `fitBounds()` method. Documentation from developers.google.com/maps/documentation/javascript : `fitBounds(bounds[, padding])` Parameters: Return Value: None Sets the viewport to contain the given bounds. Note : When the map is set to `display: none`, the `fitBounds` function reads the map's size as ... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 311
} | |
so_7588511 | Format a datetime into a string with milliseconds
How can I format a `datetime` object as a string with milliseconds? | To get a date string with milliseconds, use `[:-3]` to trim the last three digits of `%f` (microseconds): Or shorter: See the Python docs for more "`%`" format codes and the `strftime(3)` man page for the full list.
```
>>> from datetime import datetime
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
'2022... | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 144
} | |
so_11351032 | Named tuple and default values for optional keyword arguments
I'm trying to convert a longish hollow "data" class into a named tuple. My class currently looks like this: After conversion to `namedtuple` it looks like: But there is a problem here. My original class allowed me to pass in just a value and took care of th... | Python 3.7 Use the defaults parameter. Or better yet, use the new dataclasses library, which is much nicer than namedtuple. Before Python 3.7 Set `Node.__new__.__defaults__` to the default values. Before Python 2.6 Set `Node.__new__.func_defaults` to the default values. Order In all versions of Python, if you set fewer... | python | 10 | stackoverflow | {
"tier": "deep_reasoning",
"total_tokens": 927
} | |
so_8177079 | Take the content of a list and append it to another list
I am trying to understand if it makes sense to take the content of a list and append it to another list. I have the first list created through a loop function, that will get specific lines out of a file and will save them in a list. Then a second list is used to... | You probably want instead of Here's the difference: Since `list.extend()` accepts an arbitrary iterable, you can also replace by
```
# This is done for each log in my directory, i have a loop running
for logs in mydir:
for line in mylog:
#...if the conditions are met
list1.append(line)
for it... | python | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 484
} | |
so_9129928 | How to calculate number of days between two dates
I have two input dates taking from Date Picker control. I have selected start date 2/2/2012 and end date 2/7/2012. I have written following code for that. I should get result as 6 but I am getting 5. Can anyone tell me how I can get exact difference? | http://momentjs.com/ or https://date-fns.org/ From Moment docs: or to include the start: Beats messing with timestamps and time zones manually. Depending on your specific use case, you can either Use `a/b.startOf('day')` and/or `a/b.endOf('day')` to force the diff to be inclusive or exclusive at the "ends" (as suggeste... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 340
} | |
so_16607557 | Perform .join on value in array of objects
If I have an array of strings, I can use the `.join()` method to get a single string, with each element separated by commas, like so: I have an array of objects, and I’d like to perform a similar operation on a value held within it; so from perform the `join` method only on t... | If you want to map objects to something (in this case a property). I think `Array.prototype.map` is what you're looking for if you want to code functionally. (fiddle) If you want to support older browsers, that are not ES5 compliant you can shim it (there is a polyfill on the MDN page above). Another alternative would ... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 369
} | |
so_7687884 | Add 10 seconds to a Date
How can I add 10 seconds to a JavaScript date object? Something like this: | There's a `setSeconds` method as well: For a list of the other `Date` functions, you should check out MDN `setSeconds` will correctly handle wrap-around cases:
```
var timeObject = new Date()
var seconds = timeObject.getSeconds() + 10;
timeObject = timeObject + seconds;
```
```
var t = new Date();
t.setSeconds(t... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 161
} | |
so_22119673 | Find the closest ancestor element that has a specific class
How can I find an element's ancestor that is closest up the tree that has a particular class, in pure JavaScript ? For example, in a tree like so: Then I want `div.near.ancestor` if I try this on the `p` and search for `ancestor`. | Update: Now supported in most major browsers Note that this can match selectors, not just classes https://developer.mozilla.org/en-US/docs/Web/API/Element.closest For legacy browsers that do not support `closest()` but have `matches()` one can build selector-matching similar to @rvighne's class matching:
```
<div clas... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 230
} | |
so_13831601 | Disabling and enabling a HTML input button
So I have a button like this: How can I disable and enable it when I want? I have tried `disabled="disable"` but enabling it back is a problem. I tried setting it back to false but that didn't enable it. | Using Javascript Disabling a html button Enabling a html button Demo Here Using jQuery All versions of jQuery prior to 1.6 Disabling a html button Enabling a html button Demo Here All versions of jQuery after 1.6 Disabling a html button Enabling a html button Demo Here P.S. Updated the code based on jquery 1.6.1 change... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 264
} | |
so_3590165 | How can I convert each item in the list to string, for the purpose of joining them?
I need to join a list of items. Many of the items in the list are integer values returned from a function; i.e., How should I convert the returned result to a string in order to join it with the list? Do I need to do the following for ... | Calling `str(...)` is the Pythonic way to convert something to a string. You might want to consider why you want a list of strings. You could instead keep it as a list of integers and only convert the integers to strings when you need to display them. For example, if you have a list of integers then you can convert the... | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 223
} | |
so_5615648 | How can I call a function within a class?
I have this code which calculates the distance between two coordinates. The two functions are both within the same class. However, how do I call the function `distToPoint` in the function `isNear`? Currently I get a `NameError`: | Since these are member functions, call it as a member function on the instance, `self`.
```
def isNear(self, p):
self.distToPoint(p)
...
``` | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 105
} | |
so_5466618 | 'too many values to unpack', iterating over a dict. key=>string, value=>list
I am getting the `too many values to unpack` error. Any idea how I can fix this? | Python 3 Use `items()` . Python 2 Use `iteritems()` . See this answer for more information on iterating through dictionaries, such as using `items()`, across Python versions. For reference, `iteritems()` was removed in Python 3 .
```
first_names = ['foo', 'bar']
last_names = ['gravy', 'snowman']
fields = {
'first... | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 198
} | |
so_6624453 | What's the correct way to convert bytes to a hex string in Python 3?
What's the correct way to convert bytes to a hex string in Python 3? I see claims of a `bytes.hex` method, `bytes.decode` codecs, and have tried other possible functions of least astonishment without avail. I just want my bytes as hex! | Since Python 3.5 this is finally no longer awkward: and reverse: works also with the mutable `bytearray` type. Reference: https://docs.python.org/3/library/stdtypes.html#bytes.hex
```
>>> b'\xde\xad\xbe\xef'.hex()
'deadbeef'
```
```
>>> bytes.fromhex('deadbeef')
b'\xde\xad\xbe\xef'
``` | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 148
} | |
so_39740632 | Python type hinting without cyclic imports
I'm trying to split my huge class into two; well, basically into the "main" class and a mixin with additional functions, like so: `main.py` file: `mymixin.py` file: Now, while this works just fine, the type hint in `MyMixin.func2` of course can't work. I can't import `main.py... | There isn't a hugely elegant way to handle import cycles in general, I'm afraid. Your choices are to either redesign your code to remove the cyclic dependency, or if it isn't feasible, do something like this: The `TYPE_CHECKING` constant is always `False` at runtime, so the import won't be evaluated, but mypy (and othe... | python | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 631
} | |
so_18867599 | jQuery.inArray(), how to use it right?
First time I work with `jQuery.inArray()` and it acts kinda strange. If the object is in the array, it will return 0, but 0 is false in Javascript. So the following will output: "is NOT in array" I will have to change the if statement to: But this makes the code unreadable. Espec... | `inArray` returns the index of the element in the array, not a boolean indicating if the item exists in the array. If the element was not found, `-1` will be returned. So, to check if an item is in the array, use:
```
var myarray = [];
myarray.push("test");
if(jQuery.inArray("test", myarray)) {
console.log("is in... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 265
} | |
so_15615552 | Get div height with plain JavaScript
Any ideas on how to get a div's height without using jQuery? I was searching Stack Overflow for this question and it seems like every answer is pointing to jQuery's `.height()`. I tried something like `myDiv.style.height`, but it returned nothing, even when my div had its `width` a... | or `clientHeight` includes padding. `offsetHeight` includes padding, scrollBar and borders.
```
var clientHeight = document.getElementById('myDiv').clientHeight;
```
```
var offsetHeight = document.getElementById('myDiv').offsetHeight;
``` | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 146
} | |
so_56393880 | How do I detect dark mode using JavaScript?
Windows and macOS now have dark mode. I know that in CSS I could detect whether the OS is in dark mode like so: But I am using the Stripe Elements API, which puts colors in JavaScript , like so: How can I detect the OS's preferred color scheme in JavaScript? | To detect dark mode in JavaScript, you can query the user’s preferred color scheme via the CSS media feature `prefers-color-scheme` , and access it from JS using `window.matchMedia()` . If the user changes their OS/browser theme while your app is running, you can subscribe to changes by listening to the change event :
... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 384
} | |
so_4825295 | onClick to get the ID of the clicked button
How do find the id of the button which is being clicked? | You need to send the ID as the function parameters. Do it like this: This will send the ID `this.id` as `clicked_id` which you can use in your function. See it in action here.
```
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 191
} | |
so_6605640 | JavaScript by reference vs. by value
I'm looking for some good comprehensive reading material on when JavaScript passes something by value and when by reference and when modifying a passed item affects the value outside a function and when not. I'm also interested in when assigning to another variable is by reference ... | My understanding is that this is actually very simple: Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object. Changing the value of a variable never changes the underlying primitive or object, it just points the variable to a new primiti... | javascript | 10 | stackoverflow | {
"tier": "deep_reasoning",
"total_tokens": 849
} | |
so_4631928 | Convert UTC Epoch to local date
I have been fighting with this for a bit now. I’m trying to convert epoch to a date object. The epoch is sent to me in UTC. Whenever you pass `new Date()` an epoch, it assumes it’s local epoch. I tried creating a UTC object, then using `setTime()` to adjust it to the proper epoch, but t... | I think I have a simpler solution -- set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about `1234567890`. To convert that to a proper date in the local time zone: `d` is now a date (in my time zone) set to `Fri Feb 13 2009 18:31:30 GMT-0500 (EST)`
```
new Date( n... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 328
} | |
so_32536049 | Do I need to return after early resolve/reject?
Suppose I have the following code. If my aim is to use `reject` to exit early, should I get into the habit of `return`ing immediately afterward as well? | The `return` purpose is to terminate the execution of the function after the rejection, and prevent the execution of the code after it. In this case it prevents the `resolve(numerator / denominator);` from executing, which is not strictly needed. However, it's still preferable to terminate the execution to prevent a po... | javascript | 10 | stackoverflow | {
"tier": "deep_reasoning",
"total_tokens": 1086
} | |
so_18452920 | "continue" in cursor.forEach()
I'm building an app using meteor.js and MongoDB and I have a question about `cursor.forEach()`. I want to check some conditions in the beginning of each `forEach` iteration and then skip the element if I don't have to do the operation on it so I can save some time. Here is my code: I kno... | Each iteration of the `forEach()` will call the function that you have supplied. To stop further processing within any given iteration (and continue with the next item) you just have to `return` from the function at the appropriate point:
```
// Fetch all objects in SomeElements collection
var elementsCollection = Som... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 349
} | |
so_1009753 | Pass mouse events through absolutely-positioned element
I'm attempting to capture mouse events on an element with another absolutely-positioned element on top of it. Right now, events on the absolutely-positioned element hit it and bubble up to its parent, but I want it to be "transparent" to these mouse events and fo... | Is a CSS property that makes events "pass through" the HTML-element to which the property is applied. It makes the event occur on the element "below". See for details: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events It is supported by almost all browsers, including IE11; global support was ~98.2% in 05/... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 210
} | |
so_2255291 | Print the contents of a DIV
Whats the best way to print the contents of a DIV? | Slight changes over earlier version - tested on CHROME
```
function PrintElem(elem)
{
var mywindow = window.open('', 'PRINT', 'height=400,width=600');
mywindow.document.write('<html><head><title>' + document.title + '</title>');
mywindow.document.write('</head><body >');
mywindow.document.write('<h1>... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 181
} | |
so_10610402 | JavaScript - Replace all commas in a string
I have a string with multiple commas, and the string replace method will only change the first one: Result : `"thisnewcharis,a,test"` The documentation indicates that the default replaces all, and that "-1" also indicates to replace all, but it is unsuccessful. Any thoughts? | The third parameter of the `String.prototype.replace()` function was never defined as a standard, so most browsers simply do not implement it. It was eventually removed and replaced with `String.prototype.replaceAll()` (see below). Modern solution (2022) Use `String.prototype.replaceAll()` . It is now supported in all ... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 481
} | |
so_6312993 | JavaScript seconds to time string with format hh:mm:ss
I want to convert a duration of time, i.e., number of seconds to colon-separated time string (hh:mm:ss) I found some useful answers here but they all talk about converting to x hours and x minutes format. So is there a tiny snippet that does this in jQuery or just... | You can use it now like: Working snippet:
```
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minut... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 355
} | |
so_40181344 | How to annotate types of multiple return values?
How do I use type hints to annotate a function that returns an `Iterable` that always yields two values: a `bool` and a `str`? The hint `Tuple[bool, str]` is close, except that it limits the return value type to a tuple, not a generator or other type of iterable. I'm mo... | You are always returning one object; using `return one, two` simply returns a tuple. So yes, `-> Tuple[bool, str]` is entirely correct. Only the `Tuple` type lets you specify a fixed number of elements, each with a distinct type. You really should be returning a tuple, always, if your function produces a fixed number o... | python | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 575
} | |
so_15589517 | How to crop an image in OpenCV using Python
How can I crop images, like I've done before in PIL, using OpenCV. Working example on PIL But how I can do it on OpenCV? This is what I tried: But it doesn't work. I think I incorrectly used `getRectSubPix`. If this is the case, please explain how I can correctly use this fu... | It's very simple. Use numpy slicing.
```
import cv2
img = cv2.imread("lenna.png")
crop_img = img[y:y+h, x:x+w]
cv2.imshow("cropped", crop_img)
cv2.waitKey(0)
``` | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 122
} | |
so_10588644 | How can I see the entire HTTP request that's being sent by my Python application?
In my case, I'm using the Requests library to call PayPal's API over HTTPS. Unfortunately, I'm getting an error from PayPal, and PayPal support cannot figure out what the error is or what's causing it. They want me to "Please provide the... | A simple method: enable logging in recent versions of Requests (1.x and higher.) Requests uses the `http.client` and `logging` module configuration to control logging verbosity, as described here . Demonstration Code excerpted from the linked documentation: Example Output Output:
```
import requests
import logging
# ... | python | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 507
} | |
so_10388462 | Matplotlib different size subplots
I need to add two subplots to a figure. One subplot needs to be about three times as wide as the second (same height). I accomplished this using `GridSpec` and the `colspan` argument but I would like to do this using `figure` so I can save to PDF. I can adjust the first figure using ... | As of `matplotlib 3.6.0`, `width_ratios` and `height_ratios` can now be passed directly as keyword arguments to `plt.subplots` and `subplot_mosaic` , as per What's new in Matplotlib 3.6.0 (Sep 15, 2022) . `f, (a0, a1) = plt.subplots(1, 2, width_ratios=[3, 1])` `f, (a0, a1, a2) = plt.subplots(3, 1, height_ratios=[1, 1, ... | python | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 373
} | |
so_9868653 | Find first sequence item that matches a criterion
What would be the most elegant and efficient way of finding/returning the first list item that matches a certain criterion? For example, if I have a list of objects and I would like to get the first object of those with attribute `obj.val==5`. I could of course use lis... | If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found: This is however faster than a complete list comprehension. Compare these two: The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).
... | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 248
} | |
so_16878315 | What is the right way to treat Python argparse.Namespace() as a dictionary?
If I want to use the results of `argparse.ArgumentParser()`, which is a `Namespace` object, with a method that expects a dictionary or mapping-like object (see collections.Mapping ), what is the right way to do it? Is it proper to "reach into"... | You can access the namespace's dictionary with vars() : You can modify the dictionary directly if you wish: Yes, it is okay to access the __dict__ attribute. It is a well-defined, tested, and guaranteed behavior.
```
C:\>python
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win
32
Type "h... | python | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 443
} | |
so_39429526 | How to specify "nullable" return type with type hints
Suppose I have a function: How do I specify the return type for something that can be `None`? | You're looking for `Optional` . Since your return type can either be `datetime` (as returned from `datetime.utcnow()`) or `None` you should use `Optional[datetime]`: From the documentation on typing, `Optional` is shorthand for: `Optional[X]` is equivalent to `Union[X, None]`. where `Union[X, Y]` means a value of type ... | python | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 445
} | |
so_22413009 | Jasmine JavaScript Testing - toBe vs toEqual
Let's say I have the following: Both of the above tests will pass. Is there a difference between `toBe()` and `toEqual()` when it comes to evaluating numbers? If so, when I should use one and not the other? | For primitive types (e.g. numbers, booleans, strings, etc.), there is no difference between `toBe` and `toEqual`; either one will work for `5`, `true`, or `"the cake is a lie"`. To understand the difference between `toBe` and `toEqual`, let's imagine three objects. Using a strict comparison (`===`), some things are "th... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 430
} | |
so_222309 | Calculate last day of month
If you provide `0` as the `dayValue` in `Date.setFullYear` you get the last day of the previous month: There is reference to this behaviour at mozilla . Is this a reliable cross-browser feature or should I look at alternative methods? | Output differences are due to differences in the `toString()` implementation, not because the dates are different. Of course, just because the browsers identified above use 0 as the last day of the previous month does not mean they will continue to do so, or that browsers not listed will do so, but it lends credibility... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 391
} | |
so_13571700 | Get first and last date of current month with JavaScript or jQuery
As title says, I'm stuck on finding a way to get the first and last date of the current month with JavaScript or jQuery, and format it as: For example, for November it should be : | Very simple, no library required: or you might prefer: EDIT Some browsers will treat two digit years as being in the 20th century, so that: gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear :
```
var firstdate = '11/01/2012';
var lastdate = '11/30/2012';
```
```
var date = new ... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 241
} | |
so_5631384 | Remove everything after a certain character
Is there a way to remove everything after a certain character or just choose everything up to that character? I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters. Like this I want the href to be `/Controller/Acti... | You can also use the `split()` function. This seems to be the easiest one that comes to my mind :). jsFiddle Demo One advantage is this method will work even if there is no `?` in the string - it will return the whole string.
```
/Controller/Action?id=11112&value=4444
```
```
$('.Delete').click(function (e) {
e.... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 224
} | |
so_874709 | Converting user input string to regular expression
I am designing a regular expression tester in HTML and JavaScript. The user will enter a regex, a string, and choose the function they want to test with (e.g. search, match, replace, etc.) via radio button and the program will display the results when that function is... | Use the RegExp object constructor to create a regular expression from a string:
```
var re = new RegExp("a|b", "i");
// same as
var re = /a|b/i;
``` | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 317
} | |
so_6242976 | JavaScript hide/show element
How could I hide the 'Edit'-link after I press it? and also can I hide the "lorem ipsum" text when I press edit? | ```
function showStuff(id, text, btn) {
document.getElementById(id).style.display = 'block';
// hide the lorem ipsum text
document.getElementById(text).style.display = 'none';
// hide the link
btn.style.display = 'none';
}
```
```
<td class="post">
<a href="#" onclick="showStuff('answer1',... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 171
} | |
so_2007357 | How to set DOM element as first child?
I have an element E and I'm appending some elements to it. All of a sudden, I find out that the next element to append should be the first child of E. What's the trick, how to do it? Method unshift doesn't work because E is an object, not array. Long way would be to iterate throu... | ```
var eElement; // some E DOM instance
var newFirstElement; //element which should be first in E
eElement.insertBefore(newFirstElement, eElement.firstChild);
``` | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 141
} | |
so_6857468 | Converting a JS object to an array using jQuery
My application creates a JavaScript object, like the following: But I need this object as an array. So I tried to convert this object to an array by iterating with `$.each` through the object and adding the element to an array: Is there an better way to convert an object... | If you are looking for a functional approach: Results in: The same with an ES6 arrow function: With ES7 you will be able to use `Object.values` instead ( more information ): Or if you are already using Underscore/Lo-Dash:
```
myObj= {1:[Array-Data], 2:[Array-Data]}
```
```
array[1]:[Array-Data]
array[2]:[Array-Data]
... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 244
} | |
so_27639005 | How to copy static files to build directory with Webpack?
I'm trying to move from `Gulp` to `Webpack`. In `Gulp` I have task which copies all files and folders from /static/ folder to /build/ folder. How to do the same with `Webpack`? Do I need some plugin? | Requiring assets using the file-loader module is the way webpack is intended to be used ( source ). However, if you need greater flexibility or want a cleaner interface, you can also copy static files directly using my `copy-webpack-plugin` ( npm , Github ). For your `static` to `build` example: Compatibility note: If ... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 242
} | |
so_16824853 | Way to ng-repeat defined number of times instead of repeating over array?
Is there a way to `ng-repeat` a defined number of times instead of always having to iterate over an array? For example, below I want the list item to show up 5 times assuming `$scope.number` equal to 5 in addition incrementing the number so each... | Update (9/25/2018) Newer versions of AngularJS (>= 1.3.0) allow you to do this with only a variable (no function needed): This was not possible at the time the question was first asked. Credit to @Nikhil Nambiar from his answer below for this update Original (5/29/2013) At the moment, `ng-repeat` only accepts a collect... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 409
} | |
so_8603088 | SQLAlchemy IN clause
I'm trying to do this query in sqlalchemy I would like to bind the list `[123, 456]` at execution time. | How about edit : Without the ORM, it would be `select()` takes two parameters, the first one is a list of fields to retrieve, the second one is the `where` condition. You can access all fields on a table object via the `c` (or `columns`) property.
```
SELECT id, name FROM user WHERE id IN (123, 456)
```
```
session.q... | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 164
} | |
so_15012228 | Splitting on last delimiter in Python string?
What's the recommended Python idiom for splitting a string on the last occurrence of the delimiter in the string? example: `mysplit` takes a second argument that is the occurrence of the delimiter to be split. Like in regular list indexing, `-1` means the last from the end... | Use `.rsplit()` or `.rpartition()` instead: `str.rsplit()` lets you specify how many times to split, while `str.rpartition()` only splits once but always returns a fixed number of elements (prefix, delimiter & postfix) and is faster for the single split case. Demo: Both methods start splitting from the right-hand-side ... | python | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 511
} | |
so_2759067 | Rename multiple files in a directory in Python
I'm trying to rename some files in a directory using Python. Say I have a file called `CHEESE_CHEESE_TYPE.***` and want to remove `CHEESE_` so my resulting filename would be `CHEESE_TYPE` I'm trying to use the `os.path.split` but it's not working properly. I have also con... | Use `os.rename(src, dst)` to rename or move a file or a directory.
```
$ ls
cheese_cheese_type.bar cheese_cheese_type.foo
$ python
>>> import os
>>> for filename in os.listdir("."):
... if filename.startswith("cheese_"):
... os.rename(filename, filename[7:])
...
>>>
$ ls
cheese_type.bar cheese_type.foo
``` | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 179
} | |
so_2541752 | Best way to find the intersection of multiple sets?
I have a list of sets: I want s1 ∩ s2 ∩ s3 ... I can write a function to do it by performing a series of pairwise `s1.intersection(s2)`, etc. Is there a recommended, better, or built-in way? | From Python version 2.6 on you can use multiple arguments to `set.intersection()` , like If the sets are in a list, this translates to: where `*a_list` is list expansion Note that `set.intersection` is not a static method, but this uses the functional notation to apply intersection of the first set with the rest of the... | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 183
} | |
so_1402698 | Binding arrow keys in JS/jQuery
How do I go about binding a function to left and right arrow keys in Javascript and/or jQuery? I looked at the js-hotkey plugin for jQuery (wraps the built-in bind function to add an argument to recognize specific keys), but it doesn't seem to support arrow keys. | If you need to support IE8, start the function body as `e = e || window.event; switch(e.which || e.keyCode) {`. (edit 2020) Note that `KeyboardEvent.which` is now deprecated. See this example using `KeyboardEvent.key` for a more modern solution to detect arrow keys.
```
document.onkeydown = function(e) {
switch(e.... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 234
} | |
so_2727303 | jQuery counting elements by class - what is the best way to implement this?
What I'm trying to do is to count all of the elements in the current page with the same class and then I'm going to use it to be added onto a name for an input form. Basically I'm allowing users to click on a ` ` and then by doing so add anoth... | Should just be something like: As a side-note, it is often beneficial to check the length property before chaining a lot of functions calls on a jQuery object, to ensure that we actually have some work to perform. See below:
```
// Gets the number of elements with class yourClass
var numItems = $('.yourclass').length
... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 363
} | |
so_2271156 | Chrome desktop notification example
How does one use Chrome desktop notifications ? I'd like that use that in my own code. Update : Here's a blog post explaining webkit notifications with an example. | In modern browsers, there are two types of notifications: Desktop notifications - simple to trigger, work as long as the page is open, and may disappear automatically after a few seconds Service Worker notifications - a bit more complicated, but they can work in the background (even after the page is closed), are persi... | javascript | 10 | stackoverflow | {
"tier": "deep_reasoning",
"total_tokens": 778
} | |
so_17500704 | How can I set focus on an element in an HTML form using JavaScript?
I have a web form with a text box in it. How do I go about setting focus to the text box by default? Something like this: so can anybody help me with it? I don't know how to set focus to the text box with JavaScript. | Do this. If your element is something like this.. Your script would be
```
<input type="text" id="mytext"/>
```
```
<script>
function setFocusToTextBox(){
document.getElementById("mytext").focus();
}
</script>
``` | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 126
} | |
so_15287865 | Remove array element based on object property
I have an array of objects like so: How do I remove a specific one based on its property? e.g. How would I remove the array object with 'money' as the field property? | One possibility: Please note that `filter` creates a new array. Any other variables referring to the original array would not get the filtered data although you update your original variable `myArray` with the new reference. Use with caution.
```
var myArray = [
{field: 'id', operator: 'eq', value: id},
{fiel... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 182
} | |
so_19957348 | Remove all elements contained in another array
I am looking for an efficient way to remove all elements from a javascript array if they are present in another array. I want to operate on myArray to leave it in this state: `['a', 'd', 'e', 'f']` With jQuery, I'm using `grep()` and `inArray()`, which works well: Is ther... | Use the `Array.filter()` method: Small improvement, as browser support for `Array.includes()` has increased: Next adaptation using arrow functions :
```
// If I have this array:
var myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
// and this one:
var toRemove = ['b', 'c', 'g'];
```
```
myArray = $.grep(myArray, funct... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 256
} | |
so_38380462 | SyntaxError: Unexpected token o in JSON at position 1
I'm parsing some data using a type class in my controller. I'm getting data as follows: I tried to store the data like this How can I extract the user list to a new variable? | The JSON you posted looks fine, however in your code, it is most likely not a JSON string anymore, but already a JavaScript object. This means, no more parsing is necessary. You can test this yourself, e.g. in Chrome's console: `JSON.parse()` converts the input into a string. The `toString()` method of JavaScript objec... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 393
} | |
so_9538868 | Prevent BODY from scrolling when a modal is opened
I want my body to stop scrolling when using the mousewheel while the Modal (from http://twitter.github.com/bootstrap ) on my website is opened. I've tried to call the piece of javascript below when the modal is opened but without success AND Please note our website dr... | Bootstrap's `modal` automatically adds the class `modal-open` to the body when a modal dialog is shown and removes it when the dialog is hidden. You can therefore add the following to your CSS: You could argue that the code above belongs to the Bootstrap CSS code base, but this is an easy fix to add it to your site. Up... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 397
} | |
so_7905929 | How to test valid UUID/GUID?
How to check if variable contains valid UUID/GUID identifier? I'm currently interested only in validating types 1 and 4, but it should not be a limitation to your answers. | Currently, UUID's are as specified in RFC4122. An often neglected edge case is the NIL UUID, noted here . The following regex takes this into account and will return a match for a NIL UUID. See below for a UUID which only accepts non-NIL UUIDs. Both of these solutions are for versions 1 to 5 (see the first character of... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 274
} | |
so_18287482 | AngularJS 1.2 $injector:modulerr
When using angular 1.2 instead of 1.07 the following piece of code is not valid anymore, why? the issue is in the injector configuration part (app.config): If I remember correctly this issue started with angular 1.1.6. | The problem was caused by missing inclusion of ngRoute module. Since version 1.1.6 it's a separate part:
```
'use strict';
var app = angular.module('myapp', []);
app.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$ro... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 279
} | |
so_3871547 | Iterating over result of getElementsByClassName using Array.forEach
I want to iterate over some DOM elements, I'm doing this: but I get an error: document.getElementsByClassName("myclass").forEach is not a function I am using Firefox 3 so I know that both `getElementsByClassName` and `Array.forEach` are present. This ... | No, it's not an array. As specified in DOM4 , it's an `HTMLCollection` (in modern browsers, at least. Older browsers returned a `NodeList` ). In all modern browsers (pretty much anything other IE <= 8), you can call Array's `forEach` method, passing it the list of elements (be it `HTMLCollection` or `NodeList`) as the ... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 352
} | |
so_7060750 | Detect the Enter key in a text input field
I'm trying to do a function if enter is pressed while on specific input. What I'm I doing wrong? Is there a better way of doing this which would say, if enter pressed on `.input1` do function? | ```
$(".input1").on('keyup', function (e) {
if (e.key === 'Enter' || e.keyCode === 13) {
// Do something
}
});
// e.key is the modern way of detecting keys
// e.keyCode is deprecated (left here for for legacy browsers support)
// keyup is not compatible with Jquery select(), Keydown is.
``` | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 136
} | |
so_1695183 | How can I percent-encode URL parameters in Python?
If I do It doesn't encode `/` to `%2F` (breaks OAuth normalization) It doesn't handle Unicode (it throws an exception) Is there a better library? | From the Python 3 documentation : Replace special characters in string using the `%xx` escape. Letters, digits, and the characters `'_.-~'` are never quoted. By default, this function is intended for quoting the path section of a URL. The optional safe parameter specifies additional ASCII characters that should not be ... | python | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 315
} | |
so_6531482 | How to check if a string contains an element from a list in Python
I have something like this: I am wondering what would be the more elegant way to do this in Python (without using the for loop)? I was thinking of something like this (like from C/C++), but it didn't work: Edit: I'm kinda forced to explain how this is ... | Use a generator together with `any`, which short-circuits on the first True: EDIT: I see this answer has been accepted by OP. Though my solution may be "good enough" solution to his particular problem, and is a good general way to check if any strings in a list are found in another string, keep in mind that this is all... | python | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 435
} | |
so_9202224 | Getting a hidden password input
You know how in Linux when you try some Sudo stuff it tells you to enter the password and, as you type, nothing is shown in the terminal window (the password is not shown)? Is there a way to do that in Python? I'm working on a script that requires so sensitive info and would like for it... | Use `getpass.getpass()` : An optional prompt can be passed as parameter; the default is `"Password: "`. Note that this function requires a proper terminal, so it can turn off echoing of typed characters – see “GetPassWarning: Can not control echo on the terminal” when running from IDLE for further details.
```
from ge... | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 201
} | |
so_2083987 | How to retry after exception?
I have a loop starting with `for i in range(0, 100)`. Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will `continue` in the except clause (continue on to the next number for `i`). Is it possible for me to reassi... | Do a `while True` inside your for loop, put your `try` code inside, and break from that `while` loop only when your code succeeds.
```
for i in range(0,100):
while True:
try:
# do stuff
except SomeSpecificException:
continue
break
``` | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 172
} | |
so_1278705 | When I catch an exception, how do I get the type, file, and line number?
Catching an exception that would print like this: I want to format it into: | ```
import sys, os
try:
raise NotImplementedError("No error")
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
``` | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 99
} | |
so_919680 | Can a variable number of arguments be passed to a function?
In a similar way to using varargs in C or C++: | Yes. You can use `*args` as a non-keyword argument. You will then be able to pass any number of arguments. As you can see, Python will unpack the arguments as a single tuple with all the arguments. For keyword arguments you need to accept those as a separate actual argument, as shown in Skurmedel's answer .
```
fn(a, ... | python | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 163
} | |
so_40385133 | Retrieve data from a ReadableStream object?
How may I get information from a `ReadableStream` object? I am using the Fetch API and I don't see this to be clear from the documentation. The body is being returned as a `ReadableStream` and I would simply like to access a property within this stream. Under Response in the... | In order to access the data from a `ReadableStream` you need to call one of the conversion methods (docs available here ). As an example: EDIT: If your data return type is not JSON or you don't want JSON then use `text()` As an example:
```
fetch('http://192.168.5.6:2000/api/car', obj)
.then((res) => {
if(... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 408
} | |
so_20300866 | AngularJS ng-click stopPropagation
I have a click Event on a table row and in this row there is also a delete Button with a click Event. When i click the delete button the click Event on the row is also fired. Here is my code. How can I prevent that the `showUser` Event is fired when i click the delete Button in the t... | ngClick directive (as well as all other event directives) creates `$event` variable which is available on same scope. This variable is a reference to JS `event` object and can be used to call `stopPropagation()`: PLUNKER
```
<tbody>
<tr ng-repeat="user in users" class="repeat-animation" ng-click="showUser(user, $ind... | javascript | 10 | stackoverflow | {
"tier": "medium",
"total_tokens": 294
} | |
so_169506 | Obtain form input fields using jQuery?
I have a form with many input fields. When I catch the submit form event with jQuery, is it possible to get all the input fields of that form in an associative array? | Thanks to the tip from Simon_Weaver, here is another way you could do it, using `serializeArray` : Note that this snippet will fail on ` ` elements. It appears that the new HTML 5 form inputs don't work with `serializeArray` in jQuery version 1.3. This works in version 1.4+
```
$('#myForm').submit(function() {
// ... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 237
} | |
so_7196212 | How to create a dictionary and add key value pairs dynamically in JavaScript
From post: Sending a JSON array to be received as a Dictionary<string,string> , I'm trying to do this same thing as that post. The only issue is that I don't know what the keys and the values are upfront. So I need to be able to dynamically a... | Use: Basically, you're creating an object literal with two properties (called `key` and `value`) and inserting it (using `push()`) into the array. This does not create a "normal" JavaScript object literal (aka map, aka hash, aka dictionary). It is however creating the structure that OP asked for (and which is illustrat... | javascript | 10 | stackoverflow | {
"tier": "deep_reasoning",
"total_tokens": 986
} | |
so_15617164 | Parsing JSON giving "unexpected token o" error
I am having a problem parsing simple JSON strings. I have checked them on JSONLint and it shows that they are valid. But when I try to parse them using either `JSON.parse` or the jQuery alternative it gives me the error `unexpected token o`: Note: I'm encoding my strings ... | Your data is already an object. No need to parse it. The javascript interpreter has already parsed it for you.
```
<!doctype HTML>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
var ques_list = JSON.parse(cur_ques_de... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 221
} | |
so_13047923 | Working with select using AngularJS's ng-options
I have read about it in other posts, but I couldn't figure it out. I have an array, I want to render it as: And also I want to select the option with ID=000002. I have read select and tried, but I can't figure it out. | One thing to note is that ngModel is required for ngOptions to work... note the `ng-model="blah"` which is saying "set $scope.blah to the selected value". Try this: Here's more from AngularJS's documentation (if you haven't seen it): for array data sources: label for value in array select as label for value in array la... | javascript | 10 | stackoverflow | {
"tier": "deep_reasoning",
"total_tokens": 961
} | |
so_1481152 | How to detect a textbox's content has changed
I want to detect whenever a textbox's content has changed. I can use the keyup method, but that will also detect keystrokes which do not generate letters, like the arrow keys. I thought of two methods of doing this using the keyup event: Check explictly if the ascii code o... | Start observing 'input' event instead of 'change'. ...which is nice and clean, but may be extended further to:
```
jQuery('#some_text_box').on('input', function() {
// do your stuff
});
```
```
jQuery('#some_text_box').on('input propertychange paste', function() {
// do your stuff
});
``` | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 202
} | |
so_3914557 | Passing arguments forward to another javascript function
I've tried the following with no success: In function a, I can use the arguments keyword to access an array of arguments, in function b these are lost. Is there a way of passing arguments to another javascript function like I try to do? | Use `.apply()` to have the same access to `arguments` in function `b`, like this: You can test it out here .
```
function a(args){
b(arguments);
}
function b(args){
// arguments are lost?
}
a(1,2,3);
```
```
function a(){
b.apply(null, arguments);
}
function b(){
console.log(arguments); //arguments[... | javascript | 10 | stackoverflow | {
"tier": "short",
"total_tokens": 160
} |
Code & Programming Q&A — SFT Dataset
A curated instruction-tuning dataset of 47,190 high-quality programming question-answer pairs, collected from StackOverflow and GitHub, cleaned through a multi-stage quality pipeline, and formatted in Alpaca style for supervised fine-tuning (SFT) of large language models.
Dataset Summary
| Property | Value |
|---|---|
| Records | 47,190 |
| Format | Alpaca (instruction / output / system) |
| Total tokens | ~23.0 Million |
| Avg tokens / record | 486 |
| Min quality score | 5.00 / 10 |
| Avg quality score | 7.71 / 10 |
| High quality (≥ 7.0) | 31,486 records (66.7%) |
| Primary language | English |
| Primary source | StackOverflow (99.8%) |
Supported Tasks
- Supervised Fine-Tuning (SFT): Direct use with TRL
SFTTrainer, Unsloth, LLaMA-Factory, or Axolotl — no preprocessing required. - Instruction Following: Model learns to answer technical questions with explanation and code examples.
- Code Generation: 65%+ of records contain at least one code block in the output.
Data Collection
Sources
| Source | Records | % |
|---|---|---|
| StackOverflow (via API) | 47,119 | 99.8% |
| GitHub Issues / Discussions | 71 | 0.2% |
Data was collected using a custom async pipeline with the official StackOverflow API v2.3 and GitHub REST API v3.
StackOverflow Collection Rules
- Only questions with at least one accepted or upvoted answer were collected.
question_score + answer_scoreused as raw quality signal.- Questions tagged with target technology domains (SQL, Python, JavaScript, PHP, Shell, DevOps, TypeScript, System Design, WordPress).
- Collected answers: accepted answer preferred; fallback to highest-voted answer.
- API quota managed with exponential back-off on rate limits.
GitHub Collection Rules
- Issues and discussions with substantive responses only.
- Comment pagination handled to capture full thread context (100+ comment issues).
- Dismissal patterns filtered out ("please provide a repro", "closing as duplicate", etc.).
Processing Pipeline
Every raw record passes through a 4-stage pipeline before entering the dataset:
Raw API Response
│
▼
┌────────────────────────────────────┐
│ Stage 1: clean() │
│ • Whitespace normalization │
│ • Empty block removal │
│ • Within-record code dedup │ ← same code block repeated → keep first
└──────────────┬─────────────────────┘
│
▼
┌────────────────────────────────────┐
│ Stage 2: dedup() │
│ • SHA-256 hash of all content │
│ • Cross-record exact dedup │
└──────────────┬─────────────────────┘
│
▼
┌────────────────────────────────────┐
│ Stage 3: quality() │
│ • Fusion scoring (0–10) │
│ • signal_score (SO votes) │
│ • length_score (content size) │
│ • code_score (has code block) │
│ • Records < 5.0 dropped │
└──────────────┬─────────────────────┘
│
▼
┌────────────────────────────────────┐
│ Stage 4: Indexer filters │
│ • Link-only answers filtered │
│ • GitHub dismissal filtered │
│ • Content dedup (SHA-1 Q+A) │
└──────────────┬─────────────────────┘
│
▼
dataset.jsonl
Quality Scoring Formula
Scores are on a 0–10 scale, computed as a weighted fusion:
When source signal exists (SO votes, GH reactions):
score = (0.6 × signal_score + 0.3 × length_score + 0.1 × code_score) × 10
When no source signal (file sources):
score = (0.7 × length_score + 0.3 × code_score) × 10
Where:
signal_score = min(1.0, log1p(raw_votes) / log1p(1000))— 1000 votes → 1.0, 100 votes → 0.67length_score = min(1.0, total_chars / 500)— 500+ chars → full scorecode_score = 1.0 if code present else 0.3
Only records with quality_score >= 5.0 are exported to this dataset.
Dataset Structure
Data Fields
| Field | Type | Description |
|---|---|---|
id |
string |
Unique record identifier (source-prefixed, e.g. so_12345678) |
instruction |
string |
The question / prompt (from user role) |
output |
string |
The answer with optional code blocks in markdown |
system |
string |
System prompt — always empty string "" in this dataset |
technology |
string |
Domain label: python, sql, javascript, php, shell_scripting, devops, typescript, system_design, wordpress |
quality_score |
float |
Quality score 5.01–10.0 |
source |
string |
Data source: stackoverflow or github |
meta.tier |
string |
Complexity tier: short, medium, or deep_reasoning |
meta.total_tokens |
int |
Approximate token count (chars / 4) |
Example Record
{
"id": "so_53927460",
"instruction": "How do I merge two dictionaries in a single expression in Python?\n\nI want to merge two dictionaries into a new dictionary. If both dicts have the same key, the second dict's value should take precedence.",
"output": "In Python 3.9+, you can use the merge operator:\n\n```python\nz = x | y\n```\n\nFor older Python versions:\n\n```python\nz = {**x, **y}\n```\n\nThis creates a new dictionary. Values from `y` overwrite values from `x` when keys overlap.",
"system": "",
"technology": "python",
"quality_score": 9.87,
"source": "stackoverflow",
"meta": {
"tier": "medium",
"total_tokens": 312
}
}
Tier Distribution
The meta.tier field classifies records by approximate token length, designed for hardware-aware SFT sampling:
| Tier | Token Range | Records | % | Purpose |
|---|---|---|---|---|
short |
0–256 tokens | 15,582 | 33.0% | Quick Q&A, definitions |
medium |
256–768 tokens | 24,421 | 51.8% | Explained answers with code |
deep_reasoning |
768+ tokens | 7,187 | 15.2% | Complex multi-step solutions |
Technology Distribution
| Technology | Records |
|---|---|
| SQL | 8,730 |
| Shell Scripting | 8,355 |
| Python | 7,540 |
| PHP | 6,377 |
| JavaScript | 6,058 |
| System Design | 4,429 |
| DevOps | 3,255 |
| TypeScript | 1,909 |
| WordPress | 537 |
Quality Distribution
| Score Range | Records | % |
|---|---|---|
| 9.0 – 10.0 | 8,666 | 18.4% |
| 7.0 – 9.0 | 22,820 | 48.4% |
| 5.0 – 7.0 | 15,704 | 33.3% |
Usage
Load with 🤗 Datasets
from datasets import load_dataset
ds = load_dataset("hadilenya/AI-Trainer-Studio", split="train")
print(ds[0])
SFT with TRL
from datasets import load_dataset
from trl import SFTTrainer, SFTConfig
ds = load_dataset("hadilenya/AI-Trainer-Studio", split="train")
def formatting_func(example):
return f"### Instruction:\n{example['instruction']}\n\n### Response:\n{example['output']}"
trainer = SFTTrainer(
model=model,
train_dataset=ds,
formatting_func=formatting_func,
args=SFTConfig(max_seq_length=2048, ...),
)
trainer.train()
Mistral / Llama-3 Chat Format
def to_mistral(example):
return f"<s>[INST] {example['instruction']} [/INST] {example['output']}</s>"
def to_llama3(example):
return (
f"<|begin_of_text|>"
f"<|start_header_id|>user<|end_header_id|>\n{example['instruction']}<|eot_id|>"
f"<|start_header_id|>assistant<|end_header_id|>\n{example['output']}<|eot_id|>"
)
Hardware-Aware Sampling (with meta.tier)
# RTX 2060 (6GB) — VRAM-safe sampling
short = ds.filter(lambda x: x["meta"]["tier"] == "short")
medium = ds.filter(lambda x: x["meta"]["tier"] == "medium")
deep = ds.filter(lambda x: x["meta"]["tier"] == "deep_reasoning")
# Ratio: short 60% · medium 35% · deep 5%
from datasets import concatenate_datasets
n = 8000
sampled = concatenate_datasets([
short.shuffle(seed=42).select(range(min(int(n*0.60), len(short)))),
medium.shuffle(seed=42).select(range(min(int(n*0.35), len(medium)))),
deep.shuffle(seed=42).select(range(min(int(n*0.05), len(deep)))),
])
Filter by Technology
python_ds = ds.filter(lambda x: x["technology"] == "python")
sql_ds = ds.filter(lambda x: x["technology"] == "sql")
Filter by Quality
# High quality only (≥ 7.0 — 69.4% of dataset)
high_quality = ds.filter(lambda x: x["quality_score"] >= 7.0)
Data Splits
This dataset is released as a single train split. For training, we recommend creating your own train/validation/test split:
split = ds.train_test_split(test_size=0.08, seed=42)
train_ds = split["train"]
eval_ds = split["test"]
Limitations & Considerations
- Language: All records are in English. Not suitable for multilingual fine-tuning without translation.
- Source bias: 99.8% StackOverflow — answers reflect Stack Overflow community norms (concise, code-first).
- Time range: Data collected in 2026. May not reflect very recent library versions or deprecations.
- Domain scope: Focused on web development, scripting, databases, and DevOps. Not suitable for domain-specific fine-tuning in medicine, law, finance, etc.
- Code correctness: Code blocks are sourced from community answers. While high-vote answers are generally correct, no automated code execution or test verification was performed.
- GitHub records (0.2%): Very small fraction — 70 records from GitHub Issues. Treat as supplementary.
License
This dataset is released under the Creative Commons Attribution 4.0 (CC BY 4.0) license.
StackOverflow content is licensed under CC BY-SA 4.0. Attribution is preserved via the id field (e.g., so_12345678 links to https://stackoverflow.com/q/12345678).
Citation
If you use this dataset in your research or project, please cite:
@dataset{code_qa_sft_2026,
title = {Code \& Programming Q\&A — SFT Dataset},
author = {Muharrem},
year = {2026},
publisher = {HuggingFace},
url = {https://huggingface.co/datasets/hadilenya/AI-Trainer-Studio}
}
Changelog
| Version | Date | Description |
|---|---|---|
| v1.0 | 2026-05-17 | Initial release — 47,190 records, Alpaca format, meta.tier annotation |
Kod & Programlama Soru-Cevap — SFT Veri Seti
StackOverflow ve GitHub'dan derlenen, çok aşamalı bir kalite boru hattından geçirilmiş 47.190 yüksek kaliteli programlama soru-cevap çiftinden oluşan, büyük dil modellerinin ince ayarı (SFT) için Alpaca formatında hazırlanmış bir veri setidir.
Özet
| Özellik | Değer |
|---|---|
| Kayıt sayısı | 47.190 |
| Format | Alpaca (instruction / output / system) |
| Toplam token | ~23,0 Milyon |
| Ortalama token / kayıt | 486 |
| Min kalite skoru | 5,00 / 10 |
| Ort kalite skoru | 7,71 / 10 |
| Yüksek kalite (≥ 7,0) | 31.486 kayıt (%66,7) |
| Ana dil | İngilizce |
| Ana kaynak | StackOverflow (%99,8) |
Veri Toplama
Kaynaklar
| Kaynak | Kayıt | % |
|---|---|---|
| StackOverflow (resmi API v2.3) | 47.119 | %99,8 |
| GitHub Issues / Discussions | 71 | %0,2 |
Veriler, özel bir asenkron pipeline ile StackOverflow API v2.3 ve GitHub REST API v3 üzerinden toplanmıştır.
StackOverflow Toplama Kuralları
- Yalnızca kabul edilmiş veya yüksek oy almış en az bir cevabı olan sorular alındı.
soru_oyu + cevap_oyutoplamı ham kalite sinyali olarak kullanıldı.- Hedef teknoloji etiketleri: SQL, Python, JavaScript, PHP, Shell, DevOps, TypeScript, Sistem Tasarımı, WordPress.
- Önce kabul edilmiş cevap; yoksa en yüksek oylanan cevap.
- Rate limit aşımlarında üstel geri çekilme (exponential back-off) ile kota yönetimi.
GitHub Toplama Kuralları
- Yalnızca gerçek içerik barındıran yanıtlı issue ve tartışmalar.
- 100+ yorum içeren issue'larda sayfalama ile tam içerik çekildi.
- "Lütfen repro ekleyin", "duplicate olarak kapatılıyor" gibi reddedici kalıplar otomatik filtrelendi.
İşleme Boru Hattı
Her ham kayıt veri setine girmeden önce 4 aşamalı bir pipeline'dan geçer:
Ham API Yanıtı
│
▼
┌────────────────────────────────────┐
│ Aşama 1: clean() │
│ • Boşluk normalleştirme │
│ • Boş blok temizleme │
│ • Kayıt içi kod bloğu dedup │ ← aynı blok tekrar ediyorsa ilki korunur
└──────────────┬─────────────────────┘
│
▼
┌────────────────────────────────────┐
│ Aşama 2: dedup() │
│ • SHA-256 içerik hash'i │
│ • Kayıtlar arası tam eşleşme │
└──────────────┬─────────────────────┘
│
▼
┌────────────────────────────────────┐
│ Aşama 3: quality() │
│ • Füzyon skoru (0–10) │
│ • signal_score (SO oyu) │
│ • length_score (içerik uzunl.) │
│ • code_score (kod bloğu var?) │
│ • 5,0 altı kayıtlar elenir │
└──────────────┬─────────────────────┘
│
▼
┌────────────────────────────────────┐
│ Aşama 4: İndeksleyici filtresl.│
│ • Sadece link olan cevap elenir│
│ • GitHub reddedici yorum elenir│
│ • İçerik dedup (SHA-1 S+C) │
└──────────────┬─────────────────────┘
│
▼
dataset.jsonl
Kalite Skoru Formülü (0–10)
Kaynak sinyali varsa (SO oyu, GH reaksiyonu):
skor = (0,6 × sinyal_skoru + 0,3 × uzunluk_skoru + 0,1 × kod_skoru) × 10
Kaynak sinyali yoksa:
skor = (0,7 × uzunluk_skoru + 0,3 × kod_skoru) × 10
sinyal_skoru = min(1,0, log1p(ham_oy) / log1p(1000))— 1000 oy → 1,0 · 100 oy → 0,67uzunluk_skoru = min(1,0, toplam_karakter / 500)— 500+ karakter → tam puankod_skoru = 1,0 (kod varsa) | 0,3 (kod yoksa)
Yalnızca kalite_skoru >= 5,0 olan kayıtlar dışa aktarılır.
Veri Seti Yapısı
Alanlar
| Alan | Tür | Açıklama |
|---|---|---|
id |
string |
Benzersiz kayıt kimliği (örn. so_12345678) |
instruction |
string |
Soru / prompt (kullanıcı rolünden) |
output |
string |
Markdown içinde opsiyonel kod bloklarıyla cevap |
system |
string |
Sistem prompt'u — bu veri setinde her zaman boş "" |
technology |
string |
Domain etiketi: python, sql, javascript, php, shell_scripting, devops, typescript, system_design, wordpress |
quality_score |
float |
Kalite skoru 5,01–10,0 |
source |
string |
Kaynak: stackoverflow veya github |
meta.tier |
string |
Karmaşıklık kademesi: short, medium, deep_reasoning |
meta.total_tokens |
int |
Yaklaşık token sayısı (karakter / 4) |
Kademe (Tier) Dağılımı
meta.tier alanı, donanıma göre akıllı örnekleme için kayıtları uzunluklarına göre sınıflandırır:
| Kademe | Token Aralığı | Kayıt | % | Temsil Ettiği İçerik |
|---|---|---|---|---|
short |
0–256 token | 15.582 | %33,0 | Kısa S&C, tanımlar |
medium |
256–768 token | 24.421 | %51,8 | Kodlu açıklamalı cevaplar |
deep_reasoning |
768+ token | 7.187 | %15,2 | Karmaşık çok adımlı çözümler |
Kalite Dağılımı
| Skor Aralığı | Kayıt | % |
|---|---|---|
| 9,0 – 10,0 | 8.666 | %18,4 |
| 7,0 – 9,0 | 22.820 | %48,4 |
| 5,0 – 7,0 | 15.704 | %33,3 |
Teknoloji Dağılımı
| Teknoloji | Kayıt |
|---|---|
| SQL | 8.730 |
| Shell Scripting | 8.355 |
| Python | 7.540 |
| PHP | 6.377 |
| JavaScript | 6.058 |
| Sistem Tasarımı | 4.429 |
| DevOps | 3.255 |
| TypeScript | 1.909 |
| WordPress | 537 |
Kullanım
🤗 Datasets ile Yükleme
from datasets import load_dataset
ds = load_dataset("hadilenya/AI-Trainer-Studio", split="train")
print(ds[0])
TRL ile SFT Eğitimi
from datasets import load_dataset
from trl import SFTTrainer, SFTConfig
ds = load_dataset("hadilenya/AI-Trainer-Studio", split="train")
def formatting_func(example):
return f"### Instruction:\n{example['instruction']}\n\n### Response:\n{example['output']}"
trainer = SFTTrainer(
model=model,
train_dataset=ds,
formatting_func=formatting_func,
args=SFTConfig(max_seq_length=2048, ...),
)
trainer.train()
Donanıma Göre Örnekleme (meta.tier ile)
# RTX 2060 (6 GB VRAM) — güvenli örnekleme
short = ds.filter(lambda x: x["meta"]["tier"] == "short")
medium = ds.filter(lambda x: x["meta"]["tier"] == "medium")
deep = ds.filter(lambda x: x["meta"]["tier"] == "deep_reasoning")
# Oran: short %60 · medium %35 · deep %5
from datasets import concatenate_datasets
n = 8000
sampled = concatenate_datasets([
short.shuffle(seed=42).select(range(min(int(n*0.60), len(short)))),
medium.shuffle(seed=42).select(range(min(int(n*0.35), len(medium)))),
deep.shuffle(seed=42).select(range(min(int(n*0.05), len(deep)))),
])
Teknoloji veya Kaliteye Göre Filtreleme
python_ds = ds.filter(lambda x: x["technology"] == "python")
yuksek_kal = ds.filter(lambda x: x["quality_score"] >= 7.0)
Kısıtlamalar
- Dil: Tüm kayıtlar İngilizce'dir. Çok dilli ince ayar için çeviri gerekir.
- Kaynak yanlılığı: %99,8 StackOverflow — cevaplar SO topluluğu normlarını yansıtır (özlü, kod öncelikli).
- Zaman aralığı: Veriler 2026 yılında toplandı. Çok yeni kütüphane sürümleri veya kullanımdan kalkmış API'lar yansıtılmayabilir.
- Kapsam: Web geliştirme, betik yazımı, veritabanları ve DevOps odaklıdır. Tıp, hukuk, finans gibi uzmanlık alanları için uygun değildir.
- Kod doğruluğu: Kod blokları topluluk cevaplarından alınmıştır. Yüksek oylu cevaplar genellikle doğru olsa da otomatik kod çalıştırma veya test doğrulaması yapılmamıştır.
Lisans
Bu veri seti Creative Commons Attribution 4.0 (CC BY 4.0) lisansı altında yayımlanmıştır.
StackOverflow içeriği CC BY-SA 4.0 kapsamındadır. Atıf, id alanı aracılığıyla korunmaktadır (örn. so_12345678 → https://stackoverflow.com/q/12345678).
Değişiklik Günlüğü
| Sürüm | Tarih | Açıklama |
|---|---|---|
| v1.0 | 17 Mayıs 2026 | İlk yayın — 47.190 kayıt, Alpaca format, meta.tier anotasyonu |
- Downloads last month
- 57