Sunday, July 25, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


After learning how much Python can I code myself an app or a game?

Posted: 25 Jul 2021 07:48 AM PDT

I recently started learning Python basics and rn I recently learned Sets, tupules, lists and dictionaries and the next lecture is going to be about Conditional statements. i am learning from Youtube by a channel called Corey Schafers and watching his basic Python tutorials. So i wanted to know how much coding and what topics do I need to learn to make a game or a mobile app after learning the basics. and i would be glad if you could give me a link to videos which would teach those topics. And i am not saying i want to complete it fast i am just asking so i could get a proper goal and what i should be learning not just learning things which are totally out of my field. And if you do give links to places where i can watch the topics please make sure they are free i can't pay for the lectures. Thx

How dynamically instantiate a directive in an Angular component created dynamically?

Posted: 25 Jul 2021 07:48 AM PDT

I'm creating components dynamically but when I try to do it with a directive I failed. How can I create/instantiate a directive dynamically and assign/associate it with a component?

I create components in the following way:

createComponent(anyViewContainer: ViewContainerRef, aComponentClass: Type<any>) {      const aComponentFact = this.componentFactoryResolver.resolveComponentFactory(aComponentClass);      const aComponentRefs = anyViewContainer.createComponent(aComponentFact);        return aComponentRefs;    }  

How to let library users rewrite some parts of the library?

Posted: 25 Jul 2021 07:48 AM PDT

I am trying to write a library for a text based game called avalon. The game uses different dialogues at various points of time to help the players. Currently I have a file called dialogues.py in this format

# avalon/dialogues.py  start_game = "welcome to the game"  next_round = "write `next` if you are ready"    def choices(options):      sent = "Choose one of the following options:\n"      for i, option in enumerate(options):          sent += f"{i}) {option}\n"      return sent  

These dialogues are then imported in various files in different parts of the game

# avalon/a.py  from avalon.dialogues import start_game, choices    print(start_game)  print(choices(["op-1", "op-2"]))  
# avalon/b.py  from avalon.dialogues import next_round, choices    print(next_round)  print(choices(["op-1", "op-2", "op-3"]))  

Now I want the users of the library to be able to rewrite these dialogues. What is the most pythonic way to do this?

I am thinking about using something like the following in both a.py and b.py to get this done. This requires the users to copy dialogues.py in the root folder, and then edit the file.

try:      import dialogues as dlg  except ModuleNotFoundError:      from avalon import dialogues as dlg    print(dlg.start_game)  

Is there a better way?

Alternative to backdrop-filter that work with CSS animations

Posted: 25 Jul 2021 07:48 AM PDT

We have a simple CSS background animation below with a div in the foreground that has backdrop-filter applied.

