text:
Q: Running out of memory on Google Colab I'm trying to run a demo of TF Object Detection model with Faster RCNN on Google Colab Pro GPU (RAM: 25GB, Disk: 147GB), but it fails and gives me the following error:
Tensorflow/core/common_runtime/bfc_allocator.cc:456] Allocator (GPU_0_bfc) ran out of memory trying to allocate 7.18GiB (rounded to 7707033600)requested by op MultiLevelMatMulCropAndResize/MultiLevelRoIAlign/AvgPool-0-TransposeNHWCToNCHW-LayoutOptimizer
If the cause is memory fragmentation maybe the environment variable 'TF_GPU_ALLOCATOR=cuda_malloc_async' will improve the situation.

Then it gives me these stats:
I tensorflow/core/common_runtime/bfc_allocator.cc:1058] Sum Total of in-use chunks: 7.46GiB
I tensorflow/core/common_runtime/bfc_allocator.cc:1060] total_region_allocated_bytes_: 15034482688 memory_limit_: 16183459840 available bytes: 1148977152 curr_region_allocation_bytes_: 8589934592
I tensorflow/core/common_runtime/bfc_allocator.cc:1066] Stats:
Limit:                     16183459840
InUse:                      8013051904
MaxInUse:                   8081602560
NumAllocs:                        6801
MaxAllocSize:               7707033600
Reserved:                            0
PeakReserved:                        0
LargestFreeBlock:                    0

And
tensorflow.python.framework.errors_impl.ResourceExhaustedError:  OOM when allocating tensor with shape[2400,1024,28,28] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
     [[{{node MultiLevelMatMulCropAndResize/MultiLevelRoIAlign/AvgPool-0-TransposeNHWCToNCHW-LayoutOptimizer}}]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.
 [Op:__inference__dummy_computation_fn_32982]

I don't really understand why it runs out of memory allocating only 7GB on a 25GB system? How can I fix it? Here is my config file for this task:
# Faster R-CNN with Resnet-50 (v1)
# Trained on COCO, initialized from Imagenet classification checkpoint

# Achieves -- mAP on COCO14 minival dataset.

# This config is TPU compatible.

model {
  faster_rcnn {
    num_classes: 7
    image_resizer {
      keep_aspect_ratio_resizer {
        min_dimension: 640
        max_dimension: 640
        pad_to_max_dimension: true
      }
    }
    feature_extractor {
      type: 'faster_rcnn_resnet50_keras'
      batch_norm_trainable: true
    }
    first_stage_anchor_generator {
      grid_anchor_generator {
        scales: [0.25, 0.5, 1.0, 2.0]
        aspect_ratios: [0.5, 1.0, 2.0]
        height_stride: 16
        width_stride: 16
      }
    }
    first_stage_box_predictor_conv_hyperparams {
      op: CONV
      regularizer {
        l2_regularizer {
          weight: 0.0
        }
      }
      initializer {
        truncated_normal_initializer {
          stddev: 0.01
        }
      }
    }
    first_stage_nms_score_threshold: 0.0
    first_stage_nms_iou_threshold: 0.7
    first_stage_max_proposals: 300
    first_stage_localization_loss_weight: 2.0
    first_stage_objectness_loss_weight: 1.0
    initial_crop_size: 14
    maxpool_kernel_size: 2
    maxpool_stride: 2
    second_stage_box_predictor {
      mask_rcnn_box_predictor {
        use_dropout: false
        dropout_keep_probability: 1.0
        fc_hyperparams {
          op: FC
          regularizer {
            l2_regularizer {
              weight: 0.0
            }
          }
          initializer {
            variance_scaling_initializer {
              factor: 1.0
              uniform: true
              mode: FAN_AVG
            }
          }
        }
        share_box_across_classes: true
      }
    }
    second_stage_post_processing {
      batch_non_max_suppression {
        score_threshold: 0.0
        iou_threshold: 0.6
        max_detections_per_class: 100
        max_total_detections: 300
      }
      score_converter: SOFTMAX
    }
    second_stage_localization_loss_weight: 2.0
    second_stage_classification_loss_weight: 1.0
    use_static_shapes: true
    use_matmul_crop_and_resize: true
    clip_anchors_to_image: true
    use_static_balanced_label_sampler: true
    use_matmul_gather_in_matcher: true
  }
}

train_config: {
  batch_size: 8
  sync_replicas: true
  startup_delay_steps: 0
  replicas_to_aggregate: 8
  num_steps: 25000
  optimizer {
    momentum_optimizer: {
      learning_rate: {
        cosine_decay_learning_rate {
          learning_rate_base: .04
          total_steps: 25000
          warmup_learning_rate: .013333
          warmup_steps: 2000
        }
      }
      momentum_optimizer_value: 0.9
    }
    use_moving_average: false
  }
  fine_tune_checkpoint_version: V2
  fine_tune_checkpoint: "faster_rcnn_resnet50_v1_640x640_coco17_tpu-8/checkpoint/ckpt-0"
  fine_tune_checkpoint_type: "detection"
  data_augmentation_options {
    random_horizontal_flip {
    }
  }

  max_number_of_boxes: 100
  unpad_groundtruth_tensors: false
  use_bfloat16: true  # works only on TPUs
}

train_input_reader: {
  label_map_path: "label_map.pbtxt"
  tf_record_input_reader {
    input_path: "train.record"
  }
}

eval_config: {
  metrics_set: "coco_detection_metrics"
  use_moving_averages: false
  batch_size: 1;
}

eval_input_reader: {
  label_map_path: "label_map.pbtxt"
  shuffle: false
  num_epochs: 1
  tf_record_input_reader {
    input_path: "test.record"
  }
}

A: I also ran into the same problem. It took me a week to figure it out. I am using colab pro+. tesla p100 GPU(16GB) was allocated to me. My image dim is (256,256,4)
and the batch size is 32. The thing is when we design a architecture we don't think about the size of params until we ran into problems like RESOURCE EXHAUST ERROR. Then we make some changes, trying to minimize the params. But there is also another factor that takes up the memory. That is in my case I use four separate variables to hold the tensors.
 block_0=layers.Conv2D(filters=32, kernel_size=(1,1),strides=(1, 1), activation="LeakyReLU",padding='same',name='block_5_layer_1'))(x)
 block_1=tfa.layers.SpectralNormalization(layers.Conv2D(filters=64, kernel_size=(3,3),strides=(1,1), activation="LeakyReLU",padding='same',name='block_5_layer_2'))(x)
 block_1=tfa.layers.SpectralNormaliza``tion(layers.Conv2D(filters=64, kernel_size=(5,5),strides=(1, 1),padding='same',name='block_5_layer_3'))(block_1)
 # block_1=layers.BatchNormalization()(block_1)
 block_1=layers.Activation('LeakyReLU')(block_1)
 block_1=layers.Dropout(0.7)(block_1)

 block_2=tfa.layers.SpectralNormalization(layers.Conv2D(filters=32, kernel_size=(1,1),strides=(1, 1), activation="LeakyReLU",padding='same',name='block_5_layer_4'))(x)
 block_2=tfa.layers.SpectralNormalization(layers.Conv2D(filters=96, kernel_size=(3,3),strides=(1, 1), activation="LeakyReLU",padding='same',name='block_5_layer_5'))(block_2)
 block_2=layers.Dropout(0.7)(block_2)

 block_3=layers.MaxPool2D(pool_size=(3,3),strides=(1,1 ),padding='same',name='block_5_maxpool_1') (x)
 block_3=tfa.layers.SpectralNormalization(layers.Conv2D(filters=64, kernel_size=(3,3),strides=(1, 1), activation="LeakyReLU",padding='same',name='block_5_layer_6'))(block_3)

 x = layers.concatenate(
  [block_0, block_1, block_2, block_3],
  axis=3,
  name='block_5')

For me RESOURCE EXHAUST ERROR occurred at the very first layer.
The resulted shape is (32,256,256,352) which is huge and I suppose those tensors are stored in the GPU itself. So this takes up lots of space and that is why TensorFlow can't allocate memory to the layers. And when I reduced its dims it worked. So I think we should also consider the shape of the variables holding the convoluted images along with the param size. Correct me if I am wrong.

A: I realized it's the problem with the images taking up too much memory in a sample size, as per https://github.com/tensorflow/models/issues/1817, so I went and changed my batch size to 2 and it worked


text:
Q: WebClient random behavior I have very simple code that download files from a web server and here is the code. As i said it is very basic
// use the web client to download
using (var client = new WebClient())
{
    // download locally
    client.DownloadFile(from, to);
}

But for some client the file does not download completely and does not throw exception. All these client come from different location and all have the same behavior that the WebClient download exactly 10 mb of ANY file above 10mb. A 8mb file is 8mb, a 20mb file is 10mb a 34 mb file is 10mb. The funny thing is we ask those user to stop using the software.
This issue is not related to the computer as we have alot of those user on laptop that the download works fine from home and it doesn't when they are at work and some it's totally reverse, the download doesn't work at work but it does at work. The behavior is also different for client within the same physical office.
We have tried to talk to their IT and they have no problem going on our http browsable directory and downloading many files over 10mb and it works perfectly and they state they never had such issue. The issue seems to spread more and more and since last windows 10 update much more client started to have this issue.
As a side note this download code has been unchanged and running for 5 years with nearly no issues.
Does anyone know why download would complete without any error (in try..catch) without having downloaded the whole file ? and Why would all these different client with the issue would be cut at EXACTLY 10,000 bytes.
Wanted to add that we tried to reinstall .NET Framework for these user in the past without any result thinking it must be an issue with that
I just edited to add this little extra details that the files they are trying to download are on an anonymous access folder so no login required and it is browsable. All user with the issue can use Chrome and Edge to navigate to the folder and right-click and download and the file is complete that way. Only .NET cannot download files above 10mb on their PC.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Square root of 1 I know this is a dumb question but I can't get the answer to another follow up question,

*

*What is the square root of 1?

*If the square root of 1 is itself then why does other square root of number not equal to themselves?

*Is there other square root of 1 aside from 1?

This question is somewhat a deconstruction of the fundamental logic of mathematical concepts but I can't find a good reason to answer this questions. Hoping for a good reason.
[Edit] if we're going to talk about principal square roots then therefore -1 would be included but i'm only referring to non negative numbers therefore
3.1. if there are other square root of 1 which could be between 0 and 1?

A: *

*The square root of $1$ is $1$.

*This is because the number $1$ has the special property $1\cdot 1=1$. This is not true for $2$, for instance: $2\cdot 2$ is not $2$.

*Yes, there is another number $x$ with $x^2=1$, namely $x=-1$. Usually, this solution is not called a square root of $1$, however, because you want "square root" to be a function, so that its value has to be unique.
Edit: To see that there are no further solution to $x^2=1$, notice that $x^2=1$ implies $(x+1)(x-1)=0$ and thus $x=\pm 1$.

