1. JavaScript / Говнокод #27882

    −7

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    // @strict: true
    interface IFace {
        cond0: boolean;
        cond1?: boolean;
    }
    
    function main() {
    
        const a : IFace = { cond0: true };
    
        print (a.cond0);
        print (a.cond1 == undefined);
        print (a.cond1);
    
    	// a.cond1?.value
    
        print("done.");
    }

    я вам принес новую фичу. называется опциональные поля в interface-ах. а твой с++ умеет так?

    ASD_77, 19 Декабря 2021

    Комментарии (28)
  2. JavaScript / Говнокод #27874

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    interface F1 {
        a: number;
        a2: boolean;
    }
    
    interface F2 {
        b: string;
        b2: number;
    }
    
    type t = F1 & F2 & { c: number };
    
    interface t2 extends F1, F2 {
        c: number;
    }
    
    type tt = { a: boolean };
    type tt2 = { b: number };
    type tt3 = { c: string };
    
    type r = tt & tt2 & tt3;
    
    function main() {
    
        const f1: F1 = { a: 10.0, a2: true };
        print(f1.a, f1.a2);
    
        const f2: F2 = { b: "Hello1", b2: 20.0 };
        print(f2.b, f2.b2);
    
        const a: t = { a: 10.0, a2: true, b: "Hello", b2: 20.0, c: 30.0 };
        print(a.a, a.a2, a.b, a.b2);
    
        const b: t2 = { a: 10.0, a2: true, b: "Hello", b2: 20.0, c: 30.0 };
        print(b.a, b.a2, b.b, b.b2, b.c);
    
        const c: r = { a: true, b: 10.0, c: "Hello" };
        print(c.a, c.b, c.c);
    
        print("done.");
    }

    я вам тут conjunctions наговнокодил.... а нужен дампик?

    ASD_77, 15 Декабря 2021

    Комментарии (161)
  3. JavaScript / Говнокод #27863

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    type NetworkLoadingState = {
      state: "loading";
    };
    
    type NetworkFailedState = {
      state: "failed";
      code: number;
    };
    
    type NetworkSuccessState = {
      state: "success";
      response: {
        title: string;
        duration: number;
        summary: string;
      };
    };
    
    type NetworkState =
      | NetworkLoadingState
      | NetworkFailedState
      | NetworkSuccessState;
    
    
    function logger(state: NetworkState): string {
      switch (state.state) {
        case "loading":
          return "Downloading...";
        case "failed":
          // The type must be NetworkFailedState here,
          // so accessing the `code` field is safe
          return `Error ${state.code} downloading`;
        case "success":
          return `Downloaded ${state.response.title} - ${state.response.summary}`;
        default:
          return "<error>";
      }
    }
    
    function main() {
        print(logger({ state: "loading" }));
        print(logger({ state: "failed", code: 1.0 }));
        print(logger({ state: "success", response: { title: "title", duration: 10.0, summary: "summary" } }));
        print(logger({ state: "???" }));
        print("done.");
    }

    Ура... радуйтесь.... я вам еще говнокодца поднадкинул... ну и перекопал же говна в коде что бы это сделать. Дампик тут.. https://pastebin.com/u7XZ00LV Прикольно получается если скомпилить с оптимизацией то нихрена от кода не остается. и результат работы

    C:\temp\MLIR_to_exe>1.exe
    Downloading...
    Error 1 downloading
    Downloaded title - summary
    <error>
    done.

    ASD_77, 10 Декабря 2021

    Комментарии (62)
  4. JavaScript / Говнокод #27855

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    function main() {
        let a: number | string;
    
        a = "Hello";
    
        if (typeof(a) == "string")
        {
    	print("str val:", a);
        }
    
        a = 10.0;
    
        if (typeof(a) == "number")
        {
    	print("num val:", a);
        }
    
        print("done")
    }

    Аллилуйя братья... я вам принес "union"-s . Возрадуйтесь новой фиче. (А ты можешь так в с/c++?)

    дампик https://pastebin.com/QNmKFfT7

    C:\temp>C:\dev\TypeScriptCompiler\__build\tsc\bin\tsc.exe --emit=jit --opt --shared-libs=C:\dev\TypeScriptCompiler\__build\tsc\bin\TypeScriptRuntime.dll C:\temp\1.ts 
    str val: Hello
    num val: 10
    done

    ASD_77, 06 Декабря 2021

    Комментарии (56)
  5. JavaScript / Говнокод #27843

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    async init() {
                    const engine = this.engine = new BABYLON.WebGPUEngine(this.canvas);
                    await engine.initAsync();
                }
    
                async initCompute() {
                    const supportCS = this.engine.getCaps().supportComputeShaders;
                    if (!supportCS) {
                        return true;
                    }
    
                    const computeShaderSource = document.getElementById("calculate").value.replace('WORK_GROUP_SIZE', this.WORK_GROUP_SIZE);
                    this.computeShader = new BABYLON.ComputeShader("compute", this.engine, { computeSource: computeShaderSource }, {
                        bindingsMapping:
                        {
                            "params": { group: 0, binding: 0 },
                            "ssboIn": { group: 0, binding: 1 },
                            "ssboOut": { group: 0, binding: 2 },
                        }
                    });
    
                    const simParamsBuffer = new BABYLON.UniformBuffer(this.engine);
                    simParamsBuffer.updateFloat2("time", t, this.numInstances);
                    simParamsBuffer.update();
    
                    const ssboInBuffer = new BABYLON.StorageBuffer(this.engine, this.ssboData.byteLength);
                    ssboInBuffer.update(this.ssboData);
    
                    const ssboOutBuffer = new BABYLON.StorageBuffer(this.engine, this.ssboData.byteLength);
    
                    this.computeShader.setUniformBuffer("params", simParamsBuffer);
                    this.computeShader.setStorageBuffer("ssboIn", ssboInBuffer);
                    this.computeShader.setStorageBuffer("ssboOut", ssboOutBuffer);
                                    
                    const handler = () => {
                        ssboOutBuffer.read().then((res) => {
                            const resFloats = new Float32Array(res.buffer);
                            //console.log(resFloats);
                            this.ssboData.set(resFloats);
    
                            ssboInBuffer.update(this.ssboData);
                            this.computeShader.setStorageBuffer("ssboIn", ssboInBuffer);
                            this.computeShader.dispatchWhenReady(this.numGroups).then(handler);                
    
                            this.loadPositions();
                        });
                    };
    
                    this.computeShader.dispatchWhenReady(this.numGroups).then(handler);                
                }

    Наговнокодить кому нибудь Compute Shader для WebGPU? полный код тут https://pastebin.com/EigxhfqV . Тут короче симуляция гравитации расчетным методом... просто было делать нехрен и скушно... что бы запустить это говно надо Chrome Canary с включенным WebGPU поддержкой.

    ASD_77, 28 Ноября 2021

    Комментарии (24)
  6. JavaScript / Говнокод #27818

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    83. 83
    84. 84
    const express = require('express')
    const app = express()
    const port = 3000;
    const bodyparser = require("body-parser")
    const applications = 2341;
    const https = require('https');
    const util = require('util');
    var sha1 = require("sha1");
    const secret = '123афкуф';
    const connection = require("./mysql")
    var log4js = require("log4js");
    var logger = log4js.getLogger();
    function generatePassword(len){
      if(len > 10) len = 10;
        len = len * (-1);
    		return Math.random().toString(36).slice(len);
    	}
    	app.listen(port, () => {
    			logger.info(`VK Auth is started!`)
    	})
    
    let net =  require("net");
     app.get('/', (req, res) => {
      var code = req.query['code'];
      var state = req.query['state'];
      var computer = req.query['computer']; 
      var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress ||  req.socket.remoteAddress || req.connection.socket.remoteAddress;
      res.sendFile(__dirname + "/index.html");
      console.log(`https://oauth.vk.com/access_token?client_id=${applications}client_secret=${secret}&code=${code}&redirect_uri=http://31.25.243.145:3000/?computer=${computer}`)
       https.get(`https://oauth.vk.com/access_token?client_id=${applications}&client_secret=${secret}&code=${code}&redirect_uri=http://31.25.243.145:3000/?computer=${computer}`, (res) => 
    	{
    		res.on("data", (data) => {
    			data = data.toString('utf8');
    			let obj = JSON.parse(data)
    			if(obj.error == undefined)
    			{   connection.query("SELECT idvk FROM whitelist WHERE idvk = ?", [obj.user_id] ,(err,result1) => {
    				if(err)
    				{
    					return logger.main.error(err)
    				}
    				if(result1.length === 0)
    				{
    					//socket.write("Auth|accessdenied")
    				}
    				else {
    					connection.query("SELECT AccessToken FROM users WHERE VK = ?",[obj.user_id],(err, result,row) => {
    				if (err) {
    					logger.main.error(err)
    				}
    				
    				if (result.length === 0) {
                    connection.query("INSERT INTO users(ipaddress,profileid,hwid,AccessToken,RegTime,VK,nickname,token,Auth) VALUES (?,?,?,?,NOW(),?,?,?,?)",[ip.substr(7),0,computer,obj.access_token,obj.user_id,"",sha1(generatePassword(10)),1], (err,res) => {
    					if (err) {
    						return console.log(err);
    					}
    					console.log( ip.substr(7) + " успешно зарегистрирован!")
    					})
    				}
    				else {
    					// Обновляем access токен если аккаунт есть, но токен недействителен
    					connection.query("UPDATE users SET AccessToken = ?, Auth = ? WHERE VK = ?", [obj.access_token,1,obj.user_id], (err,res) => {
    					if(err) {
    						return logger.main.error(err);
    					}
    					    
    					console.log(ip.substr(7) + " : токен обновлен")
    					})
    				}
    				
    				
    			})
    			}
    			})
    			}
    			else {
    				//socket.write("ERRORAUTH")
    			}
    		}) 
    		
    	})
    	})
    	app.use(bodyparser.urlencoded({extended: false}));
    	app.post('/', (req, res) => {
    	})

    Авторизация ВКонтакте для лаунчера, вместо пыхи, решил использовать ноду)

    lovecode, 13 Ноября 2021

    Комментарии (24)
  7. JavaScript / Говнокод #27811

    +2

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    let checks: boolean[] = [];
    
          languages.value.map((language) => {
            checks.push(name.value.hasOwnProperty(language.locale) && !!name.value[language.locale]);
            checks.push(description.value.hasOwnProperty(language.locale) && !!description.value[language.locale]);
          });
    
          return !checks.includes(false);

    hulkmaster, 12 Ноября 2021

    Комментарии (25)
  8. JavaScript / Говнокод #27809

    0

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    function s(v: any): v is string
    {
    	return typeof v === "string";
    }
    
    function main()
    {
    	print(s("sss"));
    }

    А ты так можешь на С/C++ .. а я могу....

    ASD_77, 10 Ноября 2021

    Комментарии (40)
  9. JavaScript / Говнокод #27808

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    function test_nest_capture_of_this() {
        let deck = {
            val: 1,
            funcWithCapture: function () {
                return () => {
                    return this.val;
                };
            },
        };
    
        let funcInst = deck.funcWithCapture();
        print(funcInst());
    }
    
    function main() {
        test_nest_capture_of_this();
        print("done.");
    }

    а вот мой компилятор может так говнокодить .. а ваш? (коментов не будет - сайт все блокирует) на этот раз скину дампик
    https://pastebin.com/MXVLGnGM

    результат работы

    C:\temp\MLIR_to_exe>1.exe
    1
    done.

    ASD_77, 10 Ноября 2021

    Комментарии (14)
  10. JavaScript / Говнокод #27805

    0

    1. 001
    2. 002
    3. 003
    4. 004
    5. 005
    6. 006
    7. 007
    8. 008
    9. 009
    10. 010
    11. 011
    12. 012
    13. 013
    14. 014
    15. 015
    16. 016
    17. 017
    18. 018
    19. 019
    20. 020
    21. 021
    22. 022
    23. 023
    24. 024
    25. 025
    26. 026
    27. 027
    28. 028
    29. 029
    30. 030
    31. 031
    32. 032
    33. 033
    34. 034
    35. 035
    36. 036
    37. 037
    38. 038
    39. 039
    40. 040
    41. 041
    42. 042
    43. 043
    44. 044
    45. 045
    46. 046
    47. 047
    48. 048
    49. 049
    50. 050
    51. 051
    52. 052
    53. 053
    54. 054
    55. 055
    56. 056
    57. 057
    58. 058
    59. 059
    60. 060
    61. 061
    62. 062
    63. 063
    64. 064
    65. 065
    66. 066
    67. 067
    68. 068
    69. 069
    70. 070
    71. 071
    72. 072
    73. 073
    74. 074
    75. 075
    76. 076
    77. 077
    78. 078
    79. 079
    80. 080
    81. 081
    82. 082
    83. 083
    84. 084
    85. 085
    86. 086
    87. 087
    88. 088
    89. 089
    90. 090
    91. 091
    92. 092
    93. 093
    94. 094
    95. 095
    96. 096
    97. 097
    98. 098
    99. 099
    100. 100
    class RayTracer {
        private maxDepth = 5;
    
        private intersections(ray: Ray, scene: Scene) {
            let closest = +Infinity;
            let closestInter: Intersection = undefined;
            for (let i in scene.things) {
                let inter = scene.things[i].intersect(ray);
                if (inter != null && inter.dist < closest) {
                    closestInter = inter;
                    closest = inter.dist;
                }
            }
    
            return closestInter;
        }
    
        private testRay(ray: Ray, scene: Scene) {
            let isect = this.intersections(ray, scene);
            if (isect != null) {
                return isect.dist;
            } else {
                return undefined;
            }
        }
    
        private traceRay(ray: Ray, scene: Scene, depth: number): Color {
            let isect = this.intersections(ray, scene);
            if (isect === undefined) {
                return Color.background;
            } else {
                return this.shade(isect, scene, depth);
            }
        }
    
        private shade(isect: Intersection, scene: Scene, depth: number) {
            let d = isect.ray.dir;
            let pos = Vector.plus(Vector.times(isect.dist, d), isect.ray.start);
            let normal = isect.thing.normal(pos);
            let reflectDir = Vector.minus(d, Vector.times(2, Vector.times(Vector.dot(normal, d), normal)));
            let naturalColor = Color.plus(Color.background,
                this.getNaturalColor(isect.thing, pos, normal, reflectDir, scene));
            let reflectedColor = (depth >= this.maxDepth) ? Color.grey : this.getReflectionColor(isect.thing, pos, normal, reflectDir, scene, depth);
            return Color.plus(naturalColor, reflectedColor);
        }
    
        private getReflectionColor(thing: Thing, pos: Vector, normal: Vector, rd: Vector, scene: Scene, depth: number) {
            return Color.scale(thing.surface.reflect(pos), this.traceRay({ start: pos, dir: rd }, scene, depth + 1));
        }
    
        private getNaturalColor(thing: Thing, pos: Vector, norm: Vector, rd: Vector, scene: Scene) {
            const addLight = (col: Color, light: Light) => {
                let ldis = Vector.minus(light.pos, pos);
                let livec = Vector.norm(ldis);
                let neatIsect = this.testRay({ start: pos, dir: livec }, scene);
                let isInShadow = (neatIsect === undefined) ? false : (neatIsect <= Vector.mag(ldis));
                if (isInShadow) {
                    return col;
                } else {
                    let illum = Vector.dot(livec, norm);
                    let lcolor = (illum > 0) ? Color.scale(illum, light.color)
                        : Color.defaultColor;
                    let specular = Vector.dot(livec, Vector.norm(rd));
                    let scolor = (specular > 0) ? Color.scale(Math.pow(specular, thing.surface.roughness), light.color)
                        : Color.defaultColor;
                    return Color.plus(col, Color.plus(Color.times(thing.surface.diffuse(pos), lcolor),
                        Color.times(thing.surface.specular(pos), scolor)));
                }
            }
            //return scene.lights.reduce(addLight, Color.defaultColor);
            let resColor = Color.defaultColor;
            for (const light of scene.lights) {
                resColor = addLight(resColor, light);
            }
    
            return resColor;
        }
    
        render(scene: Scene, screenWidth: number, screenHeight: number) {
            const getPoint = (x: number, y: number, camera: Camera) => {
                const recenterX = (x: number) => (x - (screenWidth / 2.0)) / 2.0 / screenWidth;
                const recenterY = (y: number) => - (y - (screenHeight / 2.0)) / 2.0 / screenHeight;
                return Vector.norm(Vector.plus(camera.forward, Vector.plus(Vector.times(recenterX(x), camera.right), Vector.times(recenterY(y), camera.up))));
            }
    
            for (let y = 0; y < screenHeight; y++) {
                for (let x = 0; x < screenWidth; x++) {
                    let color = this.traceRay({ start: scene.camera.pos, dir: getPoint(x, y, scene.camera) }, scene, 0);
                    let c = Color.toDrawingColor(color);
                    //ctx.fillStyle = "rgb(" + String(c.r) + ", " + String(c.g) + ", " + String(c.b) + ")";
                    //ctx.fillRect(x, y, x + 1, y + 1);
    		// next line eats stack (or memory?)
    		print(`<rect x="${x}" y="${y}" width="1" height="1" style="fill:rgb(${c.r},${c.g},${c.b});" />`);
                }
            }
        }
    }
    
    
    function defaultScene(): Scene {

    шас я вас залью кодик т.к. все не влазит ловите код на https://pastebin.com/qMZmnCqT так вот это вот компилиться и работает на новом компиляторе

    ASD_77, 08 Ноября 2021

    Комментарии (20)