text:
Q: How to modify the JSON data and return the updated JSON data We have a requirement to update the JSON data in middle and need to return the updated JSON data using java. Also it should support any type of JSON data.
ex:
Assume {object:{"color":"red","shape":"Triangle"}} is the JSON data and in this we need to update the shape value to Rectangle and we need to return the updated JSON data as below:
{object:{"color":"red","shape":"Rectangle"}}

For this we need to pass the element path ( which element we need to update) and updateText and JSON Data to the JAVA code.
here is the methodCall:
updateValue("object/shape", "Rectangle", "{object:{"color":"red","shape":"Triangle"}}")

We tried below code using Gson library. But with this code we are able to update the targeted Json element, but the requirement is to return the  entire JSON data with the updated value.
So please suggest how do we re-build the JSON data with the updated text.
Below is the code we tried to update the Json Data.
    public String updateValue(String keyPath, String updateText, String jsonText) {
    String[] keys = keyPath.split("/");
    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
    String result = "";
    for(String key : keys)
    {
        if (jsonObject.get(key) instanceof JsonObject)
        {
          jsonObject = (JsonObject)jsonObject.get(key);
        }
        else if(jsonObject.get(key) instanceof JsonArray)
        {
          JsonArray jsonArray = (JsonArray)jsonObject.get(key);
          result = jsonArray.toString();
        }
        else
        {
          result = jsonObject.get(key).toString();
        }
    }
    result = result.replace(result, updateText);
    return result;
}

A: The problem lies in the way you do the replacements. When you translate the JsonObject to String, you lose the object, and after replacement, you just have the replaced String. To fix it, you need to operate directly on the object, instead of the String counterpart. Because JsonObject is mutable, holding a reference to the input will reflect the changes. One drawback is you can't replace a value in a JsonArray this way, partly because you don't know which element to replace. To accomplish that, you will need a little more in the input(either the value to replace or the element position).
public String updateValue(String keyPath, String updateText, String jsonText) {
    String[] keys = keyPath.split("/");
    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
    JsonObject returnVal = jsonObject; // This holds the ref to target json object
    JsonPrimitive jp = new JsonPrimitive(updateText);
    String finalKey = keys[keys.length - 1];
    for(String key : keys)
    {
        if (jsonObject.get(key).isJsonObject())
        {
            jsonObject = (JsonObject)jsonObject.get(key);
        }
    }
    jsonObject.remove(finalKey);
    jsonObject.add(finalKey, jp);
    return returnVal.toString();
}

A: You can use JsonPath lib for that and try using the following code.
private static final Configuration configuration = Configuration.builder()
     .jsonProvider(new JacksonJsonNodeJsonProvider())
     .mappingProvider(new JacksonMappingProvider())
     .build();

JsonNode updatedJson = JsonPath.using(configuration).parse(originaljson)
     .set("use the path to go for value", "new value").json();
json = updatedJson.toString();


text:
Q: Xamarin Android, How to add Canvas view to capture user sign Working on xamaring for android in Visual studio, I can see there is no CanvasView.
There are objects like Paint, Canvas, but how to implement theme into a view ?
I need to present white board where the user can sign by hand.
Thanks

A: There is an open source library called Xamarin Signature Pad. You could use that or look at the source to see how to implement this on your own.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Usb Folder is empty but full in size I have some important data on my USB whenever it's mounted it shows that it has 60GB worth of data in the properties, however, the folder shows that it's empty. Whenever I open the directory in the terminal and do ls I get

ls: reading directory '.': Input/output error


text:
Q: How to extract common number across multiple lines? http://abc/blah/hhh/25927/3456/bb
http://vfg/blahgg/hhvvh/kkk/25927/2378/bb/mm
http://lah/hhh/25927/fff/bb/somthin

in the above lines, the common number is 25927 always occurring like /25927/ and it is present in each and every line.
But the number is a variable I don't know ahead of time, so I cannot use grep 25927; instead it should be something like grep /commonnumber present in all lines/ file

A: perl -nE '%a = map { $.==1 || $a{$_} ? ($_,1):()} /(\d+)/g;
          END{ say keys %a}'   file

Explanation:

*

*-n will add a loop over the entire program, like:
while (<>) { ... }

*-E is needed for perl to execute the command line (inside that loop).  It also adds the possibility to use say

*Every line is passed to /(\d+)/g which matches each number (digits next to each other) separately.  Each number if fed into the map.

*%a is the dictionary of the numbers that appeared in all the lines until now. It is recalculated every line (%a = ...).

*in the first line $. == 1 all the numbers are stored in the dictionary -- the pair (number , 1) is added; 1 stands for True

*in the the other lines, all the number are filtered out () unless they were also present in last iteration $a{$_} ?.

*Finally END{...} prints all numbers that did repeat over all the lines.

A: $ awk -F/ 'NR==1{for(i=1;i<=NF;i++){Arr[$i]++}next}{for(j=1;j<=NF;j++){if ($j in Arr){Arr[$j]++}}}END{for (k in Arr){if(NR==Arr[k]&&k+0!=0){print k,Arr[k]}}}' input.txt

extract the first line with delimter / and store it in array. from second line onwards, check whether the field is there in array. if it's there in array, then increase the value. In the end, check the value against the line number and make sure its number.

A: If you know that it will always be 5 digits in a row delimited by the slash character (as in the path above), you could try something like:
egrep [/][0-9]{5}[/] file
Using egrep allows you to use the extended regular expression syntax if you are using other than the GNU version of grep.  See the man page for more information on your version of grep.


text:
Q: UnhandledPromiseRejectionWarning: DiscordHTTPError: 401 Unauthorized on GET /api/v7/users/@me I'm making a login system with Discord using the discord-oauth package  ... But it gives this error of unauthorized
(UnhandledPromiseRejectionWarning: DiscordHTTPError: 401 Unauthorized on GET /api/v7/users/@me)
Code:
const router = require('express').Router()
const crypto = require('crypto')
const DiscordOauth2 = require('discord-oauth2')
const request = require('snekfetch')

const rateLimit = require('../middleware/limiterBotControler.js')
const baseUrl = 'https://discord.com/api/v7/'

const oauth = new DiscordOauth2({
    clientId: '782761260620972034',
    clientSecret: '',
    redirectUri: 'http://localhost:8080/login/discord/callback'
})

router.get('/login', (req, res) => {

    let url = oauth.generateAuthUrl({
        scope: ['identify', 'email', 'guilds'],
        state: crypto.randomBytes(16).toString('hex')
    })

    return res.redirect(url)
})

router.get('/login/discord/callback', (req, res) => {
    let code = req.query.code

    oauth.tokenRequest({
        code: code,
        grantType: 'authorization_code',
        scope: ['identify', 'email', 'guilds']
    }).then((refresh_token) => {
        oauth.getUser(refresh_token).then(console.log)
    })

A: I've got a similar issue myself, although I'm pretty sure it doesn't have the same causes as you. Here's the mistakes I've noticed.
mistake 1) tokenRequest doesn't return a refresh_token, it returns an object that contains
{ access_token, refresh_token, ...etc }
mistake 2) getUser takes an access_token, you however are attempting to do this with a refresh_token
Hope this helps ^-^