* { box-sizing: border-box; margin: 0; padding: 0; } html, body { height: 100%; }  body {    display: flex; justify-content: center; align-items: center; background-color: #eee;    background-image:      linear-gradient( -135deg, #ddd 25%, transparent 25% ),      linear-gradient( 135deg, #ddd 25%, transparent 25% ),      linear-gradient( -45deg, #ddd 25%, transparent 25% ),      linear-gradient( 45deg, #ddd 25%, transparent 25% ),      linear-gradient( #27b 50%, #1a5 50% );    background-size: 2rem 2rem; background-position: 1rem 1rem, 0 0, 0 0, 1rem 1rem;    animation-name: down, grow;    animation-duration: 5s;    animation-timing-function: ease-in-out;    animation-iteration-count: infinite;    animation-direction: alternate;  }  @keyframes down {    100% { background-position: -12rem -12rem, -8rem -8rem, -8rem -8rem, -12rem -12rem; }  }  @keyframes grow {    100% { background-size: 4rem 4rem }  }  div {    border-radius: 1rem; width: 10rem; height: 10rem;    background-color: rgba( 0,0,0,0.25 ); backdrop-filter: blur( 1rem );  }
<div></div>

The limitations of backdrop filter: no Firefox support, breaks when CSS filters are applied, breaks when 3D CSS transforms are applied etc. has left the desire for a suitable workaround to be found.

How can I get a similar effect to what's in the snippet above without using the CSS backdrop-filter property?

|

Similar questions have been asked before:

Alternatives to backdrop-filter?,

Frosted glass look,

backdrop-filter: blur effect without using backdrop?

etc. but those solutions that would work all involve making a copy of the areas to be blurred and clipping them with overflow: hidden or clip-path. None of the solutions have worked for this particular example.

We want to use something that will work with animations and 3D CSS transforms behind the blurred areas. This will likely involve some JavaScript.

Preferably without libraries and with a working snippet included in the answers.

Assigning defaults of nested schema in A

Posted: 25 Jul 2021 07:48 AM PDT

I followed this instruction and it works perfectly. but if i have a nested schema how can i set defaults for inner objects? I tried this but it didn't work:

  const ajv = new Ajv({ useDefaults: true })    const schema = {      type: 'object',      properties: {        foo: { type: 'number' },        bar: {          type: 'object',          properties: {            zoo: { type: 'string', default: 'deffff' },          },        },      },      required: ['foo', 'bar'],    }      const data = {}    const validate = ajv.compile(schema)    const valid = validate(data)    console.log(data)  

Why global site-package does not see a local one?

Posted: 25 Jul 2021 07:47 AM PDT

I install python package using the system package manager:

apk add py3-gunicorn  

Then I create and fill venv with falcon:

python3 -mvenv --system-site-packages .  . ./bin/activate  pip3 install falcon  

No errors so far. But when I try to actually run my application, I get following error:

[2021-07-25 14:36:37 +0000] [2] [INFO] Starting gunicorn 20.0.4  [2021-07-25 14:36:37 +0000] [2] [INFO] Listening at: unix:/opt/xxx/sock/xxx.sock (2)  [2021-07-25 14:36:37 +0000] [2] [INFO] Using worker: sync  [2021-07-25 14:36:37 +0000] [7] [INFO] Booting worker with pid: 7  [2021-07-25 14:36:37 +0000] [7] [ERROR] Exception in worker process  Traceback (most recent call last):    File "/usr/lib/python3.9/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker      worker.init_process()    File "/usr/lib/python3.9/site-packages/gunicorn/workers/base.py", line 119, in init_process      self.load_wsgi()    File "/usr/lib/python3.9/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi      self.wsgi = self.app.wsgi()    File "/usr/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi      self.callable = self.load()    File "/usr/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 49, in load      return self.load_wsgiapp()    File "/usr/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp      return util.import_app(self.app_uri)    File "/usr/lib/python3.9/site-packages/gunicorn/util.py", line 358, in import_app      mod = importlib.import_module(module)    File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module      return _bootstrap._gcd_import(name[level:], package, level)    File "<frozen importlib._bootstrap>", line 1030, in _gcd_import    File "<frozen importlib._bootstrap>", line 1007, in _find_and_load    File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked    File "<frozen importlib._bootstrap>", line 680, in _load_unlocked    File "<frozen importlib._bootstrap_external>", line 855, in exec_module    File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed    File "/opt/xxx/src/app.py", line 1, in <module>      import falcon  ModuleNotFoundError: No module named 'falcon'  

However, when I try to run

python3 -c 'import falcon'  

it works. So it looks like the "global" gunicorn cannot see "local" falcon, but I'm not sure why. Any ideas?

pytorch_lightning: don't resume checkpoint if early_stop_callback

Posted: 25 Jul 2021 07:47 AM PDT

Is there a way to tell whether the last checkpoint experienced an early stop? So I can automatically create a new logged version, rather than resuming an overtrained checkpoint.

Trainer.early_stopping_callback.wait_count always resumes 0 after loading from last.ckpt. There is no way to tell whether wait_count has exceeded patience.

Table Control Empty cell

Posted: 25 Jul 2021 07:47 AM PDT

In my dynpro, I have a table controler, named TC300, that is showing data from my database table zma_kostl. When i change some data in the table controler, the data will be modified even in the database table. This is true when i change the data to some other random data. But when i change the data in a cell to a blank value, the change is not propagated to a database table. Do you have any idea why?? Here is my code:

Top Include:

FUNCTION-POOL zma_ic_screen.    TABLES  zma_kostl.    CONTROLS TC300 TYPE TABLEVIEW USING SCREEN 300.  DATA: cols LIKE LINE OF TC300-cols.    DATA it_zma_kostl TYPE TABLE OF zma_kostl.  

Dynpro 300:

PROCESS BEFORE OUTPUT.    MODULE data_retrieval.      LOOP AT it_zma_kostl INTO zma_kostl WITH CONTROL TC300.    ENDLOOP.      MODULE SET_LINES.    PROCESS AFTER INPUT.    LOOP AT it_zma_kostl.      MODULE read_table_control_300.    ENDLOOP.      MODULE SAVE_DATA.  

Modules:

MODULE data_retrieval OUTPUT.    IF it_zma_kostl IS INITIAL.      SELECT kostl        FROM zma_kostl        INTO CORRESPONDING FIELDS OF TABLE it_zma_kostl.    ENDIF.    ENDMODULE.    MODULE read_table_control_300 INPUT.     MODIFY it_zma_kostl FROM zma_kostl INDEX tc300-current_line.  ENDMODULE.    MODULE save_data INPUT.    MODIFY zma_kostl FROM TABLE it_zma_kostl.  ENDMODULE.    MODULE set_lines OUTPUT.    DATA VLINES TYPE I.    DESCRIBE TABLE it_zma_kostl LINES VLINES.    TC300-LINES = VLINES + 1.    DESCRIBE TABLE it_zma_work_section LINES VLINES.    TC400-LINES = VLINES + 1.  ENDMODULE.  

I think there is error somewhere in module save_data. Do you have any ideas, how to improve the code?

How to set up tkinter Combobox border color

Posted: 25 Jul 2021 07:47 AM PDT

I'm looking for a way to modify tkinter Combobox border color and thickness and cannot find a way how to do it.

from tkinter import *  from tkinter import ttk    win = Tk()  win.geometry("700x350")    style= ttk.Style()  style.theme_use('clam')    # why combobox style works only when theme is used???  style.configure("test1.TCombobox", fieldbackground= "red")  #style.configure("test2.TCombobox", How to set up border color & thickness???)    label=ttk.Label(win, text= "Select a Car",  font= ('Aerial 11'))  label.pack(pady=30)    cb= ttk.Combobox(win, width= 25, values=["Honda", "Hyundai", "Wolkswagon", "Tata", "Renault", "Ford", "Chrevolet", "Suzuki","BMW", "Mercedes"])#, style="test1.TCombobox")  cb.pack()    cb['style'] = "test1.TCombobox"     # I need to be able to set up style after widget is initialized    win.mainloop()  

In following code example I'm able to modify background but I cannot find how to modify border. Can someone smarter than me help me fill in test2.TCombobox style for red border with some thickness?

Second question. Why setting up background stops working when I comment theme???

style.theme_use('clam')    # why combobox style works only when theme is used???  

ValueError: Input 0 of layer is incompatible with the layer: expected axis -1 of input shape to have value 22 but received input with shape (None, 21)

Posted: 25 Jul 2021 07:47 AM PDT

i made trained model, with this

train_x = train_data.drop(drop_cols + PRED_INSTANCES, axis=1)  train_simple_x = np.array(train_data['batch_latency']).reshape(-1, 1)  train_y = train_data[pred_instance]    test_x = test_data.drop(drop_cols + PRED_INSTANCES, axis=1)  test_simple_x = np.array(test_data['batch_latency']).reshape(-1, 1)  test_y = test_data[[pred_instance]].to_numpy()    # Modeling  callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=5)  # Model 정의  model_dnn=tf.keras.Sequential()  model_dnn.add(tf.keras.layers.Dense(64, activation="relu", input_shape=(train_x.shape[1],)))  model_dnn.add(tf.keras.layers.Dense(32, activation="relu"))    model_dnn.add(tf.keras.layers.Dense(16, activation="relu"))  model_dnn.add(tf.keras.layers.Dense(1))  model_dnn.compile(optimizer=tf.keras.optimizers.Adam(lr=0.001),                loss=['mean_absolute_percentage_error', 'mean_squared_error'],                loss_weights=[1., 1.])    model_rfr = en.RandomForestRegressor()  model_simple = lin.LinearRegression()    # --------------------------------------------------------------------------------------------  # Fit  model_dnn.fit(train_x, train_y, epochs=200,        callbacks=[callback],        batch_size=32,        verbose=0)  model_rfr.fit(train_x, train_y)  model_simple.fit(train_simple_x, train_y)      

i trained 3 model and saved

after i open this saved trained model but error occured at predict first line

       # Predict  dnn_pred_y = model_dnn.predict(test_x)  dnn_pred_y = dnn_pred_y.reshape(-1, 1)  rfr_pred_y = model_rfr.predict(test_x)  rfr_pred_y = rfr_pred_y.reshape(-1, 1)  simple_pred_y = model_simple.predict(test_simple_x)  simple_pred_y = simple_pred_y.reshape(-1, 1)  median_pred_y = np.median(np.stack([      dnn_pred_y, rfr_pred_y, simple_pred_y  ]), axis=0)  

this is the error message

    ValueError: Input 0 of layer sequential_44 is incompatible with the layer: expected axis -1 of input shape to have value 22 but received input with shape (None, 21)  
[ERROR] ValueError: in user code:        /mnt/efs/packages/keras/engine/training.py:1544 predict_function  *          return step_function(self, iterator)      /mnt/efs/packages/keras/engine/training.py:1527 run_step  *          outputs = model.predict_step(data)      /mnt/efs/packages/keras/engine/training.py:1500 predict_step  *          return self(x, training=False)      /mnt/efs/packages/keras/engine/base_layer.py:989 __call__  *          input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)      /mnt/efs/packages/keras/engine/input_spec.py:248 assert_input_compatibility  *          raise ValueError(        ValueError: Input 0 of layer sequential_44 is incompatible with the layer: expected axis -1 of input shape to have value 22 but received input with shape (None, 21)    Traceback (most recent call last):    File "/var/task/lambda_function.py", line 233, in lambda_handler      pred_instance_dict = model_validation()    File "/var/task/lambda_function.py", line 216, in model_validation      test_y, pred_y, test_data, mape = train_test_model(    File "/var/task/lambda_function.py", line 184, in train_test_model      dnn_pred_y = model_dnn.predict(test_x)    File "/mnt/efs/packages/keras/engine/training.py", line 1702, in predict      tmp_batch_outputs = self.predict_function(iterator)    File "/mnt/efs/packages/tensorflow/python/eager/def_function.py", line 889, in __call__      result = self._call(*args, **kwds)    File "/mnt/efs/packages/tensorflow/python/eager/def_function.py", line 933, in _call      self._initialize(args, kwds, add_initializers_to=initializers)    File "/mnt/efs/packages/tensorflow/python/eager/def_function.py", line 763, in _initialize      self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access    File "/mnt/efs/packages/tensorflow/python/eager/function.py", line 3050, in _get_concrete_function_internal_garbage_collected      graph_function, _ = self._maybe_define_function(args, kwargs)    File "/mnt/efs/packages/tensorflow/python/eager/function.py", line 3444, in _maybe_define_function      graph_function = self._create_graph_function(args, kwargs)    File "/mnt/efs/packages/tensorflow/python/eager/function.py", line 3279, in _create_graph_function      func_graph_module.func_graph_from_py_func(    File "/mnt/efs/packages/tensorflow/python/framework/func_graph.py", line 999, in func_graph_from_py_func      func_outputs = python_func(*func_args, **func_kwargs)    File "/mnt/efs/packages/tensorflow/python/eager/def_function.py", line 672, in wrapped_fn      out = weak_wrapped_fn().__wrapped__(*args, **kwds)    File "/mnt/efs/packages/tensorflow/python/framework/func_graph.py", line 986, in wrapper      raise e.ag_error_metadata.to_exception(e)END RequestId: 0e3ce053-0755-408c-9b12-6d0e8f88fd53  

A way to Calculate the amount of Pixels your Mouse should Move for different Mouse Sens Settings?

Posted: 25 Jul 2021 07:47 AM PDT

Hi I created a function that moves your Mouse up and down

DllCall("mouse_event", "UInt", 0x01, "UInt", 0, "UInt", -X Value)  DllCall("mouse_event", "UInt", 0x01, "UInt", 0, "UInt", X Value)  

But when someone has different Mouse settings for Example the DPI and In Game Mouse Sensitivity The X Values are wrong

My settings are:

DPI: 800

In Game Mouse Sens: 1.7

Those 2 Make the X Value: 950

I made a Formula to calculate the X Value for everyone with different DPI + In Game Mouse Sensitivity:

Calc:  X =  Status =  DecreaseP := (Sens1 - Sens2)  X1 := (DecreaseP / Sens2) * 100    DecreaseD := (DPI1 - DPI2)  X2 := (DecreaseD / DPI2) * 100  X3 := (X1 + X2) / 2    X := 950 * (X3 / 100)  X := RegExReplace(X, "\.\d*")      Display:  GuiControl, , Results, %X%  

I tried testing it out with fake "original" settings but with the right "current" settings. The Calculator should have given me 950, instead it gave me:

This:

Can someone help me?

referencing a class from a different folder in c#

Posted: 25 Jul 2021 07:48 AM PDT

I have 2 programs from 2 different folders, currently, I have a class in SectionA.cs (namespace SectionA, class name Employee) and I want to reuse a method from the class in SectionB.cs (namespace SectionB), but I do not know how reference a class from SectionB.cs. I heard you have to use using SectionA; but it gives me this error

The type or namespace name 'SectionA' could not be found (are you missing a using directive or an assembly reference?) [SectionB]

The picture below shows the file directory, may I know how to reference the class in SectionA.cs to use it in SectionB.cs? Thank you in advance.

enter image description here

Django Queries for related models

Posted: 25 Jul 2021 07:47 AM PDT

I have these two models, product and comment.

class Product(VoteModel, models.Model):      user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=False,                               on_delete=models.CASCADE, related_name="%(class)s_listings")      product_id = models.CharField(max_length=150, null=False, default=get_id, unique=True, editable=False)      product_title = models.CharField(max_length=150, null=False)      created_at = models.DateTimeField(auto_now=False, auto_now_add=True)      updated_at = models.DateTimeField(auto_now=True, auto_now_add=False)      product_description = tinymce_models.HTMLField()      num_vote = models.IntegerField(default=0)  

The Comment Model

class Comment(VoteModel, models.Model):          user        = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, blank=True, on_delete=models.SET_NULL)          created_at     =  models.DateTimeField(auto_now=False, auto_now_add=True)          updated_at     = models.DateTimeField(auto_now=True)          ip_address = models.GenericIPAddressField(_('IP address'), unpack_ipv4=True, blank=True, null=True)          rating = models.CharField(max_length=3, default=1.0)           # Content-object field          content_type = models.ForeignKey(ContentType,                                           verbose_name=_('content type'),                                           related_name="content_type_set_for_%(class)s",                                           on_delete=models.CASCADE)          object_pk = models.TextField(_('object ID'))          content_object = GenericForeignKey(ct_field="content_type", fk_field="object_pk")  

Then, I have a serializer, in which I am trying to get the rating for the comments to come out with an average rating for each Item

class ProductSerializer(ModelSerializer):      product_rating = SerializerMethodField(read_only=True)        class Meta:          model = Product          fields = [              "product_rating"          ]               def get_product_rating(self, obj):            comments = Comment.objects.filter(object_pk=obj.pk, content_type=ContentType.objects.get_for_model(obj))            ....            return {'rating': str(float("%.1f" % average)), 'views': views}  

This seems to be creating duplicate queries

comments = Comment.objects.filter(object_pk=obj.pk, content_type=ContentType.objects.get_for_model(obj))

How can I rewrite the query better to avoid duplicate queries? Here is the view, a little long:

class ProductsListAPIView(ListAPIView):      model = Product        serializer_class = ProductSerializer      filter_backends = [SearchFilter, OrderingFilter]      permission_classes = [HasAPIKey | AllowAny]      search_fields = ['product_title', 'product_description',                       'user__first_name', 'product_type', 'product_price', 'product_city']      pagination_class = ProductPageNumberPagination        # @last_modified(my_last_modified)      # @etag(get_etag_key)      # def get(self, *args, **kwargs):      #     return super(ProductsListAPIView, self).get(*args, **kwargs)        def get_serializer_context(self, *args, **kwargs):          context = super(ProductsListAPIView, self).get_serializer_context(*args, **kwargs)          context['request'] = self.request          coordinates = self.request.GET.get("coordinates")          if not coordinates or len(coordinates) <= 4:              coordinates = '0.0,0.0'          context['coordinates'] = coordinates          return context        def get_queryset(self, *args, **kwargs):            query = self.request.GET.get("search")          lookups = ()            if query and len(query) > 0:              queryArray = query.split()              for q in queryArray:                  lookups = (Q(product_title__icontains=q) |                             Q(product_description__icontains=q) |                             Q(product_type__icontains=q) |                             Q(product_city__icontains=q) |                             Q(user__first_name__icontains=q) |                             Q(user__last_name__icontains=q) |                             Q(product_address__icontains=query)                             )          #queryset_list = queryset_list.filter(lookups).distinct()            # If user is loggedIn and discovery range / point and address is set          # Returns just in that range.          uid = self.request.GET.get("uid")          queryset_list = None          if uid and len(uid) > 5:              try:                  user = CustomUser.objects.get(uid=uid)                  from django.contrib.gis.measure import D                  if user is not None and user.point is not None and len(user.address) > 5:                        queryset_list = Product.objects.active().filter(                          point__distance_lte=(user.point, D(km=user.discovery_range))).filter(lookups).distinct(                      ) if query and len(query) > 0 else Product.objects.active().filter(                          point__distance_lte=(user.point, D(km=user.discovery_range)))                        if not queryset_list or queryset_list.count() < 3:                          queryset_list = Product.objects.active().filter(lookups).distinct(                          ) if query and len(query) > 0 else Product.objects.active()              except Exception as e:                    queryset_list = Product.objects.active().filter(lookups).distinct(                  ) if query and len(query) > 0 else Product.objects.active()                  print(f'USER ASSOCIATED QUERY EXCEPTION: {e}')                  logging.error(f'USER ASSOCIATED QUERY EXCEPTION: {e}')          else:              queryset_list = Product.objects.active().filter(lookups).distinct(              ) if query and len(query) > 0 else Product.objects.active()            return queryset_list  

how to populate the user id by where isDisliked field is false

Posted: 25 Jul 2021 07:46 AM PDT

I need to populate the user from likedBy by where isDisliked is false, please find the document schema.enter image description here

I am using the query below but can't populate the users. using this below query,

let likedBy = await StoryComment.aggregate([{"$match":{"_id": exportLib.ObjectId(currentPost)}}, {"$match":{"comments.likedBy.isDisliked": false}}]);  

getting the output like below,

[    {      _id: 60fd5b5336a2780754021ce0,      comments: { reply: [], likedBy: [Array], report: [] },      isDeleted: false,      isArchived: false,      storyId: 60fa45be78e0cc052760922f,      comment: 'New to this place bro',      userId: 60e7ce8e0812ba086dc16074,      createdAt: 2021-07-25T12:38:43.427Z,      updatedAt: 2021-07-25T13:46:28.728Z,      __v: 0    }  ]  

Expected output:

[    {      isDisliked: false,      _id: 60fd5d08ddf94d07d0da9d57,      likedBy: 60e7ce8e0812ba086dc16074    },    {      isDisliked: false,      _id: 60fd6b34fa5bdf06a743fc3c,      likedBy: 60df550da01794081fc83762    }  ]  

need the user details on the place of likedBy (as we simply do with populate), this is just the de structured version of likedBy array.

Please help me to fix this. Thanks

Send chunked Audio request to wit.ai from dart

Posted: 25 Jul 2021 07:46 AM PDT

I'm looking to use wit.ai for speech recognition. This is the post method I'm using to post audio file.

  Future<http.Response> post(      String path,      File file,    ) async {      final client = http.Client();        try {        final uri = Uri.parse('https://api.wit.ai/$path');        final len = file.lengthSync();          final request = http.StreamedRequest('POST', uri)          ..headers.addAll({            'Authorization': 'Bearer $api_key',            'Content-Type': 'audio/wav',            'Transfer-encoding': 'chunked'          })          ..contentLength = len;          file.openRead().listen((chunk) {          request.sink.add(chunk);        }, onDone: () {          print('done');          request.sink.close();        });          final res = await request.send().then(http.Response.fromStream);          return res;      } catch (e) {        rethrow;      } finally {        client.close();      }    }    

Wit.ai seems to limit audio length to 20 seconds. So, I tried to send a chunked request. I've never worked with chunked requests before and I expected it to send smaller chunks and get stream of response for each chunk seperately. But it seems that the request is sent once only and I'm still getting audio length exceeded error. Am I doing something wrong and Is it possible to get text for audio of length more than 20 seconds from wit speech api?

Upgrading to npm7 but too many library breaks

Posted: 25 Jul 2021 07:46 AM PDT

Been using NPM version of 6.14.7 and decided to move on with NPM version 7.20.1 for my react-native project. Soonest as I try npm install, most of my libraries break with the error of Could not resolve dependency:

Example(s)

// example 1  npm ERR! Could not resolve dependency:  npm ERR! peer react@"^16.8" from @react-native-community/async-storage@1.12.1    // example 2  npm ERR! Could not resolve dependency:  npm ERR! peer react@"^16.0" from @react-native-community/picker@1.8.1    // More Example(s)  ..  ...  .....  

FYI, am aware the breaking change of peer dependencies announcement made by NPM team. Need some guidance here, how can I upgrade my npm version seamlessly?

Automatically installing peer dependencies is an exciting new feature introduced in npm 7. In previous versions of npm (4-6), peer dependencies conflicts presented a warning that versions were not compatible, but would still install dependencies without an error. npm 7 will block installations if an upstream dependency conflict is present that cannot be automatically resolved.

Of course, I'm aware with the following options. If I were to execute npm install --legacy-peer-deps, isn't this the same as if Im using NPM 6? Since it's only by passing the auto installation peer dependencies.

You have the option to retry with --force to bypass the conflict or --legacy-peer-deps command to ignore peer dependencies entirely (this behavior is similar to versions 4-6).

Removing .html URLs with GREP & XARGS

Posted: 25 Jul 2021 07:49 AM PDT

I am using WGET to burn a static copy of a PHP website. I would like to remove all references to .html in every <a href for every file. So any link for example, <a href="path/project-name.html">Project Name</a>, I would like changed to <a href="path/project-name">Project Name</a>.

The command grep -rl index.html . | xargs sed -i 's/index.html//g' works great at removing every index.html in all the links.

But I can't get it to work for every .html link with the command grep -rl *.html . | xargs sed -i 's/*.html//g'.

Any assistance with my regex would be much appreciated.

SQL query, how to improve?

Posted: 25 Jul 2021 07:48 AM PDT

I did a task to write an SQL query and I wonder if I can improve it somehow.

Description:

Let's say we have a db on some online service

Let's create tables, and insert some data

create table players (      player_id integer not null unique,      group_id integer not null  );    create table matches (      match_id integer not null unique,      first_player integer not null,      second_player integer not null,      first_score integer not null,      second_score integer not null  );    insert into players values(20, 2);  insert into players values(30, 1);  insert into players values(40, 3);  insert into players values(45, 1);  insert into players values(50, 2);  insert into players values(65, 1);  insert into matches values(1, 30, 45, 10, 12);  insert into matches values(2, 20, 50, 5, 5);  insert into matches values(13, 65, 45, 10, 10);  insert into matches values(5, 30, 65, 3, 15);  insert into matches values(42, 45, 65, 8, 4);  

The output of the query should be:

group_id | winner_id  --------------------  1        | 45  2        | 20  3        | 40  

So, we should output the winner (player id) of each group. Winner is the player, who got max amount of points in matches.

If user is alone in the group - he's a winner automatically, in case players have equal amount of points - the winner is the one, who has lower id value.

Output should be ordered by group_id field

My solution:

SELECT     results.group_id,     results.winner_id   FROM     (      SELECT         summed.group_id,         summed.player_id AS winner_id,         MAX(summed.sum) AS total_score       FROM         (          SELECT             mapped.player_id,             mapped.group_id,             SUM(mapped.points) AS sum           FROM             (              SELECT                 p.player_id,                 p.group_id,                 CASE WHEN p.player_id = m.first_player THEN m.first_score WHEN p.player_id = m.second_player THEN m.second_score ELSE 0 END AS points               FROM                 players AS p                 LEFT JOIN matches AS m ON p.player_id = m.first_player                 OR p.player_id = m.second_player            ) AS mapped           GROUP BY             mapped.player_id        ) as summed       GROUP BY         summed.group_id       ORDER BY         summed.group_id    ) AS results;  

It works, but I'm 99% sure it can be cleaner. Will be thankful for any suggestions

Openmp parallel for is not following the correct loop order

Posted: 25 Jul 2021 07:48 AM PDT

I am trying to parallelize a stencil code with OpenMP which has a loop over dependency. I eliminated the dependency by making the index diagonal. But when I run the loop with OpenMP, I do not get the correct answer.

For k=1, the point x depends on newly computed values of local_mean.

. . .   . x -  - - -       
. . x - *  x - *  *  

the points xx, -- and *** are computed in parallel

void omp_stencil(int n, int k, double *grid, double *local_mean) {    int j = 0;    for (int i = 0; i < n; i++) {       // i loop      for (int c = 0; c < k + 1; c++) { // c loop          double points = 1; // max_points;          int p = i;        int q = c, l;        int loop_count = std::min(p, (n - 1 - q) / (k + 1)) + 1;    #pragma omp parallel for shared(l, p, q)        for (l = 1; l <= loop_count; l++) {          double sum = 0;            int row_min = std::max(p - k, 0);          int row_max = std::min(p + k, n - 1);          int col_min = std::max(q - k, 0);          int col_max = std::min(q + k, n - 1);          // loop for k - box          for (int mm = row_min; mm <= row_max; mm++) {            for (int ll = col_min; ll <= col_max; ll++) {              if (mm < p || (mm == p && ll < q)) { // mm >= k && ll > i) {  #pragma omp critical                sum += local_mean[ll * n + mm];              } else {  #pragma omp critical                sum += grid[ll * n + mm];              }            }          }    #pragma omp critical          {            local_mean[q * n + p] =                static_cast<double>(sum / points); // / change to multiply            p = p - 1;            q = q + (k + 1);          }        }  #pragma omp barrier      }    }  }  

for an initial grid:

   0 5 10 15 20   5 2 3 4 29   10 3 4 5 38   15 4 5 6 47   20 29 38 47 56   

and k = 1, I should be getting the following: (which I do get if the number of threads is 1).

12 37 71 142 195   69 211 480 968 1377   312 1103 2786 5712 8148   1483 5780 15506 32346 0   7312 30148 0 0 0   

(Note that I am ignoring the last few 0s).

But instead I get something in the likes of:

12 37 69 145 103   69 209 310 629 1307   310 929 1307 2657 5305   1307 3949 5305 10804 0   5305 15933 0 0 0   

And the values keeps changing each time I run it. I am not sure what I am missing here? I went through other questions on SO but I couldn't figure out the bug.

Update: For some reason, it seems like openmp threads are not going over the loop c correctly.

Here's the output for loop access pattern:

(0, 0) with thread: 0  ----  (0, 1) with thread: 0  ----  (1, 0) with thread: 0  (1, 0) with thread: 1  ----  (1, 1) with thread: 1  (0, 3) with thread: 0  ----  (2, 0) with thread: 0  (1, 2) with thread: 1  (0, 4) with thread: 2  ----  (2, 1) with thread: 0  (1, 3) with thread: 1  ----  (3, 0) with thread: 0  (3, 0) with thread: 1  (3, 0) with thread: 2  ----  (3, 1) with thread: 1  (2, 3) with thread: 0  ----  (4, 0) with thread: 2  (4, 0) with thread: 1  (4, 0) with thread: 0  ----  (4, 1) with thread: 1  (3, 3) with thread: 0  ----  

The third iterations should be (1,0) and (0,2). But instead it's (1,0) and (1,0). Same pattern is seen with (3,0).

So, I think I figured out the location of the bug. It's with the condition of p & q. If a thread access (1,0) first, then the value of p and q will be changed again to (1,0). But I am not sure how to resolve it.

Why do Shapley values increase over time?

Posted: 25 Jul 2021 07:48 AM PDT

I calculated the Shapley values (using xgboot package, gbm regression model) of several big actors in the cocoa market and received results which I cannot explain: it seems that Shapley increases (the trend, in general) for all of them. The same thing happened when I calculate it for other sectors. Does it make sense? If it does, what stands behind these results? If not, what could be my mistake? Thanks a lot for any help!

Here is the code, in general:

library(SHAPforxgboost)  library(tidyverse)  library(xgboost) #shapley for boosting method      X <- data.matrix(df[,-1]) #all regions (x)    dtrain <- xgb.DMatrix(data = X, label = df[[1]])         fit <- xgb.train( #train the gbm model      params = list(        objective = "reg:squarederror", #Regression with squared loss         learning_rate = 0.1      ),       data = dtrain,      nrounds = 100,      eval_metric = "rmse"    )          shap <- shap.prep(xgb_model = fit, X_train = X)  

enter image description here

host not found in upstream in /etc/nginx/conf.d/nginx.conf when running standalone docker containers

Posted: 25 Jul 2021 07:49 AM PDT

I have 2 containers named - flask_server and nginx , when I run those containers with docker-compose everything works as expected , the problem is that when I run each container separately I get this error massage :

"host not found in upstream "flask_server:3000" in /etc/nginx/conf.d/nginx.conf".  

I have searched for a solution and I came into the conclusion that this is networking issue between the containers .

so when I run the containers with the --network flag like so :

**flask_server**  docker run -p 3000:3000 --network custom-network flask_server  **nginx**  docker run -p 80:80 --network custom-network nginx     

its still not working .

The only way I made it work is by running the flask_server container with the --network-alias flag like so:

**flask_server**  docker run -p 3000:3000 --network custom-network --network-alias flask_server flask_server  **nginx**  docker run -p 80:80 --network custom-network nginx  

So now I'm getting into another problem which is that I want to upload these containers into amazon ecs and I don't see any alias option in the task definition, So I'll probably need to think of another creative way to resolve this issue before I upload these containers into ecs.

nginx.conf

upstream flask_server {  server flask_server:3000;  }    server {    listen 80;  server_name default_server;    location /api {      proxy_pass http://flask_server;              proxy_set_header Host $host;      proxy_set_header X-Real-IP $remote_addr;      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;     }    }  

nginx Dockerfile

FROM nginx    RUN rm /etc/nginx/conf.d/default.conf  COPY nginx.conf /etc/nginx/conf.d  

flask Dockerfile

FROM python    WORKDIR /app    COPY ./requirements.txt /app    RUN pip install -r requirements.txt    COPY . .    RUN apt-get update    RUN apt-get install python3-dev  -y    WORKDIR /app/code    EXPOSE 3000    CMD ["gunicorn", "wsgi:app", "-k gevent" ,"-w 3", "-b 0.0.0.0:3000", "-t 30"]  

hope anyone here has another workaround to solve this networking problem between the containers, or a way to use the --network-alias flag on Amazon ECS.

Any help would be great. Thanks !

============ EDIT ==============

So I found A workaround to this problem and instead of using the flask_server as my internal ip and proxy pass to the container itself , I used the host ip and passes the requests to the host ip directly .

be aware that this will only work if the flask_server container is running before the nginx In order for the requests to be forwarded to the nginx .

New nginx.conf file

server {        listen 80;      server_name default_server;        location /api {          # the host variable indicates the current host ip address          proxy_pass http://$host:3000;                      proxy_set_header Host $host;          proxy_set_header X-Real-IP $remote_addr;          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;      }    }  

Flutter widget test Clipboard.setData future then never triggered

Posted: 25 Jul 2021 07:47 AM PDT

I am trying to test a clipboard function in my app. When I press a button it should copy my text to the clipboard. When I try to test this functionality with a widget test, the future returned doesn't get resolved. Is there a way to mock the Clipboard.setData method?

Since my original code is quite large I made a reproducible widget test that has the same problem. The boolean dataCopied is false when I execute the expect().

testWidgets('test clipboard function', (WidgetTester tester) async {      var dataCopied = false;      await tester.pumpWidget(        MaterialApp(          home: Container(            width: 10,            height: 10,            child: ElevatedButton(              onPressed: (() {                Clipboard.setData(ClipboardData(text: "test")).then((_) {                  dataCopied = true;                });              }),              child: Text("Copy Text"),            ),          ),        ),      );        await tester.tap(find.byType(ElevatedButton));      expect(dataCopied, true);    });  

div elements are going top left and not centered when getting zoomed HTML/CSS

Posted: 25 Jul 2021 07:47 AM PDT

I am having difficulties in centering the background or divs when zooming in. Everything is centered when I zoom out because I set the * at 1200px. But when I zoom in the POV zooms on the left side of the background.

Here's an example of my POV when it is zoomed:

[https://imgur.com/a/gF50dhh][1]

Here is my code:

*{      width: 1200px;      margin: 0 auto;      padding: 0;  }  html {      background-color: #0f1011;      text-align: center;      font-size: 100%;      background-repeat: no-repeat;      box-sizing: border-box;      position: relative;      min-height: 100%;      margin: 0 auto;  }    /*NAVIGATION BAR*/    .nav {      padding: 20px;      background-color: #a91817;      font-size: 21px;      margin:0 auto;  }  .navbarmargin {      margin: 0 auto;  }  .product {      font-family: 'Zen Dots';      font-size: 15px;      display: flex;      float: left;  }    /*NAVIGATION BAR ELEMENT*/  .homee {      text-decoration: none;      font-family: 'Alatsi';      color: #f7f8f9;      transition: 500ms ease-in-out;      margin-left:30px;      margin-right:30px;  }  .homee:hover {      color: #292f31;      padding-top: 20px;      padding-bottom: 20px;  }          .memberss {      text-decoration: none;      font-family: 'Alatsi';      color: #f7f8f9;      transition: 500ms ease-in-out;      margin-left:30px;      margin-right:30px;  }  .memberss:hover {      color: #292f31;      padding-top: 20px;      padding-bottom: 20px;    }        .socialss{      text-decoration: none;      font-family: 'Alatsi';      color: #f7f8f9;      transition: 500ms ease-in-out;      margin-left:30px;      margin-right:30px;  }  .socialss:hover {      color: #292f31;      padding-top: 20px;      padding-bottom: 20px;  }      .contactt {      text-decoration: none;      font-family: 'Alatsi';      color: #f7f8f9;      transition: 500ms ease-in-out;      margin-left:30px;      margin-right:30px;  }  .contactt:hover {      color: #292f31;      padding-top: 20px;      padding-bottom: 20px;  }    /*BANNER*/  .banner {      background-image: url("https://cdn.discordapp.com/attachments/868146365014876250/868702765906526239/dwwdwdw.jpg");      padding: 45px;      object-fit: contain;      display: block;      margin:0 auto;  }    .logo1 {        animation-name: floating;      animation-duration: 3s;      animation-iteration-count: infinite;      animation-timing-function: ease-in-out;      margin:auto;      display: block;      border-radius: 10px;      width: 150px;  }    @keyframes floating {      from { transform: translate(0,  0px); }      65%  { transform: translate(0, 15px); }      to   { transform: translate(0, -0px); }      }    .jawbreaker {      font-family: 'Zen Dots';      font-size: 25px;      color: red;  }  .jawbreaker1 {      font-family: 'Zen Dots';      font-size: 25px;      color: cyan;  }    .sugarrush {      padding: 25px;      background-color: #45b5b5;      display: block;      margin:0 auto;    }  .sugarrushh {     font-family: 'Lobster';     text-shadow: 2px 2px 4px #000000;     text-decoration: none;     font-size:25px;     color: whitesmoke;            transition: 1000ms ease-in-out;   }   .sugarrushh:hover {       font-size: 30px;       color: rgb(245, 88, 179)   }         body {      text-align: center;        }  .aboutt {      width: 1024px;      background-color: #414849;      text-align: center;      display: block;      border-radius: 5px;      margin-top: 10px;      margin:0 auto;      margin-right: 20px;      margin-left: 20px;      width: 960px;  }  #About {      background-color: #141414;      padding: 100px;      margin:0 auto;  }
<!DOCTYPE html>  <link href="style.css" rel="stylesheet" type="text/css">  <link href="body.css" rel="stylesheet" type="text/css">  <link href="https://fonts.googleapis.com/css2?family=Alatsi&display=swap" rel="stylesheet">  <link href="https://fonts.googleapis.com/css2?family=Zen+Dots&display=swap" rel="stylesheet">  <link href="https://fonts.googleapis.com/css2?family=Lobster&display=swap" rel="stylesheet">    <html lang="en">      <head>          <title>Jawbreaker SMP</title>           <meta name="viewport" content="width=device-width, initial-scale=1.0">           <div class="nav">             <nav>                 <a href="#Home" class="homee">Home</a>                  <a href="#Members" class="memberss">Members</a>                 <a href="#Socials" class="socialss">Socials</a>                  <a href="#Contact" class="contactt">Contact</a>              </nav>             </div>            <div class="banner">              <picture>                <source srcset="https://cdn.discordapp.com/attachments/552032784890331155/867288559429615636/jawbreakerlogo.png" type="image/webp">                <source srcset>                 <img class="logo1" alt="Logo" src=""> <br> <br> <br>             </picture>             <span class="jawbreaker">Jaw</span>             <span class="jawbreaker1">Breaker</span>            </div>            <div class="sugarrush">              <a href="https://media1.tenor.com/images/e71c8574914d2cabb2c6c4bd9ad3af28/tenor.gif" class="sugarrushh">              Let The Sugar Rush Begin!</a>            </div>  </head>   <body>    <section id="About">      <div class="aboutt">        <h3>h</h3>      </div>    </section>    </body>  </html>

table with checkboxes inside

Posted: 25 Jul 2021 07:47 AM PDT

I am trying to replicate or do something similar as this: [1]: https://i.stack.imgur.com/a0yXb.jpg

Basically a table with checkboxes inside, where when you select a checkbox it changes color (instead of the usual blue tick) My HTML table body looks like this (it's in django btw):

<tbody>      {% for partido in partidos_y_horarios.itertuples %}      <tr>      <td>{{ partido.0 }}          <br>          <small class="form-text text-muted">{{ partido.1 }           </small>      </td>      <td>          <label><input type="checkbox" name="partido_{{forloop.counter}}_1" value="1"></label>          <label><input type="checkbox" name="partido_{{forloop.counter}}_X" value="X"></label>          <label><input type="checkbox" name="partido_{{forloop.counter}}_2" value="2"></label>      </td>  </tr>  {% endfor %}  </tbody>  

I'm new to web design so very any help/tip is very appreciate it!

Hyperparam search on huggingface with optuna fails with wandb error

Posted: 25 Jul 2021 07:48 AM PDT

I'm using this simple script, using the example blog post. However, it fails because of wandb. It was of no use to make wandb OFFLINE as well.

from datasets import load_dataset, load_metric  from transformers import (AutoModelForSequenceClassification, AutoTokenizer,                            Trainer, TrainingArguments)  import wandb      wandb.init()    tokenizer = AutoTokenizer.from_pretrained('distilbert-base-uncased')  dataset = load_dataset('glue', 'mrpc')  metric = load_metric('glue', 'mrpc')    def encode(examples):      outputs = tokenizer(          examples['sentence1'], examples['sentence2'], truncation=True)      return outputs    encoded_dataset = dataset.map(encode, batched=True)    def model_init():      return AutoModelForSequenceClassification.from_pretrained(          'distilbert-base-uncased', return_dict=True)    def compute_metrics(eval_pred):      predictions, labels = eval_pred      predictions = predictions.argmax(axis=-1)      return metric.compute(predictions=predictions, references=labels)    # Evaluate during training and a bit more often  # than the default to be able to prune bad trials early.  # Disabling tqdm is a matter of preference.  training_args = TrainingArguments(      "test", eval_steps=500, disable_tqdm=True,      evaluation_strategy='steps',)    trainer = Trainer(      args=training_args,      tokenizer=tokenizer,      train_dataset=encoded_dataset["train"],      eval_dataset=encoded_dataset["validation"],      model_init=model_init,      compute_metrics=compute_metrics,  )    def my_hp_space(trial):      return {          "learning_rate": trial.suggest_float("learning_rate", 1e-4, 1e-2, log=True),          "weight_decay": trial.suggest_float("weight_decay", 0.1, 0.3),          "num_train_epochs": trial.suggest_int("num_train_epochs", 5, 10),          "seed": trial.suggest_int("seed", 20, 40),          "per_device_train_batch_size": trial.suggest_categorical("per_device_train_batch_size", [32, 64]),      }      trainer.hyperparameter_search(      direction="maximize",      backend="optuna",      n_trials=10,      hp_space=my_hp_space  )  

Trail 0 finishes successfully, but next Trail 1 crashes with following error:

  File "/home/user123/anaconda3/envs/iza/lib/python3.8/site-packages/transformers/integrations.py", line 138, in _objective      trainer.train(resume_from_checkpoint=checkpoint, trial=trial)    File "/home/user123/anaconda3/envs/iza/lib/python3.8/site-packages/transformers/trainer.py", line 1376, in train      self.log(metrics)    File "/home/user123/anaconda3/envs/iza/lib/python3.8/site-packages/transformers/trainer.py", line 1688, in log      self.control = self.callback_handler.on_log(self.args, self.state, self.control, logs)    File "/home/user123/anaconda3/envs/iza/lib/python3.8/site-packages/transformers/trainer_callback.py", line 371, in on_log      return self.call_event("on_log", args, state, control, logs=logs)    File "/home/user123/anaconda3/envs/iza/lib/python3.8/site-packages/transformers/trainer_callback.py", line 378, in call_event      result = getattr(callback, event)(    File "/home/user123/anaconda3/envs/iza/lib/python3.8/site-packages/transformers/integrations.py", line 754, in on_log      self._wandb.log({**logs, "train/global_step": state.global_step})    File "/home/user123/anaconda3/envs/iza/lib/python3.8/site-packages/wandb/sdk/lib/preinit.py", line 38, in preinit_wrapper      raise wandb.Error("You must call wandb.init() before {}()".format(name))  wandb.errors.Error: You must call wandb.init() before wandb.log()  

Any help is highly appreciated.

Flutter Encrypted video player [closed]

Posted: 25 Jul 2021 07:46 AM PDT

I have set of videos which is hosted in cloud server. User can download these videos and save locally which can be played in in-app video player. In order prevent outside use/ piracy we have to protect our videos as encrypted. Technology we are using for mobile app is Flutter. I have tried AES encryption but Flutter does not have any built in solution/libraries for AES decryption video player.

Any suggestions for handling this situation ?

Cypress on other browsers

Posted: 25 Jul 2021 07:47 AM PDT

How can I run my cypress tests on Internet Explorer and Mozilla, I'm currently working with Chrome.

Is there any way like Selenium

driver = webdriver.Chrome("C:\\drivers\\chromedriver.exe") for Cypress script to IE

File browse Item uploading to BLOB column

Posted: 25 Jul 2021 07:48 AM PDT

One of the tables in my DB has a BLOB column that stores images. So now I am setting up the page for this table. I have a bunch of IGs and such to process most of the data, but I set up a modal page to process the image.

The modal page gets the ID (which is the PK) into an item, and then it reads the image currently in the table into a 'Display Image' item. And I have a 'File browse...' item to upload new images.

Except I cannot get it to save.

I initially started with the display image item just having Setting Based on : BLOB column returned by SQL statement, as I couldn't get the source to work with the SQL query(Error Expected CHAR, source is BLOB), I managed to resolve this by putting automatic row processing on the page and then having the source be a column.

So now it displays well, with no errors.

But the save does nothing. I have tried saving by having the File browse reference the column and using automatic row processing, and there is just nothing. No errors pop up, but it just does nothing.

I have tried saving to APEX_APPLICATION_TEMP_FILES and then having a PLSQL DA or a PLSQL process to

SELECT blob_content     FROM APEX_APPLICATION_TEMP_FILES   WHERE name = :FILE_BROWSER_ITEM  

And insert this into the table, but it just pops up a 'No data found' error.

I have gone through every bit of intel my google-fu has found, but I have failed to find a solution.

So I would appreciate any insight any of you might have.

Joda Time - different between timezones

Posted: 25 Jul 2021 07:48 AM PDT

I want to convert the current time to the time in a specific timezone with Joda time.

Is there a way to convert DateTime time = new DateTime() to a specific timezone, or perhaps to get the number of hours difference between time.getZone() and another DateTimeZone to then do time.minusHours or time.plusHours?

What does "use strict" do in JavaScript, and what is the reasoning behind it?

Posted: 25 Jul 2021 07:48 AM PDT

Recently, I ran some of my JavaScript code through Crockford's JSLint, and it gave the following error:

Problem at line 1 character 1: Missing "use strict" statement.

Doing some searching, I realized that some people add "use strict"; into their JavaScript code. Once I added the statement, the error stopped appearing. Unfortunately, Google did not reveal much of the history behind this string statement. Certainly it must have something to do with how the JavaScript is interpreted by the browser, but I have no idea what the effect would be.

So what is "use strict"; all about, what does it imply, and is it still relevant?

Do any of the current browsers respond to the "use strict"; string or is it for future use?

No comments:

Post a Comment