Dive into Code

Discover code snippets, tutorials, and programming insights

jQuery

Handlebars selectbox helper

Handlebars selectbox helper

javascript
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Handlebars.registerHelper("makeSelectBox", function(name, value, options){
       let items = options;
       let output = '<label for="'+name+'" class="form-label">'+name+'</label><select class="form-control" name="'+name +'">'
       for(let val in items){
         let id = parseInt(items[val].id);
         if(value != '' && parseInt(value) == id){
           output +='<option value="'+ id +'" selected>'+items[val].name +'</option>';
         }
         else{
           output +='<option value="'+ id +'">'+items[val].name +'</option>';
         }
       }
       output += '</select>'
       return output;
     });
Django

example gulpfile to work with django

<p>This is a Gulp configuration file used to automate various tasks for a web development project. It utilizes various Gulp plugins to minify CSS and JavaScript files, concatenate them, and …

javascript
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const { parallel, src, dest, watch, series } = require('gulp');
const gulp = require("gulp");
let rename = require("gulp-rename");
const cleanCSS = require('gulp-clean-css');
const minify = require('gulp-minify');
let wrap = require('gulp-wrap');
let declare = require('gulp-declare');
let concat = require('gulp-concat');
let exec = require('child_process').exec;
const browsersync = require('browser-sync').create();
let spawn = require('child_process').spawn;

function css(){
  return gulp.src([
        './static/src/css/*.css'])
     .pipe(concat('site.css'))
     .pipe(cleanCSS({compatibility: 'ie8'}))
     .pipe(rename({extname:'.min.css'}))
     .pipe(gulp.dest('./static/build/css'))
     .pipe(browsersync.reload({
       stream: true
     }))
}

function vendor(){
  return gulp.src([
        './static/src/js/jquery-3.6.0.min.js',
        './static/src/js/popper.min.js',
        './static/src/js/bootstrap.min.js',
        './static/src/js/django_ajax.js',
        './static/src/js/site.js',
      ])
     .pipe(concat('site.js'))
     .pipe(minify())
     .pipe(gulp.dest('./static/build/js'))
     .pipe(browsersync.reload({
       stream: true
      }))
}


function browsersyncServe(cb){
  browsersync.init({
          notify: false,
          proxy: "localhost:8000"
  });
  browsersync.watch('static/src/css/**/*.css', series(css));
  browsersync.watch('static/src/js/**/*.js', series(vendor));
  browsersync.watch('templates/**/*.html', browsersync.reload);
  browsersync.watch('templates/*.html', browsersync.reload);
  cb();
}


function runServer(){
  var cmd = spawn('venv/Scripts/python.exe', ['manage.py', 'runserver'], {stdio: 'inherit'});
  cmd.on('close', function(code) {
    console.log('runServer exited with code ' + code);
    cb(code);
  });
}

exports.css = css;
exports.vendor = vendor;
exports.runServer = runServer;
exports.browsersyncServe = browsersyncServe;
exports.default = parallel(css, vendor, runServer, browsersyncServe);
MySQL Server

sql cte query with closure table

<p>The provided SQL script creates two tables, &quot;categories&quot; and &quot;childcategories,&quot; and inserts some sample data into them. It then uses a recursive common table expression (CTE) to generate a breadcrumb-like …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
CREATE TABLE categories (
    id int IDENTITY(1,1) not null,
    created_date datetime not null DEFAULT GETDATE(),
    updated_date datetime not null DEFAULT GETDATE(),
    title nvarchar(max) NOT NULL,
    CONSTRAINT PK_categories_id PRIMARY KEY CLUSTERED (id),
);


CREATE TABLE childcategories (
  parent_id int,
  child_id int,
 CONSTRAINT PK_childcategories PRIMARY KEY NONCLUSTERED ([parent_id],[child_id]),
   CONSTRAINT FK_childcategories_parent_id FOREIGN KEY (parent_id) REFERENCES  categories(id),
   CONSTRAINT FK_childcategories_child_id FOREIGN KEY (child_id) REFERENCES  categories(id),
);


insert into categories(title)
values ('hardware'), ('cpu'), ('gpu') , ('intel'), ('amd'), ('nvidia') , ('geforce')



insert into childcategories(parent_id,child_id)
values (1,2), (1,3),(2,4), (2,5),(3,4), (3,5), (3,6), (6,7)

with cte as (
		select c.id,c.title as parent_title, 1 as [level],cat.title as child_title,
		case when c.title<>cat.title then c.title + ' > ' + cat.title else c.title end as breadcrumb
		from categories as c
		left join childcategories as ch on ch.parent_id=c.id
		left join categories as cat on cat.id=ch.parent_id
		where ch.parent_id is not null
		union all
		select  cat.id,cte.parent_title as parent_title, cte.[level] + 1,cat.title as child_title,
			case when cte.parent_title<>cat.title and cte.parent_title<>par.title then cte.parent_title + ' > ' +par.title + ' > ' +  cat.title else par.title + ' > ' +cat.title end as breadcrumb
		from cte
			inner join childcategories as ch on ch.parent_id=cte.id
			inner join categories as cat on cat.id=ch.child_id
			inner join categories as par on par.id=cte.id
)

select distinct * from cte  order by id, [level];
Django

Django render ajax function

<p>This code is a Django view function that handles AJAX requests and returns a JSON response containing an HTML template rendered with the given context if the request is an …

python
1
2
3
4
5
6
7
8
9
from django.shortcuts import render
from django.http import JsonResponse
from django.template.loader import render_to_string
def render_ajax(request, template, context):
    is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
    if is_ajax:
        ajax_template = render_to_string(template, context)
        return JsonResponse({'template':ajax_template})
    return render(request, template,context)
Django

Django function to create query string

<p>The <code>create_query_string</code> function appears to be a Python function that takes a <code>request</code> object as input and generates a query string from the parameters in the request&#39;s <code>GET</code> parameters. This …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def create_query_string(request):
    query_params = []

    for key in request.GET.keys():
        if key != 'page':
            values = request.GET.getlist(key)
            for value in values:
                if value:
                    query_params.append("{}={}".format(key, value))

    query_string = "&".join(query_params)
    return query_string