text:
Q: Complexity of sorting algorithm Here is a sorting algorithm, not a clever one. In this version, it works well when elements are non-negative and occur at most once. I'm confused about its time complexity. Is it O(n)? So is it better than quick sort in terms of that notation? Thanks. Here is the code:
public int[] stupidSort( int[] array ){

// Variables
int max = array[0];
int index = 0;
int[] lastArray = new int[array.length];

// Find max element in input array
for( int i = 0; i < array.length; i++ ){
  if ( array[i] > max )
    max = array[i];
}

// Create a new array. In this array, element n will represent number of n's in input array
int[] newArray = new int[max + 1];

for ( int j = 0; j < array.length; j++ )
  newArray[array[j]]++;

// If element is bigger than 0, it means that number occured in input. So put it in output array
for( int k = 0; k < newArray.length; k++ ){
  if( newArray[k] > 0 )
    lastArray[index++] = k;
}
return lastArray;
}

A: What you wrote is the counting sort, and it has O(n) complexity indeed. However, it cannot be compared to QuickSort because QuickSort is an algorithm based on comparisons. These 2 algorithms belong to different categories (yours is a non-comparison, quicksort is a comparison algorithm). Your algorithm (counting sort) makes the assumption that the range of numbers in the array is known and that all numbers are integer, whereas QuickSort works for every number.
You can learn more for sorting algorithms here. In that link you can see the complexity for sorting algorithms divided in the 2 categories: comparison and non-comparison.
EDIT
As Paul Hankin pointed out the complexity isn't always O(n). It is O(n+k) where k is the max of the input array. Quoted below is the time complexity as explained in the wikipedia article for the counting sort:

Because the algorithm uses only simple for loops, without recursion or subroutine calls, it is straightforward to analyze. The initialization of the count array, and the second for loop which performs a prefix sum on the count array, each iterate at most k + 1 times and therefore take O(k) time. The other two for loops, and the initialization of the output array, each take O(n) time. Therefore, the time for the whole algorithm is the sum of the times for these steps, O(n + k).