A: In a field such as $\,\mathbb Q,\ \mathbb R,\ \mathbb C,\,$ we have $ \ x^2 = 1 \iff (x-1) (x+1) = 0\iff x = \pm 1.\, $ In rings that are not fields there can be more than two square-roots, e.g. modulo $15$ there are two additional roots $ \ (\pm\,4)^2\equiv 1\pmod{\!15}.\,$ In some contexts authors define single-valued square-root functions that uniformly select one of the roots, e.g. the non-negative root, or principal branch, etc.
In ring theory we can adjoin a "sign" = generic square root of one $\,s = \pm1\,$ to a ring $ \,R\,$ as follows $ R[s]\cong R[x]/(x^2\!-\!1).\,$ If $\,2\,$ is invertible, CRT $\Rightarrow R[s] \cong R[x]/(x\!-\!1) \times R[x]/(x\!+\!1)\ \cong R^2,\, $ via $\, f(x)\to (f(1),f(-1));\,$ informally, this ring product implements arithmetic in two parallel universes (rings), where in the first world we have $\,s = 1\,$ , and $\, s = -1\,$ in the second.
As to your second question concerning why there aren't other numbers that are their own square root, note that $ \ \sqrt{x} = x\ \Rightarrow x = x^2\ \Rightarrow\ x\ (x-1) = 0\ $ so $ \,x = 0\,$ or $ \,x = 1\,$ in a field (or domain). Elements satisfying $ \ x^2 = x\ $ are known as idempotents. Idempotents that are nontrivial ($\ne\, 0,1$) are intimately connected with nontrivial factorizations. In the above example $\,\mathbb Z/15 =$ integers $\!\bmod 15,\,$ we have a factorization $ \mathbb Z/15 \cong \mathbb Z/3 \times \mathbb Z/5\,$ arising from idempotent $\,6,\,$ i.e. $ (0,1)\in \mathbb Z/3 \times \mathbb Z/5.\,$ Note that if $ \,e\,$ is idempotent then $ \,(1\!-\!2\,e)^2 = 4\,(e^2\!-\!e)+1 = 1,\, $ so $ \,2e\!-\!1\,$ is a square-root of $1;\,$ it is a nontrivial square root $ \,2e\!-\!1\ne \pm 1\,$ if $\,2\,$ is cancellable. In our example $ \,e=6,\,$ so $ \,1\!-\!2e \equiv 4\,$ which does indeed square to $ \,1\pmod{\!15}.\,$ We can quickly factor $15$ from this nontrivial sqrt $ \,s,\,$ namely $ \,\gcd(15,s-1) = \gcd(15,3) = 3\,;$ $ \ \gcd(15,s+1) = \gcd(15,5) = 5.\,$ In fact many integer factorization algorithms work by searching for nontrivial square-roots. This way of factoring by simple gcd computations works more generally. One can quickly factor $ \,n\,$ given any polynomial with more roots $\!\bmod n\,$ than the degree of the polynomial - see my post here.

A: *

*The square root of $1$ is $\pm1$.

*$1$ is the only number which when multiplied by itself equals $1$.

*$-1$ multiplied by itself equals $1$.


text:
Q: Javascript src property doesn't work It's a very simple one. The source of the webpage is

It works

This is the default web page for this server.

The web server software is running but no content has been added, yet.

I put the js at the very beginning.
in jscript.js, it's:

But it doesn't show the text. If I embed the js into html, it works.
And it's strange that when I directly access jscript.js from a webbrowser, the content is like:

Can anybody help?

A: You don't need the  in your javascript file. In fact, that's what is breaking everything. Remove them and it should work properly.

A: You shouldn't include tags in the JavaScript file.
Even if you remove them, your text will be written too early in the page, so I'm not certain that it will show up properly. Currently you're writing the text before the .
I'm not certain your

It works

This is the default web page for this server.

The web server software is running but no content has been added, yet.


text:
Q: DC/DC buck/bost mudules vs LM317 comparing for Bench power supply circuit I Have this two circuit, one of them based of lm317 like this:

and have some Circuit based of XL4005 or XL4015 IC like this:
Input: main using a 18V 2A transformer
Output: 0-18V
Current: 0-1.5A
Current Limiting controlled by a potentiometer
Voltage output controlled by a potentiometer

But i want the same output/input parameters for both of them like this :

Input: main using a 24V 5A transformer or AC/DC power supply  (almost 75W)
Output: 0-18V Current: 0-1.5A
Current Limiting controlled by a potentiometer
Voltage output controlled by a potentiometer

In this post said about advantage of dc/dc boost/buck modules :

We used linear regulators like LM317, LM2940 etc. As I said before
      these are so inefficient and can't be used for a battery powered
      setup. So what you can do is, find one of those cheap DC-DC buck
      modules from any online shops and replace the linear regulators with
      them. They're more efficient (>90%), has better load regulation,
      more current capability, current limiting, short circuit protection
      and all. LM2596 is one of that kind. The buck (step down) modules
      will have a precision potentiometer on top. You can replace it with
      a "multi-turn potentiometer" and use it at the front panel instead
      of normal linear pots. That'll give you more control over the output
      voltage.

One of the important thing is having max current for 0- max voltage without considerable decrease,but i have seen this current voltage output chart for XL4005 or XL4015 base:

but don't know that chart for LM317 based!
So i like to know your suggestion about which one of this two schematic or system or better for bench power supply?
And can solve the current drop based of boot/buck converter modules (like XL4005) for this purpose?
Thanks.

A: To answer you main question about LM317 performance.
The current vs voltage output chart for LM317 is much worse than for the switching module.  You're limited to less-than or equal the input current at all voltages,  and are limited to less if it starts to overheat because the heatsink is too small. (so the slope may actually be backwards compared to what you posted.  and all the numbers are worse)
some comments on your drawing.
You have drawn a "boost converter" where you probably want a buck converter
If the current is less than 10A you can use a voltmeter-ammeter module that has an integrated shunt.
you may have to place the shunt in the negative side of the output
If you connect the ground end of the voltage setting potentiometer to a small voltage instead of to ground you will be able to adjust the voltage down to zero. (eg use a resistive divider off the 12V supply to make 1.5V )

A: A power supply project like that is a great learning experience. Go for it!
You won't get 24V input, 2V output @ 1.5A from the LM317. That's 22V x 1.5A = 33W. The Rja of an LM317 on a heatsink will be far too high. You'll have to derate the current at lower output voltages or parallel up some LM317s or use external pass devices (a la some 2N3055's). You can search the internet and find many examples of such things.
If you did solve the thermal problem then you'll have the benefit of a very low broadband noise supply and a supply with nearly zero output voltage ripple. This is what most of the good bench supplies are doing and why they have big, heavy heat sinks on the back.
A switcher is going to be pretty easy - just buy a module, hook it up and use it. A super low cost module may not have the best load transient response, it may be quite noisy (output voltage ripple) under some conditions. It may even behave very poorly under some conditions. But unless you are doing work that is very sensitive to noise then that's fine. If you do run into noise sensitivity issues then you can add a linear regulator to that circuit to clean things up.
In either case, you can probably only get to ~1.2V or so, not 0V, without some additional circuit tricks because these devices have internal references of that voltage, usually.
As mentioned earlier, you want a buck converter instead of a boost converter. It would be a great learning experience to build both, test them and gain some insight and appreciation!


text:
Q: Excel Insert Hyperlink does not put full path I have an Excel spreadsheet located in a folder on a network drive.  I want to include hyperlinks to images.  These are in a sub-folder.  If I insert the hyperlinks in the spreadsheet cell, these are added with relative path.  Because of this if I email the sheet the hyperlinks are broken for the reader.
On the other hand if I copy the file somewhere else and insert hyperlinks as they were before in that original sub-folder, these hyperlinks are added with absolute path.  They work in the email.
How can I tell Excel to always put the absolute path for hyperlinks?
Here is an image of what the Insert Hyperlink dialog looks like when the link works in email.  Note how Excel puts the full path.

Here is an image of the dialog when the hyperlink is broken when accessed in an email message.

The file is the same but in the first image I copied the file to a folder on the computer before inserting the link.  In the first image the file is on the same network drive as the file that I link to.
It looks like Excel only puts the full path if the inserted link is on another drive or directory structure.
I haven't tried the Hyperlink function.  But since someone will be using the sheet, I want to stick to the Insert Hyperlink feature if possible.

A: Rather than insert a hyperlink using that method,
You can use the formula =HYPERLINK
This will keep in place the absolute file path for you.
Find the file location through browser and copy it.

Then use it within the formula:
=HYPERLINK("\\uk.finning.com\data\Group\Heavy Construction\New Sales\ORDER FULFILMENT TEAM\Deal Sheet\filename.xls")

Don't forget to add the document name and file extension also.

A: Well you could argue that Excel was actually more wrong in the firs case since it added mapped drive name instead of the full net path (which will make it totally undiscoverable from another box unless it has the exact same mapping), while the relative path will be discoverable if both files are copied.
You could go and read up this: https://support.microsoft.com/en-us/help/328440/description-of-link-management-and-storage-in-excel
but in general, if you want full control, you'll have to paste full UNC paths manually and make sure that document is read-only if Excel tries to get "too smart".


text:
Q: Can you make an app display a local notification while it's open? I've set up notifications with UNUserNotificationCenter but they're only displayed when the app isn't running. There's some older threads asking the same question but the answers to those aren't working for me so I'm wondering if there's an updated way to do it.

A: The below code triggers local notification when app is in foreground and background.
import UIKit
import UserNotifications

class ViewController: UIViewController, UNUserNotificationCenterDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        //requesting for authorization
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
                if error == nil {
                    self.triggerLocalNotification()
            }
        })
    }

    func triggerLocalNotification(){

        //creating the notification content
        let content = UNMutableNotificationContent()

        //adding title, subtitle, body and badge
        content.title = "Notification title "
        content.subtitle = "Notification sub-title "
        content.body = "We are learning about iOS Local Notification"
        content.badge = 1

        //it will be called after 5 seconds
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

        //getting the notification request
        let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)

        UNUserNotificationCenter.current().delegate = self

        //adding the notification to notification center
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        //displaying the ios local notification when app is in foreground
        completionHandler([.alert, .badge, .sound])
    }
}


text:
Q: Getting a total copied set of rows in VBA and storing it in a variable I asked this question a bit ago, but asked it incorrectly, and wasn't able to receive the best answer.
I have a fairly simple syntax question:
I'm trying to copy and paste n rows from one excel file to another. In addition, I'd like to store the total FILTERED copied rows into a variable. Can someone help me accomplish this?
For example:
'1) Activate CSV file, Apply Filter to Column B (Page Title) & uncheck "blanks" ("<>") filter
Windows("Test_Origin.xlsm").Activate
ActiveSheet.Range("$A$1:$J$206").AutoFilter Field:=2, Criteria1:="<>"
'2) Copy Filtered Lines with data (Excluding Row 1)
Range("B2:F189").Select
Selection.Copy
copiedRowTotal = Selection.Rows.Count <-- This doesn't give me the FILTERED rows
Thanks