text:
Q: Silverlight: How can I set a converter on a ComboBox ItemsSource in the code-behind? I have a combobox that is populated at runtime with values from a loadoperation (I'm using RIA services)
        cboSite.ItemsSource = lo.Entities;

However, I want to be able to add a null item to the top of the list shown in the combobox, so following the example given here:
http://clr-namespace.com/post/SilverlightWPF-ComboBox-with-Empty-Item-allows-user-to-go-back-to-no-selection.aspx
I am trying to use a converter to insert the item at the top of the list. However, the problem I have is that I can't seem to work out how to specify the converter in the code behind!
Any ideas how to achieve this?

A: If you are willing to assign ItemsSource from the code-behind you can convert your Entities in the same very place. Something like this:
var converter = new AddEmptyItemConverter();
var converted = (IEnumerable<Entity>)converter.Convert(lo.Entities,
                                                       typeof(IEnumerable<Entity>),
                                                       null,
                                                       null);
 cboSite.ItemsSource = converted;

That Entity should be the type of Entities collection element.


text:
Q: Entity Framework Migrations: Pending migration after "update-database" I'm using entity framework version 6.1.3 and .NET Framework 4.0.
I'm trying to use Migrations from Code-First from existing Database.
I'm having a trouble that whenever I use the Update-Database it makes the changes from my migration, and changes my database, but it keeps the migration as "Pending" and when I try to add another migration with Add-Migration, it says I have pending migration.
Example of the problem:

*

*Run the Enable-Migrations command from the Package Manager Console.

*Run the Add-Migration first command to create an initial migration.

*Remove all the code in Up() method for the initial migration, because I don't want to create the tables that already exists.

*Run the Update-Database command to apply the initial migration to my database (it runs successfully).

*Make changes to my code-first model (add column to existing table).

*Run the Add-Migration second command to create a new migration.

When I run step 6, I get the following error:

Unable to generate an explicit migration because the following explicit migrations are pending: [201601111013546_first]. Apply the pending explicit migrations before attempting to generate a new explicit migration.

If I delete the migration "[201601111013546_first]" from my Migrations folder, I can run step 6, and use the Update-Database, and it successfully changes my database, adding the column I wanted, but if I change my model again and use Add-Migration third, it says the same error, that the second migration is still pending.
Also, if instead of steps 5 and 6, I just run Update-Database again, it runs the same script returning the obvious error of already having a 'MigrationId' in the table dbo."__MigrationHistory":

ERROR: 23505: duplicate key value violates unique constraint "PK_dbo.__MigrationHistory"

I already tried:

*

*Create a new project (ConsoleApplication) and made the same steps getting the same errors.

*Delete entire Migration folder and run Enable-Migrations again.

*Verify the namespace of the Migration and it's .Designer file.

*I have only one connectionString but still tried the commands with -ConnectionStringName.

Any suggestions?
Thanks.


text:
Q: Make jQuery modal not block other UI elements I'm using a jQuery modal to simulate a toast message:
var modalDiv = $('div.modal');
$(modalDiv).modal({'backdrop': false});
$(modalDiv).modal('show');

runAsync(function() { $(modalDiv).modal('hide'); }, null, 3000);

It runs ok and the rest of the UI is visible (since I set backdrop to false), however the rest of the screen isn't clickable.
If I inspect the HTML, I can see that the <div class="modal fade in"> node is covering the whole screen and is above the rest.
Is there any way to change this, and let me interact with the UI without clearing the modal?
JSFiddle here: https://jsfiddle.net/6z42mw13/2/

A: Try this, I am not exactly sure what you want to accomplish, but this solution will center the modal on the screen and make your items selectable.
Change the modal CSS to this..
.modal {
   width: 200px;
   position: fixed;
   top: 50%;
   right: 50%;
   bottom: 0;
   left: auto;
   z-index: 1050;
   display: none;
   overflow: hidden;
   -webkit-overflow-scrolling: touch;
   outline: 0;
   height: 80px;
   margin-right: -100px;
}

Your problem is the invisible modal is still there and covering the entire screen, this would fix that.


text:
Q: Can I compare two fingerprints scanned from different fingerprint scanners? Can I compare two fingerprints scanned from different fingerprint scanners? As I have read each fingerprint scanner uses its own method for scanning.

A: You have to use standard formats:

*

*ANSI / INCITS 378-2004  https://www.nist.gov/itl/iad/image-group/resources/incits-standardized-biometric-data

*ISO 19794-2 /IEC with one  of these formats : FMR, FMC-NS, FMC-CS

Lot of fingerprint SDK support these formats

A: Yes, you can do. Every scanner supports giving the fingerprint template and the typical fingerprint image. With the help of the images, you can easily generate templates and compare with other fingerprints. For this, You need to implement your own Automatic Finger Identification algorithm or you have to use third party services such as

*

*CAMS

*M2Sys

*Neurotechnology
If you rely on the template collected from various scanners, it is difficult to achieve what you need as not all the scanners provide the standard format templates. Some scanner do provide the ISO/ANSI standard formate template. But comparison algorithms are not available easily to implement.


text:
Q: GNOME background window always show up when there are notifications I'm using Ubuntu 19.10 GNOME 3.34
I had a problem where gnome always change the current app (window) to be minimize when some background app had an alert (browser / chat notification).
To reproduce.

*

*Open browser (full screen / maximize)

*Open other stuff (full screen / maximize) your current app now, the browser loses focus (on your back of current app)

*Browser send some alert

*The current window become your browser, and minimize you current app suddenly

How to disable this feature? or how to fix this?


text:
Q: How to add multiple values under 1 column in database I need to create a model that allows me to store multiple values under the same column. I'm not sure if this is possible or i'm thinking of the right way to do it. Any feedback is greatly appreciated.
TaskID = models.CharField(max_length=128)
SubtaskID = models.CharField(max_length=128)
SubtaskNode = models.CharField(max_length=24)
SubtaskStatus = models.CharField(max_length=10)

In my project you can create a task which outputs a Task ID for later querying. And in a task there's n amount of subtasks created also. So i'm wondering how I could store the multiple values of the subtasks on my TaskID?
Example of structure of how they could look:
TaskID = c07de590-678f-45a2-b6ac-1110c201037b
SubtaskID1 = 87da261e-530d-40e8-8a8b-b61507c6eba2
SubtaskNode1 = Node1
SubtaskStatus1 = Waiting
SubtaskID2 = 140bb0a4-2cdb-46f0-b62d-9187592ae1e9
SubtaskNode2 = Node2
SubtaskStatus2 = Waiting
SubtaskID3 = 43e64d3a-a088-4aae-8a57-64e1c4dfba08
SubtaskNode3 = Node3
SubtaskStatus3 = Finished
SubtaskID4 = 324083fb-b9e9-471f-8946-21ed426fc646
SubtaskNode4 = Node4
SubtaskStatus4 = Failed

The purpose of all of this to later create a for loop in my template to list all SubtaskID's under the TaskID value.

A: You can create a self reference, where a task record references a parent task record, that references task record, ... , and son on.
class Task(models.Model):
    name = models.CharField()
    status = models.CharField()
    parent = models.ForeignKey('self', related_name='subtasks')

You can query for a task subtasks like this:
subtasks = Task.objects.get(id=id).subtasks

A: You'll probably want to keep Tasks and SubTasks in different models and use ForeignKeys to link them to each other.
Your question title is a bit misleading, btw.


text:
Q: Get comment authors on Youtube I want to loop though all the comments' authors text in videos on Youtube and save it somewhere one after another, but I'm having a hard time with it. I tried using Greasemonkey and writing something in jquery but it doesn't seem to run on youtube, I don't know if they blocked jquery? I had a little success in using javascript but still having undefined errors on variables, as well as some functions that aren't working with it. So can anyone suggest a way I can do this?

A: If you want to loop though all the comments' authors text in videos on Youtube and save it somewhere one after another, then for this you can use jquery, if you have broad knowledge in jquery you can use here or you can take helps w3schools.com for solving your problems. Youtube comments plays an important role to show your popularity. To know more visit:- http://www.buyyoutubelikes.com/youtube-comments/


text:
Q: Remove exact string from files in folder using grep I've got the following code:
cd /home/pi/.attract/romlists; for file in *.tag ; do grep -v -F 'Arcade Snooker [AGA]' $file > $file1.tmp && mv -f $file1.tmp $file; done

This works well to remove the fixed string "Arcade Snooker [AGA]" from a file such as "Amiga.tag".  However, it does not remove the string from "Atari 800.tag" or from any other file that has a "space" in its name.  The result for "Atari 800.tag" is the following error:
grep: Atari: No such file or directory
grep: 800.tag: No such file or directory

What changes do I need to make to the code please to get it to remove "Arcade Snooker [AGA]" from "Atari 800.tag" and from other such files containing spaces in their names?
I would prefer to have one line of code only please as I have it now.
Thanks.

A: You need to quote the variables if the file names contain spaces...
cd /home/pi/.attract/romlists; for file in *.tag ; do grep -v -F 'Arcade Snooker [AGA]' "$file" > "$file1.tmp" && mv -f "$file1.tmp" "$file"; done


text:
Q: Ember-Data beta 3 and saving hasMany relationships and additonally one record with Rails I am using Rails 4, Ember 1.2.0 and Ember Data 1.0.0-beta.3 and DS.ActiveModelSerializer.
I have trouble saving a new record with a 'has many' relationship. Two model records should be created but only by one POST request.
I have 2 models which looks like this:

Lingohub.SupportCase = DS.Model.extend({
  subject: DS.attr('string'),
  status: DS.attr('string'),
  created_at: DS.attr('date'),

  supportCaseMessages: DS.hasMany('supportCaseMessage')
});

Lingohub.SupportCaseMessage = DS.Model.extend({
  supportCase: DS.belongsTo('supportCase'),
  text: DS.attr('string'),
  created_at: DS.attr('date')
});

My NEW route creates support case and support case massage:

Lingohub.SupportCasesNewRoute = Ember.Route.extend({
  model: function() {
    var support_case = this.store.createRecord('supportCase');
    support_case.get('supportCaseMessages').createRecord();
    return support_case;
  }
});

My new form looks like this: (I don't know if you can bind an child attribute easier?)
<form {{action 'create' this on="submit"}} id="new_support_case">

  {{input value=subject}}

  {{!-- {{supportCaseMessages.0.text}} --}}
  {{#each supportCaseMessages}}
    {{textarea value=text}}
  {{/each}}

  <input type="submit">

</form>

'create' action in the controller:
Lingohub.SupportCasesNewController = Ember.ObjectController.extend({

  actions: {
    create: function(supportCase) {
      var message = supportCase.get('supportCaseMessages.content')[0];

      console.log(message.get('text'))

      supportCase.save();

    }
  }

});

The POST Request to the Server only sends the 'support case'!!

{"support_case"=>{"subject"=>"aaaaaa", "status"=>nil, "created_at"=>nil}}

How can I send the additional record 'support case message' and the relationship ?

A: I try to answer my own question. If I do the following I get "support_case_messages" embedded in "support_case", is this really the best way to send 'two models' in one POST request?

Lingohub.SupportCaseSerializer = DS.ActiveModelSerializer.extend({
  serializeHasMany: function(record, json, relationship) {
    var key, jsonKey;
    key = relationship.key;
    jsonKey = Ember.String.underscore(key);
    json[jsonKey] = [];

    record.get(key).forEach(function(item) {
      return json[jsonKey].push(item);
    });

    console.log(json)

    return json;
  }
});


text:
Q: Using offsetof to perform pointer arithmetic example I was trying to learn about acessing struct memebers by using the offsetof() macro and I ran into this example How can I access structure fields by name at run time?
This line:
//Set the value of 'a' using pointer arithmetic
*(int *)((char *)structp + offsetf) = 5;

gives me trouble.
Why is the pointer being cast to a char * and then back to an int *?

A: Firstly, the struct pointer has to be cast to "byte pointer" type, since offsetf most likely contains the byte-offset of the desired struct field. Because of this cast, pointer arithmetic in (char *)structp + offsetf subexpression is performed in terms of char objects (in terms of bytes), exactly as we want it.
Secondly, the above subexpression gives us a pointer of type char * that points to the desired data field. But in reality that data field apparently has type int. So, in order to gain access to that data field we have to cast our char * pointer to the proper int * type. After that we can perform read (or write) access to that data field by using the unary * operator.
In your case value 5 is written into an int data field located at byte-offset offsetf inside an object pointed by structp.

A: Because in order: you derreference * something casted into int* so you can acess the data and set it to 5.
The cast into char * is because casting char * to int * is easy due to the fact that every char has an integer value.


text:
Q: White screen in C# forms program Im currently developing something to track CPU usage but as soon as i started the thread that pulls the data from the CPU the screen went blank as if i started a fresh program.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Management.Instrumentation;
using System.Management;
using System.Collections.Specialized;

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
    Thread cpuData;
    public Form1()
    {

        cpuData = new Thread(new ThreadStart(cpuDataThread));
        cpuData.Start();
    }
    public void cpuDataThread()
    {
        ulong i;
        i = 0;
        try
        {
            ManagementClass cpuDataClass = new ManagementClass("Win32_PerfFormattedData_PerfOS_Processor");

            while (true)
            {
                ManagementObjectCollection cpuDataClassCollection = cpuDataClass.GetInstances();
                foreach (ManagementObject obj in cpuDataClassCollection)
                {
                    if (obj["Name"].ToString() == "_Total")
                    {
                        i = Convert.ToUInt64(obj["C1TransitionsPersec"]);
                    }
                }
                Thread.Sleep(100);
            }
        }
        catch (ThreadAbortException tbe)
        {

        }
        progressBar1.Maximum = 100;
        progressBar1.Minimum = 1;

        progressBar1.Value = (int)i;
    }
}
}

This is just a program i wrote for personal usage but id like to get it working, the progress bar also does not work id like to get some help with that as well.

A: Your constructor isn't calling InitializeComponent() which is the method that is created by the WinForms designer.

A: You probably also need to provide following properties to Your Thread(Before Start Method):
cpuData.SetApartmentState(ApartmentState.STA);
cpuData.IsBackground = true;

And following Your second problem(progressbar). If You want to pass data to UI You need to use Dispatcher, like below:
Dispatcher.Invoke((Action)delegate() { /* update UI */ });

A: I've tinkered a bit around with your code, seems to work:
You are using Win forms, so have I. Instead of manually threading I have used a Backgroundworker ("bkwCpuLoad").
To accomodate for the values, I have set the max to 10,000:
private void Form1_Load(object sender, EventArgs e)
{
    progressBar1.Maximum = 10000;
    progressBar1.Minimum = 0;
    bkwCpuLoad.RunWorkerAsync();
}

private void bkwCpuLoad_DoWork(object sender, DoWorkEventArgs e)
{
    ulong i;
    i = 0;
    try
    {
        ManagementClass cpuDataClass = new ManagementClass("Win32_PerfFormattedData_PerfOS_Processor");

        while (true)
        {
            ManagementObjectCollection cpuDataClassCollection = cpuDataClass.GetInstances();
            foreach (ManagementObject obj in cpuDataClassCollection)
            {
                if (obj["Name"].ToString() == "_Total")
                {
                    i = Convert.ToUInt64(obj["C1TransitionsPersec"]);
                }
                bkwCpuLoad.ReportProgress((int)i);
            }
            Thread.Sleep(100);
        }
    }
    catch (ThreadAbortException tbe)
    {

    }
}

private void bkwCpuLoad_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    var perc = e.ProgressPercentage;
    if (perc > progressBar1.Maximum)
        perc = progressBar1.Maximum;
    progressBar1.Value = perc;
    try
    {
        progressBar1.Value--;
        progressBar1.Value++;
    }
    catch
    {
    }
}

Exaplanation for the progressBar1.Value--, progressBar1.Value++ bit: One thing that is anything but ideal in a case like yours is the progressbar animation, which is too slow. But: if you reduce a progressbar value, it is not animated but painted directly.
Therefore, settings the value (animation starts), reducing it by 1 (jumps directly to value) the increasing it again makes your progressbar essentially faster. ;-)