A: The given algorithm is very much similar to Count sort. Whereas QuickSort is a comparison model based sorting algorithm. Only in the worst case QuickSort gives O(n^2) time complexity, otherwise it is O(nlogn). Also the QuickSort is used with it's randomized version that is pivot is selected randomly and hence the worst-case is avoided most often this way.
Edit: Correction as pointed by paulhankin in comment complexity=O(n+k):
The code you have put forth is using counting based sort, that is count sort and your code's time complexity is O(n+k). But what you must realize is that this algorithm is dependent on the range of the input and that range could be anything. Furthermore this algorithm is not InPlace but Stable. In many cases the data you want to sort is not only integer rather the data can be anything with a key that is required to be sorted with the help of the key. If Stable algorithm is not used than in such a case sorting can be problematic.
Just in case if someone does not know:
InPlace Algorithm: Is the one in which additional space required is not dependent on the given input.
Stable Algorithm: Is the one in which for example if there were two 5's in the data set before sorting, the 5 that came first before sorting comes first than the second even after the sorting.
EDIT: (Regarding aladinsane7's comment): Yes the formal version of countSort does handle this aspect also. It would be good if you have a look at CountSort. And its time complexity is O(n+k). Where K accounts for the range of data and n is complexity for remaining algorithm.


text:
Q: python : {'detail': [{'loc': ['body'], 'msg': 'value is not a valid dict', 'type': 'type_error.dict'}]} I am using fastapi and when I send post with following code, it return below error:
{'detail': [{'loc': ['body'], 'msg': 'value is not a valid dict', 'type': 'type_error.dict'}]}

My code is :
import requests
import json
import datetime

def main():
    time = datetime.datetime.now().isoformat()

    transaction = {
        "time": time,
        "sender": "COCOCOCO",
        "receiver": "AAAAAA",
        "amount": AAA,
        "description": "Christmas Dinner Fee",
        "signature": "signature_sample"
    }

    url ="https://XXXXXX.deta.dev/transaction_pool/"
    res = requests.post(url, json.dumps(transaction))
    print(res.json())

if __name__ == "__main__":
    main()

How do I fix it?

A: What you are sending in your POST request is not a valid dict object. It could be that you are converting the "transaction" dictionary to a JSON string with json.dumps before sending the request. This will cause the request to contain a JSON string instead of a Python dict object.
Instead of using json.dumps, you can use the json argument to directly send the dictionary in the request. This automatically converts the dictionary to a JSON string before sending it:
res = requests.post(url, json=transaction)

You can also send the dictionary converted to a json object using the json() method,
res = requests.post(url, data=json.dumps(transaction))

redpajama_set_name: RedPajamaStackExchange


text:
Q: My code exited after I filled up the priority queue The code is about Huffman code.
I typed in "6 a 16 b 5 c 12 d 17 e 10 f 25", to fill in the priority_queue and the program exited without an error.
The priority queue is used to set up a binary search tree for decoding.
I made a function storeBinayNumber() to store the code for each character into an unordered map
called HuffmanCode , which is used for encoding;
and two function encocde() and decode() to encode or decode the string that will be later typed in .
What might be the problem ?
#include <iostream>
#include <queue>
#include <unordered_map>
#include <vector>

using namespace std;

class Node
{

public:
    char ch = '\0';

    int freq = 0;

    Node *left;

    Node *right;
};

void storeBinaryNumber(Node *root, unordered_map<char, string> &HuffmanCode, string str = '\0')
{

    if (root = nullptr)
        return;

    if (!root->left && !root->right)
        HuffmanCode[root->ch] = str;

    storeBinaryNumber(root->left, HuffmanCode, str + "0");

    storeBinaryNumber(root->right, HuffmanCode, str + "1");
}

void decode(Node *root, Node *current, string str, int index = 0)
{

    if (index > str.length() - 1)
    {

        if (current == root)
        {

            cout << "Decoding suceeded" << endl;

            return;
        }

        else
            cout << "Invalid code" << endl;

        return;
    }

    if (!current->left && !current->right)
    {

        cout << current->ch;

        decode(root, root, str, index + 1);
    }

    else if (str[index] == '0')
    {

        decode(root, current->left, str, index + 1);
    }

    else if (str[index] == '1')
    {

        decode(root, current->right, str, index + 1);
    }
}

void encode(string str, unordered_map<char, string> HuffmanCode)
{

    for (int i = 0; i < str.length(); i++)
    {

        cout << HuffmanCode[str[i]];
    }
}

int main()
{

    int num;

    cin >> num;                                 //6 a 16 b 5 c 12 d 17 e 10 f 25

    auto compare = [](Node *a, Node *b) //lambda expression
    { return a->freq > b->freq; };

    priority_queue<Node *, vector<Node *>, decltype(compare)> q(compare);

    unordered_map<char, string> HuffmanCode;

    char character;

    int frequency;

    for (int i = 1; i <= num; i++)
    {

        cin >> character >> frequency;

        Node *node = new Node;

        node->ch = character;

        node->freq = frequency;

        node->left = nullptr;

        node->right = nullptr;

        q.push(node);
    }

    Node *root;

    while (q.size() > 1)
    {

        Node *A = q.top();

        q.pop();

        Node *B = q.top();

        q.pop();

        Node *C = new Node;

        C->left = A;

        C->right = B;

        C->freq = A->freq + B->freq;

        if (q.empty())

            root = C;

        q.push(C);
    }

    storeBinaryNumber(root, HuffmanCode);

    int en_or_de;

    string input;

    cout << "press 1 to encode ,  press 2 to decode." << endl;

    cin >> en_or_de;

    cout << "input: " << endl;

    cin >> input;

    if (en_or_de == 1)
    {

        encode(input, HuffmanCode);
    }

    else

        decode(root, root, input);

    system("pause");

    return 0;
}

A: The code have several bugs:
Assign char type to string won't compile on my compiler
void storeBinaryNumber(Node *root, unordered_map<char, string> &HuffmanCode, string str = '\0')

The comparison should use ==, this seems to be a typo.
if (root = nullptr)

And the Node type missed destructor, which needs to a memory leak. After my fix the code seems to work. But it may still have logic bugs.
#include <iostream>
#include <queue>
#include <unordered_map>
#include <vector>

using namespace std;

class Node {
 public:
  char ch = '\0';

  int freq = 0;

  ~Node() {
    delete left;
    delete right;
  }

  Node *left;

  Node *right;
};

void storeBinaryNumber(Node *root, unordered_map<char, string> &HuffmanCode,
                       string str = "") {
  if (root == nullptr) return;

  if (!root->left && !root->right) HuffmanCode[root->ch] = str;

  storeBinaryNumber(root->left, HuffmanCode, str + "0");

  storeBinaryNumber(root->right, HuffmanCode, str + "1");
}

void decode(Node *root, Node *current, string str, int index = 0) {
  if (index > str.length() - 1) {
    if (current == root) {
      cout << "Decoding suceeded" << endl;

      return;
    }

    else
      cout << "Invalid code" << endl;

    return;
  }

  if (!current->left && !current->right) {
    cout << current->ch;

    decode(root, root, str, index + 1);
  }

  else if (str[index] == '0') {
    decode(root, current->left, str, index + 1);
  }

  else if (str[index] == '1') {
    decode(root, current->right, str, index + 1);
  }
}

void encode(string str, unordered_map<char, string> HuffmanCode) {
  for (int i = 0; i < str.length(); i++) {
    cout << HuffmanCode[str[i]];
  }
  std::cout << std::endl;
}

int main() {
  int num;

  cin >> num;  // 6 a 16 b 5 c 12 d 17 e 10 f 25

  auto compare = [](Node *a, Node *b)  // lambda expression
  { return a->freq > b->freq; };

  priority_queue<Node *, vector<Node *>, decltype(compare)> q(compare);

  unordered_map<char, string> HuffmanCode;

  char character;

  int frequency;

  for (int i = 1; i <= num; i++) {
    cin >> character >> frequency;

    Node *node = new Node;

    node->ch = character;

    node->freq = frequency;

    node->left = nullptr;

    node->right = nullptr;

    q.push(node);
  }

  Node *root;

  while (q.size() > 1) {
    Node *A = q.top();

    q.pop();

    Node *B = q.top();

    q.pop();

    Node *C = new Node;

    C->left = A;

    C->right = B;

    C->freq = A->freq + B->freq;

    if (q.empty()) root = C;

    q.push(C);
  }

  storeBinaryNumber(root, HuffmanCode);

  int en_or_de;

  string input;

  cout << "press 1 to encode ,  press 2 to decode." << endl;

  cin >> en_or_de;

  cout << "input: " << endl;

  cin >> input;

  if (en_or_de == 1) {
    encode(input, HuffmanCode);
  }

  else

    decode(root, root, input);

  delete root;
  // system("pause");

  return 0;
}


text:
Q: Add key frame every five frames? Autohotkey? I am trying to make an AutoHotKey script to smoothen up my After Effects workflow. The deal is i have to make a keyframe, then go 5 keyframes ahead, this ultimately takes me 9 keypresses to do! So I tried to cut this down to just 3.
This is my code:
^+1::
Send, ^ & ! & + & {F1}

Send, ^ & {Right}
Send, ^ & {Right}
Send, ^ & {Right}
Send, ^ & {Right}
Send, ^ & {Right}

return

I want it to press
ctrl+shift+alt+F1 then ctrl+right_arrow 5 times.
What am i missing?
SOLUTION:
So I also asked this question on Reddit, where a user told me that the "Send," command is very literal, so it ended up typing " ^ & {Right}" and " ^ & ! & + & {F1}" in letters, furthermore it was unnecessary to type a & and the spaces between the others, which I also found out using a keyboard tester. So the solution was to type:
^+1::
Send ^!+{F1}

Send ^{Right}
Send ^{Right}
Send ^{Right}
Send ^{Right}
Send ^{Right}

return

A: For commands do not use the comma after send (this is for text only)

A: SendInput {ctrl DOWN}{Left 5}{CTRL UP}
This is one method. Rinse and repeat for the other keys, like shift.
Another method is an exclamation point for alt, a cap for ctrl, and a plus for shift.
SendInput ^!+{left 5}
According to the post below, I guess adding a comma converts to send raw? But I'm not sure if that's true. I'll test it out later.
You could also make a function, like a loop or whatever. That might be fun. Pass the keys and the number of times to push them as parameters. Coding challenge!


text:
Q: UISwitch ".onTintColor" and ".tintColor" not working I'm attempt to change the tint color of all my toggles within my app to blue. I tried using both UISwitch.appearance().tintColor and UISwitch.appearance().onTintColor with no help.
import SwiftUI

@main
struct Studently: App {

    init() {
        UISwitch.appearance().tintColor = .systemBlue
        UISwitch.appearance().onTintColor = .systemBlue
    }

    var body: some Scene {
        WindowGroup {
            TabBar()
        }
    }
}

Image: .onTintColor and .tintColor does nothing in another view
The weird thing is, if the state property wrapper is true, the color will be applied. But once toggled to off then on, it returns back to standard green.
Image: Color only applied if the state property wrapped is set to true
I thought maybe this was just a human error on my end. So I tested this out more using UISwitch.appearance.thumbTintColor which applies to a toggle within another view.
@main

struct Studently: App {

    init() {
        UISwitch.appearance().tintColor = .systemBlue
        UISwitch.appearance().onTintColor = .systemBlue
        UISwitch.appearance().thumbTintColor = .red
    }

    var body: some Scene {
        WindowGroup {
            TabBar()
        }
    }
}

Image: .thumbTintColor changes the circle to red
.thumbTintColor is just for example that it can be applied, but neither .tintColor or .onTintColor are applied.
Of course, using .tint works when applied to a single toggle, but I want this to apply to all Toggles without using .tint on each one.
How can I achieve or fix this?


text:
Q: ML.Net Rounding Float32 Results to 0 or 1 using System.Drawing;
using Microsoft.ML;
using Microsoft.ML.Data;
using Microsoft.ML.Transforms.Image;

namespace OnnxTest;

public static class Program
{
    public static void Main(string[] args)
    {
        var tags = File.ReadLines(@"C:\Users\da3ds\Downloads\deepdanbooru-v3-20211112-sgd-e28\tags.txt");
        var imageLocation = @"C:\Users\da3ds\Pictures\image.jpg";
        var modelLocation = @"C:\Users\da3ds\Downloads\deepdanbooru-v3-20211112-sgd-e28\model-resnet-custom_v3.onnx";
        MLContext mlContext = new MLContext();

        Console.WriteLine("Read model");
        Console.WriteLine($"Model location: {modelLocation}");
        Console.WriteLine(
            $"Default parameters: image size=({InputModel.imageWidth},{InputModel.imageHeight})");
        Console.WriteLine($"Images location: {imageLocation}");
        Console.WriteLine("");
        Console.WriteLine("=====Identify the objects in the images=====");
        Console.WriteLine("");

        // Create IDataView from empty list to obtain input data schema
        var data = new InputModel { ImagePath = imageLocation };
        // Define scoring pipeline
        var predictionEngine = GetPredictionEngine(mlContext, modelLocation);
        var outputs = predictionEngine.Predict(data);

        var outputMapped = tags.Zip(outputs.Scores).Select(t => new { Tag = t.First, f = t.Second })
            .ToDictionary(a => a.Tag, a => a.f);

        var outputTags = outputMapped.Where(a => Math.Abs(a.Value - 1) < 0.00001f).Select(a => a.Key).OrderBy(a => a)
            .ToList();
    }

    private static PredictionEngine<InputModel, OutputModel> GetPredictionEngine(MLContext mlContext, string modelLocation)
    {
        var estimator = mlContext.Transforms.LoadImages(InputModel.ModelInput, "", nameof(InputModel.ImagePath))
            .Append(mlContext.Transforms.ResizeImages(InputModel.ModelInput, InputModel.imageWidth,
                InputModel.imageHeight, InputModel.ModelInput, ImageResizingEstimator.ResizingKind.IsoPad))
            .Append(mlContext.Transforms.ExtractPixels(InputModel.ModelInput, InputModel.ModelInput))
            .Append(mlContext.Transforms.ApplyOnnxModel(OutputModel.ModelOutput, InputModel.ModelInput,
                modelLocation));

        var transformer = estimator.Fit(mlContext.Data.LoadFromEnumerable(Array.Empty<InputModel>()));

        // Fit scoring pipeline
        var predictionEngine = mlContext.Model.CreatePredictionEngine<InputModel, OutputModel>(transformer);
        return predictionEngine;
    }

    class InputModel
    {
        public const int imageHeight = 512;
        public const int imageWidth = 512;
        // input tensor name
        public const string ModelInput = "input_1:0";

        public string ImagePath { get; set; }
        [ColumnName(ModelInput)]
        [ImageType(imageHeight, imageWidth)]
        public Bitmap Image { get; set; }
    }

    class OutputModel
    {
        // output tensor name
        public const string ModelOutput = "Identity:0";

        [ColumnName(ModelOutput)]
        public float[] Scores { get; set; }
    }
}

I wrote up a very simple test program to try to get an output that matches a python project, only in C# so I could efficiently use it in an ASP.Net api (also just prefer C#). The original Python works, even after I modified it to use onnxruntime instead of keras, which is where the model originated. It gives a float[9176] of scores 0-1, which matches a list of tags in tags.txt, for whether that tag should apply to a given image.
It's a multi-classification problem with TensorFlow. I used the object detection sample to get here, and it returns a result, and the result is...correct, but not. It's rounding for whatever reason.
I'm new to ML and ML.Net has very little out there, so I figured I'd use my first question in a long time and hoping someone can shed some light on this for me.

A: Ok, new day. I traced the code path of the python project and made an MVP. In doing so, I have very few things to look at the difference of.
import os

import onnxruntime
import skimage.transform
import tensorflow as tf

def main():
    # disable CUDA acceleration for simplicity in running the test
    # you need drivers, an nvidia gpu, etc. for that
    os.environ['CUDA_VISIBLE_DEVICES'] = '-1'

    image_path = 'C:\\Users\\da3ds\\Pictures\\image.jpg'
    model_path = 'C:\\Users\\da3ds\\Downloads\\deepdanbooru-v3-20211112-sgd-e28\\model-resnet-custom_v3.onnx'

    # load tags
    tags_path = 'C:\\Users\\da3ds\\Downloads\\deepdanbooru-v3-20211112-sgd-e28\\tags.txt'
    with open(tags_path, 'r') as tags_stream:
        tags = [tag for tag in (tag.strip() for tag in tags_stream) if tag]

    # create inference session
    model = onnxruntime.InferenceSession(model_path, providers=['CPUExecutionProvider'])

    width = model.get_inputs()[0].shape[1]  # 512
    height = model.get_inputs()[0].shape[2]  # 512

    image_raw = tf.io.read_file(image_path)
    image = tf.io.decode_png(image_raw, channels=3)

    image = tf.image.resize(image, size=(width, height), method=tf.image.ResizeMethod.AREA, preserve_aspect_ratio=True)
    image = image.numpy()  # EagerTensor to np.array

    image_width = image.shape[0]
    image_height = image.shape[1]

    t = skimage.transform.AffineTransform(translation=(-image_width * 0.5, -image_height * 0.5))
    t += skimage.transform.AffineTransform(translation=(width * 0.5, height * 0.5))

    image = skimage.transform.warp(image, t.inverse, output_shape=(width, height), order=1, mode='edge')

    # at this point all widths and heights are probably 512

    # normalize the image
    image = image / 255.0

    image_shape = image.shape
    # build the input shape of Vector<1, 512, 512, 3>
    image = image.reshape((1, image_shape[0], image_shape[1], image_shape[2]))
    onnx_result = model.run(None, {'input_1:0': image})
    # onnx_result is 2 arrays deep for reason
    # 1 would make sense, as it can handle batches
    onnx_result = onnx_result[0][0]

    # print a nice result
    for i, tag in enumerate(tags):
        print(f'({onnx_result[i]:05.3f}) {tag}')

if __name__ == '__main__':
    main()

Conveniently, in doing so, I made a mistake in a default value that yielded the same result as the ML.Net results: (not) Normalizing the Image. I couldn't figure out how to do that in the ML.Net pipeline, so I made the array with Magick.Net and fed it to ML.Net directly.
Here's the final code:
using ImageMagick;
using Microsoft.ML;
using Microsoft.ML.Data;

namespace OnnxTest;

public static class Program
{
    public static void Main(string[] args)
    {
        var tags = File.ReadLines(@"C:\Users\da3ds\Downloads\deepdanbooru-v3-20211112-sgd-e28\tags.txt");
        var imageLocation = @"C:\Users\da3ds\Pictures\image.jpg";
        var modelLocation = @"C:\Users\da3ds\Downloads\deepdanbooru-v3-20211112-sgd-e28\model-resnet-custom_v3.onnx";
        MLContext mlContext = new MLContext(seed: 0);

        Console.WriteLine("Read model");
        Console.WriteLine($"Model location: {modelLocation}");
        Console.WriteLine(
            $"Default parameters: image size=({InputModel.Width},{InputModel.Height})");
        Console.WriteLine($"Images location: {imageLocation}");
        Console.WriteLine("");
        Console.WriteLine("=====Identify the objects in the images=====");
        Console.WriteLine("");

        // Create IDataView from empty list to obtain input data schema
        var data = new InputModel { Data = GetImage(imageLocation) };
        // Define scoring pipeline
        var predictionEngine = GetPredictionEngine(mlContext, modelLocation);
        var output = predictionEngine.Predict(data);

        var outputMapped = tags.Zip(output.Scores).Select(t => new { Tag = t.First, f = t.Second })
            .ToDictionary(a => a.Tag, a => a.f);

        var outputTags = outputMapped.Where(a => a.Value > 0.80f).Select(a => (Tag: a.Key, Score: a.Value))
            .ToList();
        foreach (var tag in outputTags)
        {
            Console.WriteLine($"({tag.Score:P1}) {tag.Tag}");
        }
    }

    private static PredictionEngine<InputModel, OutputModel> GetPredictionEngine(MLContext mlContext, string modelLocation)
    {
        var transformer = GetBasicTransformer(mlContext, modelLocation);

        // Fit scoring pipeline
        var predictionEngine = mlContext.Model.CreatePredictionEngine<InputModel, OutputModel>(transformer);
        return predictionEngine;
    }

    private static ITransformer GetBasicTransformer(MLContext mlContext, string modelLocation)
    {
        var estimator = mlContext.Transforms.ApplyOnnxModel(OutputModel.ModelOutput, InputModel.ModelInput,
                modelLocation);

        var transformer = estimator.Fit(mlContext.Data.LoadFromEnumerable(Array.Empty<InputModel>()));
        return transformer;
    }

    public static float[] GetImage(string imagePath)
    {
        using var mImage = new MagickImage(imagePath);
        mImage.Quality = 100;
        mImage.BackgroundColor = new MagickColor(0, 0, 0);
        mImage.HasAlpha = false;
        mImage.Resize(new MagickGeometry($"{InputModel.Width}>x{InputModel.Height}>"));
        mImage.Extent(InputModel.Width, InputModel.Height, Gravity.Center, new MagickColor(0,0,0));
        var pixels = mImage.GetPixels();
        var array = pixels.ToArray();
        var data = new float[InputModel.Width * InputModel.Height * InputModel.Channels];
        for (var index = 0; index < array.Length; index++)
        {
            data[index] = array[index] / 255.0f;
        }

        return data;
    }

    class InputModel
    {
        public const int Width = 512;
        public const int Height = 512;
        public const int Channels = 3;
        public const string ModelInput = "input_1:0";

        [ColumnName(ModelInput)]
        [VectorType(1, Width, Height, Channels)]
        public float[] Data { get; set; }
    }

    class OutputModel
    {
        // output tensor name
        public const string ModelOutput = "Identity:0";

        [ColumnName(ModelOutput)]
        public float[] Scores { get; set; }
    }
}

Obviously, the final...final code will be less of an MVP, but this was a test. I leave this as a trail of my efforts in case someone else hits a similar issue. At the very least, it gives my debugging steps and some sample code. Thanks for being my rubber ducks.


text:
Q: Get count of matches using regex in Hive? I want to get the count value from a table based on regex matching.
For example, say I want to find all strings in my table that end with
"/top" and the table contains the following data:
id  url
1   example.com/top
2   example.com/index.html
3   example2.com/top

The following query seems to hit every row, instead of just two:
  select
  sum(CASE WHEN url REGEXP '.*/top' THEN 1 ELSE 0 END) as topCount,
  sum(CASE WHEN url REGEXP '.*/index.html' THEN 1 ELSE 0 END) as defaultCount
  from myTable

Any suggestions?

A: You could use the condition in where.
select count(*) from myTable where url REGEXP '.*/top$'


text:
Q: The voltage between the plates of a capacitor I have read in one book that:

the potential difference between the plates of a capacitor when it's connected to a DC source (a battery) is in opposite direction to the potential difference of that battery.

I don't really get that point, and I don't know how could this help in the break of the DC after the capacitor charges.
I used to think that when connecting a battery to a capacitor the plate connected to the positive terminal gets a positive charge and the plate connected to the negative terminal gets a negative charge. So, how will the PD be in the opposite direction to the PD of the battery? Could someone clarify it?

A: That's a somewhat confusing way of putting it. It's related to the direction you define as "the opposite direction"; here's a diagram.

simulate this circuit – Schematic created using CircuitLab
The arrows here always point from negative to positive. The left schematic shows how you might think of it as "the same direction"; the right one shows how you might think of it as "the opposite direction". Note that these two schematics are identical.

A: The capacitor charges up to the voltage of the battery and, as a result, opposes the battery's voltage sufficiently to stop any further current.
If you connect the capacitor to the battery and wait long enough (not long, really) the capacitor will be charged to a voltage very similar to the battery so that when you pull it away and remove it the polarity of the capacitor will match the battery's polarity. Here, one might see that it is the same and not opposite. But it did oppose the battery's voltage while connected, too.
It's just a matter of what you want to convey, I suppose.


text:
Q: Oracle nvl, nvl2 and nullif functions can we apply nvl or nvl2 function with nullif in oracle
please give me some example of it
i have this query that is working fine
SELECT fName, LENGTH(fName) "First Name",
       lName, LENGTH(lName) "Last Name",
       NULLIF(LENGTH(fName), LENGTH(lName)) Output
FROM employee;

but i want to apply nvl on it when it return null value whaen fName and lName have same character

A: Not sure I followed, what's wrong with:
SELECT NVL(fName,'-1'), LENGTH(fName) "First Name",
       NVL(lName,'-1), LENGTH(lName) "Last Name",
       NVL(LENGTH(fName), LENGTH(lName)) Output
FROM employee;

And what is wrong with your query? Though I don't understand why are you using NULLIF on LENGTH(fname) , its slower and it will have the same effect as NULLIF(fname)


text:
Q: Alerting items in two minipages of a frame in beamer I divided a frame into 2 parts side by side by minipage. In the first part I have 6 items and 7 items (images) in the second part (please have a look at the following).
\begin{frame}

 \frametitle{Preliminaries}

 \setbeamercolor{normal text}{fg=blue,bg=}

\setbeamercolor{alerted text}{fg=magenta,bg=}

\usebeamercolor{normal text}

 \noindent

\begin{minipage}[t]{0.58\linewidth}

\begin{enumerate}

  \item \alert<+>{some text here}

  \item \alert<+>{some text here}

  \item\alert<+>{some text here}

  \item\alert<+>{some text here}

  \item \alert<+>{some text here}

  \item \alert<+>{some text here}

 \end{enumerate}

\end{minipage}

\begin{minipage}[t]{0.35\linewidth}

\vspace*{0.25in}

\begin{center}

   \includegraphics<1>[scale=0.5]{image1}

   \includegraphics<2>[scale=0.5]{image2}

   \includegraphics<3>[scale=0.5]{image3}

   \includegraphics<4>[scale=0.5]{image4}

   \vspace*{-0.3in}

   \includegraphics<5>[scale=0.35]{image5}

   \includegraphics<6>[scale=0.35]{image6}

   \includegraphics<7>[scale=0.35]{image7}

 \end{center}

\end{minipage}

\end{frame}

Now the question is, how to keep (highlight) the color for the first item in the first part while the first two images in the second part are being displayed? and when I display the 3rd image, the second item in the first part should be highlighted, but not the 1st item and so on. How do I do this?

A: Use \alert<1-2>, \alert<3>, \alert<4> etc instead of \alert<+>.
\documentclass{beamer}
\setbeamertemplate{navigation symbols}{} % never seen anyone using these
\begin{document}
\begin{frame}{Preliminaries}
\setbeamercolor{normal text}{fg=blue,bg=}
\setbeamercolor{alerted text}{fg=magenta,bg=}
\usebeamercolor{normal text}
\begin{columns}
  \begin{column}[t]{0.58\linewidth}
  \begin{enumerate}
  \item \alert<1-2>{some text here}
  \item \alert<3>{some text here}
  \item \alert<4>{some text here}
  \item \alert<5>{some text here}
  \item \alert<6>{some text here}
  \item \alert<7>{some text here}
  \end{enumerate}
  \end{column}

  \begin{column}[t]{0.35\linewidth}
  \begin{center}
  \includegraphics<1>[scale=0.2]{example-image}
  \includegraphics<2>[scale=0.2]{example-image-a}
  \includegraphics<3>[scale=0.2]{example-image-b}
  \includegraphics<4>[scale=0.2]{example-image-c}
  \includegraphics<5>[scale=0.2]{example-image-a}
  \includegraphics<6>[scale=0.2]{example-image-b}
  \includegraphics<7>[scale=0.2]{example-image-c}
  \end{center}
  \end{column}
\end{columns}
\end{frame}
\end{document}


text:
Q: Reset a class instance to its previous state in ios I am working on a application, that read a xml file and create and init classes based on xml data.
when needed classes create UIViews based on their variables and send that to parent classes.
The hierarchy of classes is something like this: book -> page -> layer -> character -> part
I need pages reset and recreate themselves every time need to be shown but it is not possible because the inner classes like layers and character have been changed (the books are interactives)
how can i do that?

A: If you're just reverting to a previous state, then start with Undo Architecture.
When you're presenting a new object graph, it's usually easiest to initialize a new object graph rather than convert one graph to another representation.


text:
Q: Grouping data in R to perform a function Here is an example of my data:
           id   score
1          82   0.50000
2          82   0.39286
3          82   0.56250
4         328   0.50000
5         328   0.67647
6         328   0.93750
7         328   0.91667

I want to make a column of moving average's of scores for each  id.
So I need to somehow group the data by id then apply a MA function to that grouped data and then have the output as another column "MA_score"
I would like my output to look like this:
           id   score    MA_score
1          82   0.50000   NULL
2          82   0.39286   0.xxxx
3          82   0.56250   NULL
4         328   0.50000   NULL
5         328   0.67647   0.yyyy
6         328   0.93750   0.qqqq
7         328   0.91667   NULL

A: You could use split and rollapply from the zoo package as one of many ways to approach this. Note that in the example below I set the width of the rollapply function to 1 so it just returns each value. For widths greater than one it will take the mean of that number of values.
require(zoo)
sapply( split( df , df$id) , function(x) rollapply( x , width = 1 , align = 'left' , mean) )
#Note that by setting width = 1 we just return the value
$`82`
     id   score
[1,] 82 0.50000
[2,] 82 0.39286
[3,] 82 0.56250

$`328`
      id   score
[1,] 328 0.50000
[2,] 328 0.67647
[3,] 328 0.93750
[4,] 328 0.91667

If we were to set width = 3 you would get:
$`82`
     id   score
[1,] 82 0.48512

$`328`
      id     score
[1,] 328 0.7046567
[2,] 328 0.8435467

Or you could use aggregate in base R:
aggregate(  score ~ id , data = df , function(x) rollapply( x , width = 1 , align = 'left' , mean)  )
   id                              score
1  82          0.50000, 0.39286, 0.56250
2 328 0.50000, 0.67647, 0.93750, 0.91667

There are quite a few ways to do this. I would precisely define your moving average function though, because there are many ways to calculate it (check out for example TTR:::SMA)

Or more straightforward using ave:
within(df, { MA_score <- ave(score, id, FUN=function(x)
                rollmean(x, k=3, na.pad = TRUE))})

A: You could split your data by unique ID values, calculate the rolling mean (from 'zoo' package) for each of these unique IDs and append the results to your initial dataframe:
# Required packages
library(zoo)

# Data setup
df <- data.frame(id = c(82, 82, 82, 328, 328, 328, 328),
                 score = c(0.5, 0.39286, 0.5625, 0.5, 0.67647, 0.9375, 0.91667))

# Split data by unique IDs
df.sp <- split(df, df$id)

# Calculate rolling mean for each unique ID
df.ma <- lapply(seq(df.sp), function(i) {
  rollmean(df.sp[[i]]$score, k = 3, na.pad = TRUE)
})

# Append column 'MA_score' to dataframe
for (i in seq(names(df.sp))) {
  df[which(df$id == names(df.sp)[i]), "MA_score"] <- df.ma[[i]]
}

df
   id   score  MA_score
1  82 0.50000        NA
2  82 0.39286 0.4851200
3  82 0.56250        NA
4 328 0.50000        NA
5 328 0.67647 0.7046567
6 328 0.93750 0.8435467
7 328 0.91667        NA


text:
Q: Is Debugbreak() occupies memory in c++? When I want to new an object in C++, I need to consider what should I do when there is not enough memory, so I wrote the following code:
CacheHeapItem* m_Items;
try{
    m_Items = new CacheHeapItem[m_Count];
}catch(const bad_alloc& e){
    DebugBreak();
}

But I am not sure if the DebugBreak function will be executed when there is insufficient memory?

A: If you use microsoft compiler use __debugbreak() which is functionally identical to DebugBreak() winapi function.
It's unlikely that it allocates any memory, as it simply inserts __asm 3 opcode (for x86 and equivalent opcode on arm).
This is obviously not the best code for release, you may check for debugger presence and break only if IsDebuggerPresent:
CacheHeapItem* m_Items;
try{
    m_Items = new CacheHeapItem[m_Count];
}catch(const bad_alloc& e){
    if (IsDebuggerPresent())
        __debugbreak();
}

A: If you want to catch some exceptions you should configure exception filters. This way you won't need to write any special debug handling code that must be removed in release build (DebugBreak will cause process to be terminated if no debugger is present).


text:
Q: Why Customer Community Login user doesn't see one Salesforce user but sees another? BACKGROUND
We have a trigger on the FeedItem (Chatter post) which uses a helper class:
public without sharing class FeedItemTriggerHelper
{
    public static void handleAfterInsert(List<FeedItem> chatterPosts)
    {
        System.debug([SELECT Id, Email, Name FROM User Where Id = '<user1Id>']);
        System.debug([SELECT Id, Email, Name FROM User Where Id = '<user1Id>']);
    }
}

When an external user (assigned to the Customer Community Login license) leaves chatter comment on a record in our Customer Community, the above code executes and user1 is not visible - the list is empty, and details for user2 are showed.
This is awkward since both user1 and user2 has the same User Licence - Salesforce, assigned to the same role in the role hierarchy. All sharing settings are on the screenshot below:

I checked manual sharing for both users and didn't see any sharing access.
QUESTION
As you can see from the code above the without sharing keywords were used, but that didn't help. I don't understand why with the private OWD for External Sharing, one user is visible, and the other isn't?


text:
Q: What is the best package in R to plot city maps and put points on it? That's the question, best R package to plot city maps and geolocate stuff.
Thank you very much!
EDIT: Maybe I wasn't too clear, but I mean urban city maps, where you can see its streets, neighborhoods etc.

A: For visible streets and roads, you can use a package named 'ggmap' and a function named qmap() within it.
Package named 'maps'. Install that and use map.cities() function.
You can also try rMaps, this you will find under github. Its still under development. You can work with this in R or RStudio.


text:
Q: How to simplify cases given with Piecewise function? MMA gives me an answer in the form
$$ \begin{cases}
f(k_1) & k_1=k\\
0 & else
\end{cases} $$
which is obviously just $f(k)$. Can I make MMA simplify this expression to $f(k)$?
The FullForm code I get is
Piecewise[List[List[f[k1], Equal[k1, k]]], 0].
P.S. I am aware (Full)Simplify or Reduce doesn't work here since Piecewise is a function and isn't equal to $f(k)$ everywhere.


text:
Q: Listen to Swf Panel close I'm working on a project for flash pro cs and I would like to know when a Flash Pro user closes an SWF panel.
The panel needs to know before it closes and perform a function before that.
Is there a way to do this?
I know this is possible in Air but that doesn't work as a flash pro panel.
Just to clear clarify, I mean a swf panel added to flash Professional as an extension, through the WindowSWF library under "AppData\Local\Adobe\Flash CS6\en_US\Configuration".
basically, if there is no way to do it via JSFL calls, I would need to find a way to listen to the close event from within the swf itself.
Any ideas? Hacks are more then welcome...

A: Perhaps listen for the addedToStage and removedFromStage events in the child SWF and act accordingly?
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObject.html#event:addedToStage
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObject.html#event:removedFromStage


text:
Q: Creating an array from another array? New to java and am working with RLE encoding and I am trying to create a program that takes a byte array and then returns with another byte array but it takes the number of consecutive values in an array and then prints [ (number of times repeated),(value)]. Example, [ 13,13,13,3,3,3,3 ] would return [3,13,4,3]
import java.util.Arrays;

public class testing {

    public static void main(String [] args) {

        byte [] pracArray = {13,13,13,3,3,3,3};

        int count = 1;

        for (int i = 0; i <pracArray.length-1; i++)
        {
            if (pracArray[i] != pracArray[i+1])
            {
                count++;
            }
        }

        byte numLength = 1;
        byte indexNum = 0;
        int newArraySize = count*2;

        byte [] newArray = new byte [newArraySize];

        for ( int i = 0; i < pracArray.length-1; i++)
        {
            if (pracArray[i] != pracArray[i+1] )
            {
                newArray[indexNum] = numLength;
                newArray[indexNum+1] = pracArray[i];
                indexNum = (byte) (indexNum + 2);
                numLength = 1;
            }
            else
            {
                numLength++;
            }
        }
        System.out.println(Arrays.toString((pracArray)));
        System.out.println(Arrays.toString((newArray)));
    }
}

I am aware of my problem, the last run of consecutive numbers does not get printed. If I change the array to [13,13,13,3,3,3,3,1] it will print [3,13,4,3,0,0], the last sequence of numbers is never recorded so the last two values of newArray never get filled. Any ideas on how I can change my if statement to include my last sequence of numbers?

A: On the termination of the loop, check if the last element is equal to the second last element.
Your updated code will be:
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {

        byte[] pracArray = { 13, 13, 13, 3, 3, 3, 3, 1 };

        int count = 1;

        for (int i = 0; i < pracArray.length - 1; i++) {
            if (pracArray[i] != pracArray[i + 1]) {
                count++;
            }
        }

        byte numLength = 1;
        byte indexNum = 0;
        int newArraySize = count * 2;

        byte[] newArray = new byte[newArraySize];
        int i;
        for (i = 0; i < pracArray.length - 1; i++) {
            if (pracArray[i] != pracArray[i + 1]) {
                newArray[indexNum] = numLength;
                newArray[indexNum + 1] = pracArray[i];
                indexNum = (byte) (indexNum + 2);
                numLength = 1;
            } else {
                numLength++;
            }
        }
        if (pracArray[i - 1] == pracArray[i]) {
            newArray[indexNum] = numLength;
            newArray[indexNum + 1] = pracArray[i];
            indexNum = (byte) (indexNum + 2);
            numLength = 1;
        } else {
            newArray[indexNum] = numLength;
            newArray[indexNum + 1] = pracArray[i];
        }

        System.out.println(Arrays.toString((pracArray)));
        System.out.println(Arrays.toString((newArray)));
    }
}

Output:
[13, 13, 13, 3, 3, 3, 3, 1]
[3, 13, 4, 3, 1, 1]

Output for byte[] pracArray = { 13, 13, 13, 3, 3, 3, 3 } will be as follows:
[13, 13, 13, 3, 3, 3, 3]
[3, 13, 4, 3]


text:
Q: WPF user control binding two way not working but one way work correctly I have a date picker user control :
    public static readonly DependencyProperty SelectedDateProperty = DependencyProperty.Register(nameof(SelectedDate), typeof(DateTime), typeof(DateTimePicker1), new PropertyMetadata(DateTime.Now));

    public DateTime SelectedDate
    {
        get { return (DateTime)GetValue(SelectedDateProperty); }
        set
        {
            SetValue(SelectedDateProperty, value);
        }
    }

when I'm binding SelectedDate of my user control it just work in one way.
for example this is my Xaml code:
<TextBox x:Name="A2" Text="{Binding SelectedDate,ElementName=A1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"  Width="Auto"/>

<userControl:DateTimePicker1 x:Name="A1" IconType="None" Caption="تاریخ 1" Width="400" Height="100" Margin="10" />

when I change SelectedDate in my user control text of TextBox(A1) will changed correctly, but when I change text of text box (or another DateTime value) SelectedDate in my user control will not change.

A: In my test, It will update TwoWay.

My DateTimePicker1 is this:
<UserControl
    x:Class="New_folder.DateTimePicker1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="DateTimePickerControl">
    <DatePicker SelectedDate="{Binding ElementName=DateTimePickerControl, Path=SelectedDate}" />
</UserControl>


text:
Q: Where is the state stored by default if I do not configure a StateBackend? In my program I have enabled checkpointing,
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.enableCheckpointing(5000);

but I haven't configured any StateBackend.
Where is the checkpointed state stored? Can I somehow inspect this data?

A: The default state backend keeps the working state on the heaps of the various task managers, and backs that up to the job manager heap. This is the so-called MemoryStateBackend.
There's no API for directly accessing the data stored in the state backend. You can simulate a task manager failure and observe that the state is restored. And you can instead trigger a savepoint if you wish to externalize the state, though there is no tooling for directly inspecting these savepoints.

A: It's not the answer, but small addition to the correct answer. I can't write comments cause of reputation.
If you use flink version earlier then v1.5 then default state backend will MemoryStateBeckend with asynchronous snapshots set to false. So you will use synchronous saving checkpoints every 5 seconds in your case (your pipeline will block every 5 seconds for saving checkpoint).
To avoid this use explicit constructor:
env.setStateBackend(new MemoryStateBackend(maxStateSize, true));
Since flink version v1.5.0 MemoryStateBackend uses asynchronous snapshots by default.
For more information see flink_v1.4 docs


text:
Q: What is the ratio distribution of a spacing and the sample mean? Let $X_1,\dots,X_n$ be a sample of iid exponential random variables with mean $\beta$, and let $X_{(1)},\dots,X_{(n)}$ be the order statistics from this sample. Let $\bar X = \frac{1}{n}\sum_{i=1}^n X_i$.
Define spacings $$W_i=X_{(i+1)}-X_{(i)}\ \forall\ 1 \leq i \leq n-1\,.$$ It can be shown that each $W_i$ is also exponential, with mean $\beta_i=\frac{\beta}{n-i}$.
Question: How would I go about finding $\mathbb{P}\left( \frac{W_i}{\bar X} > t \right)$, where $t$ is known and non-negative?
Attempt: I know that this is equal to $1 - F_{W_i}\left(t \bar X\right)$. So I used the law of total probability like so:
$$
\mathbb{P}\left( W_i > t \bar X \right) = 1 - F_{W_i}\left( t \bar X \right) = 1 - \int_0^\infty F_{W_i}(ts)f_{\bar X}(s) \mathrm{d}s \,,
$$
which turns into a messy but I think tractable integral.
Am I on the right track here? Is this a valid use of the Law of Total Probability?
Another approach might be to look at the difference distribution:
$$
\mathbb{P}\left( W_i - t \bar X > 0\right)
$$
Or even break apart the sums:
$$
\mathbb{P}\left( W_i - t \bar X > 0 \right) = P \left( \left(X_{(i+1)} - X_{(i)}\right) + \frac{t}{n}\left(X_{(1)} + \dots + X_{(n)} \right) \right)
$$
A solution to the exponential case would be great, but even better would be some kind of general constraints on the distribution. Or at the very least, its moments, which would be enough to give me Chebyshev and Markov inequalities.

Update: here's the integral from the first method:
$$\begin{align}
1 - \int_0^\infty \left( 1 - \exp \left( -\frac{ts}{\beta_i} \right) \right) \left( \frac{1}{\Gamma(n)\beta^n} s^{n-1} \exp \left( -\beta s \right) \right) \mathrm{d}s \\
1 - \int_0^\infty \left( 1 - \exp \left( -\frac{(n-i)ts}{\beta} \right) \right) \left( \frac{1}{\Gamma(n)\beta^n} s^{n-1} \exp \left( -\beta s \right) \right) \mathrm{d}s
\end{align}$$
I've been playing around with it for a little while and I'm not sure where to go with it.

A: The difficulty you have here is that you have an event relating non-independent random variables.  The problem can be simplified and solved by manipulating the event so that it compares the independent increments.  To do this, we first note that for $X_1, ..., X_N \sim \text{IID Exp}(\beta)$, each of the order statistics can be written as:
$$X_{(k)} = \beta \sum_{i=1}^{k} \frac{Z_i}{n-i+1},$$
where $Z_1, Z_2, ..., Z_n \sim \text{IID Exp} (1)$ (see e.g., Renyi 1953, David and Nagaraja 2003).  This allows us to write $W_k = \beta Z_{k+1} / (n-k)$ and we can write the sample mean as:
$$\begin{equation} \begin{aligned}
\bar{X} \equiv \frac{\beta }{n} \sum_{k=1}^n X_{(k)} &= \frac{\beta }{n} \sum_{k=1}^n \sum_{i=1}^k \frac{Z_i}{n-i+1} \\
&= \frac{\beta }{n} \sum_{i=1}^n \sum_{k=i}^n \frac{Z_i}{n-i+1} \\
&= \frac{\beta }{n} \sum_{i=1}^n Z_i.
\end{aligned} \end{equation}$$
To facilitate our analysis we define the quantity:
$$a \equiv \frac{t(n-k)}{n-t(n-k)}.$$
For $a > 0$ we then have:
$$\begin{equation} \begin{aligned}
\mathbb{P}(W_k \geqslant t \bar{X})
&= \mathbb{P} \left( \frac{Z_{k+1}}{n-k} \geqslant \frac{t}{n} \sum_{i=1}^n Z_i \right) \\
&= \mathbb{P} \left( \frac{n}{n-k} \cdot Z_{k+1} \geqslant t \sum_{i = 1}^k Z_i \right) \\
&= \mathbb{P} \left( \left( \frac{n}{n-k} - t \right) Z_{k+1}  \geqslant t \sum_{i \neq k} Z_i \right) \\
&= \mathbb{P} \left( \left( \frac{n}{n-k} - t \right) Z  \geqslant t G \right) = \mathbb{P} \left( Z  \geqslant a G \right),
\end{aligned} \end{equation}$$
where $Z \sim \text{Exp} (1)$ and $G \sim \text{Ga}(n-1, 1)$ are independent random variables.  For the trivial case where $t \geqslant n / (n-k)$ we have $\mathbb{P}(W_k \geqslant t \bar{X}) = 0$.  For the non-trivial case where $t < n / (n-k)$ we have $a>0$, and the probability of interest is:
$$\begin{equation} \begin{aligned}
\mathbb{P}(W_k \geqslant t \bar{X}) &= \int\limits_0^\infty \text{Ga} (g| n-1, 1 )  \int\limits_{ag}^\infty \text{Exp}(z|1) dz dg \\
&= \int\limits_0^\infty \frac{1}{\Gamma{(n-1)}} g^{n-2} \exp{(-g)}  \int\limits_{ag}^\infty \exp{(-z)} dz dg \\
&= \int\limits_0^\infty \frac{1}{\Gamma{(n-1)}} g^{n-2} \exp{(-g)} \left( 1 - \exp (ag) \right) dg \\
&= \int\limits_0^\infty \frac{1}{\Gamma{(n-1)}} g^{n-2} \exp{(-g)} dg  - \int\limits_0^\infty \frac{1}{\Gamma{(n-1)}} g^{n-2} \exp{(-(a+1)g)} dg \\
&= 1 - (a+1)^{-(n-1)} \\
&= 1 - \left( 1- \frac{n-k}{n} \cdot t \right)^{n-1}.
\end{aligned} \end{equation}$$
This answer is intuitively reasonable.  This probability is strictly decreasing in $t$, with unit probability when $t=0$ and zero probability when $t = \frac{n}{n-k}$.


text:
Q: Items on Page will not Fill Page when Zooming Out When I zoom out in my browser, the items in #workspaceMain like #pagename, #toolbar, #content and #tabs will not fill the remainder of the screen space in #workspaceMain even though I have set all widths to 100%. The #workspaceMain width has been set to 70% to accommodate for the sideBar #workspaceSide on the right.
You can see when the zoom is set to 100%, it looks completely normal, when the zoom is set at 75% for example, the items will not fill the remainder white space.
How would I be able to fix this error.

Code:

/*
    ~ Copyright (c) Summit Learning Management System (made by students, for students). 2019.
*/

html > body {
    height: 100%;
    overflow: hidden;
    font-family: "Trebuchet MS", sans-serif;
}

#wrapper {
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    position: absolute;
    overflow: hidden;
    background: #FFF;
}