A: dim i as long
i = Application.WorksheetFunction.Subtotal(2,worksheets("Sheet").Range("B2:F189"))

Gave you the description here
Getting a total copied set of rows in VBA and storing it in a variable

A: Try:
copiedRowTotal  = Range("B2:B189").SpecialCells(xlCellTypeVisible).Count


text:
Q: How to disable ASLR on Linux so the initial value of the stack pointer is the same every time? I've been writing Heap-based buffer overflow exploits for a deliberately vulnerable (that I wrote).
To hijack control flow, I overwrite the function's return address on stack.
These exploits depend on the stack being at a particular (hardcoded) location.
I assumed this OK because I disabled ASLR (I'm running Ubuntu 14.04, x86_64):
I disabled ASLR by adding kernel.randomize_va_space = 0 to my /etc/sysctl.conf and rebooting the machine.
I've confirmed ASLR has been disabled through the following command:
$ cat /proc/sys/kernel/randomize_va_space
0

But the address of the stack when main begins clearly changes.
To test this, I loaded the program in gdb and broke on the first asm instruction and did the following:
(gdb) p $rsp
$1 = (void *) 0x7fffffffe538

Then I rebooted and I did the same
(gdb) p $rsp
$1 = (void *) 0x7fffffffe558

Is this behavior expected?
Can I disable it so that a particular binary will always have the same stack address?
If not do real exploits need to leak the stack's address to do this? Is there a common technique for this?


text:
Q: Logfile processing: shorten long hex strings I have a logfile which is hard to read because of long hex strings (hashes, signatures) and am looking for a way to replace those strings with a shortened version.
Example:
$ cat sample_line
2018-04-17 13:08:03  IO Worker #2 TRACE engine  Handling a valid ConsensusMessage { vote_step: VoteStep { height: 1, view: 1, step: Precommit }, block_hash: Some(c70cd816cd441fda978f6302739892c0877349901c71f1bc9e637159b47989a7), signature: dfc14c535a9cddd861d640310a9d94252aa7d67c330a218312705d26c0d8b8d1670976566754033798d08b6c484470af18e985420f9048c782cd61ea212d416500 }

I tried with sed and managed to shorten the signature:
$ cat sample_line | sed 's/signature: \(.\{6\}\)\w* \(.*\)/signature: \1…\2/'
2018-04-17 13:08:03  IO Worker #2 TRACE engine  Handling a valid ConsensusMessage { vote_step: VoteStep { height: 1, view: 1, step: Precommit }, block_hash: Some(c70cd816cd441fda978f6302739892c0877349901c71f1bc9e637159b47989a7), signature: dfc14c…}

However this isn't a very satisfying solution as it's not very generic.
What I want:
A command which replaces any hex string with a min. length of say 32 chars with its leading 6 chars plus an ellipsis. For the given example:
2018-04-17 13:08:03  IO Worker #2 TRACE engine  Handling a valid ConsensusMessage { vote_step: VoteStep { height: 1, view: 1, step: Precommit }, block_hash: Some(c70cd8…), signature: dfc14c… }

It would even suffice to shorten any string with a min. length (as there's no other long strings in that log anyway).
I suspect that other tools (awk) are better suited for the task.

A: You can use sed. Just get the 1st initial 6 hex characters into a capturing group and ignore the rest hexadecimal characters.
$ cat sample_line
2018-04-17 13:08:03  IO Worker #2 TRACE engine  Handling a valid ConsensusMessage { vote_step: VoteStep { height: 1, view: 1, step: Precommit }, block_hash: Some(c70cd816cd441fda978f6302739892c0877349901c71f1bc9e637159b47989a7), signature: dfc14c535a9cddd861d640310a9d94252aa7d67c330a218312705d26c0d8b8d1670976566754033798d08b6c484470af18e985420f9048c782cd61ea212d416500 }
$ sed -r 's/([a-f0-9]{6})[a-f0-9]+/\1.../g' sample_line
2018-04-17 13:08:03  IO Worker #2 TRACE engine  Handling a valid ConsensusMessage { vote_step: VoteStep { height: 1, view: 1, step: Precommit }, block_hash: Some(c70cd8...), signature: dfc14c... }


text:
Q: Worklight LDAP Error When trying the LDAP sample project provided by Worklight, I get the following error:

[ERROR   ] FWLSE0020E: Ajax request exception: Adapter 'DummyAdapter'
  does not exist [project module_23_2_LDAPLoginModule] [ERROR   ]
  FWLSE0117E: Error code: 1, error description: INTERNAL_ERROR, error
  message: FWLSE0069E: An internal error occurred during gadget request
  [project module_23_2_LDAPLoginModule]Adapter 'DummyAdapter' does not
  exist, User Identity {SubscribeServlet=null, LDAPRealm=null,
  wl_authenticityRealm=null, wl_remoteDisableRealm=null,
  wl_antiXSRFRealm=(name:rtm5uf72muh56gak3ms4gvvt42,
  loginModule:WLAntiXSRFLoginModule),
  wl_deviceAutoProvisioningRealm=null,
  wl_deviceNoProvisioningRealm=null,
  myserver=(name:776c1909-3ae4-45b5-a029-f0372b507a7d,
  loginModule:WeakDummy),
  wl_anonymousUserRealm=(name:776c1909-3ae4-45b5-a029-f0372b507a7d,
  loginModule:WeakDummy)}. [project module_23_2_LDAPLoginModule]
com.worklight.common.log.filters.ErrorFilter

In order to make it work, what values do I need to change. I want to use my IBM LDAP server.
Thanks..Johnson

A: At least by reading the error message, it is pretty clear.
Did you make sure to also deploy the adapter and not just the application?
In your Worklight project, find the adapters folder. Open it. Then, right-click on the adapter folder within and select Run As > Deploy Worklight adapter.
Try the application again and see if it works, or if there are other errors displayed.
I suggest that instead of jumping right into what you want to do in your app, first learn the basics. Review the IBM Worklight Getting Started training modules, from the top.


text:
Q: Check if client is connected to Workflow Service I'd like to write a selfhosted .NET Workflow Service like this:

(http://i.stack.imgur.com/Hij20.png)
But how can I determine if the client is still alive? The InactivityTimeout of the WCF binding doesn't seems to trigger. I could write a Timeout function(measure the time between the last request an now). But this doesn't ensure that the client is disconnected and not only idle. Isn't there a common way in the .NET Framework?
Thank You.

A: you run this service from somewhere and you have to run a server to get back response from the service. you can make a callback server by using this code:
 var host = new ServiceHost(serviceCallback, new Uri("localhost:8080"));

and then in the service you need to send information back to this address. so you can track the current status of your service dynamically in the caller client.


text:
Q: Spring Boot with AngularJS I have a Spring Boot project using Jersey as my REST service and using AngularJS for my front end development. While I run it without using any controller and go to index.html (which is in resource/static/index.html) it works fine. When I add a controller it renders gives the string "index.html" as an output. Spring Boot Configuration:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

 @SpringBootApplication
 @ComponentScan(basePackages = {"com.cst.interfaces","com.cst.configuration","com.cst.application","com.cst.application.implmentation"})
 @EnableAutoConfiguration
 public class ApplicationConfiguration {
    public static void main(String args[]) throws Exception{
        SpringApplication.run(ApplicationConfiguration.class, args);
    }
    public ServletRegistrationBean jerseyServlet(){
        ServletRegistrationBean register = new ServletRegistrationBean(new ServletContainer(),"/*");
        register.addInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS, JerseyInitalize.class.getName());
        return register;
    }
}

JerseyConfiguration:
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;
@Component
public class JerseyInitalize extends ResourceConfig{
    public JerseyInitalize(){
        super();
        this.packages("com.cst.interfaces");
    }
}

Controller Class:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Path("/home")
public class HomeResource {
    @GET
    @Produces("application/json")
    public String getString(){
        return "index.html";
    }
}

A: This is because you annotated your controller with @RestController, which is a shorthand for @Controller with @ResponseBody. The latter annotation instructs the controller to render the output as-is directly into the response.
Use @Controller for controllers that are not RESTful instead.


text:
Q: Change asp.net form view to insert mode from another page I have 2 ASP.NET pages written in ASP.NET Web Froms .
    On Page 1 I have the Main Grid View Control .
On Page 2 I have details listed within a From View control.
I have a button on Page 1 . On clicking the button . I would like to change the
    From View Mode to Insert. Is there a way I can do it ?
I have my code below :
Page 1 : ASPX page : Button & Grid View
<asp:Panel ID="pnl" runat="server">

                    <asp:Button ID="btnNewIssue" Text="Create New Issue" runat="server" OnClick="btnNewIssue_Click" />

</asp:Panel>
 <asp:Panel>
    <asp:GridView ID="gvTasks" runat ="server">
Grid View Code--------------------------------
</asp:GridView>
</asp:Panel>

Page 2 : ASPX.CS page :
 protected void btnNewIssue_Click(object sender, EventArgs e)
        {
            int index = 0;

            What should go here ????

        }

 protected void gvTasks_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Details")
            {
                int index = Convert.ToInt32(e.CommandArgument);

                StringBuilder sb = new StringBuilder();
                sb.Append("~/Details.aspx?TaskID=");
                sb.Append(index);

                Response.Redirect(sb.ToString());

                //Response.Redirect("~/Details.aspx?TaskID=1234");

            }

    }

Page 2 : aspx Form View
<asp:FormView ID="FormView1" runat="server">
<ItemTemplate>
---Item Template Code....
</ItemTemplate>
<EditItemTemplate>
--- Edit Item Template Code....
</EditItemTemplate>
<InsertItemTemplate>
--- Insert Item Template Code....
</InsertItemTemplate>
</asp:FormView>

page 2 : aspx.cs
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                FillFormView();
            }
        }

   private void FillFormView()
        {
           int taskid = int.Parse(Request.QueryString["TaskID"]);

            ----- Fetch dlist from Service based on taskid-----
            FormView1.DataSource = dlist;
            FormView1.DataBind();
}

protected void FormView1_ModeChanging(Object sender, FormViewModeEventArgs e)
        {

            if (e.NewMode == FormViewMode.Edit)
            {
                Label lblTaskId = ((Label)FormView1.FindControl("lblTaskID"));
                Label lblTaskTitle = ((Label)FormView1.FindControl("lblTaskTitle"));
                FormView1.ChangeMode(e.NewMode);
                FillFormView();
            }
            else
            {
                FormView1.ChangeMode(e.NewMode);
                FillFormView();
            }

        }

A: Change your FillFormView function
private void FillFormView()
    {

       var taskId = Request.QueryString["TaskID"];

       if (taskId == null){
           FormView1.ChangeMode(FormViewMode.Insert);
           return;
       }

       FormView1.ChangeMode(FormViewMode.Edit);
       /// dlist from Service based on taskid-----
       FormView1.DataSource = dlist;
        FormView1.DataBind();
}

