text:
Q: Accessing RubyOnRails variable in Javascript says variable is undefined I created an instance variable in my RubyOnRails controller (index.rb) named @var_ror
In my javascript file (fetchingDataFromRoR.js.erb) I try to access this RubyOnRails variable and assign it to a javascript variable.
var var_js = '<%= @var_ror %>'

I get an error saying @var_ror is undefined.
However, if I use a global variable named $var_ror and access it in javascript like this:
var var_js = '<%= $var_ror %>'

It works. However, I don't want a variable of global scope and also it causes other problems.

A: try something like this
controller:
respond_to do |format|
  format.js { render "fetchingDataFromRoR", :locals => {:var_ror => @var_ror} }
end

fetchingDataFromRoR.js.erb:
var var_js = <%= var_ror %>;

A: you are mixing js and ruby incorrectly. the correct syntax is
var var_js = '<%= @var_ror %>'

reason:
let @var_ror = "some_string"
then your
var var_js = <%= @var_ror %>
resulting in  var var_js = some_string , now some_string looks like a variable which not defind and so, will throw an error


text:
Q: How much energy do photons lose when they hit a material that reflects that wavelength? since germanium has the required energy of 0.72 eV. to brake an electron free, what if a photon has say, 100 eV? would the photon (if reflected by the germanium) lose only 0.72 eV each time it hits a germanium atom, or lose more eV?

A: This is really two questions. The title

How much energy do photons lose when they hit a material that reflects that wavelength?

is a different problem than in the question.
Reflection means that photons elastically scatter in the center of mass system of the "material +photon". In the lab frame, the mass of the material is so large that the relativistic Doppler effect is very small, so the small loss of energy of the photon in the lab is not measureable.
The question in the body

since germanium has the required energy of 0.72 eV. to brake an electron free, what if a photon has say, 100 eV? would the photon (if reflected by the germanium) lose only 0.72 eV each time it hits a germanium atom, or lose more eV?

Is about the photoelectric effect. Reflection means elastic scattering by definition, therefore if the photoelectric effect happens there is no reflection. The total energy of the photon scatters off an electron and releases it to interact further or to leave the surface of the material. Compton scattering may also happen, and a photon may lose part of its energy to the ejected electron, but it is not a reflection.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to decide which unicode character is a word seperator? In most text editors, like notepad-plus-plus and vscode, when you double click on a character, they will select the whole word. I am curious how to implement that, this function(in Python) could be:
separators = 'some characters' # word separators
def select_word_at_offset(line, offset):
    line_length = len(line)
    if offset < 0 or offset > line_length:
        raise RuntimeError('offset is not a valid index of line')

    # ignore the cases when you double click on a word separator

    start_index = offset
    end_index = offset

    # look left to find the start index
    while start_index >= 0:
        if line[start_index] in separators:
            break
        start_index -= 1

    # look right to find the end index
    while end_index < line_length:
        if line[start_index] in separators:
            break
        end_index += 1
    return start_index + 1, end_index - 1

It's easy to do that if you just consider ASCII characters, but to support unicode, I have to decide which unicode character should be considered as a word separator. Whether to use a whitelist or a blacklist, it's gonna be a very long list.
So, is there any easy way to cover all unicode word seperators? And how did these editors do that?

A: Thanks @Shawn,  Unicode Word Boundary Rules helps a lot, I read this post and looks like perl already got it, I never learned perl, so still need some time to confirm that.
And I found out vscode use these characters as word separators:
export const USUAL_WORD_SEPARATORS = '`~!@#$%^&*()-=+[{]}\\|;:\'",.<>/?';

Apparently, they didn't consider non-English language symbols, like 。, which indicates the end of a sentence in Chinese.


text:
Q: Preact component not rendering elements inside loop I have a Preact component which should render an array. The array is not multidimensional; I'm mapping a 2D array to a 1D array (so I can't just .map()). Anyway, it is only rendering the parent div but is still iterating correctly when debugging.
export const Grid = ({ width, height }: { width: number, height: number }) => {
    const [grid] = useState<Cell[]>(initialiseArray({ width, height, fill: () => ({ active: Math.random() < 0.5 }) }));

    return (

            {[...Array(width)].map((_, indexX) =>
                {
                    {[...Array(height)].map((_, indexY) => (

                                X

                        )
                    )}
                }
            )}

    );
};

Which is simply returning

. What's wrong here?

A: The outer map doesn't return anything.
When you use .map(() => { ... }) (emphasis on the curly braces), you need to explicitly return a value. For example:
const x = foo.map(() => {

foo

});

x in this example will be empty, but either of the following will fix this:
const x = foo.map(() => {
    return
foo

});

const x = foo.map(() =>

foo

);

So you need to either add in return or remove the curly braces ({}).
export const Grid = ({ width, height }: { width: number; height: number }) => {
  const [grid] = useState<Cell[]>(initialiseArray({ width, height, fill: () => ({ active: Math.random() < 0.5 }) }));

  return (

-     {[...Array(width)].map((_, indexX) => {
+     {[...Array(width)].map((_, indexX) => (
        {
          [...Array(height)].map((_, indexY) => (

              X

          ));
        }
-     })}
+     ))}

  );
};


text:
Q: Retrain image detection with MobileNet Several ways of retraining MobileNet for use with Tensorflow.js have failed for me. Is there any way to use a retrained model with Tensorflow.js?
Both using the modern, hub-based tutorial, as well as using retrain.py seem to fail.

*

*Convert output of retrain.py to tensorflow.js

*Error converting keras model to tfjs: duplicate weight name Variable
as well as some other open questions

*

*Retrain an Image Classifier in tensorflow js

*Loading of mobilenet v2 works, but pretrained mobilenet v2 fails

*Can't convert TensorFlow saved model to tfjs_layers_model webmodel
The top two other questions show the code that failed in both instances, both are unsolved.
The aim is to load the mobilenet, retrain using custom data, and use it in Tensorflow.js. Following both tutorials seem to fail. Could this be done inside node.js? Is there another way? Where did I make mistakes (or is the software unable to use retrained models)? How can this work?
EDITs: latest github issue and one more question

A: I encountered the same problem and it seems that we use the wrong method.
There are loadGraphModel for TF converted models and loadLayersModel for Keras ones
my comment about the issue

A: The retrain.py python script does not generate a saved model, it actually generates a frozen graph model. That is why you cannot convert it using the tfjs 1.x converter. You need to use tfjs 0.8.5 pip to convert.
Also, the output node name is different from the mobilenet model graph, it is 'final_result' for retrained graph.
To convert it you need to use the tensorflowjs 0.8.5 pip:

*

*use virtualenv to create an empty env.

*pip install tensorflowjs==0.8.5

*run the converter

tensorflowjs_converter \
  --input_format=tf_frozen_model \
  --output_node_names='final_result' \
  --output_json=true /tmp/output_graph.pb \ /tmp/web_model

This should give you something like the following:
ls /tmp/web_model/
group1-shard10of21  group1-shard14of21  group1-shard18of21  group1-shard21of21  group1-shard5of21  group1-shard9of21
group1-shard11of21  group1-shard15of21  group1-shard19of21  group1-shard2of21   group1-shard6of21  model.json
group1-shard12of21  group1-shard16of21  group1-shard1of21   group1-shard3of21   group1-shard7of21
group1-shard13of21  group1-shard17of21  group1-shard20of21  group1-shard4of21   group1-shard8of21

A: To use the latest TFjs:
python retrain.py --tfhub_module https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/feature_vector/2 \
    --image_dir /tmp/flower_photos --saved_model_dir /tmp/saved_retrained_model
tensorflowjs_converter --input_format=tf_saved_model \
    --output_format=tfjs_graph_model \
    --saved_model_tags=serve \
    /tmp/saved_retrained_model/ /tmp/converted_model/

creates a model.json file. Command described in https://github.com/tensorflow/tfjs-converter#step-1-converting-a-savedmodel-keras-h5-tfkeras-savedmodel-or-tensorflow-hub-module-to-a-web-friendly-format.
Yet, loading the model with tf.loadLayersModel("file:///tmp/web_model/model.json") failed with

'className' and 'config' must set.

A: Maybe somebody can modify retain.py to support mobileV2 use my way.
The original retrain.py link.  This link is Google's GitHub code, not my link.
I changed retrain.py, the below is my git diff:
diff --git a/scripts/retrain.py b/scripts/retrain.py
index 5fa9b0f..02a4f9a 100644
--- a/scripts/retrain.py
+++ b/scripts/retrain.py
@@ -1,3 +1,5 @@
+# -*- coding: utf-8 -*-
+
 # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
@@ -112,6 +114,13 @@ from tensorflow.python.framework import graph_util
 from tensorflow.python.framework import tensor_shape
 from tensorflow.python.platform import gfile
 from tensorflow.python.util import compat
+from tensorflow import saved_model as sm
+from tensorflow.python.saved_model import builder as saved_model_builder
+from tensorflow.python.saved_model import signature_constants
+from tensorflow.python.saved_model import signature_def_utils
+from tensorflow.python.saved_model import tag_constants
+from tensorflow.python.saved_model import utils as saved_model_utils
+

 FLAGS = None