#navigation {
    height: 100%;
    width: 40px;
    float: left;
    position: relative;
    background: #1B315E;
}

#navigation > a {
    display: block;
    margin: 12px 0 12px 4px;
    padding: 12px 0;
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
    text-align: center;
    font-size: 18pt;
    color: #FFF;
}

#navigation > a.current {
    background: #FFF;
    color: #1B315E;
}

#navigation > a:not(.current):hover {
    background: #FFF;
    opacity: 0.75;
    color: #1B315E;
}

#navigation > .navLinks {
    bottom: 40px;
    position: absolute;
    left: 2px;
}

#navigation > .navLinks > button {
    margin: 0 0 8px 0;
    cursor: pointer;
    background: none;
    outline: none;
    border: none;
    color: #FFF;
    font-size: 14pt;
}

.buffer {
    display: block;
    margin: 0 0 120px 0;
}

#workspaceMain {
    float: left;
    height: 100%;
    width: 70%;
    position: relative;
    border: 2px solid #FFF;
    background: #FFF;
}

#pagename {
    float: left;
    width: 100%;
    font-size: 14pt;
    color: #1B315E;
    background: #FFF;
}

#toolbar {
    width: 100%;
    background: #CCC;
    border-bottom: 2px solid #BBB;
}

#toolbar > .toolLinks {
    cursor: pointer;
    background: none;
    border: none;
    outline: none;
    padding: 4px 4px;
    margin: 0 0 0 4px;
    font-size: 10pt;
    color: #1B315E;
    text-transform: uppercase;
}