there is no ned for FormView1_ModeChanging function.
One more thing, use string.Format instead of StringBuilder class
protected void gvTasks_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Details")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            Response.Redirect(string.Format("~/Details.aspx?TaskID={0}", index));
            //Response.Redirect("~/Details.aspx?TaskID=1234");

        }

}

A: protected void btnNewIssue_Click(object sender, EventArgs e)
{
     Response.Redirect("~/Details.aspx");
}

or You can use an anchor tag instead of button.
Create New Issue

in your FillForView or You can also use #Cruiser-KID Answer
private void FillFormView()
{
   if (string.IsNullOrEmpty(Request.QueryString["TaskID"])){
       FormView1.ChangeMode(FormViewMode.Insert);
   }
   else
   {
       int taskid = int.Parse(Request.QueryString["TaskID"]);
       FormView1.ChangeMode(FormViewMode.Edit);
       ----- Fetch dlist from Service based on taskid-----
       FormView1.DataSource = dlist;
       FormView1.DataBind();
   }
}


text:
Q: How do user user id relate between local user store and oauth providers? My context
I'm trying to create a custom User/Role storage for ASP.NET Identity
Background
There are several questions here at SO about getting the user id when using ASP.NET Identity. Most of them resolve around parsing the NameIdentifier claim.
However, most of them seem to miss an import point. When using OAuth the NameIdentifier seem to point at the identity that the OAuth provider returned.
This can be observed by setting a break point in the AccountController just after the authentication finished.
My problem
If you look at the UserStore you can see that GetUserIdAsync will return the Id of the IdentityUser object which is your internal id from the database. All good so far.
However, if you look at the UserManager it got the following code:
/// <summary>
/// Returns the User ID claim value if present otherwise returns null.
/// </summary>
/// <param name="principal">The <see cref="T:System.Security.Claims.ClaimsPrincipal" /> instance.</param>
/// <returns>The User ID claim value, or null if the claim is not present.</returns>
/// <remarks>The User ID claim is identified by <see cref="F:System.Security.Claims.ClaimTypes.NameIdentifier" />.</remarks>
public virtual string GetUserId(ClaimsPrincipal principal)
{
  if (principal == null)
    throw new ArgumentNullException("principal");
  return principal.FindFirstValue(this.Options.ClaimsIdentity.UserIdClaimType);
}

.. which looks just fine on the first peak. But if you look at the constant value for UserIdClaimType it's the same as ClaimTypes.NameIdentifier. Thus it will fetch the oauth user id.
Code that wont work due to the above problem:
//this returns the oauth id, can't be used to work with the application user
var id = await _userManager.GetUserIdAsync(currentClaimPrincipal);

//this returns null as it internally uses the above line
await user = _userManager.GetUserAsync(currentClaimPrincipal);

The code above will invoke UserStore.FindByIdAsync with the oath user id as user id. the user storage will therefore try to find the application user by using the incorrect key.
A hack would be to use the oAuth userId as the PK in the local user table, but that can break if two oauth providers return the same id (not unlikely). It also wont work when multiple oauth identifies are associated with the same application user.
My question
Am I doing something wrong? How do user ids relate between the application user store and oauth providers?

A: You shouldn't be calling GetUserId with the claims principal from an OAuth provider.  The only ClaimsPrincipal that should be used with that is one generated via the ClaimsPrincipalUserFactory that identity uses.  Associating OAuth with the local user is usually done via the AddLogin method which links the OAuth id to the local user id.


text:
Q: About Android Mobile Application Realtime Architecture? In terms of Android mobile development's extends Application, would it be possible to create a Websocket listener (Socket.IO, etc) in the application for notification, while also creating a flag in the extends Application class, while ALSO having the class or fragment of some sorts that displays the actual data to have a while loop of the flag from the extends Application class to lets say refresh the data display?  Or is extends Application static in a way and the live time updates cannot work?

A: From what I know, yes. Yes it is possible to utilise the Application class to listen for external events. Application instance lives alongside your app. So in theory it is feasible to use it as a somewhat listener and then dispatch the events to the currently resumed Activity/Fragment.
That said, I don't think deriving Application just to act as a listener would deemed as a good practice. Android has provided the Service class which was built for these use-cases in mind. Put simply, they act just like Activity but without any UI whatsoever.
It is where I think would be the best place to listen for events. You could then command the aforementioned Service to fire off a Broadcast whenever an event of interest is being detected. After all of that, what is left is to assign a BroadcastReceiver in your Activity/Fragment and update its state according to the event you've just received.


text:
Q: How to add global functions in Laravel webpack.mix.js? I am using Laravel mix to compile my assets and combining them into single file. I created a new js file and wrote some methods in this. I combined this file with app.js file. From my blade file when i try to call those methods i get an error function not defined . I am unable to access those methods.
Please help me out to call those methods.
Laravel Mix code
mix.js([ 'js/app.js',
         'js/custom.js'
        ], 'public/js'),
.....

Custom.js
function test(){
  alert('test')
}

test.blade.php
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript">
    test();
</script>

Error : test is not defined

A: Just assign it to window. So in your Custom.js
window.test = function(){
  alert('test')
}

and use it in your test.blade.php:
<script type="text/javascript">
    window.test();
</script>

A: Try this:
custom.js
function test(){
    alert('test')
}

export { test };

app.js
...
import { test } from './custom.js';

A: Rather than just concatenating the new file onto the end of the app.js a cleaner approach (imho) is to leave your webpack.mix.js untouched.
Create your custom.js file in resources/assets/js and simply add require('./custom'); at the bottom of resources/assets/js/app.js
This will then be required as part of the rest of the build process.


text:
Q: Passing data from view to view in laravel I need to pass information from view to another view when pushing "Edytuj" button

Here is my SlideController (secondView)
 public function slideindex()
{
    $list = Slide::all();

    return view('slide-list', ["slidesList" => $list, "title" => "Slides index"
        ]);

My routes
Route::get('index/createpresentation','DataController@createpresentation');

Route::post('index/','DataController@storepresentation');

Route::get('index/delete/{ID}','DataController@deletepresentation');

Route::get('index/edit/{ID}','SlideController@slideindex');

Route::get('index/','DataController@index');

Route::get('index/slideindex','SlideController@slideindex');

Blade of second view
@extends('template')

@section('title'){{@title}} @endsection

@section('content')

                Index (current)

                Dodaj slajd (current)

                Presentation Name

            Id
            Nazwa
            Typ
            Akcja

        @foreach ($slidesList  as $slides )

                {{$slides ->id}}
                {{$slides->slideName}}
                {{$slides->type}}

        @endforeach

@endsection('content')

<
It needs to be working same way when adding another records
Next i will need to assign same ID  to all new records in second view . In same ID i mean to send them ID that is corresponding to name that im trying to send

A: There is couple of ways you can try

*

*Posting the data between forms with all the values you need

*Join the forms together and toggle between them using jquery/js
functions

*Store the values in reddis or db of some sort so they can be re-used

A: I think you want to pass the ID of the row you want to edit?
You could create a route and a controller for this.
For example:
controller.php
public function show($id)
{
// logic here
}

web.php
Route::get('/{id}', 'controller@show')->name('show.edit.form');

You could then create a link inside your forloop:
    @foreach ($slidesList  as $slides )

            {{$slides ->id}}
            {{$slides->slideName}}
            {{$slides->type}}
            id) }}">EDIT

    @endforeach

If you want to show all slides corresponding to a presentation.
You could add a method inside your Presentation model:
public function slides()
{
    return $this->hasMany(Slide::class, 'your_foreign_key');
}

Then if you pass a presentation to a view, you could do something like this:
@foreach ($presentation->slides as $slide)
    // logic here
@endforeach


text:
Q: How to get the x,y coordinates of a 2d contour conic with Scilab? I am a very beginner with SciLab.
My problem with a conic is:
My equation is of the form :

axx + bxy + cyy + dx + ey + f = z where z = 0

I would like to get the (x,y) coordinates of all points on the ellipse where z=0
For example my function with the Scilab code is:
function [z] = fct(x,y)
    z = -0.04088*x^2 - 0.10063*y^2 - 0.21767*x + 0.44632*y + 0.04286*x*y
endfunction

I set the working space with:
x=-10:10; y=-10:10;

I draw my ellipse with:
fcontour2d(x, y, fct, [0,0], style=[9,9])

Now how can i get all points ((x,y) coordinates) of the plotted ellipse where z=0 ?
Maybe i can do something with z=feval(x,y,fct) i don't know.
Thank you i advance for your help.
Julien

A: I finally found the solution thanks to some pdf documentations i found on the web.
Here is my source code for Scilab:
// conic function
function [z]=fct(x,y)
z=-0.04088*x^2-0.10063*y^2-0.21767*x+0.44632*y+0.04286*x*y
endfunction
// plane surface z=0
function [z]=f(x,y)
z=0*x*y
endfunction
// working space
x=-10:10;y=-10:10;
// we draw the 2d ellipse from the conic function where z=0
fcontour2d(x,y,fct,[0,0],style=[9,9])
// we write a function to find the intersection between the conic and the place surface
function [Y]=coniques(X) , Y=[fct(X(1),X(2)),f(X(1),X(2))]
endfunction
for i=-10:0.1:10 // for each offset off the y axis (with i from -10 to 10 with a step of 0.1)
rep=fsolve([-10,i],coniques); // we find the coordinates (rep(1)=x, rep(2)=y) of the first point of intersection (search from the left to the right)
xpolys(rep(1),rep(2),-1) // we plot the point on the chart
rep=fsolve([10,i],coniques); // we find the coordinates (rep(1)=x, rep(2)=y) of the second point of intersection (search from the right to the left)
xpolys(rep(1),rep(2),-1) // we plot the point on the chart
end