@@ -319,6 +328,7 @@ def maybe_download_and_extract(data_url):
   Args:
     data_url: Web location of the tar file containing the pretrained model.
   """
+  print(FLAGS.model_dir)
   dest_directory = FLAGS.model_dir
   if not os.path.exists(dest_directory):
     os.makedirs(dest_directory)
@@ -827,6 +837,7 @@ def save_graph_to_file(sess, graph, graph_file_name):
       sess, graph.as_graph_def(), [FLAGS.final_tensor_name])
   with gfile.FastGFile(graph_file_name, 'wb') as f:
     f.write(output_graph_def.SerializeToString())
+
   return

@@ -971,6 +982,7 @@ def main(_):

   # Prepare necessary directories  that can be used during training
   prepare_file_system()
+  sigs = {}

   # Gather information about the model architecture we'll be using.
   model_info = create_model_info(FLAGS.architecture)
@@ -1002,6 +1014,9 @@ def main(_):
       FLAGS.random_brightness)

   with tf.Session(graph=graph) as sess:
+    serialized_tf_example = tf.placeholder(tf.string, name='tf_example')
+    feature_configs = {'x': tf.FixedLenFeature(shape=[784], dtype=tf.float32),}
+    tf_example = tf.parse_example(serialized_tf_example, feature_configs)
     # Set up the image decoding sub-graph.
     jpeg_data_tensor, decoded_image_tensor = add_jpeg_decoding(
         model_info['input_width'], model_info['input_height'],
@@ -1133,6 +1148,73 @@ def main(_):
                           (test_filename,
                            list(image_lists.keys())[predictions[i]]))

+    """
+    # analyze SignatureDef protobuf
+    SignatureDef_d = graph.signature_def
+    SignatureDef = SignatureDef_d[sm.signature_constants.CLASSIFY_INPUTS]
+
+    # three TensorInfo protobuf
+    X_TensorInfo = SignatureDef.inputs['input_1']
+    scale_TensorInfo = SignatureDef.inputs['input_2']
+    y_TensorInfo = SignatureDef.outputs['output']
+
+    # Tensor details
+    # .get_tensor_from_tensor_info() to get default graph
+    X = sm.utils.get_tensor_from_tensor_info(X_TensorInfo, sess.graph)
+    scale = sm.utils.get_tensor_from_tensor_info(scale_TensorInfo, sess.graph)
+    y = sm.utils.get_tensor_from_tensor_info(y_TensorInfo, sess.graph)
+    """
+
+    """
+    output_graph_def = graph_util.convert_variables_to_constants(
+      sess, graph.as_graph_def(), [FLAGS.final_tensor_name])
+
+    X_TensorInfo = sm.utils.build_tensor_info(bottleneck_input)
+    scale_TensorInfo = sm.utils.build_tensor_info(ground_truth_input)
+    y_TensorInfo = sm.utils.build_tensor_info(output_graph_def)
+
+    # build SignatureDef protobuf
+    SignatureDef = sm.signature_def_utils.build_signature_def(
+                                inputs={'input_1': X_TensorInfo, 'input_2': scale_TensorInfo},
+                                outputs={'output': y_TensorInfo},
+                                method_name='what'
+    )
+    """
+
+    #graph = tf.get_default_graph()
+    tensors_per_node = [node.values() for node in graph.get_operations()]
+    tensor_names = [tensor.name for tensors in tensors_per_node for tensor in tensors]
+    print(tensor_names)
+
+    export_dir = './tf_files/savemode'
+    builder = saved_model_builder.SavedModelBuilder(export_dir)
+
+    # name="" is important to ensure we don't get spurious prefixing
+    graph_def = tf.GraphDef()
+    tf.import_graph_def(graph_def, name="")
+    g = tf.get_default_graph()
+    inp1 = g.get_tensor_by_name("input:0")
+    inp2 = g.get_tensor_by_name("input_1/BottleneckInputPlaceholder:0")
+    inp3 = g.get_tensor_by_name("input_1/GroundTruthInput:0")
+    out = g.get_tensor_by_name("accuracy_1:0")
+
+    sigs[signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = \
+        tf.saved_model.signature_def_utils.predict_signature_def(
+            {'input_1': inp1, 'input_2': inp3}, {"output": out})
+
+    builder.add_meta_graph_and_variables(sess,
+                                         tags=[tag_constants.SERVING],
+                                         signature_def_map=sigs)
+
+    """
+    builder.add_meta_graph_and_variables(
+            sess=sess,
+            tags=[tag_constants.SERVING],
+            signature_def_map={sm.signature_constants.CLASSIFY_INPUTS: SignatureDef})
+    """
+
+    builder.save()
+
     # Write out the trained graph and labels with the weights stored as
     # constants.
     save_graph_to_file(sess, graph, FLAGS.output_graph)

Using my diff, I can generate Tensorflow Served model.
And then I use the command to convert TensorFlow served model to Tfjs model.
tensorflowjs_converter \
    --input_format=tf_saved_model \
    --output_format=tfjs_graph_model \
    ./tf_files/savemode \
    ./tf_files/js_model

Still unsupported Ops for lasted Tensorflow JS version.
I just make a video here to explain why we cannot convert Tensorflow frozen model to Tensorflow JS model, tells how to find the input Tensor and Output Tensor. The running steps and result, finally, give unsupported Ops ScalarSummary and the reason.
Now that I cannot change the Mobilenet Model to Tensorflow JS model, so my workaround is using Python tensorflow and flask library on Server side, user upload the image to server and then return the result.


text:
Q: Getting elements from an array which adds up to a value greater than given value JavaScript I recently just started to learn JavaScript to improve on my skills and a challenge came up which has thrown me off course.
I have a set of values of which I need to find elements in an array which would add up to give a number greater than the individual set of values. For instance
An array of [50, 100, 400, 800]
if I have a value say 50 it should return 50 as 50 is on the list. That is fine, but when If I have a value of say 421 it should return [400, 50] or if I have a value of 1751 it should return [800, 800, 100, 50, 50] as values that would add up to give the minimum value close to the given value.
I have tried the following:

*

*I sorted the array values

*Checked to see if the array includes a given value, if so return that value in a new array

*If a value is less than min value and greater than the next value, return the next value
I tried looking into reduce method but I cant get my head around it and would like some expertise please.

The following is my code

const ItemSize = [50, 100, 400, 800]

function getItemSize(itemSize, n) {
  const sortedItemSizes = ItemSize.sort(function compare(a, b) {
    return a - b;
  });
  let item = [];
  if (sortedItemSizes.includes(n)) {
    item.push(n);
  } else if (n > Math.min.apply(Math, sortedItemSizes) && n < sortedItemSizes[1]) {
    item.push(sortedItemSizes[1]);
  }

  return item;
}

console.log(
  getItemSize(ItemSize, 50)
)

A: You can:

*

*Sort the array in descending values

*Element by elment, check if it can be added to the solution, multiple times.

*Return the resulting array

const arr = [50, 100, 800, 400];

function findSet(arr, sum) {
  const sorted = arr.sort((a, b) => a < b ? 1 : -1);
  const res = [];
  sorted.forEach(n => {
    while(n <= sum) {
      sum -= n;
      res.push(n);
    }
  });
  return res;
}

console.log(findSet(arr, 51));
console.log(findSet(arr, 100));
console.log(findSet(arr, 150));
console.log(findSet(arr, 1751));


text:
Q: CARTO not styling 36 total representatives I'm extremely new to CARTO and I'm still learning the ropes. I currently have this territory map where the colors represent a representative in a county.

However, it isn't shading the 36 total representatives. It only shades 10 then groups the other 26 in Others.
This is my current layer style setup in Builder:

All I want to be able to do is a have a color for every representative and not have the Others category. I read that I may have to do something with CartoCSS, but it didn't guide me in the right direction.
What's the best way to go about this? If there's a better way for me to visualize what I'm trying to accomplish, please tell me.
I'm running CARTO self-hosted.

A: You were on the right track. In order to style all your categories using CARTO Builder, you need to switch from values to CartoCSS as shown in the following gif:

Secondly, you need to update the code using basic CartoCSS conditionals. Notice that you would need to know the category names and colors in advance. You can use a code like this one.
#layer {
  polygon-fill: #666666;
  [ name = "Afghanistan" ] {
    polygon-fill: #5F4690;
  }
  [ name = "Åland Islands" ] {
    polygon-fill: #1D6996;
  }
  [ name = "Albania" ] {
    polygon-fill: #38A6A5;
  }
  [ name = "Algeria" ] {
    polygon-fill: #0F8554;
  }
  [ name = "American Samoa" ] {
    polygon-fill: #73AF48;
  }
  [ name = "Andorra" ] {
    polygon-fill: #EDAD08;
  }
  [ name = "Angola" ] {
    polygon-fill: #E17C05;
  }
  [ name = "Anguilla" ] {
    polygon-fill: #CC503E;
  }
  [ name = "Antarctica" ] {
    polygon-fill: #94346E;
  }
  [ name = "Antigua and Barbuda" ] {
    polygon-fill: #6F4070;
  }
}
#layer::outline {
  line-width: 1;
  line-color: #FFFFFF;
  line-opacity: 0.5;
}

On the other hand, this problem could be easily overcome using just one line of code of CARTO VL as explained in this example:
color: ramp($name, vivid)

Link to the working example here.

What CARTO VL is doing behind the scenes is interpolating the colors when the 10 categories are reached.

A: You have the correct idea that CartoCSS is something that would assist in this effort of yours. I believe the color ramp will generally work with about 7 or so colors before it lumps everything else in the "Other" category.
I would suggest referencing Tips & Tricks - Geospatial Analysis
SELECT cartodb_id,
   the_geom,
   the_geom_webmercator,
   cartodb_id % 36 as modulus
 FROM populated_places

Using the modulus, you can input your each of the fills as such
#layer {
marker-width: 3;
marker-fill-opacity: 2;
marker-allow-overlap: false;
marker-line-width: 1;

[modulus=0]{marker-fill: #73AF48;}
[modulus=1]{marker-fill: #CC503E;}
.
.
.
[modulus=36]{marker-fill: #0F8554;}
}


text:
Q: Buidling with grunt: grunt-rev task changes my images by adding a random hash and thus prevents my html from identify them This is my html:

However after running grunt build the image name is:
5cadd58e.zulazlogo.png
This is due to the grunt-rev task.
is there a way to tweak the html to include a build statement to change the file according to the new name? something like:

A: Have you tried commenting out the grunt-rev images sections?
rev: {
  dist: {
    files: {
      src: [
        '<%= yeoman.dist %>/scripts/{,*/}*.js',
        '<%= yeoman.dist %>/styles/{,*/}*.css',
//            '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
        '<%= yeoman.dist %>/styles/fonts/*'
      ]
    }
  }
}


text:
Q: How to feed Keras model with multiple inputs through fit_generator I'm trying to solve a machine learning problem which accepts both an image input as well as a text input, for which I am simply vectorizing using a bag-of-words model.
I've used the function below to set up two generators to the model. This was largely based off simonst's answer in In keras, how to fit multiple input data with different type, which was really helpful.
def create_generators(x_train_feat, x_val_feat, train_batch_size, val_batch_size):

    '''
    Training function
    '''

    train_datagen = ImageDataGenerator(
        featurewise_center=False,
        samplewise_center=False,
        featurewise_std_normalization=False,
        samplewise_std_normalization=False,
        zca_whitening=False,
        zca_epsilon=0,
        rotation_range=0.05,
        width_shift_range=0.05,
        height_shift_range=0.05,
        channel_shift_range=0,
        fill_mode='nearest',
        cval=0,
        vertical_flip=False,
        rescale=1./255,
        shear_range=0.,
        zoom_range=0.,
        horizontal_flip=False)

    val_datagen = ImageDataGenerator(
        rescale=1./255,
        featurewise_std_normalization=False,
        featurewise_center=False)

    train_generator=train_datagen.flow_from_dataframe(
        dataframe=subset_df_train,
        directory='./',
        x_col="image_path",
        y_col="Category_Name",
        batch_size=train_batch_size,
        seed=42,
        shuffle=True,
        class_mode="categorical",
        target_size=target_size)

    validation_generator = val_datagen.flow_from_dataframe(
        dataframe=subset_df_valid,
        directory="./",
        x_col="image_path",
        y_col="Category_Name",
        batch_size=val_batch_size,
        seed=42,
        shuffle=True,
        class_mode="categorical",
        target_size=target_size)

    def train_feat_gen(x_train_feat, train_batch_size):
        while True:
            for batch in range(len(x_train_feat) // train_batch_size + 1):
                if batch > max(range(len(x_train_feat) // train_batch_size)):
                    yield x_train_feat[batch*train_batch_size:]
                else:
                    yield x_train_feat[batch*train_batch_size:(1+batch)*train_batch_size]

    def val_feat_gen(x_val_feat, val_batch_size):
        while True:
            for batch in range(len(x_val_feat) // val_batch_size + 1):
                if batch > max(range(len(x_val_feat) // val_batch_size)):
                    yield x_val_feat[batch*val_batch_size:]
                else:
                    yield x_val_feat[batch*val_batch_size:(1+batch)*val_batch_size]

    def merge_generator(gen1, gen2):
        while True:
            X1 = gen1.__next__()
            X2 = gen2.__next__()
            yield [X1[0], X2], X1[1]

    final_train_gen = merge_generator(train_generator, train_feat_gen(x_train_feat, train_batch_size))
    final_val_gen = merge_generator(validation_generator, val_feat_gen(x_val_feat, val_batch_size))

    return (final_train_gen,final_val_gen)

final_train_gen,final_val_gen = create_generators(aux_train, aux_valid, 16, 16)

Unfortunately when I then run the model with the below code,
hist = model.fit_generator(
    final_train_gen,
    steps_per_epoch=train_len // 16,
    epochs=3,
    validation_data=final_val_gen,
    validation_steps=valid_len // 16)

I encounter the following error: ValueError: All input arrays (x) should have the same number of samples. Got array shapes: [(16, 128, 128, 3), (0, 2160)].
This only occurs on the 2nd epoch, however. The first one trains okay. Based on the (0,2160), it looks like the 2nd epoch is not loading the batches (my batch size is 16) properly. Unfortunately, as I don't have a strong grasp of how the above create_generators function works to merge the two, I'm not very sure where the problem lies, and would greatly appreciate help/guidance on this.
Apologies as the code is experimental and hence a little messy and some of the underlying context is missing - I hope I've included information enough to understand the issue.
Thanks in advance.

A: You can create a single generator to pair up each image with its associated text. Simply pass the data frame or file for both the images and texts to your fit_generator function, and process them such that they match based on the criteria you have (e.g. an ID), and yield arrays that have a certain size, matching your desired batch size. Then, you can yield a tuple like in your code, but now you can guarantee that the batch sizes match.
If you really want to use two generators, you can have a look here:
https://github.com/keras-team/keras/issues/8130


text:
Q: how to render video from youtube iframe into canvas? guys! How to render video from You_Tube
<iframe></iframe>

tag into canvas?

A: It seems this is not supported. Looking at Drawing DOM objects into a canvas, there is no mention of iframes being drawn to canvas.
You might want to try another alternative from this SO post.


text:
Q: jQuery show() and hide() vs classes with display:block / none Just out of curiosity, which of these two techniques is more "valid" to use?
I had a discussion with my supervisor and he told me that I should create two classes with display:block/none and assign them to elements using jQuery, rather than using jQuery's own functions show/hide.
I had the impression that show/hide are widely used functions that work without any issues and they were made to make our lives easier by not forcing us to assign classes.

A: They are the same - show() and hide() just switches between display: block (or inline, inline-block, etc) and display: none or similar.  Using these or using simple classes to switch between those styles are both perfectly "valid".
The main difference is that show() and hide() support jQuery animations out of the box.  Also, classes do not add inline CSS, whereas show() and hide() do (inline html to override whatever the initial display value is).  Depending on your use case this may or may not be convenient.
show() and hide() also cache the initial display value so if you hide() an element and then show() it, it will remember what the original display value was (which means it's more flexible since you don't need unique visible classes for elements with different types of display values).

A: You can use such CSS classes to initially hide element on the page to show it later with jQuery.show().
Anyway jQuery.show() sets the style property directly so the browser don't need to lookup through CSS declaration to find a class each time you assign it. So I believe it will work faster and also is more convenient to developer. By the way the code with show/hide is also more readable.
Just compare
$username.hide();

to
$username.addClass('hidden');

Seems the code is more readable, so that it's more maintainable, therefore it's cheaper for customer to support it... and so on.

A: There is nothing "invalid" about using either of the two techniques. It boils down to your preference I believe. jQuery's show/hide methods work perfectly well. Some points to consider

*

*If you use show/hide, it's a pure javascript/jquery based solution.

*If you use CSS classes by assigning them USING jquery this method involves CSS + jquery

Having said that it's always recommended to use a CSS solution wherever possible. If you create classes with display block/none like you said, you can use them throughout your application. So I guess in the end it's up to ypur personal choice.

A: I think the difference in the approaches is that by doing it with classes you can chose how you hide in future re-stylings.  You might want to swap in a new CSS one day where hidden is actually crossed through and grayed out.  By using classes you maintain a separation of presentation and data.


text:
Q: How to read/convert arc000dat files? I have a number of files that I am trying to import, but I'm just failing at the first hurdle.
I've got a directory structure and file list that looks like this:
 Directory of C:\blah

01/04/2011  14:41    <DIR>          info
01/04/2011  17:01               951 log
01/04/2011  14:41    <DIR>          mastertic
01/04/2011  14:41    <DIR>          site
01/04/2011  14:41    <DIR>          street
01/04/2011  17:01               575 verify.wat
               2 File(s)          1,526 bytes

 Directory of C:\blah\info

01/04/2011  14:41    <DIR>          .
01/04/2011  14:41    <DIR>          ..
01/04/2011  17:01                80 arc000dat
01/04/2011  17:01               432 arc000nit
01/04/2011  17:01                80 arc001dat
01/04/2011  17:01               576 arc001nit
01/04/2011  17:01                80 arc002dat
01/04/2011  17:01               432 arc002nit
01/04/2011  17:01                80 arc003dat
01/04/2011  17:01             1,008 arc003nit
01/04/2011  17:01                80 arc004dat
01/04/2011  17:01               576 arc004nit
01/04/2011  17:01                80 arc005dat
01/04/2011  17:01               864 arc005nit
01/04/2011  17:01                80 arc006dat
01/04/2011  17:01               576 arc006nit
01/04/2011  17:01                80 arc007dat
01/04/2011  17:01             1,728 arc007nit
01/04/2011  17:01                80 arc008dat
01/04/2011  17:01               432 arc008nit
01/04/2011  17:01             3,420 arcdr9
01/04/2011  17:01                 0 arcnsp
              20 File(s)         10,764 bytes

 Directory of C:\blah\mastertic

01/04/2011  14:41    <DIR>          .
01/04/2011  14:41    <DIR>          ..
01/04/2011  17:01                32 dblbnd
01/04/2011  17:01                80 dbltic
01/04/2011  17:01               169 log
               3 File(s)            281 bytes

 Directory of C:\blah\site

01/04/2011  14:41    <DIR>          .
01/04/2011  14:41    <DIR>          ..
01/04/2011  17:01            17,732 arc
01/04/2011  17:01               780 arx
01/04/2011  17:01             1,504 cnt
01/04/2011  17:01               452 cnx
01/04/2011  17:01                32 dblbnd
01/04/2011  17:01                80 dbltic
01/04/2011  17:01             2,508 lab
01/04/2011  17:01             1,024 log
01/04/2011  17:01             4,424 pal
01/04/2011  17:01               260 par
01/04/2011  17:01             1,496 pat
01/04/2011  17:01               452 pax
              12 File(s)         30,744 bytes

 Directory of C:\blah\street

01/04/2011  14:41    <DIR>          .
01/04/2011  14:41    <DIR>          ..
01/04/2011  17:01             1,288 aat
01/04/2011  17:01             9,268 arc
01/04/2011  17:01               324 arx
01/04/2011  17:01                32 dblbnd
01/04/2011  17:01                80 dbltic
01/04/2011  17:01           352,802 log
01/04/2011  17:01             1,330 nat
01/04/2011  17:01               260 par
               8 File(s)        365,384 bytes

There are no file extensions, but from googling, it suggests that you could convert these using Arc Workstation?  Does anybody know if there is another way of loading or converting these files?
I have an ArcGIS 10 desktop licence, and a variety of open source tools at my disposal!

A: In ArcGIS (any licence level)
Import from E00 (Conversion)  [in To Coverage ToolSet]
"Imports an ArcInfo interchange file (.e00). An interchange file is used to transport coverages, INFO tables, text files such as AML macros, and other ArcInfo files. For coverages, grids, and tins, it contains all information, including appropriate INFO table information. Interchange files are designated with the .e00 file suffix. This is the ArcView 3.x version of the utility for importing .e00 files. "
http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//001200000046000000

A: ArcInfo Workstation includes a CONVERTWORKSPACE command that will convert a workspace from pre-7 format to the 7.0 format readable by current versions of ArcGIS.
It's a good thing ogr2ogr can do this too!

A: Looks like you have three coverage files, mastertic, site, and street.  You should be able to load these files using the Add Data button in arcmap.

A: You can convert those coverage files to shape files using the Feature Class to Shapefile tool.

Converts a shapefile, coverage feature class, or geodatabase feature
  class to a shapefile or geodatabase feature class.

A: The documentation for OGR indicates ogr2ogr will read Pre version 7 ArcInfo Coverage data. So, you should be able to convert the vector data to Shapefile or other usable format. Another option is using AVCexport, to convert each coverage to an E00 (export file). Then ArcGIS might be able to import each e00.  Also, the TatukGIS Viewer should allow you to view the native arcinfo coverage.


text:
Q: Do both of these modify the previous noun phrases?
"Yes," said Professor McGonagall. "And I don't suppose you're going to
  tell me why you're here, of all places?"  "I've come to bring Harry to
  his aunt and uncle. They're the only family he has left now."
  (Harry Potter and the Sorcerer's Stone)

Do he has and left both modify the previous noun phrase, as an adjective clause and a participle, respectively?

A: To be an adjective clause, it needs:

*

*To contain a subject and a verb

*To start with a relative pronoun, or a relative adverb

*To function as adjective

If the sentence is "They're the only family that he has left now." then that he has left is an adjective clause.
I understand the sentence as saying they are the only family he still has. I would not say that left modifies they are the only family.


text:
Q: Is there a way to localize php's error output? We're teaching a class in chinese (Mandarin). For our students, it would be easier (and make more sense to them) if the error output running php (on the commandline) was localizable to Mandarin. Is there a way to configure our php setup to support this (i.e. edit a php.ini file)?

A: I have downloaded the PHP source code and searched how the source handles it's errors. After going through a couple of (randomly picked) files and found these kinds of lines all over the place:
// warning for the sleep() function
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of seconds must be greater than or equal to 0");

// warning for the constant() function
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't find constant %s", const_name);

// warning for the mysql_free_result() function
php_error_docref("function.mysql-free-result" TSRMLS_CC, E_WARNING, "%lu result set(s) not freed. Use mysql_free_result to free result sets which were requested using mysql_query()", MySG(result_allocated));

// error for the mysql-escape-string function()
php_error_docref("function.mysql-escape-string" TSRMLS_CC, E_DEPRECATED, "This function is deprecated; use mysql_real_escape_string() instead.");

This goes on and on forever which makes me conclude that errors are hardcoded and thus not available in any other language...
Too bad :(

After hours of searching (5 hours and 45 minutes to be exact) - I have found a couple of solutions that probably aren't worthwhile but who am I to judge.
Translations are often saved in files with the .po extension. These files contain a bunch of original strings and the translated strings. This means that you have to translate every string each, manually. You can create files with PoEdit.
Then you need to parse these files. You can build a PHP version that has the Gettext module installed. Alternatively, the Zend Framework is able to parse these files as well.
Clearly, you don't want to translate every possible string manually. Last option is using a translator service such as Google Translate or Microsoft Translate.
In all cases, you have to replace the existing error string with the new error string. There's a native PHP function called set_error_handler(). This allows you to set a custom error handling function. If you want to translate the existing error string you should do it there. Here's a set up that you could use (I haven't tested this thoroughly):
<?php
set_error_handler('error_handler');

function error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
    // Get the correct string for the error type
    switch($errno){
        case E_ERROR:
            $type = 'Error';
            break;
        case E_WARNING:
            $type = 'Warning';
            break;
        case E_PARSE:
            $type = 'Parse Error';
            break;
        case E_NOTICE:
            $type = 'Notice';
            break;
        case E_CORE_ERROR:
            $type = 'Core Error';
            break;
        case E_CORE_WARNING:
            $type = 'Core Warning';
            break;
        case E_COMPILE_ERROR:
            $type = 'Compile Error';
            break;
        case E_COMPILE_WARNING:
            $type = 'Compile Warning';
            break;
        case E_USER_ERROR:
            $type = 'User Error';
            break;
        case E_USER_WARNING:
            $type = 'User Warning';
            break;
        case E_USER_NOTICE:
            $type = 'User Notice';
            break;
        case E_STRICT:
            $type = 'Strict Notice';
            break;
        case E_RECOVERABLE_ERROR:
            $type = 'Recoverable Error';
            break;
        default:
            $type = 'Unknown error (' . $errno . ')';
            break;
    }

    // translate text
    $type = error_handler_translate($type);
    $str = error_handler_translate($errstr);
    $in = error_handler_translate('in');
    $line = error_handler_translate('on line');

    // echo the error in "default" PHP format
    echo '
'. $type .': ' . $str . ' '. $in .' ' . $errfile . ' '. $line .' ' . $errline . '
';

    // ignore the original PHP error handling
    return true;
}

function error_handler_translate($str) {
    // translate $str here

    return $str;
}
?>

All that remains is including this code to your script and you should be all good!

A: you can try, this may work
/* Set locale to Dutch */
setlocale(LC_ALL, 'nl_NL');


text: Q: What is the difference between ROOT_QUERY and $ROOT_QUERY in Apollo In-memory Cache? In my Apollo In-memory Cache, some fields have a prefix of $ROOT_QUERY while others just have ROOT_QUERY. I can't seem to crack what the difference is, both from the behavior of my cache, the docs, or the code.


text:
Q: Unable to trigger firestore changes locally I just started doing firebase and I need to do something when a new document is created but in functions and I setup cli and started locally but the function is not triggered.
while doing firebase init I chose firestore,functions,storage
after that did firebase login and firebase serve --only functions
and the server is up but whenever I add new document the function is not getting triggered?

A: You should be able to do that with firebase emulators:start. This starts emulators for Cloud Functions, Cloud Firestore, Realtime Database and Firebase Hosting. If that doesn't work, please share your code and I can have a look.
The docs may be useful too: https://firebase.google.com/docs/functions/local-emulator#run_the_emulator_suite


text:
Q: looking for a better way of parsing XML retrieved from web API c# I've been trying to parse XML retrieved from a web api all day. This is the only implementation I've found that worked for me. I tried with the Serializer class but couldn't seem to get it working.
Some of the Web APIs I need to get data from to have many elements and this implementation doesn't seem very scale-able...
I'm relatively new to this so any help is appreciated. What would be ideal is if somebody could show me how to have the same functionality as shown, using less code.. I imagine using the serializer class.
List<OpeningHours> openingHoursList = new List<OpeningHours>();
HttpClient client = new HttpClient();
Uri geturi = new Uri("Insert Uri name");

HttpResponseMessage responseGet = await client.GetAsync(geturi);
string response = await responseGet.Content.ReadAsStringAsync();
XDocument doc = XDocument.Parse(response);

foreach (var item in doc.Descendants("OpenHours"))
{
    openingHoursList.Add(new OpeningHours() {
        DayOfWeek = item.Element("DayOfWeek").Value.ToString(),
        CloseTime = item.Element("CloseTime").Value.ToString(),
        OpenTime = item.Element("OpenTime").Value.ToString()
    });
}

For reference, this is the XML that I'm currently trying to parse.
<NewDataSet>
<OpenHours>
<DayOfWeek>Wednesday </DayOfWeek>
<OpenTime>07:30:00</OpenTime>
<CloseTime>18:00:00</CloseTime>
</OpenHours>
<OpenHours>
<DayOfWeek>Thursday </DayOfWeek>
<OpenTime>07:30:00</OpenTime>
<CloseTime>18:00:00</CloseTime>
</OpenHours>
<OpenHours>
<DayOfWeek>Monday </DayOfWeek>
<OpenTime>07:30:00</OpenTime>
<CloseTime>18:00:00</CloseTime>
</OpenHours>
<OpenHours>
<DayOfWeek>Tuesday </DayOfWeek>
<OpenTime>07:30:00</OpenTime>
<CloseTime>18:00:00</CloseTime>
</OpenHours>
<OpenHours>
<DayOfWeek>Friday </DayOfWeek>
<OpenTime>07:30:00</OpenTime>
<CloseTime>18:00:00</CloseTime>
</OpenHours>
</NewDataSet>

However, what is I wanted to parse something like this...
This is what I mean by scale-able. If I use my current solution I'll need to Initialise every field of my C# class by hand. As well as this, some of the XML elements have varying numbers of decedents...
<Dish>
<DishID>180</DishID>
<DishName>Caesar Salad (v) - Large</DishName>
<DishDesc>
Romaine Lettuce, Homemade Croutons, Shaved Grana Padano, Black Pepper & Caesar Dressing (separate) (v)
</DishDesc>
<DishPrice>21.5000</DishPrice>
<DishCat>22</DishCat>
<DishPosition>6</DishPosition>
<DishSpecial>0</DishSpecial>
<DishOn>true</DishOn>
<DishNumber/>
<DishHasOptions>false</DishHasOptions>
<VATable>true</VATable>
<UPC/>
<SKU/>
<Timer>0</Timer>
<FilterClasses/>
<DishDesc2/>
</Dish>
<Dish>
<DishID>179</DishID>
<DishName>Caesar Salad (v) - Small.</DishName>
<DishDesc/>
<DishPrice>4.3000</DishPrice>
<DishCat>22</DishCat>
<DishPosition>7</DishPosition>
<DishSpecial>0</DishSpecial>
<DishOn>true</DishOn>
<DishNumber/>
<DishHasOptions>false</DishHasOptions>
<VATable>true</VATable>
<UPC/>
<SKU/>
<Timer>0</Timer>
<FilterClasses/>
<DishDesc2/>
</Dish>
<Dish>
<DishID>53</DishID>
<DishName>Caesar salad (v)(small or large)</DishName>
<DishDesc>
Romaine lettuce, parmesan shavings, croutons with Caesar dressing
</DishDesc>
<DishPrice>4.0000</DishPrice>
<DishCat>7</DishCat>
<DishPosition>4</DishPosition>
<DishSpecial>0</DishSpecial>
<DishOn>false</DishOn>
<DishNumber>0</DishNumber>
<DishHasOptions>true</DishHasOptions>
<VATable>true</VATable>
<UPC/>
<SKU/>
<Timer>0</Timer>
<FilterClasses/>
<DishDesc2/>
<Option>
<DishOptionID>62</DishOptionID>
<DishID>53</DishID>
<DishOptionDesc>Select your size</DishOptionDesc>
<DishOptionSeqNo>1</DishOptionSeqNo>
<DishOptionPickerType>3</DishOptionPickerType>
<SubOption>
<dishSubOptionID>955</dishSubOptionID>
<DishOptionID>62</DishOptionID>
<DishSubOptionDesc>Small</DishSubOptionDesc>
<DishSubOptionPrice>0.0000</DishSubOptionPrice>
<DefaultChoice>true</DefaultChoice>
<DishID>53</DishID>
<DishSubOptionSeqNo>0</DishSubOptionSeqNo>
</SubOption>
<SubOption>
<dishSubOptionID>956</dishSubOptionID>
<DishOptionID>62</DishOptionID>
<DishSubOptionDesc>Large</DishSubOptionDesc>
<DishSubOptionPrice>15.0000</DishSubOptionPrice>
<DefaultChoice>false</DefaultChoice>
<DishID>53</DishID>
<DishSubOptionSeqNo>0</DishSubOptionSeqNo>
</SubOption>
</Option>
</Dish>

A: If you only want shorter code, you're looking for a Linq Select method here, something like:
using System.Linq;
using System.Xml.Linq;

...
List<OpeningHours> openingHoursList = doc.Descendants("OpenHours").Select(x => new OpeningHours()
{
    DayOfWeek = x.Element("DayOfWeek").Value.ToString(),
    CloseTime = x.Element("CloseTime").Value.ToString(),
    OpenTime = x.Element("OpenTime").Value.ToString()
}).ToList();

Getting used to lambdas and creating and assigning variables in the same statement will help you write shorter code, but the shortest code isn't always the best option, for instance where scalability and maintainability are also a priority.
Because you haven't provided much by way of examples of the XML you want to parse, there's little more that I can safely recommend - I've not found a single, self-scaling XML-parsing approach that will elegantly handle a variety of purposes.
Another approach I have used in the past is to shift the focus onto the data class itself, in this case OpeningHours.
In your OpeningHours class, create a constructor that accepts an XElement as parameter, and write the code to validate and parse that XML in there:
//in your OpeningHours class:
public OpeningHours(XElement xmlResponse)
{
    DayOfWeek = xmlResponse.Element("DayOfWeek").Value.ToString();
    CloseTime = xmlResponse.Element("CloseTime").Value.ToString();
    OpenTime = xmlResponse.Element("OpenTime").Value.ToString();
} //etc..

Then in your parsing method you replace the lambda in the .Select() with:
List<OpeningHours> openingHoursList = doc.Descendants("OpenHours")
     .Select(x => new OpeningHours(x)).ToList();

Building you classes this way helps keep the relevant logic together with the structure it is loaded into, and as new properties are added, I find it easier to update the relevant XML parsing routine.


text:
Q: Magento 2 GraphQL ProductInterface says "String" but schema says "ComplexTextValue" I have an issue with Magento 2 (2.4.4-p2) and GraphQL.
Im trying to filter products with the attributes:
short_description {
    html
}
description {
    html
}

And get the following error:
{
  "errors": [
    {
      "message": "Field \"description\" of type \"String\" must not have a sub selection.",
      "extensions": {
        "category": "graphql"
      },
      "locations": [
        {
          "line": 5,
          "column": 18
        }
      ]
    }
  ]
}

If I use ChromeiQL and check the schema definition is says:
description String
But according to the magento/vendor/magento/module-catalog-graph-ql/etc/schema.graphqls it is set to "ComplexTextValue". (See below, I just cut it a bit shorter)
interface ProductInterface @typeResolver(class: "Magento\\CatalogGraphQl\\Model\\ProductInterfaceTypeResolverComposite") @doc(description: "Contains fields that are common to all types of products.") {
    description: ComplexTextValue @doc(description: "Detailed information about the product. The value can include simple HTML tags.") @resolver(class: "\\Magento\\CatalogGraphQl\\Model\\Resolver\\Product\\ProductComplexTextAttribute")
}

I can not find any other module that modifies the ProductInterface.
I have tried to define my own schema.graphqls schema but that did not work.


text:
Q: HttpSessionListener.sessionCreated() not being called I have a very simple Servlet and a very simple HttpSessionListener:
@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        getServletContext().setAttribute("applicationHits", new AtomicInteger(0));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("get");

        ((AtomicInteger) request.getServletContext().getAttribute("applicationHits")).incrementAndGet();
        ((AtomicInteger) request.getSession(true).getAttribute("sessionHits")).incrementAndGet();
        request.setAttribute("requestHits", 0);

        getServletContext().getRequestDispatcher("/view/HelloWorld.jsp").forward(request, response);
    }

}

@WebListener
public class SessionListener implements HttpSessionListener {

    public SessionListener() {
    }

    public void sessionCreated(HttpSessionEvent arg0)  {
        System.out.println("session listener");
        arg0.getSession().setAttribute("sessionHits", new AtomicInteger(0));
    }

    public void sessionDestroyed(HttpSessionEvent arg0)  {
    }

}

My HttpSessionListener.sessionCreated() method is never called (no log output), and I end up getting a NullPointerException on the line where I'm calling getSession()
((AtomicInteger) request.getSession(true).getAttribute("sessionHits")).incrementAndGet();
        request.setAttribute("requestHits", 0);

I tried calling getSession() without true as well, but same problem.
I don't get it - isn't the @WebListener annotation enough to invoke my listener? Eclipse even displays it as a listener under Deployment Descriptor/Listeners.

A: If you're not using @WebListener make sure your listeners are referenced in the web.xml.
<web-app>...
    <listener>
        <listener-class>com.yoursite.YourSessionListener</listener-class>
    </listener>

In order to receive these notification events, the implementation class must be either declared in the deployment descriptor of the web application, annotated with WebListener, or registered via one of the addListener methods defined on ServletContext.

A: Well, I'll try to go a bit deeper here. This problem (sessionCreated(..) not being invoked) may occur even without any correlation with [any] IDE. To be honest, I think, that cleaning the project (and the like) just coincided with problem solving (which is - cookies) and it's not related to the cleaning of project per se.
I ran into same problem and was resolving for about an hour or so.
Important clue and the actual problem here is that your browser may have stored Cookies it received in the previous runtime of the same application from the server, and those cookies aren't timed-out, killed or destroyed anyhow, hence, session will not get created with .getSession(true) because every time you issue the request, you send cookie along.
If, during the runtime of the application, you'll open dev-tools (or respective utility in other browser than Chrome) and clear cookies, and then re-try to access URL servlet of which creates the session, you will see that container will invoke sessionCreated method, as new session will be created.

A: Turns out it was one of those stupid Eclipse issues...
Project->Clean... and restarting Tomcat did the trick.


text:
Q: Why does calling File.Delete() and File.Move() in ASP.NET cause my worker process to hang? When I execute the following code to delete and move a file my worker process hangs:
File.Delete(FullSourceFilePath);
File.Move(FullTempFilePath, FullSourceFilePath);
// update db
Data.AdminUpdateFileSizeandBitrate(FileId, SizeInbytes, Bitrate);
Response.Redirect("?m=File replaced!");

The folder FullSourceFilePath has more than 15000 files in it.
Above code causes site to hang (only this site) if the file that needs to be moved is larger than around 5 MB. When this problem arises my worker process starts consuming memory and gradually my server is brought to its knees.
The only recovery solution is then to issue the IISRESET /RESTART command.
My environment is:

IIS6 running on Windows 2003 x86 SP2
  Web site written using ASP.NET 4.0 and C#

A: At a guess, the problem here is probably the large number of files in the folder you're moving the file to.
Does the worker process hang just on the File.Move()?
Try doing:
File.Delete(FullSourceFilePath);
File.Copy(FullTempFilePath, FullSourceFilePath);

Other things to try are performing the same actions from the command line and see if that causes the same problem to arise.
If it does then you're filesystem may be heavily fragmented and the disk is thrashing.
Windows also doesn't handle large numbers of files very well, if the files can be categorised in any way (for example by ID range or date range) then break this down into subfolders.
You could also run DebugDiag and capture a minidump to see where the bottleneck is happening.
Tess Ferrandez' blog has some great articles on how to use this tool to determine causes of worker process high memory use, crashes and hangs.

.NET Debugging Demos - Information and setup instructions


text:
Q: Application not starting up due to postgres db drivers not found error Am trying to deploy mulesoft application thourgh maven to cloudhub. It got deployed successfully, but the application start up gives errors. I verified the POM file and dependency jars related to postgres and all were in place.
Please help to resole this issue
POM file
<sharedLibraries>
     <sharedLibrary>
            <groupId>org.postgresql</groupId>
                            <artifactId>postgresql</artifactId>
                        </sharedLibrary>
                </sharedLibraries>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.5</version>
        </dependency>

Error:
Caused by: java.sql.SQLException: Error trying to load driver: org.postgresql.Driver : Cannot load class 'org.postgresql.Driver': [
    org.postgresql.Driver,
    Cannot load class 'org.postgresql.Driver': [
    Class 'org.postgresql.Driver' has no package mapping for region 'domain/default/app/loggingframework-app-dev'.,
    Cannot load class 'org.postgresql.Driver': [
    org.postgresql.Driver,
    Class 'org.postgresql.Driver' not found in classloader for artifact 'container'.]]]


text:
Q: How to execute batch queries? If I have an array containing a number of urls:
['http://www.abc.com', ..., 'http://www.xyz.com']

for each url, I would like to fetch the html with the following query:
select * from html where url=[url from array]

Question: do I need to make request to yql for every single url in the array or is there a way to send a single request to yql with all the urls and receive a bulk response ?

A: You could use the following query:
select * from html where url in ('http://www.yahoo.com','http://www.google.com')

Alternatively, you could also use yql.query.multi YQL table which allows you to combine different YQL queries.eg:
select * from yql.query.multi where queries="select * from html where url='http://www.google.com';select * from html where url='http://www.javarants.com/rss'"


text:
Q: Simple JQuery Logic I think I wrote myself into a corner and don't know quite how to back up. I really just need to make each div close separately onclick as well as the close all option.
http://jsfiddle.net/7U9QY/4/
$(function() {
    $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: target.offset().top
                }, 1000);
                return false;
            }
        }
    });
});

$(function() {
    $('.bar').click(function() {
        $('.full').toggle(600);
    });

});

A: The solution is simple,  you need to have a relative selector where you're toggling your full class element. It would be better if your parent div had some sort of selectable attribute / class, but for now it just happens that the first parent div satisfies the relative selector to target the .full div next to the bar
$('.full', $(this).parents('div:first')).toggle(600);

You can see the working solution here : http://jsfiddle.net/7U9QY/5/

A: Fiddle Demo
$(function () {
    $('.bar').click(function () {
        $(this).closest('a').next().next().toggle(600);
    });
});

Find the closest a tag than find the next next element and toggle

.closest()

Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

.next()
this keyword


text:
Q: ModuleNotFoundError Could not find module in path: '@emotion/weak-memoize' I started with one of my projects as a watch-along from youtube and I myself was coding it in a Code-Sandbox.
Link to the sandbox - https://codesandbox.io/s/shy-grass-wswrtd?file=/src/App.jsx
It is where I got the error:
Could not find module in path: '@emotion/weak-memoize' relative to '/node_modules/@emotion/cache/dist/emotion-cache.cjs.dev.js'
My package.json file is:
package.json
Even though i have the weak-memoize module in my dependencies, why am i still getting this error?

A: Change your weak-memoize version to 0.7.5.
This is a CodeSandBox bug, reverting back to a previous version of the module fixes the problem.
https://github.com/codesandbox/codesandbox-client/issues/6473


text:
Q: Bunnyhopping in quake: how does the movement model allow this? I was watching this interesting video about bunnyhopping and speedrunning in Quake's E1m1:

I must confess I've never really understood how bunnyhopping works (in Quake, or any other game for that matter).
The video provides a few clues, such as:

*

*Turning in a tight circle while strafing in the same direction provides additional speed

*Zigzagging (rapidly pressing Strafe left and Strafe right) while going forward also provides additional speed

*Jumping itself doesn't provide a speed boost, but rather preserves speed because there is no friction when you're airborne.

But these facts don't elucidate why bunnyhopping was possible in Quake, yet impossible in other games like Unreal.
How does the movement model of quake allow for the increase of player velocity through bunnyhopping and other techniques?
I am also interested in how bunnyhopping works in other games like Quake 2, Half-life and Half-life 2, but as I understand it, the movement models are slightly different, and so I'll limit this question to Quake.
I should also note that the Quake source code has been available since 1999, so this question ought to be perfectly answerable.

A: Bunnyhopping an artifact of how the game handles space, and specifically unit speed along diagonals. Without a deep understanding of source code, its difficult to get more specific than that. Some games, especially ones that are built on the source or HL engine, use physics that causes bunnyhopping to be possible; some of the later games using this engine just preform speed checks at regular intervals to prevent this.
If you're interested in the mathematics behind why this happens, I would suggest reading this article that explains it.


text:
Q: regex for accepting only persian characters I'm working on a form where one of its custom validators should only accept Persian characters.  I used the following code:
var myregex = new Regex(@"^[\u0600-\u06FF]+$");
if (myregex.IsMatch(mytextBox.Text))
{
    args.IsValid = true;
}
else
{
    args.IsValid = false;
}

However, it seems that it can only detect Arabic characters, as it doesn't cover all Persian characters (it lacks these four: گ,چ,پ,ژ ).
Is there a way to solve this problem?

A: attention: persianRex is written in Javascript however you can use the source code and copy paste the characters
Detecting Persian characters is a tricky task due to veraiety of keyboard layouts and operating systems. I faced the same challenge sometime before and I decided to write an open source library to fix this issue.
you can fix your issue like this:
    persianRex.text.test(yourInput); //returns true or false
here is the full documentation:
http://imanmh.github.io/persianRex/

A: i searched a lot for validating persian phone numbers with persian characters like ۱۲۳۴ using regex in laravel but found no suitable answer so instead of validating persian number with regex i decided to change peisan numbers to english and validate it myself, it helped me a lot, hope this helps:
if (is_numeric($mobile) && strlen($mobile) == 11) {
      // if number in english
      }else{
            $mobile = str_split($mobile , 2);
            if (count($mobile) != 11) {
                return redirect()->back()->withErrors('فرمت شماره موبایل باید عدد و ۱۱ رقم باشد');
            }
            foreach ($mobile as $key => $number) {
                if ($number == '۰') {
                    $mobile[$key] = 0;
                }elseif ($number == '۱') {
                    $mobile[$key] = 1;
                }elseif ($number == '۲') {
                    $mobile[$key] = 2;
                }elseif ($number == '۳') {
                    $mobile[$key] = 3;
                }elseif ($number == '۴') {
                    $mobile[$key] = 4;
                }elseif ($number == '۵') {
                    $mobile[$key] = 5;
                }elseif ($number == '۶') {
                    $mobile[$key] = 6;
                }elseif ($number == '۷') {
                    $mobile[$key] = 7;
                }elseif ($number == '۸') {
                    $mobile[$key] = 8;
                }elseif ($number == '۹') {
                    $mobile[$key] = 9;
                }
            }
            $mobile = implode($mobile);
            if(is_numeric($mobile) == false){
                return redirect()->back()->withErrors('فرمت شماره موبایل باید عدد و ۱۱ رقم باشد');
            }
        }

A: What you currently have in your regex is a standard Arabic symbols range. For additional characters your need to add them to the regex separately. Here are their codes:
ژ \u0698
پ \u067E
چ \u0686
گ \u06AF

So all in all you should have
^[\u0600-\u06FF\u0698\u067E\u0686\u06AF]+$

A: Farsi, Dari and Tajik are out of my bailiwick, but a little rummaging through the Unicode code charts tells me that Arabic covers 5 Unicode code blocks:

*

*Arabic: http://www.unicode.org/charts/PDF/U0600.pdf

*Arabic Supplement: http://www.unicode.org/charts/PDF/U0750.pdf

*Arabic Extended-A: http://www.unicode.org/charts/PDF/U08A0.pdf

*Arabic Presentation Forms-A: http://www.unicode.org/charts/PDF/UFB50.pdf

*Arabic Presentation Forms-B: http://www.unicode.org/charts/PDF/UFE70.pdf
You can get at them (at least some of them) in regular expressions using named blocks instead of explicit code point ranges: \p{IsArabicPresentationForms-A} will give you the 4th Unicode block in the preceding list.
You might also read Persian Computing in Unicode: http://behdad.org/download/Publications/persiancomputing/a007.pdf

A: The named blocks, e.g \p{Arabic} cover the entire Arabic script, not just the Persian characters.
The presentation forms (u+FB50-u+FDFF) should not be used in text, and should be converted to the standard range (u+0600-u+06FF).
In order to only cover Persian we need the following:

*

*The subset of Farsi characters out of the standard Arabic range, i.e (U+0621-U+0624, U+0626-U+063A, U+0641-U+0642, U+0644-U+0648)

*The standard Arabic diacritics (U+064B-U+0652)

*The 2 additional diacritics (U+0654, U+0670)

*The 4 extra Farsi characters "گ چ پ ژ" (U+067E, U+0686, U+0698, U+06AF)

*U+06A9: Persian Kaf (formally: "Arabic Letter Keheh"; different notation from Arabic Kaf)

*U+06CC: Farsi Yeh (a different notation from the Arabic Yeh)

*U+200C: Zero-Width-Non-Joiner

So, the resulting regexp would be:
^[\u0621-\u0624\u0626-\u063A\u0641-\u0642\u0644-\u0648\u064B-\u0652\u067E\u0686\u0698\u06AF\u06CC\u06A9\u0654\u670\u200c}]+$

See also the exemplar characters for Persian listed here:
http://unicode.org/cldr/trac/browser/trunk/common/main/fa.xml

A: In addition to the accepted answer(https://stackoverflow.com/a/22565376/790811), we should consider Zero-width_non-joiner (or نیم فاصله in persian) characters too.
Unfortunately we have 2 symbols for it. One is standard and the other is not standard but widely used :

*

*\u200C : http://en.wikipedia.org/wiki/Zero-width_non-joiner

*\u200F : Right-to-left mark (http://unicode-table.com/en/#200F)

So the final regix can be :
^[\u0600-\u06FF\uFB8A\u067E\u0686\u06AF\u200C\u200F]+$

If you want to consider "space", you can use this :
^[\u0600-\u06FF\uFB8A\u067E\u0686\u06AF\u200C\u200F ]+$

you can test it JavaScript by this :
/^[\u0600-\u06FF\uFB8A\u067E\u0686\u06AF7\u200C\u200F ]+$/.test('ای‌پسر تو چه می‌دانی؟')

A: TL;DR
Farsi MUST used character sets are as following:

*

*Use ^[آابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهی]+$ for letters or use codepoints regarding your regex flavor (not all engines support \uXXXX notation):
^[\u0622\u0627\u0628\u067E\u062A-\u062C\u0686\u062D-\u0632\u0698\u0633-\u063A\u0641\u0642\u06A9\u06AF\u0644-\u0648\u06CC]+$

*Use ^[۰۱۲۳۴۵۶۷۸۹]+$ for numbers or regarding your regex flavor:
^[\u06F0-\u06F9]+$

*Use [ ٌ ًّ َ ِ ُ ْ ] for vowels or regarding your regex flavor:
[\u202C\u064B\u064C\u064E-\u0652]

or a combination of those together. You may want to add other Arabic letters like Hamza ء to your character set additionally.
Why are [\u0600-\u06FF] and [آ-ی] both wrong?
Although \u0600-\u06FF includes:

*

*گ with codepoint 06AF

*چ with codepoint 0686

*پ with codepoint 067E

*ژ with codepoint 0698
as well, all answers that suggest [\u0600-\u06FF] or [آ-ی] are simply WRONG.

i.e. \u0600-\u06FF contains 209 more characters than you need! and it includes numbers too!

Whole story
This answer exists to fix a common misconception. Codepoints 0600 through 06FF do not denote Persian / Farsi alphabet (neither does [آ-ی]):
[\u0600-\u0605 ؐ-ؚ\u061Cـ ۖ-\u06DD ۟-ۤ ۧ ۨ ۪-ۭ ً-ٕ ٟ ٖ-ٞ ٰ ، ؍ ٫ ٬ ؛ ؞ ؟ ۔ ٭ ٪ ؉ ؊ ؈ ؎ ؏
۞ ۩ ؆ ؇ ؋ ٠۰ ١۱ ٢۲ ٣۳ ٤۴ ٥۵ ٦۶ ٧۷ ٨۸ ٩۹ ءٴ۽ آ أ ٲ ٱ ؤ إ ٳ ئ ا ٵ ٮ ب ٻ پ ڀ
ة-ث ٹ ٺ ټ ٽ ٿ ج ڃ ڄ چ ڿ ڇ ح خ ځ ڂ څ د ذ ڈ-ڐ ۮ ر ز ڑ-ڙ ۯ س ش ښ-ڜ ۺ ص ض ڝ ڞ
ۻ ط ظ ڟ ع غ ڠ ۼ ف ڡ-ڦ ٯ ق ڧ ڨ ك ک-ڴ ػ ؼ ل ڵ-ڸ م۾ ن ں-ڽ ڹ ه ھ ہ-ۃ ۿ ەۀ وۥ ٶ
ۄ-ۇ ٷ ۈ-ۋ ۏ ى يۦ ٸ ی-ێ ې ۑ ؽ-ؿ ؠ ے ۓ \u061D]

255 characters are fallen under Arabic block (0600–06FF), Farsi alphabet has 32 letters that in addition to Farsi demonstration of digits it would be 42. If we add vowels (Arabic vowels originally, that rarely used in Farsi) without Tanvin (ً, ٍِ , ٌ ) and Tashdid (ّ ) that are both a subset of Arabic diacritics not Farsi, we would end up with 46 characters. This means \u0600-\u06FF contains 209 more characters than you need!
۷ with codepoint 06F7 is a Farsi representation of number 7 and ٧ with codepoint 0667 is Arabic representation of the same number. ۶ is Farsi representation of number 6 and ٦ is Arabic representation of the same number. And all reside in 0600 through 06FF codepoints.

The shapes of the Persian digits four (۴), five (۵), and six (۶) are
  different from the shapes used in Arabic and the other numbers have
  different codepoints.

You can see different number of other characters that doesn't exist in Farsi / Persian too and nobody is willing to have them while validating a first name or surname.
[آ-ی] includes 117 characters too which is much more than what someone needs for validation. You can see them all using Unicode CLDR.

A: I'm not sure if regex is the way to do this, however the problem is not specific to only persian or arabic, chinees, russian text. so perhaps you could see if the character is existing in your Codepage, if not in the code page then I doubt the user can insert them using a input device....
 var encoding = Encoding.GetEncoding(1256);
 var expect = "گ چ پ ژ";
 var actual= encoding.GetBytes("گ چ پ ژ");
 Assert.AreEqual(encoding.GetString(actual),expect);

The test tests a round trip where input should match the string to bytes and back. The link shows those code pages supported.

A: just add this code to your TextField or TextFormField
for example:
inputFormatters: [FilteringTextInputFormatter.allow(RegExp("[ آ-ی]"))],

To create an empty space, just enter a space in the RegEx list
♥♥♥خلاصه تمام حروف فارسی رو بدون مشکل میتونی داشته باشی برای فاصله بین حروف هم اسپیس کارو راه میندازه♥♥♥


text:
Q: how to test servlet result JSON string with http GET request? I have a bean that generates JSON string, how can I test run the result -- retrievable through a URL via GET HTTP request by opening it in my browser -- to check whether the url is working correctly is by opening it up in the browser
I have mapped the bean in web.xml
  <servlet>
    <servlet-name>queryreturn</servlet-name>
    <servlet-class>com.queryData.Return.QueryReturn</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>queryreturn</servlet-name>
    <url-pattern>/queryreturn</url-pattern>
  </servlet-mapping>

Here is the bean, how do I test it to see the JSON string?
package com.queryData.Return;
//Import required java libraries
import java.io.*;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
import org.json.JSONObject;
import com.queryData.main.Main;
// Extend HttpServlet class
public class QueryReturn extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    public void init() throws ServletException
      {
          // Do required initialization
      }
      public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
                throws ServletException, IOException
      {
          Main m = new Main();
          List<JSONObject> jObj = m.getJsonObject();
          StringBuilder sb = new StringBuilder();
          for(int i =0 ; i < jObj.size(); i++)
          {
             sb.append(jObj.get(i).toString());
          }
          String responseStr = "{\"data\":[" + sb + "]}";

          // Set response content type
          response.setContentType("application/json");
          // Actual logic goes here.
          PrintWriter out = response.getWriter();
          out.println(responseStr);

      }
      public void destroy()
      {
          // do nothing.
      }
}

A: If you are running tomcat in the default port (8080) you should be able to access the servlet on http://localhost:8080/queryreturn.
A well known application to make HTTP requests is Postman. You can use that to test the servlet response. If you are a linux user you can also use curl.


text:
Q: Axios. How to get error response even when api return 404 error, in try catch finally for e.g.
(async() => {
  let apiRes = null;
  try {
    apiRes = await axios.get('https://silex.edgeprop.my/api/v1/a');
  } catch (err) {
    console.error(err);
  } finally {
    console.log(apiRes);
  }
})();

in finally, apiRes will return null.
Even when the api get a 404 response, there is still useful information in the response that I would like to use.
How can I use the error response in finally when axios throws error.
https://jsfiddle.net/jacobgoh101/fdvnsg6u/1/

A: According to the AXIOS documentation (here: https://github.com/axios/axios) you can pass validateStatus: false in the config object to any axios request.
e.g.
axios.get(url, { validateStatus: false })
axios.post(url, postBody, { validateStatus: false })

You can also pass a function like this: validateStatus: (status) => status === 200
According to the docs the default behaviour is function that returns true if (200 <= status < 300).

A: You can treate the status code:
exemple using Ts:
let conf: AxiosRequestConfig = {};

    conf.validateStatus = (status: number) => {

        return (status >= 200 && status < 300) || status == 404
    }

    let response = await req.get(url, conf);

A: According to the documentation, the full response is available as a response property on the error.
So I'd use that information in the catch block:
(async() => {
  let apiRes = null;
  try {
    apiRes = await axios.get('https://silex.edgeprop.my/api/v1/a');
  } catch (err) {
    console.error("Error response:");
    console.error(err.response.data);    // ***
    console.error(err.response.status);  // ***
    console.error(err.response.headers); // ***
  } finally {
    console.log(apiRes);
  }
})();

Updated Fiddle
But if you want it in finally instead, just save it to a variable you can use there:
(async() => {
  let apiRes = null;
  try {
    apiRes = await axios.get('https://silex.edgeprop.my/api/v1/a');
  } catch (err) {
    apiRes = err.response;
  } finally {
    console.log(apiRes); // Could be success or error
  }
})();


text:
Q: how to find circle circumference point from a point inside the circle given the image bellow how can i find the points of a circles circumference from a point inside the circle with given X and Y ? also can how to calculate it from a point outside the cirlce ?
https://i.stack.imgur.com/0fv9G.png

A: If $(x_0, y_0)$ is the centre of the circle and if $R$ is the ray, then the points of the circle can be represented as $(x_0 + R\,\cos\theta, \,y_0 + R\,\sin\theta)$
The point inside or outside the circle can be represented as $M = (x_0 + \rho \,\cos\phi,\, y_0 + \rho\, \sin\phi)$
Then, the nearest point from $M$ on the circle is:
$$ A = (x_0 + R \,\cos\phi,\, y_0 + R\, \sin\phi)$$
I guess this corresponds to your question ... which was not so clear

A: Three given points are vertices of a triangle $\triangle.$ The center of the circumcircle of $\triangle\;$ is the intersection of line bisectors of the sides of $\triangle.$ To find the center, it suffices to take two of the bisectors.
The  point of the circle that is nearest to a given point lies on the diameter through the center and the given point. It is the red point at the picture.


text:
Q: Building own smart dns-proxy with powerdns and Squid to socks5 I want to build my own small smart dns-proxy server with following features:

*

*Client sets DNS Server like (2.2.2.2 <- MY DNS Server includes Proxy Squid)

*Client sends request for sepcial domains (youtube.com etc.)

*DNS responses: 2.2.2.2 (my proxy server)

*My proxy is now connecting to another-location-proxy: 3.3.3.3:6060 (SOCKSv5)

*My Proxy is getting the content which is requested and sends only this back to the client.

So my goal is to send only this specific request to the SOCKS Proxy.
Is it possible with the software powerdns and squid for example?
Thanks.

A: Okay I just found a shell script on github which fully fulfills its purpose with squid sslbump, sniproxy and dnsmasq installed. (Instead of powerdns).

*

*Cloning https://github.com/suuhm/unblock-proxy.sh

*Setting my wished SOCKS Proxy in the proxies file.

*Running in bash to start the smartdns:

./unblock-proxy.sh dns --squid --debug

This solution works for me


text:
Q: Android encrypt/decrypt sqlite database 100% secure I am a new born baby in android security point of view. What I am trying to do is encrypt/decrypt Sqlite Database.
I have gone through multiple tutorial but nothing seems to work.I have gone through Sql Cipher link but here I code and I am getting issue given below:
Type Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lnet/sqlcipher/AbstractCursor$SelfContentObserver;

Also I don't need password protected file. I have use Cipher default class that Android library provide like below:
Cipher c = Cipher.getInstance("RSA");
            c.init(Cipher.ENCRYPT_MODE, privateKey);

But I doesn't find it secure. I suppose it can be decrypt by hackers. I need proper 100% encryption and decryption security of Sqlite Database.

A: SQL Lite is a lightweight database system.Having said that it also has few hacks possible into the system to make it encrypted OR password protected. Here are few of them which I know :-

*

*SEE:

The SQLite Encryption Extension (SEE) is an add-on to the public domain version of SQLite that allows an application to read and write encrypted database files. Four different encryption algorithms are supported:
RC4
AES-128 in OFB mode
AES-128 in CCM mode
AES-256 in OFB mode

*WxSQLite:

A wxWidgets style c++ wrapper that also implements SQLite's encryption.

3.SQLCipher

SQLCipher has a small footprint and great performance so it's ideal for protecting embedded application databases and is well suited for mobile development.

Personally I recommend as per your needs SQLCipher is the best one to go for.I have tried it.Its highly recommended Open-Source System.


text:
Q: What is an effective field theory (EFT)? Is the standard model (SM) an EFT? Till which scale? How is included gravity? What is an effective field theory (EFT)? and why all the observable interactions until one scale are only a finite number that we know? Is the standard model (SM) an EFT? till what distances? I real "introductions" to EFT, but they are examples, not an explanation what it is

A: In the sense you are asking (there is also a notion of Wilsonian effective theory), an Effective Field Theory is a theory where only "light" degrees of freedom appear, while "heavier" degrees of freedom are modeled by interactions between the light elements. For instance, the Fermi theory of radioactive decay (see here) models with point-like four-fermion the interactions between things like protons neutrons electron neutrinos are resolved in the the standard model by the exchange of a massive W/Z boson between these guys. But if you don't have enough energy to resolve that interaction, it looks point-like, and you don't see that a massive object was exchanged here. So you add an interaction term in your Lagragian to account for this observed decay.
The standard model does not need extra interactions which we cannot explain by particles. People try to add terms of the form of the four-fermion coupling to the Lagrangian of the standard model and see if they fits the tiny deviations of the disintegration patterns at LHC -- so far, no success.
However, the standard model is an EFT from the gravitationnal's perspective, and from grand unification as well. The effect at which the heavier degrees of freedom start to materialize as particle is kind of linked to the mass of those particles.
If you like grand unification, the fact that the magnitude of the three interactions we know seem to unify at high energies is a low energy sign of a high energy symmetry at high energies. We also know that, at the Planck scale the gravitational interaction becomes strong, so there must new degrees of freedom there.  So, at worst, the standard model will need to be supplemented with new degrees of freedom at the Planck scale, because we know that gravity exist.


text:
Q: What is the relationship between the some of the first n natural numbers and the number of unique pairs in n+1 The sum of the first $n$ natural numbers is $\displaystyle\frac{n}{2}(n+1)$
$\displaystyle
{n+1 \choose 2}$ is $\displaystyle\frac{n}{2}(n+1)$
Obviously they are equal, but how should I think about why they are equal.  It seems there must be some logical explanation that I can't figure out.

A: Consider the numbers $1,2,3\dots n,n+1$ on the number line. How many segments have their endpoints on two of these points? Easy, there are $\binom{n+1}{2}$ ways to select the endpoints.
Another way to count it is the following. How many segments have length $1$? Well, if know the endpoint that is at the left we can uniquely determine the segment. Since there are $n$ options for that point (since it can be any number from $1$ to $n$), the answer is $n$.
How many segments have length $2$? The answer is $n-1$ since there are $n-1$ options for the endpoint at the left.
Following this line of thought the number of segments is $n+(n-1)+(n-2)\dots+2+1$
However when we counted it using the other method we got there where $\binom{n}{2}$. Since we counted the same thing we obtain $\binom{n+1}{2}=1+2+3+\dots +n$

A: Consider $\binom {n+1}2$ ways of choosing 2 balls from $n+1$ balls. Order the balls in some way.
If the first ball is chosen, then there are $n$ ways to choose next. If the first ball is not chosen and the second ball is chosen, then there are $n-1$ ways to choose next.
$$\vdots$$
If all the first, second, ..., $(n-1)$th balls are not chosen and the $n$th ball is chosen, then there is 1 way to choose next.
$$\binom{n+1}2 = n+(n-1) + \cdots + 1$$

A: Think about a way to count the number of ways you can choose $2$ from $n+1$.
Take the $n+1$st object. You can pair it with any of the $n$ other objects.
So far that makes $n$ ways to choose two objects.
You could also have a pair that includes the $n$th object.
We have already counted the pair of the $n$ and $n+1$st object, but
we can pair the $n$th object with any of the $n-1$ lower-numbered objects.
We add $n-1$ new pairs this way.
And we can pair the $n-1$st object with any of the next $n-2$ objects
to make $n-2$ new pairs.
As we look at each new object in turn and pair it with lower-numbered objects,
the number of pairs we find adds up like this:
$$n + (n-1) + (n-2) + \cdots + + 2 + 1$$
where the final "$1$" is the pair formed from the $2$nd object and the $1$st,
after which all objects have been paired once with every other object.
And that's the sum of the integers $1$ through $n$.


text:
Q: Got "ValueError: invalid literal for int() with base 10: 'Trancel'" when using two paramenters in detailview in Django I am trying to use two other url tags other then pk and slug in a detail view. I have the following code snippet:

views.py

    class UseCaseDetailView(DetailView):
        template_name = "useCaseExtract/useCaseDetail.html"
        model = UseCaseProfile
        context_object_name = 'usecaseprofile'
        '''I am trying to override the get_object method of DetailView to accept url tags project and usecasename instead of pk and slug'''
        def get_object(self):
            obj = get_object_or_404(UseCaseProfile, project=self.kwargs['project'], useCasename=self.kwargs['useCasename'])
            return obj

urls.py
...

    path('/UseCaseDetail/', UseCaseDetailView.as_view(), name='UseCaseDetail')

...

in my template file, I have the following link:
/Trancel/UseCaseDetail/Nothing

after I clicked the link, I got:
ValueError: invalid literal for int() with base 10:  'Trancel'

can you some please explain to me why I am getting this error?

A: Do you have the ability to rename Trance1 to something like TranceOne? So that it doesn't include an integer?
I think your issue is that 1 when it comes time to parse the URL..( as its expecting a sting, but it gets string w/ a 1 in it).

A: The project url tag is a foreign key in the UseCaseProfile model. In order to query the UseCaseProfile, I modified the get_object code in the detailview as below.
def get_object(self):
        project=Project.objects.all()
        x=project.filter(projectName=self.kwargs['project'])
        obj = get_object_or_404(UseCaseProfile, project=x.first(), useCasename=self.kwargs['useCasename'])
        return obj


text:
Q: How to find the probability distribution of a two-variable metric? I have a certain metric $f(x,y) \in [-1, 1]$. I would like to study the metric assuming $x$ and $y$ are random variables. The input variables are typically normally distributed in most applications of the metric $f$, so I could assume that.
I realize one way to look at this is draw random numbers, and see how the metric behaves. However, it would be really nice to find a closed form solution.
Given the function $f$, is it possible to obtain its probability distribution? I was thinking would something like $\int\int f(x,y)\ \mathrm{d}x\ \mathrm{d}y$ be the solution?
I am not very experienced in mathematics or statistics.

A: Intuitively, you must generate all values of $f(x,y)$, then put them in bins $[f,f+\Delta f]$. This will give you the distribution of $f$. This is very common in finance, it's called value-at-risk, where you have a bunch of factors $x,y,\dots$ which impact your losses $f(x,y,\dots)$. The loss is a single dollar number, while factors are all kinds of things like stock market indices, commodity prices etc.


text:
Q: Using Youtube API to find videos with zero views I have been trying to use the Youtube API to fetch videos with zero views, and I have not had much luck.
It is my current impression that I can fetch videos made in the last day, and then sort them in descending order, but this does not help much.
Has anyone attempted to do this before, and could you point me in the correct direction?


text:
Q: Group by identifier and divide every indicator in the group by the value in the first row Taking the following example:
import pandas as pd
import numpy as np

d = {'Group': [1,1,1,2,2,2], 'P': [100,101,96,200,204,208], 'PL': [99,100,94, 199,203,207]}
df = pd.DataFrame(d)
df

    Group   P   PL
0   1      100  99
1   1      101  100
2   1      96   94
3   2      200  199
4   2      204  203
5   2      208  207

For each group in the 'Group' column, I want to divide every element in the 'PL' column by the first element in the 'P' column. These values would be stored in a new column
The desired output would look like this:
    Group   P    PL   Division
0   1       100  99   0.99
1   1       101  100  1
2   1       96   94   0.94
3   2       200  199  0.995
4   2       204  203  1.015
5   2       208  207  1.035

A: Use GroupBy.transform with GroupBy.first values per groups and divide by Series.div:
df['Division'] = df['PL'].div(df.groupby('Group')['P'].transform('first'))
print (df)
   Group    P   PL  Division
0      1  100   99     0.990
1      1  101  100     1.000
2      1   96   94     0.940
3      2  200  199     0.995
4      2  204  203     1.015
5      2  208  207     1.035

Another idea with map:
s = df.drop_duplicates('Group').set_index('Group')['P']
df['Division'] = df['PL'].div(df['Group'].map(s)


text:
Q: Java Bean not getting loaded I have a xpage which uses a java bean to generate some content on the page. The page gives error "Error 500 HTTP Web Server: Command Not Handled Exception". But error just disappears once I open the database using designer. I do not do any modifications to the database, but just open the database using designer client. I have to open the database every day to fix this problem. Can anybody tell me why this is happening and how can I fix it?

A: "Error 500" is a pretty catch-all error description, and I believe it shows up if you don't tell the app to display the XPages runtime error page (the default with the stack trace) or provide your own. If you do one of those (or look at the server console and error-log-0.xml in the data/domino/workspace/logs folder), you may be able to get a more-specific description of the problem.
But one plausible "crops up every day" type of problem I've run into is the "X is incompatible with X" ClassCastException problem - at some point in the growth of most XPages apps, this starts to crop up (I don't know why other than "using Java") and gets to the point where even changing non-XPage design and potentially data docs triggers it. Fortunately, the fix is easy: assuming you're running 8.5.3 or above, go into the xsp.properties and check the option to "Refresh entire application on design change" (or thereabouts). That should fix it if this is indeed your problem.

A: Looks like it was my designer client. I was using 8.5.3 without any fix packs. I installed FP6 and signed the design again and the problem is fixed.


text:
Q: How to create a function that can't be used as constructor I am trying to create a function in javascript which can't be called as constructor like lets say if function is function SomeFunction(){}, on calling it like new SomeFunction() it should throw an exception but calling it without new should work.
Is there a way to achieve this?

A: Use new.target. This is a special property, which is set when the function is called as constructor. See the following example.

function test() {
  if (new.target) {
    throw new Error('Can not call as constructor');
  }

  return 'test';
}

console.log(test());
console.log(new test());

A: You can also use an es6 arrow => function for this, as they are not allowed as constructor functions.

let SomeFunction = ()=>{ console.log("called");}
SomeFunction();
//Error for arrow function
new SomeFunction();

A: The constructor call creates an instance, so you can check if an instance is not created.

function SomeFunction () {
 if(this instanceof SomeFunction)
  throw('constructor called');
 console.log('function called')
}

SomeFunction();

new SomeFunction()


text:
Q: How to make an inApp "Chat" I'm making an app, the user must have the option to send messages to other users.
Based on this i have the doubt how it works, initially i thought that works with push notifications, but researching about this, it seems that is no the way to do this (or i dont understand a freaking thing).
After that i think "Ok, when the 'chat' controller is open it calls a method every X seconds and look for new messages", but that no make much sense if i see how whatsapp works (I know that is an exaggerated comparison) and i think this will cause a crash or memory problems.
So, i dont know how the app "knows" that there is a new message.
Can anyone please tell me where to start looking?
I'm really lost about this.
Thanks in advance.
Edit:
Ok ok, based on answer, i know a screw it asking this, sorry to all, specially to  moonwave99

A: Doing this well is an enormous project. Adium (a popular Mac chat app) is about 200,000 lines of code not counting the libraries it uses to interact with IM servers.
Depending on how simple you're willing to get, you can do much less than that, but it'll still be a bunch of work. I would suggest starting by looking for XMPP libraries; it's a standardized flexible protocol for this.

A: If you're open to using an external system to manage this, the data behind and the push notifications, take a look at Parse.com. I've used it and it will give you a back end and iOS classes to manage this for you.

A: I have 0 experience on chat programming but I'll still try to answer your question.
You will need a server to manage the messaging between clients.
Then you could follow two routes:

*

*Having the client fetch the server for new messages every X seconds (the easiest option if you ask me)

*Having a socket connection between client and server and have the client listen on that socket for incoming messages forwarded by the server (the best option if you ask me)

Developing the first option is not hard at all but the second one will require quite a little bit of studying effort especially if you are new to networking and stuff like that.
Edit: To develop the first option you could use a library AFNetworking to send an http request to the server and have the server return the incoming messages maybe in the form of JSON or XML data.
Take a look at this for a very good get-started tutorial. http://www.ibm.com/developerworks/library/x-ioschat/


text:
Q: Python - memory efficiency - range I am seeking ways to make the below minimal code for MaxPower() function more memory efficient & examples using my code.
Purpose of MaxPower(): for integers i and N_remainder, to return the maximum value of m such that i^m divides N_remainder.
MaxPower() is only called in the factorise() function if i divides N_remainder
Currently the linked code below has the following results for the number to factorise (wrote in standard form):

*

*1x10^8 - works fine. Two arrays of results produced and are correct

*5x10^8 - hangs Linux & OS is totally unresponsive. Computer needs hard restart.

*1x10^9 - gives memory error in terminal.

Python version used is 2.74 on Linux Mint 17.
I am currently learning python.
def MaxPower(i,N_remainder):
    m=1
    MxP=1
    for n in range (2, N_remainder + 1):
        b = i**n
        a = N_remainder % b
        if a==0:
            m = m+1
        else:
            MxP = m
            break
    return MxP

Revised code since originally posted:
def MaxPower(i,N_remainder):
    m=1
    MxP=1
    for n in xrange (2, N_remainder + 1):
        b = pow(i,n)
        a = N_remainder % b
        if a==0:
            m = m+1
        else:
            MxP = m
            break
    return MxP

I am aware of the following (which I haven't tried since new & out of my depth currently);

*

*Could do more work in compiled C code - converting to "list comprehension"

*Use threading & make sure each thread is deleted after use.

A: The Python 2 range function creates a list with one entry for each number in the given range. This entire list needs to be stored in memory, so for large values of N_remainder it can get pretty big.
Instead, there is the xrange function, which does almost the same thing. This uses constant memory, only storing the parameters and calculating each value only when it's needed and not storing old values once they're used. If you replace the call to range with a call to xrange, your function should use almost-constant memory.
Note that if N_remainder + 1 is too big for a python int, the xrange function won't work, but the documentation provides an alternative.

Not a memory issue, but you don't need the explicit calls to long; Python 2 automatically converts to the long type when necessary.