#content {
    position: relative;
    overflow-y: scroll;
    height: 100%;
    width: 100%;
}

[contenteditable]:focus {
    outline: 0px solid transparent;
}

.mainHeader {
    text-align: center;
    text-transform: uppercase;
    color: #1B315E;
}

.gridSet {
    width: 100%;
    font-size: 12pt;
    color: #1B315E;
}

.gridName {
    text-align: center;
    font-weight: bold;
}

table, th, td {
    border-collapse: collapse;
    border: 1px solid #1B315E;
}

table, th {
    background: #1B315E;
    text-align: center;
    color: #FFF;
    width: 50%;
}

table, tr {
    background: #BBB;
    color: #1B315E;
}

td {
    text-align: left;
    padding: 12px;
}

#tabs {
    position: fixed;
    bottom: 0;
    width: 70%;
    height: 30px;
    overflow: hidden;
    background: #CCC;
    border-top: 2px solid #BBB;
}

#tabs > a {
    float: left;
    display: block;
    padding: 4px 4px;
    margin: 0 0 0 4px;
    text-align: center;
    text-decoration: none;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    font-size: 10pt;
    color: #1B315E;
    text-transform: uppercase;
}

#tabs > a.current {
    background: #FFF;
    color: #1B315E;
}

#tabs > a:not(.current):hover {
    background: #FFF;
    opacity: 0.75;
    color: #1B315E;
}