text:
Q: Move sub directory to different directory using camel How can I move sub directory containing files to different directory using apache camel.
for example
/home/camel/inbox/tenant/aws/*.txt to /home/camel/processed/tenant/aws/*.txt

A: You can do something like this:
UPDATED:
from("file:///home/camel/inbox/?recursive=true&delete=true&sortBy=file:name&include=(.*[.](txt|TXT)$)")
.to("file:///home/camel/processed/");


text:
Q: Preloading images in Javascript? Without jQuery There are several questions about this in the forum, but I couldn't get a good answer for what I need.
I am getting into Canvas and Javascript, and I want to preload some images as soon as the game opens. I made an example of the method I wanted to build (and didn't work)
I have 3 files:
"main.html" where the canvas (there is only one in this example) is declared and I try to load an image, "ImagePreloader.js" where I preload all the images and "Variables.js" where I have my variables.
Could anyone please help me with this image preloading metod, or suggest me a viable one? I think the image is not loading because I am not using an onLoad() function, which I couldn't understand in the tutorials I read so far (I know how to apply it to an image, but not to an array of images)
main.html:
<!DOCTYPE HTML>
<html>
  <body>
    <canvas id="myCanvas" width="800" height="600"></canvas>

    <script type="text/javascript" src="Variables.js"></script>
    <script type="text/javascript" src="ImagePreloader.js"></script>
    <script>
    // Basic canvas info
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    // Draw one of the images. Somehow it doesn't work :(
    context.drawImage(imageArray[3], x, y, width, height);
    </script>
  </body>
</html>

ImagePreloader.js
// This should preload the images in imageArray[i] with 0 <= i <= 5 ... right?
function preloader()
 {
     for(var i=0; i<5; i++)
     {
          imageArray[i].src=images[i];
     }
 }

Variables.js
// array of sources of my images
images = new Array();
images[0]="img1.jpg"
images[1]="img2.jpg"
images[2]="img3.jpg"
images[3]="img4.jpg"
images[4]="img5.jpg"

// Stuff to draw the image
var x = 50;
var y = 50;
var width = 256;
var height = 256;

// Is this actually an array of images?
imageArray = new Image();

Thanks in advance!

A: Well, you will want to use a function which loads the images at a certain point, so you might as well try to understand onLoad. It's not that hard to grasp.
"onload" is a javascript event that occurs immediately after something is loaded. In other words: onLoad is like a javascript-native function which triggers when something is loaded. That something can be a window (eg: window.onload) or a document. What you want is the document onLoad event, as it triggers when your document is loaded.
Let's provide you with a simple example...
<body onload="preloadMyImages();">

This tells the browser "when you've loaded the document, run the preloadMyImages function".
All you have to do is then use that function to load your images into the client's browser cache.
function preloadMyImages()
{
    var imageList = [
        "image.gif",
        "example/image.jpg",
        "whatever/image.png"
    ];
    for(var i = 0; i < imageList.length; i++ )
    {
        var imageObject = new Image();
        imageObject.src = imageList[i];
    }
}

That practically wraps it up and provides you with a fully working example. Enjoy!
EDIT
Since - according to your comment - you are looking for some more help, I would like to point you to https://stackoverflow.com/a/1038381/2432317 which (as one of many examples) shows how that you can (and probably should - depending on what you're planning do draw on your canvas) use img.onload too.
Yet, as I stated in my comment: it will all depend on where you want to take it. The more you dive into Javascript coding, the more you will understand what's going on. There are several good (partly free) books out there explaining how to code Javascript, use the HTML5 canvas, create preloaders, animations, talk about scopes etc.
A quick check at the big G of search engines turns up ample examples and tutorials too which will be helpfull for you. One of many examples: "How To Draw Images Onto Your HTML5 Canvas" which shows you preloading and looping an animation in a short and crisp tutorial.
But please, don't expect us to code it all for you - it's not going to happen. This is one of the not-so-rare cases where "learning by doing" will actually make you smarter. And if you hit another problem on your way to your final goal, you can always post a new question related to that new problem.

A: You have to make sure these 5 images are loaded (downloaded doesnt alwaysmean its loaded and ready to use, only onload guarantees that image is ready to use) before you use it.
So add onload for the images, then count from the onload function and trigger the draw after 5 of them are loaded
function prefetchImages(sources){
        var images = [];
        var loadedImages = 0;
        var numImages = sources.length;
        for (var i=0; i < numImages; i++) {
            images[i] = new Image();
            images[i].onload = function(){
                if (++loadedImages >= numImages) {
                    //ready draw with my images now
                    drawThePainting();
                }
            };
            images[i].src = sources[i]; //bind onload before setting src bug in some chrome versions
        }
    };

prefetchImages(["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"]);

function drawThePainting(){
        // Basic canvas info
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    // Draw one of the images. Somehow it doesn't work :(
    context.drawImage(imageArray[3], x, y, width, height);
}

A: try this
put this script in head section
<script type="text/javascript">
    function preload(arrayOfImages) {
      for(i = 0 ; i < arrayOfImages.length ; i++)
         {
     var img = new Image();
             img.src = arrayOfImages[i];
         }
    }

 preload(['img1.png','img2.png']);
</script>


text:
Q: firefox detecting xlsx file as 97-2003 workbook(.xls) which saves the file as example.xlsx.xls I am saving the xlsx file in firefox and the browser recognized it as 97-2003 workbook(.xls)

when I open the xls file it generates pop-up window

I have also tried this in the different machine in which it works fine in firefox where it detects it as Microsoft Office Excel Worksheet( which is for .xlsx)

I have also tried to open the browser preferences where I found in application tab of second machine microsoft excel worksheet in content type list

but in the first machine content-type list contains only microsoft excel 97-2003 worksheet. Is that the issue ? If yes, please guide how to fix that ?
Also want to update on this :
First Machine Firefox Version is 39.0.3
Second Machine Firefox Version is 40.0.2
Edit :
In the code , I am using PHPExcel library for generating excel file where I am passing application/vnd.ms-excel as mime type in the header.
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"example.xlsx\"");
header("Cache-Control: max-age=0");

If this is the issue,then please let me know ?

A: application/vnd.ms-excel is the mime/content type for a BIFF format .xls file.
The mime/content type for an OfficeOpenXML format .xlsx file is application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Firefox is only interpreting the content type that you send in your headers, and this doesn't match with the extension or format of the file that you're sending.
For reference with PHPExcel

*

*OfficeOpenXML format files

*

*Excel2007 Writer

*.xlsx Extension

*application/vnd.openxmlformats-officedocument.spreadsheetml.sheet content/mime type

*BIFF format files

*

*Excel5 Writer

*.xls Extension

*application/vnd.ms-excel content/mime type


text:
Q: make different requests forward to different interfaces I have a gateway computer which connects Internet via ADSL and got a virtual interface ppp0. The I establish a pptp vpn through the ADSL and got a virtual interface ppp1.
There are several computers connect to this gateway computer in order to share the Internet and vpn connection.
I want to set some route rules or iptables rule to let the specific requests of specified IP ranges from the internal computers forward to the vpn connection(ppp1) and other requests go directly through the ADSL connection(ppp0).
How should I do?

A: Hi you could do that by DNAT in iptable on the PREROUTING chain
Below example will redirect http traffic from the range of ips specified ("start-ip" to "end-ip") to the destination ip and port specified(gatewayip:vpnportnumber).
iptables -A PREROUTING -t nat -m iprange --src-range "start-ip"-"end-ip" -i "interface"   -p tcp -m tcp --dport 80 -j DNAT --to-destination "gatewayip:vpnportnumber"


text:
Q: Do something after div loads with jquery i have some problem with my jquery. I need to remove first two elements from some list after specify div loads. When document is ready I didn't have this div in my DOM, it's appending after some click action. So, what i need to do is make function which this specify div will be adding to my DOM. This is my code, thx for help.
setTimeout(function(){
    if ($('.sv_flex_slider .slides').find('li').size() > 3) {
        $('#fancybox-thumbs').load(function(){
            setTimeout(function(){
                $('#fancybox-thumbs ul').find('li').eq(1).remove();
                $('#fancybox-thumbs ul').find('li').eq(2).remove();
            },200);
        })
    }
},200);

A: You need a trigger when the div is created. Like this:
$('#some_element').on('click', function () {
    var $element = $(document.createElement('div')).attr('id', 'newDiv');
    $element.trigger('created');
});

Then you can listen to that:
$('body').on('created', '#newDiv'....


text:
Q: Converting CSV from two rows into columns with a timestamp I have a CSV file which is in the format of two rows with 24hr of data in it:
(Comma separated. I failed to specify this in my original question, sorry!)
Site ID,Meter Reference,Date,Units,00:30,A,01:00,A,01:30,A,02:00,A,02:30,A,03:00,A,03:30,A,04:00,A,04:30,A,05:00,A,05:30,A,06:00,A,06:30,A,07:00,A,07:30,A,08:00,A,08:30,A,09:00,A,09:30,A,10:00,A,10:30,A,11:00,A,11:30,A,12:00,A,12:30,A,13:00,A,13:30,A,14:00,A,14:30,A,15:00,A,15:30,A,16:00,A,16:30,A,17:00,A,17:30,A,18:00,A,18:30,A,19:00,A,19:30,A,20:00,A,20:30,A,21:00,A,21:30,A,22:00,A,22:30,A,23:00,A,23:30,A,00:00,A
Building,A,12/06/15,kWh,1,A,2,A,2,A,1,A,2,A,2,A,1,A,2,A,2,A,1,A,2,A,2,A,1,A,2,A,2,A,1,A,2,A,1,A,2,A,2,A,2,A,1,A,2,A,2,A,0,A,1,A,0,A,1,A,3,A,2,A,2,A,1,A,0,A,0,A,0,A,1,A,0,A,0,A,0,A,1,A,0,A,0,A,0,A,1,A,0,A,0,A,0,A,1,A

I need to get it into a format which I can use in another process. Which contains a full timestamp, value and Building ref. I am going to push this into a MySQL table.
Building,   Kwh,    Timestamp
A,  2,  12/06/15 00:30
A,  3,  12/06/15 01:00
A,  4,  12/06/15 01:30
A,  4,  12/06/15 02:00
A,  2,  12/06/15 02:30
A,  3,  12/06/15 03:00

I have tried to use this to pivot the data:
import csv

from itertools import izip
a = izip(*csv.reader(open("Logger.csv", "rb")))
csv.writer(open("Long.csv", "wb")).writerows(a)

But this gives me headers over four rows and data over two.
Only starting with Python today, can I modify the import csv making the conversion a bit cleaner.
I have tried to run a second python file to append each row to add a timestamp and the remove the Row with 'A A' in it. I know this is not the right approach and looking for guidance.
This is my current results
Site ID Building
Meter Reference A
Date    11/06/15
Units   kWh
00:30   2
A   A
01:00   2
A   A
01:30   2
A   A
02:00   2
A   A
02:30   2
A   A
03:00   3

Any help is appreciated

A: This works :
## Reading input
input_file = open("input_file_name.csv",'r')

input_data = []
for line in input_file:
  input_data.append(line.split(";"))

date = input_data[1][4]
input_file.close()

## Writting output
output_file = open("output_file_name.csv",'w')

output_file.write("Building;Kwh;Timestamp\n")

swift = 6
size_data = len(input_data[0]) - swift
for i in range(size_data/2):
  hour = input_data[0][swift + 2*i]
  reference = input_data[0][swift + 2*i + 1]
  kwh = input_data[1][swift + 2*i]
  output_file.write(reference+";"+kwh+";"+date+" "+hour+"\n")

output_file.close()

A: I had some fun with this one.
import re

input_file = 'in.txt'
output_file = 'output.txt'

data = {}

with open(input_file) as fh:
    for line in fh:
        line = line.rstrip()

        if 'Date' in line:
            times = []
            for i in re.split(r'\s+', line):
                if re.match(r'\d{2}:\d{2}', i):
                    times.append(i)

        else:
            building = (re.split(r'\s+', line))[1]
            data[building] = {}
            data[building]['times'] = times
            data[building]['results'] = []
            data[building]['count'] = 0

            for i in re.split(r'\s+', line):
                if re.match(r'^\d+$', i):
                    data[building]['results'].append(i)
                    data[building]['count'] += 1
            data[building]['date'] = \
                re.search(r'(\d{2}/\d{2}/\d{2})', line).group()

wfh = open(output_file, 'w')
wfh.write("Building Kwh Timestamp\n")

for k in data.keys():

    building = k

    for i in range(0, data[building]['count']):
        wfh.write("{}   {}  {}\n".format(
            k,
            data[building]['results'].pop(0),
            data[building]['times'].pop(0))
        )

wfh.close()


text:
Q: TS-Jest; how to remove linter errors? We are running a project with typescript and are now looking into adding tests. Are we able to use TS-jest with types, or do we need to use any? Right now we get linter errors if we use mock.
An example:
const emit: Emit = jest.fn()

callFunctionWithEmit(emit)

expect(emit.mock.calls[0][0]).toEqual({
  result: null
})

This works, but the linter tells us that Emit doesn't have a mock-property. Is there any good ways to remove these linter-errors?
We're using VSCode together with these plugins:

*

*Prettier

*TSLint

A: The way to solve this is to use jest.Mock.
The solution would look like this:
const emit: jest.Mock<Emit> = jest.fn()

callFunctionWithEmit(emit)

expect(emit.mock.calls[0][0]).toEqual({
   result: null
})


text: Q: Normalizing of _score field in a search query in elasticsearch I want the _score field returned by elasticsearch to be in the range say (0 to 100). Is there a way this can be done by the Elasticsearch, so that I don't have to do it manually in the code.


text:
Q: Convert Robot Framework xPath to Selenium Python equivalent. I am trying to convert xpath in robot to python code. I wanted the below xpath in Robot to be converted to python code
This works in Robot:
xpath=(//th[@class="picker-switch"])[2]

I have tried in python
self._driver.find_element_by_xpath("//th[@class='picker-switch'][2]")

Which resulted in the following error:
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//th[@class='datepicker-switch'][2]"}

and
self._driver.find_element_by_xpath("//th[@class='picker-switch']")[2]

That caused:
'WebElement' object does not support indexing

A: It start working when I  encased the xpath statement with brackets (...):
self._driver.find_element_by_xpath("(//th[@class='picker-switch'])[2]").click()

A: It failed, as what you have put in the first python attempt was not the same xpath as in RF ;).
In the original xpath the expression is surrounded with brackets (expression), and then the index. Which reads - find all elements matching the expression, and return the second one.
Without the brackets it is - find all th with that class, which are the 2nd child of their parents element - quite different :)
For the record, the corrected second python attempt should be
self._driver.find_elements_by_xpath("//th[@class='picker-switch']")[1]

find_elements_by_xpath will return all elements matching the expression as a list, and [1] will return the 2nd element in that list - python's lists are zero-based (start from index 0), while xpath's - one-based.


text:
Q: XMLHTTP status code 0 when connecting to salesforce Disclaimer:
I've seen several posts regarding status codes 0 here, but a lot of them give answers of the form "it's API specific" etc... and don't seem to serve my purpose. So i'm going to ask again a specific question here to platform i'm working on Salesforce, this is a very popular tool, so I don't believe the scope of this will be too narrow, for those that wish to close the question.
Question Begins:
I'm working on making an APEX page that should query a REST resource built in Salesforce.
The REST resource works just fine when tested with POSTMAN, as well as my own python client, but somehow I cannot access it via javascript from the website. The code is given below:
<apex:page>
<html>
    <head>

        <script>

            var xhr = new XMLHttpRequest();

            xhr.open("GET", "http://URLredacted.salesforce.com/apexrest/resourcenameredacted", false);
            xhr.send();
            alert(xhr.state);
            alert(xhr.status);
        </script>
    </head>
    <body>

    </body>
</html>
</apex:page>

When i set the async parameter to true, the values I get back are xhr.status = 0, and xhr.state = undefined. When it is false, the alerts just never happen in the first place.
Once again the resource being consumed is a working and tested REST API.
Is there a fix for this, in salesforce specifically?


text:
Q: How do I add a page to this zend project So I've been assigned to this project that uses Zend Framework 1.12. I'm trying to add a page to the project but I seem to be missing something somewhere. The directory structure is a bit different than any example Zend project I have seen (no bootstrap dir).
-application
---controllers
------modules
---------------nopage
------------------------ IndexController.php
---model
---- a bunch of db files
---views
----templates (smarty tpl files)
---------------nopage
------------------------ nopage.tpl
---backend
----router.php
Here is my code for the router.php
$controller -> addControllerDirectory(ROOT . 'application/controller/nopage', 'nopage');
$router = $controller -> getRouter();

$nopage = new Zend_Controller_Router_Route_Regex(
'nopage.html',
array('module' => 'nopage', 'controller' => 'index', 'action' => 'index')
);

$router -> addRoute('nopage', $nopage);

Here is my IndexController code for nopage IndexController.php
<?php

/** Zend_Controller_Action */
Zend_Loader::loadClass('System_Controller_Action');