text:
Q: Python cv2 .mp4 codec unable to be displayed in browser When I record my webcam using the below Python code, it saves it into webcam.mp4. On my local computer I am able to view the video, but when I display it in my browser, it doesn't work. It seems, that the codec is wrong, but I have not figured out why, nor how to get it correct.
The Python code
    global rec_bool
    rec_bool = False

    def timer(seconds):
        global rec_bool
        rec_bool = True
        time.sleep(seconds)
        rec_bool = False

    seconds = 3
    timer_thread = threading.Thread(target=timer, args=(seconds,)).start()
    vid_capture = cv2.VideoCapture(0)
    vid_cod = cv2.VideoWriter_fourcc(*'mp4v')
    output = cv2.VideoWriter("webcam.mp4", vid_cod, 20.0, (640,480))
    while(rec_bool == True):
        ret,frame = vid_capture.read()

        output.write(frame)

    vid_capture.release()
    output.release()
    cv2.destroyAllWindows()

The HTML code
<iframe class="video" id="webcam_video" src="/static/videos/webcam.mp4" frameborder="0" allowfullscreen></iframe>

It just shows a loading symbol. When I on the other hand use curl to download it, it works perfectly fine. I have tried with other mp4 files, and they work, like they should.

A: Not all codecs work in web browser. See in Wikipedia: HTML5 video
For all browsers should work codec H.264 so you can try
vid_cod = cv2.VideoWriter_fourcc(*'H264')

If this can't work - ie. when cv2 was compiled without this codec - then you can convert it with external tools like ffmpeg
In system console/shell
ffmpeg -i webcam.mp4 -vcodec libx264 -f mp4 output.mp4

In code
os.system("ffmpeg -i webcam.mp4 -vcodec libx264 -f mp4 output.mp4")

or
import subproces

# with `shell=True`
subproces.run("ffmpeg -i webcam.mp4 -vcodec libx264 -f mp4 output.mp4", shell=True)

# without `shell=True`
subproces.run( ["ffmpeg", "-i", "webcam.mp4", "-vcodec", "libx264", "-f", "mp4", "output.mp4"] )

or using modules like ffmpeg-python or MoviePy which use ffmpeg.

BTW: ffmpeg installs also program ffprobe which may show details about codecs used in file.
 ffprobe webcam.mp4

EDIT:
You can also use ffmpeg to record from WebCam
For Linux (which I use)
ffmpeg -f v4l2 -i /dev/video0 -t 00:00:03 output.mp4

or with some settings
ffmpeg -f v4l2 -framerate 20 -video_size 640x480 -i /dev/video0 -t 00:00:03 output.mp4

3 seconds = -t 00:00:03 or -t 3
For other systems you should find information in documentation WebCam


text:
Q: SQL Server - filter specific rows I am trying to select rows where the TYPE 'f' is selected over TYPE 'i' for the same Me (Metric) if the Type 'f' exists.
Example
from:
╔════╦══════╦═══════╗
║ Me ║  VAL ║  TYPE ║
╠════╬══════╬═══════╣
║  1 ║    0 ║     f ║
║  1 ║    1 ║     i ║
║  2 ║    1 ║     i ║
║  2 ║    0 ║     f ║
║  3 ║    1 ║     i ║
║  4 ║    0 ║     i ║
║  5 ║    0 ║     i ║
╚════╩══════╩═══════╝

get:
╔════╦══════╦═══════╗
║ Me ║  BIT ║  TYPE ║
╠════╬══════╬═══════╣
║  1 ║    0 ║     f ║
║  2 ║    1 ║     f ║
║  3 ║    1 ║     i ║
║  4 ║    0 ║     i ║
║  5 ║    0 ║     i ║
╚════╩══════╩═══════╝

A: The statement below uses ROW_NUMBER() which is a ranking function that generates sequential number. The number is generated for every Me and sorted by Type. This uses CASE assuming that there are other values of TYPE in the table.
SELECT  Me, Val, Type
        FROM
        (
            SELECT  Me, Val, Type,
                    ROW_NUMBER() OVER (PARTITION BY Me
                                        ORDER BY CASE WHEN Type = 'f'
                                                    THEN 0 ELSE 1 END) rn
            FROM    tableName
        ) a
WHERE   a.rn = 1

*

*SQLFiddle Demo


text:
Q: Best way to handle ephemeral tokens when using SimplePreAuthenticator & PreAuthenticatedToken I'm using the SimpleAuthentication feature as described here : http://symfony.com/doc/2.6/cookbook/security/api_key_authentication.html
The purpose is to provide an authentication through a token string passed as a query (get) parameter or a header. This token, let's call it TemporaryAccessToken to avoid confusion with the Sf2 token, is generated by a controller, sent to the user by email (not described here) and should be available for a limited amount of time (there's a valid_until \DateTime column in the dedicated entity).
For the record, when the protected page (by the simple_user_account firewall) is accessed the first time the authentication process goes like this :

*

*SimplePreAuthenticationListener is triggered

*Basically, calls MyAuthenticator->createToken()

*Then calls AuthenticationManager->authenticate(), which calls MyAuthenticator->authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
Problem is : once the user has been authenticated, and because I'm using stateless: false in the firewall configuration, the authentication process is not triggered again since there's already a valid Sf2 token in session.
I see 2 logic solutions but I can't figure out how to do this properly :

*

*make the session valid until the date which is set into my TemporaryAccessToken.valid_until column. Is there a way to achieve that "natively" ? (I saw that the remember_me firewall has a lifetime parameter)

*or, be able to re-check the TemporaryAccessToken validity (see the if( $accessToken && $accessToken->isValid() ) line in my Authenticator)

app/config/security.yml
firewalls:
    simple_user_account:
        pattern:   ^/account/access
        stateless:  false
        simple_preauth:
            authenticator: app.security.simple_user_authenticator
        logout:
            path:   /logout_simple
            target: /

My authenticator class looks like :
class SimpleUserAuthenticator implements SimplePreAuthenticatorInterface, AuthenticationFailureHandlerInterface
{
    /**
     * @var AccessTokenManager
     */
    private $accessTokenManager;

    /**
     * SimpleUserAuthenticator constructor.
     * @param AccessTokenManager $accessTokenManager
     */
    public function __construct(AccessTokenManager $accessTokenManager)
    {
        $this->accessTokenManager = $accessTokenManager;
    }

    public function createToken(Request $request, $providerKey)
    {
        $TemporaryAccessToken = $request->query->get('simple_user_token');
        if (!$TemporaryAccessToken) {
            throw new BadCredentialsException('No simple_user token found');
        }

        return new PreAuthenticatedToken(
            'anonymous',
            $TemporaryAccessToken,
            $providerKey
        );
    }

    public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
    {
        if( $token->getUser() instanceof SimpleUser )
        {
            $newToken = new PreAuthenticatedToken(
                $token->getUser(),
                $token->getCredentials(),
                $providerKey,
                array('ROLE_USER')
            );
            return $newToken;
        }

        $accessToken = $this->accessTokenManager->getRepository()->findOneByToken($token->getCredentials());
        if( $accessToken && $accessToken->isValid() )
        {
            $user = $userProvider->loadUserByUsername($accessToken->getAccount()->getEmailCanonical());
            $newToken = new PreAuthenticatedToken(
                $user,
                $token->getCredentials(),
                $providerKey,
                array('ROLE_USER')
            );
            return $newToken;
        }
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        $response =  new RedirectResponse(
            '/login'
        );
        return $response;
    }

    public function supportsToken(TokenInterface $token, $providerKey)
    {
        return $token instanceof PreAuthenticatedToken && $token->getProviderKey() === $providerKey;
    }

}

Symfony2 version : 2.5.6

A: Well, if you need to use session, you can set lifetime under your config.yml session settings:
# config.yml
framework:

    session:
        # handler_id set to null will use default session handler from php.ini
        handler_id: ~
        lifetime: 3600

You can change lifetime value to anything in seconds (it defaults to 3600 or 1 hour)
Also, you can try to configure garbage collector.
If this answer was not helpful, please, let me know.


text:
Q: Prove that $\lim_{x\to -\infty} (x^2)^\frac{1}{5} = \infty$ Prove that $\lim_{x\to -\infty} (x^2)^\frac{1}{5} = \infty$ by using the definition stated below.
For all $M>0$, there exists a $N \in \mathbb R$, such that for all $x \in \mathbb R$, $x < N \implies f(x) > M$.
Scratchwork: If $(x^2)^\frac{1}{5} > M$, then $x > M^\frac{5}{2}$. Note that for all $N>0$, $x<-N$, so $x^2>N^2$, so$(x^2)^\frac{1}{5} > N^\frac{2}{5}$, so choose $N \in \mathbb R$ such that $N = M^\frac{5}{2}$.
Proof: For all $M>0$, there exists a $N \in \mathbb R$ such that $N = M^\frac{5}{2}$, such that for all $x \in \mathbb R$, for all $N>0$, from $x<-N$, we get $x^2>N^2$, so $x^\frac{2}{5} > N^\frac{2}{5} = M$ as required. $\square$
I have to use this method by the way. I am unsure on whether my logic in my proof is correct because I feel like I should have taken $x<N$ rather than $x<-N$ but this is how it was done in an example in my notes which I used to write this solution.

A: Let: $$t = x^2 $$
$$ x \to -∞ \implies t \to +∞$$
$$\underset{x\rightarrow-\infty}{\lim\;(x^2)^{\textstyle\frac {1}{5}}}=\underset{t\rightarrow+\infty}{\lim\;\sqrt[5]{t}}=+∞$$


text:
Q: Vitali's Convergence Theorem but one hypothesis changes We have the following problem:
Let $(Y, \Gamma , \nu)$ be a measure space. Suppose that $\{g_{n}\} \, \subset \, L^{p} \, := \, L^{p}(Y,\Gamma , \nu).$ Prove that  $\lim_{n} g_{n} = g$ in $L^p$ if and only if:
1) For each $\epsilon > 0$
$$\lim_{n\to\infty} \nu(\{y \in Y \, : \, |g_{n}(y)-g(y)| > \epsilon \}) = 0.$$
2) If $\epsilon > 0$ exists $\delta(\epsilon) > 0$ such that if $E \in \Gamma$ and $\nu(E) < \delta(\epsilon)$, then
            $$\left|\int_{E} g \, d\nu \right| < \epsilon . $$
3) For each $\epsilon > 0$ exists $N \in \mathbb{N}$ and a set $E_{\epsilon} \in \Gamma$ with $\nu(E_{\epsilon}) < \infty$ such that
            $$ \int_{E_{\epsilon}^{c}} \left| g_{n} \right| ^{p} \, d\nu  < \epsilon \quad \forall n \geq N.  $$
As you can see the conditions are pretty similar to the Vitali's Convergence Theorem, except for the second one.
I have been following the proof in the book of Rober G. Bartle called Element of Integration but I can't change that proof so that fits in my problem.
So far the idea that I had is consider $\epsilon>0$ and let $E_{\epsilon}$ be as in 3). Then apply the Minkowski inequality to the function $g_n-g=(g_n-g)\chi_{E_{\epsilon}}+g_n\chi_{E_{\epsilon}^c}+(-g)\chi_{E_{\epsilon}^c}$.
From there I can narrow the second and the first elements, but not the last one.
I would really appreciate some help.
Thank you so much.