#workspaceSide {
    margin: 0 0 0 70%;
    height: 100%;
    width: 340px;
    top: 0;
    right: 0;
    float: right;
    position: absolute;
    overflow: hidden;
    background: #1B315E;
}

#tabsPanel {
    position: fixed;
    float: right;
    right: 0;
    bottom: 0;
    width: 336px;
    height: 30px;
    overflow: hidden;
    background: #CCC;
    border-top: 2px solid #BBB;
}

#tabsPanel > button {
    cursor: pointer;
    background: none;
    outline: none;
    border: none;
    display: block;
    padding: 4px 8px;
    margin: 0 auto;
    text-align: center;
    text-decoration: none;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    font-size: 10pt;
    color: #1B315E;
}

#tabsPanel > button.current {
    background: #FFF;
    color: #1B315E;
}

.infoPanel {
    width: 336px;
    height: calc(100vh - 32px);
    float: right;
    position: relative;
    right: 0;
    top: 0;
    overflow: hidden;
}

.infoPanel > iframe {
    width: 100%;
    height: calc(100vh - 32px);
    top: 0;
    right: 0;
}
<!DOCTYPE HTML>

    <title>Welcome — Summit</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">
    <link rel="stylesheet" href="../style.css" type="text/css">

        <button title="Quick Links"></button>
        <button title="Sign Out"></button>

 Welcome

            <button class="toolLinks" title="Save Changes"> Save</button>
            <button class="toolLinks" title="Print This Page"> Print</button>

School

Weekly Outline

Date	Outline

             Notices
             Dashboard
             Timetable
             Welcome

            <button class="current" title="Summit News"></button>

Any Help is Appreciated.
Thanks, Tom

A: I have edited your CSS and solved your problem using flex properties of CSS. Please compare your CSS code and this new one, you will get idea.
Using display: flex; or display: table;, you can achieve this kind of results.
To know more about these, refer https://www.w3schools.com/css/css3_flexbox.asp

/*
~ Copyright (c) Summit Learning Management System (made by students, for students). 2019.
*/

/*
    ~ Copyright (c) Summit Learning Management System (made by students, for students). 2019.
*/

html > body {
    height: 100%;
    overflow: hidden;
    font-family: "Trebuchet MS", sans-serif;
    margin: 0;
    padding: 0;
}

#wrapper {
    width: 100%;
    height: 100vh;
    overflow: hidden;
    background: #FFF;
    display: flex;
    align-items: stretch;
}

#navigation {
    height: 100%;
    max-width: 45px;
    float: left;
    background: #1B315E;
}

#navigation > a {
    display: block;
    margin: 12px 0 12px 4px;
    padding: 12px 0;
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
    text-align: center;
    font-size: 18pt;
    color: #FFF;
}

#navigation > a.current {
    background: #FFF;
    color: #1B315E;
}

#navigation > a:not(.current):hover {
    background: #FFF;
    opacity: 0.75;
    color: #1B315E;
}

#navigation > .navLinks {
    bottom: 40px;
    position: absolute;
    left: 2px;
    display: grid;
}

#navigation > .navLinks > button {
    margin: 0 0 8px 0;
    cursor: pointer;
    background: none;
    outline: none;
    border: none;
    color: #FFF;
    font-size: 14pt;
}

.buffer {
    display: block;
    margin: 0 0 120px 0;
}

#workspaceMain {
    border: 2px solid #FFF;
    background: #FFF;
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    align-content: stretch;
}