class Nopage_IndexController extends System_Controller_Action
{

public function indexAction() {

            $this -> smarty -> assign('PageBody', 'nopage/404.tpl');
            $this -> smarty -> assign('Title', 'PetIdMe - 404');
            $this -> smarty -> display('layouts/main.tpl');
    }
}

and I get this error:
Invalid controller specified (index)
My code seems to follow the same structure and everything that all the other routes do, I have searched and searched to no avail on this. Would the knowledgeable and generous folks here at SO have any ideas here? If you need more information I would be glad to provide it. Thanks so much in advance for any insight into this.
EDIT SOME EXTRA CODE FROM THE ROUTER
$controller -> addControllerDirectory(ROOT . 'application/controllers/lostandfound',      'lostandfound');

$controller -> addControllerDirectory(ROOT . 'application/controllers/search', 'search');

$controller -> addControllerDirectory(ROOT . 'application/controllers/orderstatus', 'orderstatus');

$controller -> addControllerDirectory(ROOT . 'application/controllers/myaccount', 'myaccount');

$controller -> addControllerDirectory(ROOT . 'application/controllers/giftcard', 'giftcard');

$controller -> addControllerDirectory(ROOT . 'application/controller/nopage', 'nopage');

$router = $controller -> getRouter();

$nopage = new Zend_Controller_Router_Route(
'nopage.html',
array('module' => 'nopage', 'controller' => 'index', 'action' => 'index')
);

$router -> addRoute('nopage', $nopage);
//****************** Gift Card ************************************************************

$giftcard = new Zend_Controller_Router_Route_Regex(
'giftcard.html',
array('module' => 'giftcard', 'controller' => 'index', 'action' => 'index')
);
$router -> addRoute('giftcard', $giftcard);

$GiftCardsPages = new Zend_Controller_Router_Route_Regex(
'admin/gift/page/(\d*)',
array('module'=>'admin', 'controller'=>'gift', 'action'=>'index'),
array(1  =>'page')
);
$router -> addRoute('GiftCardsPages', $GiftCardsPages);

//****************** SEARCH ***************************************************************
$topsearchserult = new Zend_Controller_Router_Route_Regex(
'topsearchserult.html',
array('module'=>'search', 'controller'=>'index', 'action'=>'search'),
array(1  =>'page')
);
$router -> addRoute('topsearchserult', $topsearchserult);

//****************** MY ACCOUNT *********************************************************

$myaccount = new Zend_Controller_Router_Route_Regex(
'myaccount.html',
array('module' => 'myaccount', 'controller' => 'index', 'action' => 'index')
);
$router -> addRoute('myaccount', $myaccount);

AND SOME FROM OTHER IndexController PAGES:
Zend_Loader::loadClass('System_Controller_Action');