A: The statement is wrong: Take $g_n = n 1_{(0,1/n]}$. Then $g_n(x) \rightarrow 0$ for all $x \in \mathbb{R}$. The measure space under consideration should be $(\mathbb{R},\mathcal{B}(\mathbb{R}),\lambda)$, i.e. the Lebesgue measure on $\mathbb{R}$. Then we have $\lambda(|g_n|> 0) = 1/n \rightarrow 0$. Since $g=0$, the condition (2) is always satisfied. In (3) you can take  $E_\varepsilon = [0,\varepsilon]$. Then $\nu(E_\varepsilon) <  \varepsilon$ and for all $n \ge N$ with $1/N < \varepsilon$ we have
$$\int_{E_\varepsilon^c} |g_n| d \lambda =0,$$
i.e. the modifacted version of Kavi Rama Murthy holds.
The problem is that (2) should be replaced by the condition that for all measurable sets $A$ with $\nu(A)< \delta$
$$\int_{E} |g_n| \, d \nu < \varepsilon \quad \text{for all } n \in \mathbb{N}.$$
By taking $E \cap \{g_n \ge 0 \}$, resp. $E \cap \{g_n \le 0 \}$ the last conidition can be replaced by
$$\left| \int_{E} g_n \, d \nu \right| < \varepsilon \quad \text{for all } n \in \mathbb{N}.$$
This is exactly the condition which can be found in the corresponding Wikipedia article, as cited in the comments. Note that we don't need to make the modification as made in Kavi Rama Murthy answer.

A: As I mentioned in one of the comments 3) should say $\nu (E_{\epsilon}) <\epsilon$. Here is how you handle the last term in your decomposition: by going to a subsequence we may replace 1) by almost everywhere convergence. Let $\epsilon >0$ Then we have $\int_{E_{\epsilon}^{c}} |g_n|^{p}d\nu <\epsilon$ for $n$ sufficiently large. By Fatou's Lemma this gives $\int_{E_{\epsilon}^{c}} |g|^{p}d\nu \leq\delta$. Hence $\|-gI_{E_{\epsilon}^{c}}\|_p \leq \epsilon^{1/p}$.


text:
Q: file-loader with postTransformPublicPath I have an issue loading fonts with a dynamic public path replaced cdn at run time. So I have something like this:
vue.config.js file
chainWebpack: config => {
        config.module
            .rule('fonts')
            .use('file-loader')
            .loader('file-loader')
            .options({
                emitFile: true,
                name: '[name].[hash].[ext]',
                outputPath: 'staticV2/fonts/',
                publicPath: process.env.NODE_ENV === "production" ? "./#CDN#" : "/",
                postTransformPublicPath: (p) => `__webpack_public_path__ + ${p}`
            });
}

main.js (entry point) file
__webpack_public_path__ = window.cdnHost; // this is set at load time by the server side rendered index.html and works for all other resources like js, svg, png, etc except fonts

font-face.scss
@font-face {
  font-family: 'Noto Sans Regular';
  src: local('Noto Sans Regular'), local('NotoSans-Regular'),
  url(~@/design/assets/fonts/NotoSans-Regular.woff2) format('woff2'),
  url(~@/design/assets/fonts/NotoSans-Regular.woff) format('woff');
  font-display: swap;
}

font-face.css is loaded in App.vue file (root component)
it all works fine in development mode since i set the publicPath: "/" but when i build for production mode, the call for the fonts is something like : http://localhost/#CDN#/NotoSans-Regular.36747d3d16c9a73c831cb804fb8b1fab.woff2  as you can see the #CDN# placeholder is not getting replaced as the documentation for file-loader would suggest.
Thanks!


text:
Q: Unexpected token error when using d3.js? when I refer to d3.js, I am getting the error
Uncaught SyntaxError: Unexpected token ILLEGAL
bar.html:27 Uncaught ReferenceError: d3 is not defined

 var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π;
  function d3_sgn(x) {
    return x > 0 ? 1 : x < 0 ? -1 : 0;
  }

when I refer o d3.min.js, everything is fine. But I need to refer to d3.js for debugging purpose, please help.

A: You need to include <meta charset="utf-8"> in your HTML. d3 uses some special math symbols that aren't available in plain ASCII so you need to tell the browser to use UTF-8.
(for examples see the definition of d3.random.normal, line 7396 in 3.5)


text:
Q: Bash Shell Piping $() vs direct command Newbie to shell programming.
To run a command and put its output in variable we use:
var=$(command)

What's the difference with redirect piping between command and $(command).
Works:
command | while read line
do
  echo $line
done

Error
$(command) | while read line
do
  echo $line
done

A: A Command substitution is executed in a subshell and the output is then placed in the original command.
So, basically you are tying to do this;
$(command)        | while read line    # Example
result-of-command | while read line    # Bash reads

Read more about Command Subsitution at tldp, or unix.stackexchange


text:
Q: Pythonic way to extract elements in nested lists I was attempting to extract elements in a list of lists using this code snippet - arr[0[0]]. It would give me the "int not subscriptable" error.
I eventually found that arr[0][0] would return the first element of the first list. But in the various SO answers I found, none gave this style as an option. (The specific problems were better addressed using list comprehension.)
Is there a reason why more experienced coders wouldn't use this to access elements within a list? Or is this a problem that's better solved using Numpy arrays, so it just doesn't come up often for standard Python 3?


text:
Q: Get character out of image with python I want to detect the characters in a image like this with python:

In this case the code should return the result '6010001'.
How can I get the result out of this image? What do I need?
For your information, if the solution is a AI-solution, there are about 20.000 labeled images.
Thank you in forward :)

A: Question: Are all the pictures of similar nature?
Meaning the Numbers are stamped into a similar material, or are they random pictures with numbers with different techniques (e.g. pen drawn, stamped etc.)?
If they are all quite similar (nice contrast as in sample pic), I would recommend to write your "own" AI, otherwise use an existing neural network / library (as I assume you may want to avoid the pain of creating your own neural network - and tag a lot of pictures).
If they pics are quite "similar", following suggested approach:

*

*

*

*greyscale Image with increase contrast

*

*define box (greater than a digit), scan over image and count 0s, define by trial valid range to detect a digit, avoid overlaps

*

*each hit take area, split it in sectors, e.g. 6x4, count 0s

*

*build a little knowledge base (csv file) of counts per sector for each number from 0-9 (e.g. a string); you will end up in the database with multiple valid strings per each number, just ensure they are unique (otherwise redefine steps 1-3)

In addition I recommend to make yourself a smart knowledge database, meaning: if the digit could not be identified, save digit picture and result. Then make yourself a little review program where it shows you the undefined digits and the result string, you can then manually add them to your knowledge database for the respective number.
Hope it helps. I used the same approach read a lot of different data from screen pictures and store them in a database. Works like a charm.
#better do it yourself than using a standard neural network :)

A: You can use opencv-python and pytesseract
import cv2
import pytesseract

img = cv2.imread('img3.jpeg')
text = pytesseract.image_to_string(img)
print(text)

It doesn't work for all images with text, but works for most.


text:
Q: Python won't assign the right value in simple "if" statement I have a Django project where users can create reservations.
I am using Tastypie for the API to which I submit simple POST request to  in order to create a reservation in the database.
Let's say we have a request like this(from Chrome Network Tab)
{passenger_name: "John", service_time_start: "12:12:12", flight_time: "12:12:12",…}
car_type: false
passenger_email: "john@gmail.com"
passenger_lastname: "Smith"
passenger_name: "John"
passenger_number: "5"
route_end: "Los Angeles"
route_start: "New York"

I'm using this code(models.py) at the server-side.
I want to assign a car_type to the instance with Django Signals.
''' Change car type for new reservation '''
@receiver(pre_save, sender=Reservation)
def smart_car_options(sender, instance, *args, **kwargs):

    print 'SIGNAL: pass_no: ', instance.passenger_number
    print 'SIGNAL: car_type: ', type(instance.car_type)

    if instance.car_type == False:
        if instance.passenger_number <= 3:
            instance.car_type = 'CAR'
        if 4 < instance.passenger_number <= 8:
            instance.car_type = 'VAN'
        if instance.passenger_number > 8:
            instance.car_type = 'BUS'

    print "--------------------------------------------"
    print 'SIGNAL: pass_no: ', instance.passenger_number
    print 'SIGNAL: car_type: ', instance.car_type

As you can see, the instance.car_type is beeing set to 'BUS', when it should be set to 'VAN'. What am I doing wrong?
Also, here is my console output for the request:
[20/Mar/2015 02:10:21] "POST /api/reservation/ HTTP/1.1" 201 736
[20/Mar/2015 02:10:40] "GET /forms/as_shuttle/ HTTP/1.1" 200 16237
[20/Mar/2015 02:10:52] "GET /static/debug_toolbar/css/toolbar.css HTTP/1.1" 304 0
SIGNAL: pass_no:  5
SIGNAL: car_type:  <type 'bool'>
--------------------------------------------
SIGNAL: pass_no:  5
SIGNAL: car_type:  BUS
[20/Mar/2015 02:11:06] "POST /api/reservation/ HTTP/1.1" 201 732

It looks like passenger_number is beeing set correctly, but it still won't assign the right value to the instance. It's always assigning the last value, 'BUS'.
PS: The same code is working fine in the django admin.

A: It may be that you are not converting passenger_number to an integer so the comparison operators are comparing between a string and an integer.
>>> "5" < 8
False
>>> "5" > 8
True

So try something like num_passengers = int(instance.passenger_number) and then do your comparisons against that instead.


text:
Q: Notification Access Permission Not Working When App is Closed(oppo,vivo and mi) I'm developing an app (Notification History Log for Everyone).
I received a lot of negative reviews from the user using MIUI and Color OS saying the app is not working. I checked with Redmi Note 4 and started testing the apps.
Here is what I observed:
Case 1: Installing for the first time.
My app cannot read any new notifications. onNotificationPosted method in NotificationListenerService is not called at all.
Case 2: Uninstalled the app and reinstalled again and the app is in the foreground.
My app now started to read new notifications and onNotificationPosted method is called this time
Case 3: I closed the app and app is in the background
onNotificationPosted method is called only sometimes (25% times it is called)
Case 4: Removed app from recent apps list
onNotificationPosted method is never called.

I downloaded around 10 other apps from play store which uses the same Notification Access Permission and I observed the same problem with every app.
Is this a bug or restriction?
Note 1: I tested the same app with the same code on Stock Android, Oxygen, CM, TouchWiz and it is working fine without any issues.
The problem is only with Xiaomi (MIUI), Oppo (Color OS) and Vivo (FunTouch OS) devices.
I have checked with PushBullet app in the app store which uses the same notification access permission and yet works.
Is there a workaround?


text: Q: Apply gradient on VectorDrawable inside ImageView in Android programmatically I have a vector drawable, which is inside of imageview in layout. I would like to set gradient color programmatically (depending on some cases). I'm able to set a specific color to the imageview by using ColorFilter. How can I also set a gradient to a vector drawable?


text:
Q: Alfresco Search with a direct URL Parameter We have an existing web application that has configurable URLs with parameters for an easy integration of other systems. For example: I can easy generate a clickable URL like https://external-system/&query=Invoice_123456.
We also run Alfresco for document storage and an archive of PDFs. If I go to Alfresco Share and search for "Invoice_123456", I can see the documents that I was looking for.
Is there something like an URL for searching the Alfresco Repo globally for content by using a GET or POST parameter? For example: "https://alfresco.local/share/search/query=Invoice_123456"
We're using Alfresco 5.0.b currently.
Thanks