#pagename {
    float: left;
    width: 100%;
    font-size: 14pt;
    color: #1B315E;
    background: #FFF;
}

#toolbar {
    width: 100%;
    background: #CCC;
    border-bottom: 2px solid #BBB;
}

#toolbar > .toolLinks {
    cursor: pointer;
    background: none;
    border: none;
    outline: none;
    padding: 4px 4px;
    margin: 0 0 0 4px;
    font-size: 10pt;
    color: #1B315E;
    text-transform: uppercase;
}

#content {
    overflow-y: scroll;
    width: 100%;
    flex-grow: 1;
}

[contenteditable]:focus {
    outline: 0px solid transparent;
}

.mainHeader {
    text-align: center;
    text-transform: uppercase;
    color: #1B315E;
}

.gridSet {
    width: 100%;
    font-size: 12pt;
    color: #1B315E;
}

.gridName {
    text-align: center;
    font-weight: bold;
}

table, th, td {
    border-collapse: collapse;
    border: 1px solid #1B315E;
}

table, th {
    background: #1B315E;
    text-align: center;
    color: #FFF;
    width: 50%;
}

table, tr {
    background: #BBB;
    color: #1B315E;
}

td {
    text-align: left;
    padding: 12px;
}

#tabs {
    width: 100%;
    height: 30px;
    overflow: hidden;
    background: #CCC;
    border-top: 2px solid #BBB;
}

#tabs > a {
    float: left;
    display: block;
    padding: 4px 4px;
    margin: 0 0 0 4px;
    text-align: center;
    text-decoration: none;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    font-size: 10pt;
    color: #1B315E;
    text-transform: uppercase;
}

#tabs > a.current {
    background: #FFF;
    color: #1B315E;
}

#tabs > a:not(.current):hover {
    background: #FFF;
    opacity: 0.75;
    color: #1B315E;
}

#workspaceSide {
    height: 100%;
    min-width: 340px;
    top: 0;
    right: 0;
    float: right;
    overflow: hidden;
    background: #1B315E;
}

#tabsPanel {
    position: fixed;
    float: right;
    right: 0;
    bottom: 0;
    width: 336px;
    height: 30px;
    overflow: hidden;
    background: #CCC;
    border-top: 2px solid #BBB;
}

#tabsPanel > button {
    cursor: pointer;
    background: none;
    outline: none;
    border: none;
    display: block;
    padding: 4px 8px;
    margin: 0 auto;
    text-align: center;
    text-decoration: none;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    font-size: 10pt;
    color: #1B315E;
}

#tabsPanel > button.current {
    background: #FFF;
    color: #1B315E;
}

.infoPanel {
    width: 336px;
    height: calc(100vh - 32px);
    float: right;
    position: relative;
    right: 0;
    top: 0;
    overflow: hidden;
}

.infoPanel > iframe {
    width: 100%;
    height: calc(100vh - 32px);
    top: 0;
    right: 0;
}
<!DOCTYPE HTML>

    <title>Welcome — Summit</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">
    <link rel="stylesheet" href="../style.css" type="text/css">

        <button title="Quick Links"></button>
        <button title="Sign Out"></button>

 Welcome

            <button class="toolLinks" title="Save Changes"> Save</button>
            <button class="toolLinks" title="Print This Page"> Print</button>

School

Weekly Outline

Date	Outline

             Notices
             Dashboard
             Timetable
             Welcome

            <button class="current" title="Summit News"></button>


text:
Q: Compare multiple JSON responses with JMeter I need to convince JMeter to do an A/B comparison on JSON web service request responses. The challenge I'm facing is that the responses might have the same contents but still not be the same.
Example response1:
[
    {
        "id": 1,
        "name": "Canada",
        "provinceNames": [
            "Alberta",
            "British Columbia"
        ]
    },
    {
        "id": 2,
        "name": "United States",
        "provinceNames": [
            "California",
            "New York"
        ]
    }
]
This response is fully sorted "id", "name", "provinceNames" and within the provinceNames, "Alberta", "British Columbia" and respectively "California", "New York" are sorted as well.
Example response2:
[
    {
        "name": "United States",
        "provinceNames": [
            "New York",
            "California"
        ],
        "id": 2
    },
    {
        "name": "Canada",
        "provinceNames": [
            "British Columbia",
            "Alberta"
        ],
        "id": 1
    }
]
This response is not sorted.
The two responses have equal contents even though they are not the same.
Has anyone ever had this problem before and has a solution for it?
My approach was to post-process the response, sort the JSON objects, and compare them. Up to now, I couldn't figure out a way neither in javascript nor in beanshell. I found some solutions to similar problems but they use JQuery or other libraries not available in JMeter.
Firstly, I'd like to know whether I'm even on the right track with this approach, or does anyone figured out a much more elegant solution?
Secondly, if this approach is ok, does anyone have any code snippets either in javascript / beanshell I could use in JMeter?
Thank you for all your help :)

A: There are several options available:

*

*Use JSONPath Extractor to extract individual values like name, provinceNames, etc., store them to JMeter Variables and compare the variables

*Use JSON Path Assertion for the same

*Use Beanshell PostProcessor to convert JSON response into a sorted string and compare the strings. Example Beanshell code to do it will look like:
String response = prev.getResponseDataAsString();
char [] responseCharArray = response.toCharArray();
Arrays.sort(responseCharArray);
response = Arrays.toString(responseCharArray);
prev.setResponseData(response.getBytes());

where prev is the instance of SampleResult class holding parent sampler result details.
Above code will override original sampler response with original response split into chars, sorted using Dual-Pivot Quicksort and again put back.
If the data is the same in both cases, result string entities will also be the same.
To learn more about enhancing your tests with scripting refer to How to use BeanShell: JMeter's favorite built-in component guide.


text:
Q: Inline formsets Django Olá, sou até que experiente em django mas estou tendo um erro que não estou conseguindo resolver, bom o erro é o seguinte, tenho um inlineformset_factory e quando vou salvar ele não salva e diz que is_valid é falso, já fiz de tudo mas a função não funciona.
view.py
@login_required(login_url="/login/")
def cadastro_movimentacao_produtos(request):
    nivel = permissao(request)
    nome_empresa = consulta_nome_empresa(request)

    empresa = consulta_usuario(request)

    produtos = Produtos.objects.filter(empresa=empresa)

    ItensMovProdutosFormset = inlineformset_factory(MovimentacaoProdutos, ItensMovProdutos, extra=1, form=ItensMovProdutosForm)

    if request.method == 'POST':

        data_mov = request.POST['data_mov']

        form = MovimentacaoProdutosForm(request.user, request.POST)
        formset = ItensMovProdutosFormset(request.POST)
        print(formset.is_bound)
        if form.is_valid() and formset.is_valid():
            form.save()
            last_mov = MovimentacaoProdutos.objects.latest('id')

            for inline_form in formset:
                if inline_form.cleaned_data:

                    produto_form = inline_form.save(commit=False)
                    produto_form.question = ItensMovProdutos
                    produto_form.save()

            messages.success(request, 'Movimentação de produtos cadastrado com sucesso!')

            user = request.user.id

            obj_mov = MovimentacaoProdutos.objects.filter(id=last_mov.id)

            obj_mov.update(usuario_id=user)

            return HttpResponseRedirect('/lista-movimentacao-produtos/')

        else:
            print(form.errors, 'Comum form')
            print(formset.errors, 'Formset')

    else:
        form = MovimentacaoProdutosForm(request.user)
        formset = ItensMovProdutosFormset()

    perm = permissao(request)
    if perm >= 2:
        return render(request, 'cadastros/cadastro-mov-produto.html', locals())
    else:
        return render(request, 'verificacao/no-access.html', locals())

JS e HTML

    {% for forms in formset %}

Produto

            {% for campo in forms.visible_fields %}

                        {% for hidden in forms.hidden_fields %}
                            {{ hidden }}
                        {% endfor %}
                            {{ campo.errors.as_ul }}
                            {{ campo|as_crispy_field }}

            {% endfor %}

    {% endfor %}

Form
class ItensMovProdutosForm(forms.ModelForm):

    status = forms.ChoiceField(label='Status', required=False, choices=[
            (0, 'Ativo'),
            (1, 'Desativo'),
        ])

    motivos = forms.CharField(label='Motivo')
    class Meta:
        model = ItensMovProdutos

        fields = ['empresa', 'produto', 'qtde', 'vlr_unit', 'total', 'status', 'motivos']

        exclude = ['movimentacaoprodutos', 'usuario']

Model
class ItensMovProdutos(models.Model):

    empresa = models.ForeignKey("EmpresaFilial", on_delete=models.CASCADE, null=True)
    produto = models.ForeignKey("Produtos", on_delete=models.CASCADE, null=True)
    movimentacaoprodutos = models.ForeignKey("MovimentacaoProdutos", on_delete=models.CASCADE, null=True)
    usuario = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    motivos = models.TextField(u'Motivos', max_length=70, null=True)
    qtde = models.DecimalField(u'Quantidade', max_digits=8, decimal_places=2, null=True)
    vlr_unit = models.DecimalField(u'Valor Unitário', max_digits=8, decimal_places=2, null=True)
    total = models.DecimalField(u'Total', max_digits=8, decimal_places=2, null=True)
    status = models.IntegerField(u'Status', null=True)

    class Meta:
        ordering = ['produto']

    def __str__(self):
        return str(self.produto)

A: Bom depois de muito pesquisar acabei descobrindo o problema, e é o seguinte, o formset precisa que você referencie ele como management_form então é só adicionar {{ formset.management_form }} antes do loop de repetição do seu formset.
{{ formset.management_form }} <--Desta forma-->
{% for forms in formset %}

Produto

            {% for campo in forms.visible_fields %}

                  {% for hidden in forms.hidden_fields %}
                      {{ hidden }}
                  {% endfor %}
                  {{ campo.errors.as_ul }}
                  {{ campo|as_crispy_field }}

              {% endfor %}

{% endfor %}


text:
Q: Why is my output not as expected? Java ACM For the following program I am expecting output as:
5 * 2^3 = 40
But the output is:
40 * 2^0 = 40
First I build a class "HandyInt":
/**
* An integer that provides arithmetic operations for great glory.
*/
public class HandyInt {

/** The integer represented by an instance of this class. */
private int theInt;

/**
 * Constructs a new handy integer representing the given int.
 *
 * @param theInt
 *            the integer to be represented by this instance.
 */
public HandyInt(int theInt) {
    this.theInt = theInt;
}

/**
 * Constructs a new handy integer representing the integer represented by
 * the given handy integer.
 *
 * @param handyInt
 *            the handy integer to intialize the new object with.
 */
public HandyInt(HandyInt handyInt) {
    this.theInt = handyInt.theInt;
}

/**
 * Returns the integer represented by this instance.
 *
 * @return the represented integer.
 */
public int getInt() {
    return theInt;
}

/**
 * Returns a handy integer that represents the sum of this and the other
 * handy integer.
 *
 * @param other
 *            the handy integer to add.
 * @return sum of the two handy integers.
 */
public HandyInt add(HandyInt other) {
    theInt += other.theInt;
    return this;
}

/**
 * Returns a handy integer that represents the result of subtracting the
 * other integer from this one.
 *
 * @param other
 *            the handy integer to subtract from this one.
 * @return difference of the two handy integers.
 */
public HandyInt sub(HandyInt other) {
    theInt -= other.theInt;
    return this;
}

@Override
public String toString() {
    return Integer.toString(theInt);
 }
}