class News_IndexController extends System_Controller_Action {

public function init() {
    parent::init();
}

public function viewAction() {
    $new = $this -> News -> getNewById($this->_getParam('new_id'));
    $this->smarty->assign('new', $new);
    $this->smarty->assign('Title', $new['new_title']);
    $this->smarty->assign('PageBody', 'news/show_item.tpl');
    $this->smarty->display('layouts/main.tpl');
}

public function indexAction() {

    $page = $this->_hasParam('page')?((int)$this->_getParam('page')-1):0;
    $items = $this->News->getNewsForPage($page);

    $this->smarty->assign('items', $items);
    $this->smarty->assign('Title', 'News items');
    $this->smarty->assign('page_num', $page+1);
    $this->smarty->assign('page_count', $this->News->getPagesCount());
    $this->smarty->assign('PageBody', 'news/index.tpl');
    $this->smarty->display('layouts/main.tpl');
}

AND ANOTHER
Zend_Loader::loadClass('System_Controller_Action');
include_once ROOT . 'application/models/GiftCardsDb.php';
class GiftCard_IndexController extends System_Controller_Action
{
private $giftcard;
 public function init() {
    $this->giftcard = new GiftCardDb();
    parent::init();
}

public function indexAction() {
    if($this->_hasParam('product_id')){
        $this -> smarty -> assign('giftcard_text', $this -> Content ->     getPageByLink('giftcard.html'));
        $this -> smarty -> assign('giftcard_agreement_text', $this -> Content -> getPageByLink('giftcard_agreement.html'));
        $this -> smarty -> assign('PageBody', 'giftcard/index.tpl');
        $this -> smarty -> assign('product_id', $this->_getParam('product_id'));
        $this -> smarty -> assign('Title', 'Pet Id Me - Gift Card');
        $this -> smarty -> display('layouts/main.tpl');
    } else {
        $this->_redirect("/");
    }
    }

A: you add zend framework extra page some steps given
1.zend is MVC pattern
2.create view file name  and controller file name same name
example : view->save.phtml
controller:saveAction
3.you include database connection implement controller (or) call db method
  refer follow link
     http://www.phpeveryday.com/articles/Zend-Framework-Basic-Tutorial-P840.html

A: I think the solution is add this line
Zend_Loader::loadClass('System_Controller_Action');

at the starting of your IndexController. i.e
Zend_Loader::loadClass('System_Controller_Action');

class Nopage_IndexController extends System_Controller_Action
{


text: Q: Consistently getting error "Emulator: ANSICON: cmd.exe: unsupported process." in Android Studio Any project I test in Android Studio fails and gives the error "Emulator: ANSICON: could not obtain the parent process." I have tried several different emulators and completely reinstalling but have had no success. Any help in solving this problem would be appreciated.


text:
Q: 2D binned scatter plot in d3.js? Rect bins are not drawn from origin? I'm trying to make 2D binned scatter plot in d3.js. The idea is when the user selects number of bins n, we get the nxn matrix of bins colored by number of elements inside. I tried to do it with d3.bin(), but the problem is if we have a different scales on x and y axis and these bins are defined by side value which could be different for x and y axis. How can I fix this code to make it work for 2D binning?
var margin = {top: 40, right: 40, bottom: 40, left: 40},
    w = 380 - margin.left - margin.right,
    h = 380 - margin.top - margin.bottom;
var color = d3.scale.linear()
    .domain([0, 1000])
    .range(["yellow", "darkred"])
    .interpolate(d3.interpolateLab);

var svg = d3.select("body").append("svg")
    .attr("width", w + margin.left + margin.right)
    .attr("height", h + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" +margin.left+ "," +margin.top+ ")");
var points = [];
d3.csv("static/data/data_for_density2d.csv", function(error, data) {
    data.forEach(function(d) {
        d.time = +d.x;
        d.intensity = +d.y;
        points.push([d.time, d.intensity]);
    });
    function split(left, right, parts) {
    var result = [],
        delta = (right - left) / (parts - 1);
    while (left < right) {
        result.push(left);
        left += delta;
    }
    result.push(right);
    return result;
}
    console.log(split(0, d3.max(data, function(d) {return parseFloat(d.x);}), 10));
    console.log(d3.min(data, function(d) { return parseFloat(d.x); }));
    var x = d3.scale.linear()
    .domain(split(0, d3.max(data, function(d) {return parseFloat(d.x);}), 10))
    .range([0, d3.max(data, function(d) {return parseFloat(d.x);})]);
       console.log(x.domain());
    var y = d3.scale.linear()
        .domain([0, d3.max(data, function(d) { return parseFloat(d.y); })])
        .range([h, 0]);

    var yinv = d3.scale.linear()
        .domain([0, d3.max(data, function(d) { return parseFloat(d.y); })])
        .range([0, h]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");
    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");
    console.log(h);
    console.log(parseFloat(h/10));
    var side = 2;
    console.log(w, h);
    var bins = d3.bin()
        .size([d3.max(data, function(d) { return parseFloat(d.x); }), d3.max(data, function(d) { return parseFloat(d.y); })])
        .side(side);
    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + h + ")")
        .call(xAxis);
    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);
        console.log(x(side));
    svg.selectAll(".square")
        .data(bins(points))
        .enter().append("rect")
        .attr("class", "square")
        .attr("x", function(d) { return x(d.x); })
        .attr("y", function(d) { return y(d.y)-yinv(side); })
        .attr("width", x(side))
        .attr("height", yinv(side))
        .style("fill", function(d) { return color(d.length); }); });

I've tried to adjust the domain by spliting it in 10 parts, where 10 should be number of bins user selected.
UPDATE: I've decided to use d3.rectbin() function based on this example: https://d3-graph-gallery.com/graph/density2d_histogram2d.html
I define sizes of rectangle like this:
    var numBin=10;
  // Compute the rectbin
  var size = (d3.max(data, function(d) {return parseFloat(d.x);})-d3.min(data, function(d) {return parseFloat(d.x);}))/numBin;
var sizeY=(d3.max(data, function(d) {return parseFloat(d.y);})-d3.min(data, function(d) {return parseFloat(d.y);}))/numBin;
var rectbinData = d3.rectbin()
    .dx(size)
    .dy(sizeY)
    (inputForRectBinning)

But rectangles are not drawn from origin of the scatterplot, how do I fix this so whatever number of bins user selects rectangles are drawn from origin of plot? Example of rects not being drawn from origin:


text:
Q: 3 columns 2 rows responsive to 2 columns 3 rows I'm using Bootstrap css grid layout it works great.
I haven't found an example where it can be responsive and convert 3 columns and 2 rows into 2 columns and 3 rows.
What it does is create single column of 6 rows. I can convert even columns from 4 to 2 but how to do 3 as they are in 2 different rows?
I thought if there is solution for an even number of columns then it could be done for odd.

A: Try using

A: Take into consideration that you may have to think outside of the box (punny I know) on this one. It may help visualize it better if you drew out the different stages first.
Then consider you may not need rows, except the one to contain the columns. In Bootstrap extra columns will force a second or third row automatically.
http://getbootstrap.com/css/#grid-example-mixed
You have 6 total divs. Then just adjust the column class width numbers.
Now you didn't say if you wanted the three columns on a desktop-sized screen or a mobile. I'm going to assume here, for the sake of simplicity, that the 2 columns layout is a mobile layout.

 Content

 Content

 Content

 Content

 Content

 Content

You CAN switch it up, but why put that many columns into such a small space... there could be reasons to do it that way but it's not common due to finger-width issues. However, Bootstrap is that level of flexible.

 Content

 Content

 Content

 Content

 Content

 Content

Edit
There are also ways to keep it centered using offsets, if you have say a 7 column layout. It just requires adjusting the width of the columns and then adding offsets to keep it centered.
http://getbootstrap.com/css/#grid-offsetting
An important thing to remember when adding an offset, is that the col width plus the offset cannot equal 12 or it will be pushed all the way to the right. It also works best when the column width is an even number (2, 4, 6, 8, or 10).
You can practice in JSfiddle or CodePen (codepen live updates in a WYSIWYG viewer).


text:
Q: Eclipse couldn't startup tomcat server after configuring SSL at server.xml of tomcat As I want to change tomcat from http to https, so I change server.xml like this:
<!--
<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
-->
<Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
               SSLEnabled="true" maxThreads="150" scheme="https"
               secure="true" clientAuth="false" connectionTimeout="20000"
               keystoreFile="D:/sslDemo/tomcat.keystore"
               keystorePass="123456" sslProtocol="TLS" />

Before change, I could startup tomcat at Eclipse, but failed after changing.
The error tips like this:
Server Tomcat v7.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.

I could start it up by cmd.
Could anyone kindly advise what is the problem? Thanks a lot in advance.

A: Just increase server startup timeout
goto server view, double click on one of the server, expand time out option and set value to it


text:
Q: What do you call the roads along the coast or borders of a country? In Portuguese we call it marginal (which I would say relates to the word margin, i.e at the border of something).
No result from Google Translate felt as the right answer.
We may say for example Vou pela marginal which means I'm going to take the __ road.
edit
My bad, I posed the question wrong I guess. I forgot to mention that what I had in mind was roads at the coast, I'm not sure every country has roads at their borders (probably not), but countries with beaches usually have roads for better access. So I meant, roads touching the ocean or something like that. Coastal road/highway would be it.

A: It depends on the   morphology   and the boundaries of the country.
Coastal  road/highway is an example of a road running along the border of a country partly surrounded by the sea.
A more generic expression  is border road!

A:

*Estrada ou rua junto à margem ou junto a uma grande extensão de água. in Dicionário Priberam da Língua Portuguesa [em linha], 2008-2013, https://www.priberam.pt/dlpo/marginal [consultado em 20-07-2018].
Priberam is an excellent Portuguese dictionary.
Translation of the definition: A highway or road alongside or to the side of a large body of water.
So, roads run along rivers, coastlines or lakes.
That would give us: coastal road, riverine road (technical), road along a river or river road or riverside road (non-technical) and lakeside road or road along a lake.
In Portugal, the highway (BrE: motorway) that runs along the coast, is said to be a marginal, but not all marginals need run along the seacoast.
Example: Cascais coastal road
The article says: Marginal de Cascais cortada devido às ondas Via está encerrada entre Caxias e Paço de Arcos.
Cascais Coastal Highway [or Road] Shut Off due to waves
Estrada marginal in the article is again: Coastal road. Because the road is "by the sea" (alongside), it is "uma estrada à margem do mar.

coastal highway [American English]or coastal motorway [British
English]

A: In Ame usage:
a beltway TFD

A high-speed highway that encircles or skirts an urban area.

a bypass TFD

A highway or section of a highway that passes around an obstructed or
  congested area.

As America is composed of 50 states and only has 2 contiguous countries, these terms are used to circumvent said areas when traveling by car (not to be confused with detour, which is usually a temporary re-routing).

A highway or section of a highway that passes around an obstructed or
  congested area.


text:
Q: Which element does the yahoo pipes "unique" module return If there are multiple matching elements, which element does the yahoo pipes "unique" module return? Is it the first, the last or can it be any?

A: From the docs:

This module removes items that contain duplicate strings. You select the element to filter on, and Unique removes the duplicates - if the original feed has five items with the same title, you can configure Unique so only one of these items is included in the output feed.

It would seem unspecified. However, after a couple of tests, it seems to me that the first item is selected. So you should be able to get the right items selected by using a Sort operator before Unique.
To illustrate this, I created 2 example pipes. In both pipes there are 3 input items with attributes:

*

*author=jack title=Bazaar

*author=jack title=Git

*author=jack title=Arch

In the first pipe, using the Unique operator selects the first item. If you delete the first item, it selects the second.
In the second pipe, I used the Sort operator to order the items by title before piping to Unique. This way Arch is selected. If you delete it, then Bazaar is selected, and so on.


text:
Q: Inconsistent doc count Hi I am running Elasticsearch 1.5.2
I indexed 6,761,727 documents in one of my indexes.
When I run the following query....
GET myindex/mytype/_search
{
    "size": 0
}

The hits.total count keeps alternating between 2 values...
"hits": {
    "total": 6761727,
    "max_score": 0,
    "hits": []
}

and
"hits": {
    "total": 6760368,
    "max_score": 0,
    "hits": []
}

No matter how many times I run the query the count goes back and forth between the 2.
I searched around a bit and found out that it seems that primary vs replica shards don't have exact same number of docs. If I use preference=primary then the doc count returned is correct.
What is the easiest way to check which shard is the culprit and try to fix him without re-indexing everything?

A: Set the replica count to 0 for that index
PUT /my_index/_settings
{
  "index": {
    "number_of_replicas": 0
  }
}

wait to see no more replicas for that index when you do GET /_cat/shards/my_index?v and then set back to the initial number of replicas.
This will delete all the replicas for that index and then make a new copy of the primaries.


text:
Q: Media Query is triggered by lightbox I am using Fancybox 2, and have a mediaquery which looks like this:
@media (max-width : 1200px) {

#columnset1_column1 {
    display: none;
}
#sitelayout6 {
    width: 980px !important;
}
#columnset3 {
    display: block;
}
#columnset2 {
    margin-top: 70px;
}
}

But the weird thing is the media query is trigger when a lightbox which shows a iframe. The page it shows is only 700 px wide.
It is only a problem in Internet Explorer, not Chrome.
The window size is not resize at any point.

A: I found an answer here that helped:
Fancybox 2 Forcing Responsive Media Queries in IE
Basically, in the iframe, update the references to your CSS to include a query string...
So in your parent page, you have:
<link rel="stylesheet" href="screen.css" />

and in your iframe, you have
<link rel="stylesheet" href="screen.css?iframe=true" />

This gets around a bug in IE which is causing the iframe to trigger the media query in your css for the parent page.


text:
Q: How to deploy HTML webpages from IIS? I have developed some webpages and all the web pages are working fine, Now I need to deploy in my localhost. How can I do this?
I tried by creating a virtual directory and copied the HTML pages, CSS, JS and images in the virtual directory but this is not working, It shows

Internet Explorer cannot display the webpage

My default webpage name is 'index.html'

A: You need to point your IIS virtual directory to the physical location of your sites files. This can be anywhere on your machine.
It is common for a website to physically live in disk:\inetpu\websites\ under its own directory.
A virtual directory is just that, it doesn't physically exist on your machine.
You should then be able to browse to your site as follows:
http://localhost/virtualdirectory/index.html