A: Hopefully I'm not oversimplifying this, but yes... basically you just need to include a "searchTerm" hash parameter... for example:
/share/page/dp/ws/faceted-search#searchTerm=Invoice_123456
It is also possible to add in further URL hash parameters for scope (e.g. repository wide, within sites, within a specific site), sort field/direction and any facet filters that should be applied.
The simplest way to achieve this it to perform the search you want and then copy/paste the URL from the browser (this is why I'm wondering if I'm missing some nuance from the question!?)

A: I would use the slingshot API
This is the definition of the webscript :
GET /alfresco/s/slingshot/search?term={term?}&tag={tag?}&site={site?}&container={container?}&sort={sort?}&query={query?}&repo={repo?}

Since I don't exactly have your case, here is an example for a document search by the name property :
http://localhost:8080/alfresco/s/slingshot/search?query={"prop_cm_name":"Invoice_123456","datatype":"cm:content"}

You can find more information in the description of this webscript at this url of your local alfresco :
http://localhost:8080/alfresco/s/script/org/alfresco/slingshot/search/search.get

Now, if you want a html output instead of a JSON one, you cant create your own template search.get.html.ftl and create the view you need.
(you have many ways to do this (inside the war, or in the extension folder)
Then you can call your webscript with the format parameter :
http://localhost:8080/alfresco/s/slingshot/search?query={"prop_cm_name":"Invoice_123456","datatype":"cm:content"}&format=html


text:
Q: What does "." (Dot) do in Visual Studio Code "runtimeArgs" property of launch.json Today, I opened up my Visual Studio Code and saw that a new update has been released. Like any other normal (and ignorant) user, I just installed the update without any research about the changes. It's been months since I haven't had a problem with the updates so I assumed this one would be no different. But after the update, "launch" options would no longer work!
I have an Electron/Angularjs app. This launch config simply runs the app. Everything was working fine before the VS Code update but after the latest update (v 1.22.1), the app fails to launch from within VS Code.
I can, however, run my app through command line, so there are no changes/problems with Electron or others. The main Electron process would fail to find a module at $workspaceFolder (something about electron.asar resolvePaths?).
After a couple of hours of research, I found out that adding this simple property, grants my wish:
"runtimeArgs": [
    "."
]

Does anyone know what this little guy does in VS Code launch.json?
Here's the full launch.json in case you need it:
"version": "0.2.0",
"configurations": [
    {
        "type": "node",
        "request": "launch",
        "name": "Electron",
        "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
        "windows": {
            "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
        },
        "program": "${workspaceFolder}/Src/main.js",
        "protocol": "inspector",
        "console": "integratedTerminal",
        "cwd": "${workspaceRoot}",
        "runtimeArgs": [
            "."
        ]
    }
]

A: dot "." would pass your current working directory(cwd) to runtimeExecutable
,which in this case is .bin/electron.
So this executes
$ electron .

I'm guessing"program": "${workspaceFolder}/Src/main.js" is redundant and can be removed, because electron accepts a directory as path , given there's a package file in it.


text:
Q: mock request with webpack server I'm developing a chrome extension for tiktok. I'm creating a development environment and i need to mock some requests, for example, when you load a profile page there is a network call that i want to mock:
web-privacy-config?lang=en
it's a GET request and responds with a payload in body.
So far i'm trying this without success:
devServer: {
    contentBase: path.resolve(__dirname, './src'),
    hot: true,
    proxy: {
        // tiktok mock requests
        '/node/common/web-privacy-config': {
            target: 'http://localhost:8080/mocks/web-privacy-config.json',
            pathRewrite: {'^/node/common/web-privacy-config': ''}
        }
    },
},


text:
Q: Removing a substring from a column in a text file I have a shell script:
a ab.mi
3 jm.mi
56 uh.mi

I want to remove .mi from the 2nd column and make it like:
a ab
3 jm
56 uh

How can I do this with shell script?

A: Using awk:
awk 'gsub("\.mi", "", $2)1' inputfile

This would remove .mi from the second column.

A: If you really just want to remove the string .mi then a simple sed substitution will do:
$ sed 's/[.]mi//' file
a ab
3 jm
56 uh

If you really want to restrict to the second column awk is better choice but with sed you could do:
$ sed -r 's/(\S+\s+\S+)[.]mi/\1/' file
a ab
3 jm
56 uh

A: Perl One-Liner:
perl -pe -i.bak 's/\.mi$//i' file


text:
Q: Julia: Broadcasting pairwise distance calculation across tensor of observations I am trying to use the Distances package in Julia to perform a broadcasted computation of distance matrices.
I understand how to calculate a single N x N distance matrix for some matrix X (with dimensions D x N), where each column X[:,i] stores a D-dimensional feature vector for observation i. The code would be:
using Distances

dist_matrix = pairwise(Euclidean(), X, dims = 2)

dist_matrix contains the Euclidean distances between each pair of D-dimensional columns, e.g. dist_matrix[m,n] stores the Euclidean distance between X[:,m] and X[:,n].
Now imagine my array X is actually an entire tensor or 'volume' of D-dimensional observations, so that X[:,i,j] stores the j-th 'slice' of my D x N observations. The whole array X thus has dimensions D x N x T, where T is the number of slices.
Accordingly, I want to compute a tensor or 'volume' of distance matrices, so that dist_matrix will have dimensions N x N x T.
Is there a way to do this in a single line by broadcasting the pairwise() function in Julia? What's the fastest way to do this? Below shows the idea with a basic for loop:
using Distances

dist_matrix_tensor = zeros(N,N,T);

for t = 1:T
        dist_matrix_tensor[:,:,t] = pairwise(Euclidean(), X[:,:,t], dims = 2)
end

EDIT:
I figured out how to do this using mapslices, but still not sure if it's the best way.
using Distances

dist_function(x)  = pairwise(Euclidean(), x, dims = 2) # define a function that gets the N x N distance matrix for a single 'slice'

dist_matrix_tensor = mapslices(dist_function, X, dims = [1,2]) # map your matrix-operating function across the slices of the main tensor X

This can of course also be parallelized since each 'slice' of X is independent in this computation, so I'm basically just looking for the fastest way to do this. I'm also in general interested in how you would do this with broadcasting specifically.

A: Your solution with mapslices is reasonably performant if the dimension of X is large. Below is an example with JuliennedArrays which is slightly faster for small X, but has the same performance as mapslices when the two first dimensions are of size 100.
using Distances, JuliennedArrays, BenchmarkTools

dist_function(x)  = pairwise(Euclidean(), x, dims = 2) # define a function that gets the N x N distance matrix for a single 'slice'

X = randn(10,10,20);
dist_matrix_tensor = @btime mapslices(dist_function, X, dims = [1,2]); # 61.172 μs (198 allocations: 42.28 KiB)
dist_matrix_tensor2 = @btime map(dist_function, Slices(X, 1, 2)); # 41.529 μs (62 allocations: 21.67 KiB)

Note, however, that JuliennedArrays returns a Vector of Matrix rather than a three-dimensional array.


text:
Q: javascript code not working if placed at top of file I have the following code. It set a filter bar in a search results page in a fixed position in the window after scrolling down to a certain point:
var docked;
var filters = document.getElementById('filters');
var init = filters.offsetTop;

function scrollTop() {
  return document.body.scrollTop || document.documentElement.scrollTop;
}

window.onscroll = function () {
  if (!docked && (init - scrollTop() < 0)) {
    filters.style.top = 0;
    filters.style.position = 'fixed';
    filters.className = 'docked';
    docked = true;
  } else if (docked && scrollTop() <= init) {
    filters.style.position = 'absolute';
    filters.style.top = init + 'px';
    filters.className = filters.className.replace('docked', '');
    docked = false;
  }
}

My issue is (and it's more curiosity) - if I place this code at the top of my file (in the <head>), it doesn't work at all. The filter section doesn't scroll with the window as it should. However, when I place this code at the bottom of the file (right above the closing </body> tag), it works just fine.
Why is this? Does this have something to do with the way the code works? Or could it be just a quirk or bug in the rest of my file causing this?

A: Wrap your assignments in window.onload = function(){ /* your code here */ }; and it will run. The reason being that your assignment of var filters = document.getElementById('filters'); comes back as undefined since that element does not exist during page load at the time you reference it.
Example:
var docked;
var filters;
var init;
window.onload = function(){
 filters = document.getElementById('filters');
 init = filters.offsetTop;
};

A: if you do this, it should work:
$(document).ready(window.onscroll = function () {
  if (!docked && (init - scrollTop() < 0)) {
    filters.style.top = 0;
    filters.style.position = 'fixed';
    filters.className = 'docked';
    docked = true;
  } else if (docked && scrollTop() <= init) {
    filters.style.position = 'absolute';
    filters.style.top = init + 'px';
    filters.className = filters.className.replace('docked', '');
    docked = false;
  }
}
);


text:
Q: How does DrawPdfPage() know which parts to draw when used in CATiledLayer? In my CATiledLayerDelegate I have the following code to draw a PDF page. This works but I don't understand why! CATiledLayer is supposed to ask me whick tile to draw. The code below always draws the complete PDF page. Nevertheless I can see the tiles appearing one by one. How does that work?
If I subclass CATiledLayer, I can override drawRect: which asks me for a specific rectangle to draw, but using the delegate this is not the case. So how does that magic work?
public override void DrawLayer (CALayer layer, CGContext context)
                {
                    context.SaveState ();
                    context.SetRGBFillColor (1.0f, 1.0f, 1.0f, 1.0f);
                    context.FillRect (context.GetClipBoundingBox ());
                    context.TranslateCTM (0.0f, layer.Bounds.Size.Height);
                    context.ScaleCTM (1.0f, -1.0f);
                    context.ConcatCTM (this.oParentController.oPdfPage.GetDrawingTransform (CGPDFBox.Media, layer.Bounds, 0, true));
                    context.DrawPDFPage (this.oParentController.oPdfPage);
                    context.RestoreState ();
                }

A: Figured out after more research. DrawLayer() is really drawing the whole layer. CATiledLayer is then taking care of passing on only the required tiles to the scrollview for instance.
This means: if the PDF page being drawn s big enough (memory wise), iOS will run OOM even though tiling is used. One would have to write the tiling from scratch like the guys of Goodreader probably did.


text:
Q: Area by integration Find the area of $\int_{0}^{3} xf(x^2)dx$, with $f(x)=\sqrt{-x^2+4x}$
I've integrated this into a pretty gross form, where $A=\frac{1}
{2}sin(2arccos(\frac{1}{2}x^2-1))-arccos(\frac{1}{2}x^2-1)+C{]_0}{_,}{_3}$

A: $$f(x) = \sqrt{-x^2+4x} = \sqrt{2^2-(x-2)^2}$$
This is the equation of the upper-half of a circle centered at $(2,0)$ of radius 2.
This means that $f(x)$ takes real values from $x=0$ to $x=4$. So, for $4 < x < 9$, the function is complex. This means, you have:
$$\int_0^3 xf(x^2)dx = \int_0^2 xf(x^2)dx + \int_2^3 xf(x^2)dx$$
The middle one can be simplified using $u=x^2, du=2xdx$, which gives:
$$\int_0^2 xf(x^2)dx = \dfrac{1}{2}\int_0^4 f(u)du$$
But, this integral is just half the area of the upper half of a circle of radius $2$, or a quarter the area of the full circle of radius $2$:
$$\dfrac{1}{4}\pi r^2 = \dfrac{1}{4}\pi(2^2) = \pi$$
This is the real part of the solution. If the original upper bound were $2$, we would stop here and the solution would be $\pi$.
But, the original upper bound was $3$. So, you have:
$$\int_2^3 xf(x^2)dx = \dfrac{1}{2}\int_4^9 f(u)du$$
But, this is a complex-valued function (no real component).


text:
Q: Show that a Linear transformation does not change shape of a distribution It is easy to show how a linear transformation affects the mean or the variance of a distribution. It is easy to find over the internet that a linear transformation does not change the shape of a distribution.
My question is, why a linear transformation does not change the shape of a distribution? Is it an easy to show proof?

A: This question urges us to consider what the "shape" of a distribution might be.  I would like to describe a perspective in which it is intimately connected with the meaning of "shape" in (elementary) geometry.  It leads to an answer that requires no proof at all: it's all part of the definition.
The bottom line is this: two distributions on a geometrical space "have the same shape" when there is a geometrical transformation that converts one of the distributions into the other.  Thus, the sense of "same shape" depends on what you consider a "geometrical transformation" to be.  There are many reasonable and interesting choices, so ultimately the answer must depend on the context in which you are manipulating distributions.
In the following discussion, which is abbreviated and abstract, I include many practical, well-known examples to demonstrate the applicability and importance of these ideas.  The examples can be greatly extended.  Other common applications include distributions on Complex vector spaces; distributions in space $\mathbb R^3$ and high dimensions; and distributions on the circle, sphere, and their higher-dimensional analogs.

Because "shape" is a geometrical concept and "distribution" is a probabilistic or measure-theoretic concept, common ground is found within geometric spaces that might support distributions.
Geometry
The modern (post 19th century) conception of geometry is taught in Lang & Murrow's Geometry (a textbook written for early high school students).  It is the study of a group of transformations acting on a set.  The archetypical examples, analyzed by Euclid, are the actions of reflections and isotheties (uniform scalings) in the plane $\mathbb R^2$ and space $\mathbb R^3.$
For the present purposes, it suffices to characterize the situation this way:

*

*A transformation is a one-to-one correspondence of the set elements with themselves.

*Undoing any transformation in the group, followed by applying any other (potentially the same) transformation, is also in the group.
The elements of the underlying set are called "points" and, together with a group of transformation, deserve to be called a "geometric space."
A "geometric figure" is any set of points in a geometric space.  The "shape" of a figure is the set of its properties that are not changed by any of the group transformations.
As examples,

*

*The Euclidean group is generated by all the reflections in the plane.  It includes all rotations about arbitrary points, as well as translations.  We say two plane figures are "congruent" when one of them can be transformed to the other via some transformation in this group.

*The group generated by all reflections along with all isotheties (uniform scalings) in the plane is the "similarity group."  We say two figures are "similar" (that is, they have the same (Euclidean) shape) when one of them can be transformed to the other via some transformation in this group.
These are the two examples studied in detail in any high school plane geometry course.
Given a geometry, let's agree to say generally that two figures are congruent when one can be transformed to the other, as illustrated in these examples.
Distributions
A "distribution" on a set (which in our applications will support a geometric structure) consists of (1) a specified collection of figures, often called "events," and (2) an assignment of a number to each figure, called its "measure."  Various familiar axioms permit us to deduce the measures of figures that are assembled from other figures by adjoining them or removing parts of them.
Transformations of the set induce transformations of distributions.  When $g$ is a geometric transformation, $\mathbb P$ a distribution, and $\mathcal E$ is a figure, the transformed distribution assigns the value $\mathbb{P}(\mathcal E)$ to the figure $g(\mathcal E).$  Since the transformation is one-to-one, all figures can be written in the latter form, thereby fully defining the transformed distribution.
Putting the ideas together

Two distributions on a geometric space have the same shape when there is a transformation in the geometry that transforms one of the distributions into the other.

"Have the same shape" determines equivalence classes of distributions in which the value of a figure depends only on its shape.
Examples
Translation (and reflection) invariance on the line
One of the simplest geometric spaces is the real line $\mathbb R^1$ with the group generated by all reflections.  Any reflection can be expressed numerically as a function of the form $$\mathcal{R}_h: x \to 2h-x$$ where the point $h\in\mathbb R$ is the "center" of the reflection (because clearly it is not moved).  A reflection undoes itself.  So, the result of any reflection followed by another must also be in the transformation group.  Letting the two centers be $h$ and $k,$ we find the result of applying $\mathcal{R}_h$ and then $\mathcal{R}_k$ to be
$$\mathcal{R}_k \circ \mathcal{R}_h: x \to 2k - (2h-x) = x + 2(k-h).$$
These are all translations of the line.  So, for instance, the intervals $[0,1]$ and $[2,3]$ are congruent via the translation by $+2.$  The unions $[0,1]\cup[2,4]$ and $[0,2]\cup[3,4]$ are congruent via the reflection $\mathcal{R}_2.$  However, the unions $[0,1]\cup[2,3]$ and $[0,1]\cup[3,4]$ are not congruent in this geometry.
Two distributions on the line have the same shape when they differ either by a translation or a reflection.  When $\mathbb P$ is a probability distribution (it doesn't assign any negative values to events and it assigns the value $1$ to the entire space), the other distributions with the same shape are those that differ from it by a translation or reflection.
For instance, the Normal distribution with parameters $\mu$ and $\sigma\ne 0,$ written $\mathcal{N}(\mu,\sigma),$ arises when (1) all intervals are considered events (along with additional shapes that can be constructed from intervals) and (2) the value assigned to any event $\mathcal E$ is given by
$$\Pr(\mathcal E;\mu, \sigma) = \int_{\mathcal{E}} \frac{1}{\sqrt{2\pi\sigma^2}}\exp(-(x-\mu)^2/(2\sigma^2))\,\mathrm{d}x.$$
Using basic rules of Calculus it is straightforward to show that for any number $\delta,$ $\mathcal{N}(\mu,\sigma)$ and $\mathcal{N}(\mu + \delta,\sigma)$ have the same shape.
In this geometry, however, if $\sigma\ne\tau,$ then $\mathcal{N}(\mu,\sigma)$ and $\mathcal{N}(\mu,\tau)$ do not have the same shape: neither is a translate nor a reflection of the other.
Affine invariance on the line
The affine group of transformations of the real line consists of all those of the form
$$x \to ax + b,\quad a \ne 0.$$
Two distributions are congruent in this geometry when one can be rescaled (possibly reversing it) and shifted into the other.  In this geometry, all Normal distributions have the same shape.  In effect, there is only one Normal distribution.
Special affine invariance on the line
The special affine group of transformations does not allow reversal of direction: $a$ in the preceding formula must be positive.  This is the usual sense in which statisticians mean that (univariate) distributions have the same shape.
For example, all Beta$(a,b)$ distributions have distinct shapes ($a,b\gt 0$) in the special affine geometry.  However, a Beta$(a,b)$ and Beta$(b,a)$ distribution have the same shape in the full affine geometry because the reflection $\mathcal{R}_{1/2}$ converts one distribution to the other.
Another nice set of examples is offered by Bernoulli$(p)$ distributions, $0\lt p \lt 1,$ written B$(p).$  These all have different shapes in special affine geometry, but B$(p)$ and B$(1-p)$ have the same shapes in affine geometry.
Higher dimensional geometries
The foregoing trivialities become more interesting when we contemplate multivariate distributions.  To illustrate, the Binormal distribution with parameters $\mu_1,$ $\mu_2,$ $\sigma_1,$ $\sigma_2,$ and $\rho$ generalizes the Normal distribution.  (To avoid unnecessary distractions, I exclude the possibilities $\sigma_1=0$ or $\sigma_2=0$ from the following discussion.)  Let's call this BN$(\mu_1,\ldots, \rho).$  Contours of its probability density function are ellipses centered at $(\mu_1,\mu_2).$ Consider just three of the commonest geometries in the plane.

*

*In Euclidean geometry, BN$(\mu_1,\ldots, \rho)$ and BN$(\mu_1^\prime,\ldots,\rho^\prime)$ are congruent if and only if

*

*$|\rho|=|\rho^\prime|$ (their contour ellipses have the same eccentricities).

*Either $\sigma_1=\sigma_1^\prime$ and $\sigma_2=\sigma_2^\prime$ or $\sigma_1=\sigma_2^\prime$ and $\sigma_2=\sigma_1^\prime.$
This is because a Binormal distribution with correlation coefficient $\rho$ can be rotated into one with correlation coefficient $-\rho$ and its variances $\sigma_i^2$ can be switched when it is rotated by a quarter circle; and they can be freely shifted to any location.

*When similarity transformations are permitted, the criterion for two Binormal distributions to be congruent is relaxed.  Now it suffices that $|\rho|=|\rho^\prime|$ and that either $\sigma_2/\sigma_1 = \sigma_2^\prime/\sigma_1^\prime$ or $\sigma_2/\sigma_1 = \sigma_1^\prime/\sigma_2^\prime.$  That is, size no longer matters.

*The most general group of invertible linear transformations of the plane is the general linear group, $GL(\mathbb R, 2).$  This includes skew transformations along with reflections and isotheties.  This is the group I exploited heavily in an analysis of regression and correlation at What is the intuition behind conditional Gaussian distributions?.  As shown there, two Binormal distributions are congruent (with respect to the general linear group) if and only if they have a common center.  Moreover, when we include translations in the geometry (thereby producing the general affine group), any two Binormal distributions are affinely congruent.
In the sense of $(3),$ there is only one Binormal distribution!

Conclusions
What it means for two distributions to "have the same shape" depends on a geometric structure you elect to use for the space on which those distributions are defined.
When that space is the set of real numbers and the geometry's group consists of all translations and positive rescalings, we recover the standard statistical sense in which two univariate distributions have the same shape.
When the space has more than one dimension, we're discussing multivariate distributions.  Because there is a rich set of possible geometries to consider, the meaning of "have the same shape" will depend on which geometry is applicable to any particular problem or context.  In some settings, for instance, all Binormal distributions have the same shape.
Accordingly, to paraphrase the geometric definition of shape,

The shape of a distribution is the set of its properties that are not changed by any geometrical transformation.

To resolve the present question, then, it should now be clear that the answer depends on which geometry you chose to use.  When your geometry is that of the general group of affine transformations of the line, then the answer is yes: two distributions have the same shape if and only if they are related by an affine transformation.  Otherwise, the answer is no.

A: Showing this requires a definition of "shape". All that comes to mind to me is what the distribution looks like if it is centered and scaled. This is straightforward when the mean exists and variance is finite, so I will proceed with such an assumption.
Let $X$ be a random variable with distribution function $F_X(x)$. Define a new random variable, $Z$, as a function of $X$.
$$
Z(X) = \dfrac{X-\mathbb E \big[X\big]}
{\sqrt{var(X)}}
$$
Now let $T(X) = a + bX$ be a linear transformation with $b \ne 0$.
$$
\mathbb E\big[ T(X)\big] = a + b\mathbb E\big[ X \big]\\
var(T(X)) = b^2var(X)
$$
Let's apply that same logic of centering and scaling $T(X)$.
$$
Z(T(X)) = \dfrac{
T(X) - \mathbb E\big[ T(X)\big]
}{
\sqrt{var(T(X))}
}
= \dfrac{
a + bX -(a + b\mathbb E\big[ X \big])
}{
\sqrt{b^2var(X)}
}
=\dfrac{
bX-b\mathbb E\big[ X \big]
}{
b\sqrt{var(X)}
} \\= \dfrac{X-\mathbb E \big[X\big]}
{\sqrt{var(X)}} = Z(X)
$$


text:
Q: Create a Spring Search DTO with defined list Is it possible to create a DTO with validation tag which accepts only defined list of values? For example:
@Getter
@Setter
public class SearchParams {

    private String title;

    @NotNull
    private String type; // type can be only 'approved', 'new' and 'closed'
}

Is there some way to use tags to have only this strict list of values?

A: @Getter
@Setter
public class SearchParams {
    private String title;

    @NotNull
    private TypeEnum type;

}

public enum TypeEnum {
    APPROVED,
    NEW,
    CLOSED
}

You can enrich the enum with a description in order to have control on the case sensitiveness
public enum TypeEnum {
    APPROVED("approved"),
    NEW("new"),
    CLOSED("closed");

    private String desc;

    TypeEnum(String desc) {
        this.desc = desc;
    }

    public String getDesc() {
        return desc;
    }

    static TypeEnum fromDesc(String desc) {
        TypeEnum[] values = TypeEnum.values();
        for (TypeEnum typeEnum: values) {
            if (typeEnum.getDesc().equals(desc)) {
                return typeEnum;
            }
        }

        return null;
    }
}

So you can get the relevant enumeration via a lowercase String as:
TypeEnum.fromDesc("new") // this will return TypeEnum.NEW


text:
Q: How to save data in the link table using jpa I have two master table named person and department. I had also created one link table called person_department. The design of the table is as below.
Person Table
------------------
person_id  varchar primary key
first_name varchar
last_name  varchar

Department Table
----------------------------------
dept_id   varchar primary key
dept_name varchar

Persone_department Table
----------------------------------
person_dept_id varchar  primary key
person_id      varchar  foreign key person table
dept_id        varchar  foreign key dept table

The classes for the above design is as below.

@Entity
Class Persoon {
    @Id
    String id;

    @Column(name="first_name")
    String firstName;

    @Column(name="last_name")
    String lastName;
}

@Entity
Class Department {
   @Id
   String departmentId;

   @column(name="dept_name")
   String deptName;
}

@Entity
Class PersonDepartment {
   @Id
   String personDeptId;

   @ManyToOne
   @Column(name="person_id")
   List<String> personId;

   @ManyToOne
   @Column(name="dept_id")
   List<String> deptId;
}

One person can work in multiple department and one department can have multiple person. I have below three use cases.

*

*fetch person's department.

*add person to a new department.

*list all person of a department.

Could anyone please help me on how to implement this use cases ?
When I'm trying to save the data in person_department table I'm getting error.


text:
Q: How to change Iconbutton once you click on it to a different Iconbutton i want to change the icon on the IconButton once you click on it then make my slider slideup. so like this
when you click list view - slides up
when you click map- slides down
bool _pressAttention = true;

IconButton(
     icon: (_pressAttention? Icon(Icons.view_list, color: Colors.grey): Icon(Icons.map, color: Colors.grey)),
     onPressed: (){
         setState(() {
              if (_pressAttention=true){
                   _pc.open();

                  } else{
                     _pc.close();

                    }
                    });
                  }
                 )

A: Your if statement needs == instead of = or you can shorten it down to if (_pressAttention) {. Also you're never changing _pressAttention's value. First make sure you put _pressAttention = true between Widget build(BuildContext context) { and return, otherwise it will be true on every reload. Then change your code to this:
setState(() {
  _pressAttention = _pressAttention ? false : true;

  if (_pressAttention) {
    _pc.open();
  } else {
    _pc.close();
  }
});

A: try this ,
 _pressAttention ?
    IconButton(
        icon:  Icon(Icons.view_list, color: Colors.grey) , onPressed: () => setState(() {  _pc.open();})) :
  IconButton(
      icon:  Icon(Icons.map, color: Colors.grey) , onPressed: () => setState(() {  _pc.close();}) );


text:
Q: Logstash 1.4.2 grok filter: _grokparsefailure
*

*i am trying to parse this log line:
-  2014-04-29 13:04:23,733 [main] INFO  (api.batch.ThreadPoolWorker) Command-line options for this run:
here's the logstash config file i use:

input {
        stdin {}
}

filter {
 grok {
    match => [ "message", " - %{TIMESTAMP_ISO8601:time} \[%{WORD:main}\] %{LOGLEVEL:loglevel} %{JAVACLASS:class} %{DATA:mydata} "]
  }

    date {
    match => [ "timestamp" , "dd/MMM/yyyy:HH:mm:ss Z" ]
  }

output {
  elasticsearch {
    host => "localhost"
  }
  stdout { codec => rubydebug }
}

Here's the output i get:

{
       "message" => " - 2014-04-29 13:04:23,733 [main] INFO (api.batch.ThreadPoolWorker) Commans run:",
      "@version" => "1",
    "@timestamp" => "2015-02-02T10:53:58.282Z",
          "host" => "NAME_001.corp.com",
          "tags" => [
        [0] "_grokparsefailure"
    ]
}

Please if anyone can help me find where the problem is on the gork pattern.
I tried to parse that line in http://grokdebug.herokuapp.com/ but it parses only the timestamp, %{WORD} and %{LOGLEVEL} the rest is ignored!

A: There are two error in your config.
First
The error in GROK is the JAVACLASS, you have to include ( ) in the pattern, For example:  \(%{JAVACLASS:class}\.
Second
The date filter match have two value, first is the field you want to parse, so in your example it is time, not timestamp. The second value is the date pattern. You can refer to here
Here is the config
input {
        stdin {

        }
}

filter {
        grok {
                match => [ "message", " - %{TIMESTAMP_ISO8601:time} \[%{WORD:main}\] %{LOGLEVEL:loglevel} \(%{JAVACLASS:class}\) %{GREEDYDATA:mydata}"
                ]
        }
        date {
                match => [ "time" , "YYYY-MM-dd HH:mm:ss,SSS" ]
        }
}

output
{
        stdout {
                codec => rubydebug
        }
}

FYI. Hope this can help you.


text:
Q: Short in front and short in back I've stumbled upon Ray Bradbury's odd way of using prepositions in his book "Death is a lonely business".

Cal, of course, had done that awful job. So I had several reasons to
  go visit. Cal, the worst barber in Venice, maybe the world, but cheap,
  called across the tidal waves of fog, waiting with his dull scissors,
  brandishing his Bumblebee Electric clippers that shocked and stunned
  poor writers and innocent customers who wandered in.
  Cal, I thought. Snip away the darkness.
  Short in front. So I can see.
  Short on the sides. So I can hear.
  Short in back. So I can feel things creeping up on me.

The way he asks the barber to cut his hair "short in front" and "short in back" maybe me really wonder if it is correct.
I'm used to "short at the front" and "short at the back".
Can someone explain this to me?

A: Personally, I would use in, not at, when talking about the front and back of my hair. And, just as Bradbury did, I would use on for the sides.
I don't know how else this can be explained, except to assure you that it's indeed acceptable idiomatic speech and to remind you that most prepositions are not confined to a single meaning but have multiple meanings and usages. It's also not uncommon for more than one preposition to be acceptable in a given context (e.g., "He lives up/down the street from the store.")
In this particular case, either in or at is acceptable. Consider the way these two dictionaries define mullet (emphasis added):

mullet (n.) a hairstyle in which the hair is short on the sides and top and long at the back
(source: Merriam-Webster)
mullet (n.) A hairstyle formed by cutting the hair short on the top and sides of the head and allowing it to grow longer in back.
(source: American Heritage)


text:
Q: how to restrict access to page via url in drupal 6 i am building an web store.
the store have 4 steps form like so:
($items['soda/checkout/1'] , $items['soda/checkout/2'] , $items['soda/checkout/3'] , $items['soda/checkout/4'])
each step can be access only if the former steps have been submited.
I want to restrict access so that users cant jump from 1st stage to 3rh 4th...
how can i do it?

A: Although, you can use value of $_SERVER['HTTP_REFERER'] to determine the referrer of current page. But it is not reliable.
Instead, you can store this information in cookies & check the current stage of user & take action accordingly.


text:
Q: Unable to capture the wild card(Garbage) word in speech recognition using SRGS namepsace C# I am a developing a C#.net application using speech recognition grammar specification (SRGS) namespace. I like to capture the wild card word. I have seen some examples where wild card word is captured using GrammarBuilder, But I am using SRGS namespace. I could not find any way to capture using this SRGS namespace.
I have written the below code to capture wildcard word. Below code should recognize phrases like " Execute report call statistics for E080755 event number:
SrgsOneOf reportsList = new SrgsOneOf();
reportsList.Add(new SrgsItem("Call Statistics"));

SrgsRule reportName = new SrgsRule("ReportName");
reportName.Add(reportsList);
reportName.Scope = SrgsRuleScope.Public;

SrgsRule executeReportRule = new SrgsRule("ExecuteReport");
SrgsItem executeReportWord = new SrgsItem("Execute report");
executeReportRule.Scope = SrgsRuleScope.Public;

SrgsItem forWord = new SrgsItem("for");
SrgsRule wildCardRule = new SrgsRule("WildCardRule");
wildCardRule.Scope = SrgsRuleScope.Public;

wildCardRule.Add(SrgsRuleRef.Garbage);
SrgsRuleRef wildCardRuleref = new SrgsRuleRef(wildCardRule, "WildCardWord");

SrgsItem eventNumberWord = new SrgsItem("event number");

executeReportRule.Add(executeReportWord);
executeReportRule.Add(new SrgsRuleRef(reportName, "ReportName"));
executeReportRule.Add(forWord);
executeReportRule.Add(wildCardRuleref);
executeReportRule.Add(eventNumberWord);

SrgsDocument document = new SrgsDocument();
document.Rules.Add(new SrgsRule[] { reportName, executeReportRule, wildCardRule });

document.Root = executeReportRule;

Grammar grammar = new Grammar(document, "ExecuteReport");

// Write the completed grammar to an XML-format SRGS grammar file.
System.Xml.XmlWriter writer =
System.Xml.XmlWriter.Create("c:\\Temp\\EventNumberGrammar.grxml");
document.WriteSrgs(writer);

writer.Close();

Tried to capture wild card word using "WildCardWord" semanti key . but i could get only "..." instead of original spoken word.
Thanks,
Vamshi Epuri

A: Better late than never...
"SrgsRuleRef.Garbage" means you expect some unimportant text till the aproach of the next explicitly expected word.
You cannot access it because it is declared to be "garbage".


text:
Q: SVG use tag and ReactJS So normally to include most of my SVG icons that require simple styling, I do:
<svg>
    <use xlink:href="/svg/svg-sprite#my-icon" />
</svg>

Now I have been playing with ReactJS as of late evaluating it as a possible component in my new front-end development stack however I noticed that in its list of supported tags/attributes, neither use or xlink:href are supported.
Is it possible to use svg sprites and load them in this way in ReactJS?

A: As already said in Jon Surrell's answer, use-tags are supported now. If you are not using JSX, you can implement it like this:
React.DOM.svg( { className: 'my-svg' },
    React.createElement( 'use', { xlinkHref: '/svg/svg-sprite#my-icon' }, '' )
)

A: Update september 2018: this solution is deprecated, read Jon's answer instead.
--
React doesn't support all SVG tags as you say, there is a list of supported tags here. They are working on wider support, f.ex in this ticket.
A common workaround is to inject HTML instead for non-supported tags, f.ex:
render: function() {
    var useTag = '<use xlink:href="/svg/svg-sprite#my-icon" />';
    return <svg dangerouslySetInnerHTML={{__html: useTag }} />;
}

A: MDN says that xlink:href is deprecated in favor of href. You should be able to use the href attribute directly. The example below includes both versions.
As of React 0.14, xlink:href is available via React as the property xlinkHref. It is mentioned as one of the "notable enhancements" in the release notes for 0.14.

<svg>
  <use xlinkHref='/svg/svg-sprite#my-icon' />
</svg>

<svg>
  <use xlink:href="/svg/svg-sprite#my-icon"></use>
</svg>

Update 2018-06-09: Added info about href vs xlink:href attributes and updated example to include both. Thanks @devuxer
Update 3: At time of writing, React master SVG properties can be found here.
Update 2: It appears that all svg attributes should now be available via react (see merged svg attribute PR).
Update 1: You may want to keep an eye on the svg related issue on GitHub for additional SVG support landing. There are developments in the works.
Demo:

const svgReactElement = (
  <svg
    viewBox="0 0 1340 667"
    width="100"
    height="100"
  >
    <image width="667" height="667" href="https://i.imgur.com/w7GCRPb.png"/>
    { /* Deprecated xlink:href usage */ }
    <image width="667" height="667" x="673" xlinkHref="https://i.imgur.com/w7GCRPb.png"/>
  </svg>
);

var resultHtml = ReactDOMServer.renderToStaticMarkup(svgReactElement);
document.getElementById('render-result-html').innerHTML = escapeHtml(resultHtml);

ReactDOM.render(svgReactElement, document.getElementById('render-result') );

function escapeHtml(unsafe) { return unsafe.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'"); }

Render result of rendering:

<svg
  viewBox="0 0 1340 667"
  width="100"
  height="100"
>
  <image width="667" height="667" href="https://i.imgur.com/w7GCRPb.png"/>
  { /* Deprecated xlink:href usage */ }
  <image width="667" height="667" x="673" xlinkHref="https://i.imgur.com/w7GCRPb.png"/>
</svg>

ReactDOMServer.renderToStaticMarkup() output:

ReactDOM.render() output:

A: I created a little helper that works around this issue: https://www.npmjs.com/package/react-svg-use
first npm i react-svg-use -S then simply
import Icon from 'react-svg-use'

React.createClass({
  render() {
    return (
      <Icon id='car' color='#D71421' />
    )
  }
})

and this will then generate the following markup
<svg>
  <use xlink:href="#car" style="fill:#D71421;"></use>
</svg>

A: If you encounter xlink:href, then you can get the equivalent in ReactJS by removing the colon and camelcasing the added text: xlinkHref.
You'll probably eventually be using other namespace-tags in SVG, like xml:space, etc..  The same rule applies to them (i.e., xml:space becomes xmlSpace).

A: I had problems with showing SVG in Gutenberg block, by referencing it with xlink:href. We used xlinkHref property in react, but after compiling, instead to render as xlink:href it was rendered to xlinkhref, and SVG was not displayed. After a lot of examining, I found out that xlink:href is deprecated (although it worked if we add it in html, or directly in chrome dev tools), and that href should be used instead. So after changing it to href it worked.
"SVG 2 removed the need for the xlink namespace, so instead of xlink:href you should use href." https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href
This is the code I used
SVG file
<svg id="svg-source" style="display: none;" aria-hidden="true" xmlns="http://www.w3.org/2000/svg">
    <symbol id="svg-arrow-accordion" viewBox="0 0 15 24" fill="none">
        <path id="Path_1662" data-name="Path 1662" d="M15.642,14.142h-3V1.5H0v-3H15.642Z" transform="translate(2 2) rotate(45)" fill="currentColor"></path>
    </symbol>
</svg>

React file
<svg xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" width="15" height="24">
<use href="#svg-arrow-accordion"></use>
</svg>

A: This is svg Component.
const SvgComponent = () => {
    return <svg width="0" height="0">
        <defs>
            <symbol id="test" viewBox="0 0 100 100">
                <line x1='0' y1='50' x2='100' y2='50' strokeWidth='8' stroke="#000" />
            </symbol>
        </defs>
    </svg>
}

export default SvgComponent

use component
import SvgComponent from './SvgComponent';

export default function App() {
  return (
    <>
      <SvgComponent/>
      <svg>
        <use xlinkHref="#test"></use>
      </svg>
    </>
  );
}


text:
Q: Prevent a Duplicate contact role on opportunity with Lightning Flow error There are several ways to avoid/restrict creation of duplicate contacts as contact roles on opportunity using APEX triggers. I am trying to build one using the 'Before Create/Update' lightning flow

*

*I created a checkbox field on the OpportunityContact Role object called: Duplicate Assertion

*I created a Validation Rule that checks if: Duplicate Assertion it TRUE - and prevents the save.

In my 'Before Create/Update', it's a simple flow:

*

*Get all records from OpportuniyContactRoles where OpportunityID equals $record.opportunityID

*loop all records, if $record.contactid equals any returned entry

*The Decision rule

*set the $record.DuplicateAssertion field to true

*The Assignment

*The save of the newly/updarted OCR's should fail if DuplicateAssertion is TRUE.

*The issue is that it's not working. If I only test the assignment within the flow (as a test) - the records are correctly not saved.
But if I let the process work, it saves even with a duplicate.
Any ideas?

A: There is a mistake in the Loop object.
The return arrow from the 'Assignment' object, needs to go to the Loop object, and not the 'Decision' object.
A way to identify this was also to use the 'Auto-Layout' feature. It mentioned the error, only I had to figure out what it meant.


text:
Q: "~" and "/" Not giving the root folder on asp.net-mvc On a shared view (like _layout.cshtml), I'm asking for the root folder in many ways ("/Content/design.css", @Url.Content("~/Content/design.css") ) But I'm always getting the controller name and then the requested url ("localhost:3333/MyControllerName/Content/design.css")
Why?
I'm running my project on IIS express.
This is the problematic line:
     <link rel="stylesheet" href="@Url.Content("~/Content/design.css")" />

also tried:
     <link rel="stylesheet" href="@Url.Content("/Content/design.css")" />

A: not sure if you fixed this, I know I'm late, can you try this?
I'm thinking you don't need @Url.Content
<link href="~/Content/design.css" rel="stylesheet" />


text:
Q: Broken links in Dreamweaver I am changing the url structure of a website, to have it extensionless.
For example:
example[.]com/hello.html

would become:
example[.]com/hello

I have everything set up in my .htaccess file, and all works perfectly. However I want to drop the .html throughout the website, rather than by using a 301 redirect everything.
I tested it on a few pages and published them, it works fine online, however locally it doesn't know where to search, plus it's being counted as a broken link.
Is there a way to tell Dreamweaver not to look at the ".html" when viewing links?  So that when I search for broken links it doesn't report false positives?
Thanks for any help, it's really appreciated.

A: If you would like to see the result, I would suggest you to use a free FTP. As for the ".html" links you may show the name without html but for linking you do need to link it to the proper link.


text:
Q: ramfs mounted through fstab is automatically owned by root ramfs was chosen specifically because there is zero chance of files being written to disk (swap space is used with tmpfs). tmpfs is out of scope for this question.
Here is my fstab entry for the mount point:
ramfs /path/to/mount ramfs  defaults,nofail   0 0

After mounting, I can set the permissions just fine:
chown -R myuser:myuser /path/to/mount

The problem comes after a reboot. The owner becomes root after reboot and it manually has to change back to my user. All I need to do is have the user id set at mount time (or persist through reboots).

A: ramfs has absolutely no mount options, so it isn't possible to set a mount uid/gid as it is with tmpfs.
From the man page:

Ramfs is a memory based filesystem.  Mount it and you have it.  Unmount it and it is gone.  Present since Linux 2.3.99pre4.  There are no mount options.

Obviously you are aware of the danger of your system running out of memory and crashing because your user accidentally overflowed the ramfs, and you have accepted that risk. So we won't mention that tmpfs solves this problem, and is why ramfs hasn't gotten much developer attention and is rarely used. To quote the kernel developers:

One downside of ramfs is you can keep writing data into it until you fill
  up all memory, and the VM can't free it because the VM thinks that files
  should get written to backing store (rather than swap space), but ramfs hasn't
  got any backing store.  Because of this, only root (or a trusted user) should
  be allowed write access to a ramfs mount.
A ramfs derivative called tmpfs was created to add size limits, and the ability
  to write the data to swap space.  Normal users can be allowed write access to
  tmpfs mounts.  See Documentation/filesystems/tmpfs.txt for more information.

The only way you can do this, therefore, is to continue to set the ownership after the filesystem is mounted, e.g. in rc.local.


text:
Q: Python: How to concatenate adjacent strings in list having combined length less than threshold? I would like to merge/concatenate adjacent strings in a list whose combined length is below a threshold. The concatenated string should have a single space separating the individual strings.
For example, if the list contains the following strings:
list = ['This', 'is', 'a', 'sample', 'example']

and the threshold is 10, then the list should be modified to:
list = ['This is a', 'sample', 'example']

Edit: I am using a for loop comparing adjacent strings.
for i in range(1, len(list)):
    if len(list[i]) + len(list[i-1]) < 10:
        list[i-1] = list[i-1]+' '+list[i]
        del list[i]

but this gives IndexError: list index out of range because the loop counter has been initialized to the initial len(list).

A: One (a bit lazy) way to do this is using the textwrap module from the standard library:
>> import textwrap
>> textwrap.wrap('This is a sample example', width=10)
['This is a', 'sample', 'example']

(If your text is already split into words, you'll have to join it back first, which is a bit wasteful, but still works.)

A: import re
import textwrap

sample = ['This', 'is', 'a', 'sample', 'example', 'stringbiggerthan10', 'otherstring']

sample_join = " ".join(sample)

textwrap.wrap(sample_join, width=10, break_long_words=False)

['This is a', 'sample', 'example', 'stringbiggerthan10', 'otherstring']


text:
Q: How can I tell the wireless protocols being used by devices on my network? I have a ASUS router setup using dd-wrt in Mixed mode wireless. Having recently read an article about how even having a/b devices on your network can slow down all connections I am interested in disabling those protocols. How can I tell which devices are using which protocols from the router?
I have a combination of iPads, phones, SONOS, PCs and Macs accessing the network. Going to each device might be an option but one that I would like to avoid. Is there a way from the router to see the protocols in use or a separate program I can run to scan the network?

A: Any 802.11g device will use 802.11b rates only when the signal is poor. The only way to reliably disable 802.11b is to do it on your access point.
Note that it may disconnect these devices if their signal is very poor.
Anyway. If you have a Linux machine, you can put an interface into monitor mode, use tcpdump/wireshark to capture packets and try to get information about what modulation schemes are actually in use by looking at the radiotap headers.

A: If you have access to the router, you can setup a monitor port that sends all traffic to a particular port where you can then setup a monitoring software on an end devices such as Wireshark.
If you have a wireless device that can install the monitoring software, you should be able to view the traffic as well and determine which protocols are being used.  If you have a separate key for each connection then you wont be able to decrypt the traffic and view it this way.
Each router and firmware will vary from each different kind of device so it would be best to refer to the documentation on the options you have from the router.