And when I build a public run code, that build on my class "HandyInt":
import acm.program.ConsoleProgram;

public class ComplexMathSolver extends ConsoleProgram {
@Override
public void run() {
    HandyInt factor = new HandyInt(5);
    HandyInt exp = new HandyInt(3);

    HandyInt result = multiplyWithPowerOfTwo(factor, exp);

    println(factor + " * 2^" + exp + " = " + result);
}

/**
 * Returns the result of multiplying {@code factor} with 2 to the power of
 * {@code exp}.
 *
 * @param factor
 *            the handy integer to multiply with the power.
 * @param exp
 *            the exponent of the power.
 * @return the result of the multiplication.
 */
private HandyInt multiplyWithPowerOfTwo(HandyInt factor, HandyInt exp) {
    HandyInt one = new HandyInt(1);

    while (exp.getInt() > 0) {
        factor = factor.add(factor);
        exp = exp.sub(one);
    }

    return factor;
 }
}

What is wrong in my class "HandyInt" to fix the output?
Thank you!

A: Objects are mutating, because when you called multiplyWithPowerOfTwo() method  you changed the internals of the objects factor and exp. Also, your result is pointing to the same object as factor.


text:
Q: How to use FlywayDB without align databases with Production dump? I'd like to start using a flyway to keep our different db environments synced.
The problem I have is that we can't align all the environments using a Prod dump on test and dev since our Prod env contains sensitive data that testers and developers can't access.
I understand that to start using flyway on an existing environment the steps are:

*

*Create Prod dump

*Execute Flyway Init

*Align Test with prod dump

*Execute Flyway Clean on Dev

*Execute prod dump on Dev

*Start using flyway migration normaly

I based on Axel Fontaine's video on minute 32:00 maybe there is another way to achieve this. So the question is how can I do to use flyway without using a production dump? Any help or idea?

A: As as I said in the talk, dump the structure and the reference data. These are the things you will be managing using Flyway. The application data doesn't need to be dumped.
What you want is the structure and the reference data to be in sync, not the application data.


text:
Q: Build PJMEDIA (pjsip library) for Android I'm trying to build pjmedia for Android.
From pjsip library (http://www.pjsip.org/).
I've followed official tutorial (https://trac.pjsip.org/repos/wiki/Getting-Started/Android#OtherAndroidprojects)
1.Created config_site.h with next configuration:
define PJ_CONFIG_ANDROID 1
include <pj/ config_site_sample.h>

2.Specified path to NDK
export ANDROID_NDK_ROOT=/path_to_android_ndk_dir

3.Run android configurations and do make
./configure-android
make dep && make clean && make

I've got builded pjmedia libraries in /pjmedia/lib directory
libpjmedia-arm-unknown-linux-androideabi.a
libpjmedia-audiodev-arm-unknown-linux-androideabi.a
libpjmedia-codec-arm-unknown-linux-androideabi.a
libpjmedia-videodev-arm-unknown-linux-androideabi.a
libpjsdp-arm-unknown-linux-androideabi.a

And questions:

*

*How should I use only pjmedia in Android app?

*Where is JNI for pjmedia?

*Should I create JNI .cpp wrapper by myself (with SWIG) and build it with pjmedia libraries into single library?

*How to generate JNI with SWIG only for pjmedia?
I'm just little bit confused. They give me pjsua example with JNI and library but I don't want pjsua I need pjmedia!
I just don't know how can I use it in Android.
OS: OS X Yosemite
NDK: v9d x86
Help me somebody please! :)
Thanks!


text:
Q: What could cause this pyomo error: "ERROR: evaluating object as numeric value"? Very occasionally I get this error when running pyomo: "ERROR: evaluating object as numeric value: 0.0". It looks a little like the error that results when some solvers return, for example, 0.0 instead of 0 and this then leads to an error when re-using the results with the, for example, within=Binary keyword argument of the Var function. I don't believe this is the case here. Can anyone give me some ideas as to what may cause this error? I was using glpk at the time.
Here's some more info. I'm solving an optimisation problem sequentially, a day at a time. So the solution from yesterday becomes an input to today's problem. Here are some simplified code spinets:
results = manager.solve(instance, kwargs...)
instance.solutions.load_from(results)
states_dict = get_next_states(instance, time, args...)

def get_next_states(instance, time, args...):
    states_dict = {}
    for state in states:
        var = getattr(instance, state)
        for a in a_list:
            value = var[a, time].value
            states_dict[state, a] = force_domain(value, integer, tolerance)
    return states_dict

force_domain forces value to be integer and/or nonnegative, depending on the integer and tolerance arguments. The code fails when evaluating force_domain; sometimes with the above error, and sometimes with a TypeError exception: TypeError: unorderable types: NoneType() < int(). Here's force_domain:
def force_domain(x, integer, nonnegative):
    y = x
    if x < 0 and nonnegative:
        y = chop_tiny(y, nonnegative)
    if integer:
        y = round_if_int(y)
    return y

def chop_tiny(x, tol):
    if abs(x) > tol or isinstance(x, int):
        return x
    else:
        return 0.0

def round_if_int(x):
    if isinstance(x, float) and (x).is_integer():
        return int(x)
    else:
        return x

These errors occur in less than 1 in 2000 runs.
Does this extra info help you to answer my question?

A: I've managed to isolate and reproduce the error. It turns out to be due to numerical instability in GLPK v4.57 that resulted in a crash. This numerical instability appears to have been fixed in GLPK v4.60. See https://lists.gnu.org/archive/html/info-gnu/2016-04/msg00000.html.


text:
Q: Alternatives to XDialog Are there any alternatives to XDialog?
Ideally something that would support both X server and terminal interface.

A: Zenity - GTK-based, neat, relatively lightweight (if you already have GTK pulled in by other programs, that is).


text:
Q: URL Encoding - Illegal Character Replacement I am doing some URL redirections in a project that I am currently working on. I am new to web development and was wondering what the best practise was to remove any illegal path characters, such as '-? etc.
I'm hoping I don't have to resort to manually replacing each character with their encoded URLs.
I have tried UrlEncode and HTMLEncode, but UrlEncode doesn't cater for the ? and HTMLEncode doesn't cater for '
E.g. If I was to use the following:
Dim name As String = "Dave's gone, why?"
Dim url As String = String.Format("~/books/{0}/{1}/default.aspx", bookID, name)

Response.Redirect(url)

I've tried wrapping URL like this:
Dim encodedUrl As String = Server.UrlEncode(url)

And
Dim encodedUrl As String = Server.HTMLEncode(url)

A: The specification for URLs (RFC 1738, Dec. '94) poses a problem, in that it limits the use of allowed characters in URLs to only a limited subset of the US-ASCII character set:

"...Only alphanumerics [0-9a-zA-Z],
  the special characters "$-_.+!*'(),"
  [not including the quotes - ed], and
  reserved characters used for their
  reserved purposes may be used
  unencoded within a URL."

So I think you need to worry about ?, and on my system
URL Encode; converts: %7e%2fbooks%2f1%2fDave's+gone%2c+why%3f%2fdefault.aspx
Now, are you using any url rewriting into this??

A: Try following,
String.Format("~/books/{0}/{1}/default.aspx", bookID, Server.UrlEncode(name))

String.Format("~/books/{0}/{1}/default.aspx", bookID,
    Server.UrlEncodeComponent(name))

I think its HttpUtility.UrlEncodeComponent , please see msdn for further information.


text:
Q: How to retrieve and modify HTML content from WebView with Http Post I'm developing an android app that shows some part of a HTML page. For the first step, I use this code provided in question How to retrieve HTML content from WebView.

*

*Full html picture

*

*That part i want to show

/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface
{
    @SuppressWarnings("unused")
    public void processHTML(String html)
    {
        // process the html as needed by the app
    }
}

final WebView browser = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);

/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");

/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url)
    {
        /* This call inject JavaScript into the page which just finished loading. */
        browser.loadUrl("javascript:window.HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
    }
});

/* load a web page */
browser.loadUrl("http://example.com/gethtml.html");

but when a user click on a button in second picture a HTTP post method will be called and this will be the result HTML

my question is how retrieve and modify the Post Result Html before showing to user? and show something like this

A: A simple solution could be to inject custom css code inside your webview, changing the style of the HTML element you want to display "alone".
You should inject a css like this:
#central-box {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 100%;
    // depends on the structure of the page
}

See also in this answer for an example of how to do it.

A: There are at least three ways to do this that I can think of and you're really close to all of them:

*

*You already have a rough idea of the quick and dirty method, from @lifeisfoo, although to handle both GET and POST pre-API 21 you would need to use onPageCommitVisible(WebView view, String url).  As onPageFinished(WebView view, String url) and shouldOverrideUrlLoading (WebView view, String url) only trigger on GET requests.

Here's why, straight from the SDK...
..."onPageCommitVisible callback can be used to determine the point at which it is safe to make a recycled WebView visible, ensuring that no stale content is shown. It is called at the earliest point at which it can be guaranteed that onDraw(Canvas) will no longer draw any content from previous navigations. The next draw will display either the background color of the WebView, or some of the contents of the newly loaded page." it's called on all content updates POST or GET.

*Slightly better, you can create a local proxy web page with the javascript interface and other fun bits already in place and stored as a resource, if the content you want is loaded into full-window iframe you can get really good control, you can interact with your proxy using onPageFinished since it's in an iframe you can interact with the target page using onLoadResource, handle interception using the old shouldInterceptRequest which returns a WebResourceResponse and deal with POST driven updates using onFormResubmission.

*Finally, If API support earlier than 21 isn't a big issue the best method would be to use the new shouldInterceptRequest which takes the new WebResourceRequest object that allows you to specify different handling for different request types.
Here's the API Links for the new WebResourceRequest object and the new shouldInterceptRequest method on the WebViewClient...
http://developer.android.com/reference/android/webkit/WebResourceRequest.html
http://developer.android.com/reference/android/webkit/WebViewClient.html#shouldInterceptRequest(android.webkit.WebView, android.webkit.WebResourceRequest)
hope that helps :)


text:
Q: Which layout to use for a 2x2 image-based menu? I am trying to create a screen (in portrait mode) that shows 4 images (same size, intended to scale down to fit screen), taking up the entire screen, breaking up the screen into quadrants (a tall, 2x2 grid).  This will act as a main menu type of activity and each image should be clickable, in order to take the user to a different activity.
I have tried using a GridView inside a LinerLayout (using a lot from Google's GridView tutorial) but cannot get the images to all scale properly to fill the entire screen.  I get extra margins around the images and/or scrolling of the entire screen.
I have also tried using a TableLayout, placing 2 images in each of the 2 rows.  Visually, that worked perfectly.  Unfortunately when using that, I cannot seem to reference the ImageView items in the TableLayout in my activity code (findViewById always returns null).
I feel like a TableLayout is really not the "right thing to do" but I would like to hear what others have to say.  Either way, what should be done to accomplish my desired functionality?
Thanks.
Edit 1.1:
The relative layout works much better for getting things lined up.  Now I'm just left with the issue where findViewById always returns null.  Here is my code so far:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:background="@color/homescreen_bgcolor"
        >
    <ImageView id="@+id/one"
               android:layout_alignParentTop="true"
               android:layout_alignParentLeft="true"
               android:src="@drawable/item1"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"/>
    <ImageView id="@+id/two"
               android:layout_alignParentTop="true"
               android:layout_alignParentRight="true"
               android:src="@drawable/item2"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"/>
    <ImageView id="@+id/three"
               android:layout_alignParentBottom="true"
               android:layout_alignParentLeft="true"
               android:src="@drawable/item3"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"/>
    <ImageView id="@+id/four"
               android:layout_alignParentBottom="true"
               android:layout_alignParentRight="true"
               android:src="@drawable/item4"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"/>
    </RelativeLayout>

public class HomeScreenActivity2 extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.homescreen2);

    ImageView imageView = (ImageView) findViewById(R.id.one);

    imageView.setClickable(true);
    imageView.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        Log.i("Test", "test");
      }
    });
  }
}