text:
Q: CDATA does not work as expected I wrote a function :

function wrapWithTag($tag, $data) {
  $cdata = "<![CDATA[$data]]>";
  echo "<$tag>$cdata</$tag>";
}

For instance I like to use it as

$name = 'myCellContent - <extra>';
wrapWithTag("td", $name);

The expected output would be a html table cell with string:

myCellContent - <extra>

What it actually does is printing empty cells. How can I use CDATA properly?
Edit: I have got a simple workaround:

function wrapWithTag($tag, $data) {
  $data = str_replace("<", "<", $data);
  echo "<$tag>$data</$tag>";
}

However, I would prefer using a CDATA section. Feel free to post a solution :P

A: CDATA sections are a feature of XML. HTML does not support them.
XHTML does, but you must ensure the browser is parsing the document in XML mode (by setting Content-Type: application/xhtml+xml in the HTTP response headers).
In HTML, if you want to use characters which have special meaning, you must use entities such as <.
PHP has the htmlspecialchars function; there's no need to roll your own with str_replace.


text:
Q: How do I make urls with ".php" return an "Object not found" Error? After some googling, I was able to allow my php website load without having to put the ".php", but I want to return an object not found error if it finds the ".php", hence making it a requirement to remove the ".php" extension.

A: You could try something like this:
// PHP 8
if(str_contains($_SERVER["REQUEST_URI"], ".php")) {
    http_response_code(404);
    echo "404 - page not found";
}

// PHP < 8
if(strpos($_SERVER["REQUEST_URI"], ".php") !== false) {
    http_response_code(404);
    echo "404 - page not found";
}


text:
Q: Deleting row in a table with delete button in PHP I have some data coming from database and I have a delete button in last column. I want to delete the row on which delete button is clicked. But whenever I click delete button only last row is deleted even if I click on first row.
My delete function:
if(isset($_POST['formDelete'])){
if(isset($_POST['quoteid']) && !empty($_POST['quoteid'])){
    require_once('config.php');
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE)
    or die ('Cannot connect to db');
    $quoteid = $_POST['quoteid'];
    echo "DELETE FROM quotes WHERE quoteid =".$quoteid;
    $result = $conn->query("DELETE FROM quotes WHERE quoteid =".$quoteid);
}

Table code:
<form action="<?php $_PHP_SELF ?>" method="post">
<?php
    require_once('config.php');
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE)
    or die ('Cannot connect to db');
    $result = $conn->query("SELECT quoteid, quote, cat.catid catid, cat.name cat, scat.catid catid, scat.name scat, author FROM quotes q
                           INNER JOIN category cat ON q.catid = cat.catid LEFT OUTER JOIN category scat ON q.subcatid = scat.catid order by quoteid");
    echo "
";
    echo "
Category	Sub-Category	Quote	Author
";
    while ($row = $result->fetch_assoc()) {
        echo "
$row[cat]	$row[scat]	<input type='hidden' id='quoteid' name='quoteid' value=$row[quoteid] />$row[quote]	$row[author]
        <input type='submit' name='formDelete' id='formDelete' value='Delete' />
";
    }
    echo "
";
?>
</form>

I am trying to delete on the basis of quoteid.

A: The idea is create a separate form for each delete button so the right value for quoteid will be send
<?php
    require_once('config.php');
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE)
    or die ('Cannot connect to db');
    $result = $conn->query("SELECT quoteid, quote, cat.catid catid, cat.name cat, scat.catid catid, scat.name scat, author FROM quotes q
                           INNER JOIN category cat ON q.catid = cat.catid LEFT OUTER JOIN category scat ON q.subcatid = scat.catid order by quoteid");
?>

                Category

                Sub-Category

                Quote

                Author

        <?php
        while ($row = $result->fetch_assoc()) {
            ?>

                    <?php echo $row['cat']; ?>

                    <?php echo $row['scat']; ?>

                    <?php echo $row['quote']; ?>

                    <?php echo $row['author']; ?>

                    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method='post' style="display: inline;">
                        <input type='hidden' id='quoteid' name='quoteid' value="<?php echo $row['quoteid']; ?>" />
                        <input type='submit' name='formDelete' id='formDelete' value='Delete' />
                    </form>

            <?php
        }
        ?>


text:
Q: granting Cloud CDN access to your buckets? im trying to use Cloud CDN with backend bucket but it keeps telling me that i should "grant Cloud CDN access to your buckets by adding the Cloud CDN service account to your access control list".
I tried modifying the bucket permissions so that "AllUsers" IAM had every permission, but the CloudCDN still kept telling me to "grant Cloud CDN access to your buckets"
So how do you add the Cloud CDN service account to your access control list?
Thanks in advance

A: The only IAM permission required for a file to be usable by the CDN is to have the "allUsers" IAM user with "Reader" access permissions. This can be easily accomplished by simply making sure that the file is Shared Publicly. What you see in the Cloud Console UI is a warning rather than an error. If this is not affecting your service, just ignore this warning.


text:
Q: How can I animate 'bars' on a tkinter canvas object to simulate the running of my sorting algorithms? For a self development project in python I'm trying to create an algorithm animation program but I'm currently stuck on the animation part of my project. So I have gotten the bars to display on the tkinter canvas but I can't figure out how I can get the bars to animate.  PS I am new to python so explanations of code will be helpful or just any explanation of the best way to move forward would be, thanks
from algorithms import *
from tkinter import *
import random
import time

a_list = [] # values of the list I want to sort, starts empty
bar_coords = [] # list of lists of coordinates for each of the bars represented in the canvas

def initialize_list_elements(num_of_elements, up_to):
    list_of_numbers = []
    canvas.delete('all')
    for _ in range(num_of_elements):
        list_of_numbers.append(random.randint(1, up_to))
    return list_of_numbers

def clear_list():
    a_list.clear()
    canvas.delete('all')
    return a_list

def draw():
    x = 0
    a_list = initialize_list_elements(30, 600)
    for value in a_list: # so for each value in our list of values
        x = x + 30 # each
        y = 700 - int(value) # assign a point y
        bars = canvas.create_line((x, 700, x, y), width = 10, fill='black') # then we draw a line using the points (x, 200) and (x, y)
        canvas.create_text(x, y-10, text=str(value))
        bar_coords = canvas.coords(bars)

algorithm_list = ['Binary Search', 'Jump Search', 'Linear Search', 'Bubble Sort', 'Heap Sort', 'Insertion Sort', 'Merge Sort', 'Quick Sort', 'Selection Sort']

window = Tk()
window.title('Algorithm Testbed')
title_frame = Frame(window) # a frame used to display the title of the program
button_frame = Frame(window) # a frame to hold the buttons
canvas_frame = Frame(window) # a frame for the canvas

var = StringVar(button_frame)
var.set(algorithm_list[0])

canvas = Canvas(canvas_frame, width=910, height=700, background='white')

title_label = Label(title_frame, text='Searching & Sorting Algorithm Testbed', font='Helvetica 20 bold')

init_button = Button(button_frame, text='     Initialise     ', width=15, pady=10, command=draw)
start_button = Button(button_frame, text='     Start     ', width=15, pady=10)
pause_button = Button(button_frame, text='     Pause     ', width=15, pady=10)
step_button = Button(button_frame, text='     Step     ', width=15, pady=10)
clear_button = Button(button_frame, text='     Clear     ', width=15, pady=10, command=clear_list)
drop_down_menu = OptionMenu(button_frame, var, *algorithm_list)

# putting the label onto the title_frame
title_label.grid(rowspan=2, column=0)
# putting buttons onto the button_frame
init_button.grid(rowspan=1, column=0, pady=10, padx=5)
start_button.grid(rowspan=1, column=0, pady=10, padx=5)
pause_button.grid(row=2, column=0, pady=10, padx=5)
step_button.grid(row=3, column=0, pady=10, padx=5)
clear_button.grid(row=4, column=0, pady=10, padx=5)
drop_down_menu.grid(row=5, column=0, pady=10, padx=5)
# putting canvas onto canvas_frame
canvas.grid(row=0, column=0)

# putting frames on the window
title_frame.grid(row=0, columnspan=2)
button_frame.grid(row=1, column=0)
canvas_frame.grid(row=1, column=1)
window.mainloop()

my code for the algorithms I've left out as there are in a different file and the file is about 200 lines of code didn't want to clog up with too much code.
But where I am drawing the bars on the tkinter canvas is there, again thanks for any suggestions.


text:
Q: Background image set as no-repeat but it is repeated on server I need the background of html to be an image, centered and without repeating.
If the img is smaller - it should be streched and vice versa. So the entire image should be visible.
I know, the quality of the image could be damaged, but it doesn't matter.
I tried:
html{
    background:url(img/back04.jpg);
    background-repeat:no-repeat; // is ok on localhost, but on server - repeating appears !?
    background-size:cover;  //also tried
    background-size:contain; //also tried
}

What is the right way, pls ?

A: First, verify that your server's copy matches your local copy.
Second, clear your cache. It's possible the CSS file for the server is cached and it's using an old version.
Third, are you using the same browser (and version) to test both local and server versions? CSS is always rendered client side, so if the CSS files match and you're using the same browser, you shouldn't have any discrepancies between the two versions.

A: I would try the following:
body {
    background: url(img/back04.jpg);
    background-repeat: no-repeat;
    background-position: top center;
    background-size: auto;
}

*Jost


text:
Q: GUI design in GTK I am trying to use GTK with Ruby 2.0.0 to design a user interface that looks like this:
ColHead1                         ColHead2
(box for user number input)      (box for user number input)

                               SubmitBtn

Based on the GTK tutorials I read I got this far:
require 'gtk3'

class RubyApp < Gtk::Window

def initialize
    super
    init_ui
end

def init_ui

    table = Gtk::Table.new 2, 2, true
    submit = Gtk::Button.new :label => "Submit Btn"

    submit.signal_connect "clicked" do
        on_submit
    end

    label = Gtk::Label.new "ColHead1"

    entry = Gtk::Entry.new
    entry.signal_connect "key-release-event" do |w, e|
        on_key_release w, e, label
    end

    set_title "Gtk::Entry"
    signal_connect "destroy" do
        Gtk.main_quit
    end

    table.attach label, 0,1,0,1
    table.attach submit, 1, 0, 1, 0

        add table

    set_default_size 250, 200
    set_window_position :center

    show_all
end
=begin
def on_key_release sender, event, label
    label.set_text sender.text
end
=end
end

Gtk.init
window = RubyApp.new
Gtk.main

Can someone explain how to correctly implement the example gui I have shown above?

A: I think that you have two choices:

*

*Encapsulate different containers:

Create a vertical box (Gtk::Box), add to it an horizontal box in which you add Col1 widget and Col2 widget.
Then add your Submit button to the vertical box.
The vertical Box should be added to the main window. This way, you can configure easily how each widgets will fill in theirs allocated spaces.

*Use a Gtk grid (which is the replacement of Gtk Table)