A: Here is a sample layout showing how you can achieve a 2 X 2 grid that covers the entire screen using just a RelativeLayout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<View
    android:id="@+id/centerVerticalShim"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_centerVertical="true"
    android:visibility="invisible" />

<View
    android:id="@+id/centerHorizontalShim"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:visibility="invisible" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/centerVerticalShim"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_toLeftOf="@+id/centerHorizontalShim"
    android:background="#42A5F5"
    android:gravity="center"
    android:text="@string/one"
    android:textColor="#FFFFFF" >
</TextView>

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/centerVerticalShim"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/centerHorizontalShim"
    android:background="#EF5350"
    android:gravity="center"
    android:text="@string/two"
    android:textColor="#FFFFFF" >
</TextView>

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/centerVerticalShim"
    android:layout_toLeftOf="@+id/centerHorizontalShim"
    android:background="#66BB6A"
    android:gravity="center"
    android:text="@string/three"
    android:textColor="#FFFFFF" >
</TextView>

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/centerVerticalShim"
    android:layout_toRightOf="@+id/centerHorizontalShim"
    android:background="#5C6BC0"
    android:gravity="center"
    android:text="@string/four"
    android:textColor="#FFFFFF" >
</TextView></RelativeLayout>

The above layout results in this:

A: I think a TableLayout could work for you, but I'd recommend trying out RelativeLayout as well. You can basically pin your images to the four quadrants by using combinations of
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"`

on your images.
I'm doing something similar in my app where I have multiple buttons on a homepage that can launch corresponding activities.  RelativeLayout works fine, and it avoids nested Layout objects, which can hamper performance during render and layout procedures (if it gets out of hand).


text:
Q: iPad SplitViewController Show Popover programmatically I have an iPad SplitViewController application in which I hide the left pane in both portrait and landscape modes.  I need to show the left pane in its popover when a certain notification is received by the application.  Despite experimenting with a number of different suggested solutions I am struggling to work out how to achieve this.
I am using a MultipleMasterDetailManager implementation that includes the following code:
/* forward the message to the current detail view
 * all detail views must implement UISplitViewControllerDelegate
 */
-(void)splitViewController:(UISplitViewController *)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController:(UIPopoverController *)pc
{
    self.masterBarButtonItem = barButtonItem;
    self.masterPopoverController = pc;

    barButtonItem.title = NSLocalizedString(@"Show Sidebar", @"Show Sidebar");

    [self.currentDetailController.navigationItem setLeftBarButtonItem:self.masterBarButtonItem animated:YES];
}

/* forward the message to the current detail view
 * all detail views must implement UISplitViewControllerDelegate
 */
-(void)splitViewController:(UISplitViewController *)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
    //if (![self.currentDetailController isKindOfClass:[SyncSourceDetailViewController class]])
    //{
        self.masterBarButtonItem = nil;
        self.masterPopoverController = nil;

        [self.currentDetailController.navigationItem setLeftBarButtonItem:nil animated:YES];
    //}
}

Similar methods exist in the detail view controllers themselves.
The method that I'm calling when the notification is received is as follows:
- (void)navigateToLatest
{
        [self navigateToDocumentsTab];
        [[self dataLoader] navigateToLatest];  // populates data for the left table view
        UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
        UIView *view = [[[[[splitViewController viewControllers] objectAtIndex:1] viewControllers] objectAtIndex:0] view];

        [self.masterDetailManager.masterPopoverController presentPopoverFromRect:CGRectMake(0, 0, 100, 100) inView:view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

This does not work.  I've also tried using the presentPopoverFromBarButtonItem method but I cannot seem to locate the leftBarButtonItem in code.
Maybe I am going about this completely the wrong way.

A: I ended up solving this problem by setting a "showSidebar" variable in my app delegate to true in the navigateToLatest method. Then in my DetailViewController's ViewDidAppear event I check the value of this variable, if it is true then I show the sidebar using the following code:
UIPopoverController *masterPopoverController= [[theAppDelegate masterDetailManager] masterPopoverController];
        [masterPopoverController presentPopoverFromBarButtonItem:[self.navigationItem leftBarButtonItem] permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        [theAppDelegate setShowSidebar:NO];


text:
Q: jquery populate json data for radio buttons i have an edit form with input fields and radio buttons, as page is loaded a function retrieves data via json to fill those fields and edit them.
i have no problem with input fields, i get the data to fill them this way:
var fields =  $("#name").val(element.name);$("#surname").val(element.surname);

the problem is when i try to get the value for a radio button group, like
  <input type="radio" name="sex" value="H" id="sex_0" />
  <input type="radio" name="sex" value="M" id="sexo_1" />

how can i put the right radio button checked based on the json data retrieved?
many thanks!

A: Not knowing what your JSON looks like, generally speaking this is how you check and uncheck a radio box or check box.
//Check a radio button
$('#sex_0').attr('checked', 'checked');

//Uncheck a radio button
$('#sexo_1').removeAttr('checked');

PS - bipen's solution is probably closer to what you're looking for, though.

A: Use val() itself, though you need to make sure of selector you use
 $('input[name="sex"]').val('H'); //json return value here.


text:
Q: Cross platform app in Windows 7 using Visual Studio Goal: to develop cross platform app for Android, Windows and iOS.
I have Visual Studio 2015 and Windows 7 including the Xamarin platform.
Problem is that when I create a new project with a blank app (Xamarin.forms portable), it doesn't create project for Windows phone. And when I create blank app (Xamarin.forms shared), it throws the following error:
This computer must be upgraded to windows 8.1 to load this project.

What do I have to do to create a cross platform app (that works on Android, iOS, Windows Phone) using Windows 7 and Visual Studio 2015.

A: You are getting error for Windows Phone project because Visual Studio(not Xamarin) doesn't support WP8/8.1 development on Windows 7 out of the box. Google "WP8 SDK on Windows 7".

A: WP 8.1 SDK is required window 8.1 or later. Then the best solution is upgrade your OS to Window 8.1


text:
Q: org.openqa.selenium.UnsupportedCommandException: Variable Resource Not Found using Selenium I am using the phantomjs webdriver using selenium protocol to render the webpage.When I try to render the webpage ,I am getting the following error in
RemoteWebDriver.get(url)

method eventhough my webdriver is running.
I have also tried restarting the phantomjs webdriver.
org.openqa.selenium.UnsupportedCommandException: Variable Resource Not Found - {"headers":{"Accept-Encoding":"gzip,deflate","Connection":"Keep-Alive","Content-Length":"39","Content-Type":"application/json; charset=utf-8","Host":"10.20.1.239:9517","User-Agent":"Apache-HttpClient/4.5.5 (Java/1.8.0_171)"},"httpVersion":"1.1","method":"POST","post":"{\"url\":\"http://example.com/\"}","url":"/session/07e53c90-6b45-11e9-892c-4faf7180871b/url","urlParsed":{"anchor":"","query":"","file":"url","directory":"/session/07e53c90-6b45-11e9-892c-4faf7180871b/","path":"/session/07e53c90-6b45-11e9-892c-4faf7180871b/url","relative":"/session/07e53c90-6b45-11e9-892c-4faf7180871b/url","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/session/07e53c90-6b45-11e9-892c-4faf7180871b/url","queryKey":{},"chunks":["session","07e53c90-6b45-11e9-892c-4faf7180871b","url"]}}
Command duration or timeout: 10.20 seconds
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'ip-10-20-1-73.ec2.internal', ip: '10.20.1.73', os.name: 'Linux', os.arch: 'amd64', os.version: '3.10.0-862.2.3.el7.x86_64', java.version: '1.8.0_171'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, handlesAlerts=false, databaseEnabled=false, version=2.1.1, platform=LINUX, browserConnectionEnabled=false, proxy=Proxy(direct), nativeEvents=true, acceptSslCerts=false, driverVersion=1.2.0, locationContextEnabled=false, webStorageEnabled=false, browserName=phantomjs, takesScreenshot=true, driverName=ghostdriver, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: 07e53c90-6b45-11e9-892c-4faf7180871b
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_171]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[?:1.8.0_171]
        at

A: RemoteWebDriver is a keyword/researved word. So instances of RemoteWebDriver should be differently named. Additionally while invoking RemoteWebDriver you need to pass the URL of the Selenium Grid Hub  and the instance of DesiredCapabilities as mandatory arguments and you can use the following (Windows based) solution:
File path=new File("C:\\Utility\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
System.setProperty("phantomjs.binary.path",path.getAbsolutePath());
DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
capabilities.setPlatform(Platform.XXX);
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilities);
driver.get("https://www.google.co.in");
System.out.println(driver.getTitle());
driver.quit();


text:
Q: Need more information about jQuery selector in Chrome Developer Tools Whenever I use Console in Chrome's Developer Tools or Firebug to interpret a jQuery selector, it only returns the innerHTML of the result of the selector if only one item matches.  If multiple items match, I'm given the array of matched items, with their innerHTML as the contents of each array slot.  However, in Safari, a navigable tree representing the actual returned jQuery object is presented.  This is far easier to work with when looking for properties I want to get/set, etc.  I can get similar output in Firebug or Chrome Developer Tools if I pass the selector to a console.log() call, but this is a pain.  Is there any way to have the WebKit Console behave similarly in Chrome to how it behaves in Safari?

A: Also try using the jQuery shell extension for Google Chrome.

A: You can view in the scope variables sub section. If you put a breakpoint in your selected script.


text:
Q: How small can a JavaScript number be without displaying in scientific notation? I've made some code that rounds off a number to a given number of decimal places but will use more places when there is underflow to avoid rounding just to zero, which wouldn't be informative enough for the user.
But I've noticed that occasionally a small number is displayed in scientific notation. My target users are not expected to be comfortable with scientific notation and in any case such numbers are too small even after handling the underflow and should be treated as zero.
How can I know when a number is so small that it would display in scientific notation?
Is there a smallest number I can compare to and if so what is it?
Or is there a better way?
(I know I can convert the number to a string and check if it has an "e" but I'm the type who is curious to know of any math-only solution too.)

A: There are a few reasons the number is displayed in scientific notation:

*

*If the length of significant digits in the number is greater than 21.

*If the number of zeros before a nonzero number is greater than 6. (e.g. 0.00000001)

The conversion to scientific notation in numbers is specified in Section 9.8.1 of ECMA-262.
An implementation of this specification can be found in the V8 engine here.