text:
Q: In memory data processing in R?: save -> readBin ->? How can I access the R data originally saved with the SAVE command and later read with readBin?
Let me try to explain:
I have saved some data (mostly matrices and lists) to a file using SAVE command.
Later I have transformed this file (encrypted) and saved it using writeBin.
Since the file is transformed I cannot get the data directly using LOAD but need to do it with readBin and perform opposite transformation in memory.
The problem is, after reading with readBin and transforming, the data are in memory, but I cannot access them as R objects (such as matrices or lists), since they are not recognized as such (there is just singular binary object).
The easiest way would be to use this binary object as connection for LOAD.
Unfortunately, LOAD does not accept in-memory binary connections.
I guess .Internal(loadFromConn2(...)) may be a key to this, but I do not have details of it internal workings.
Is there any way to make R recognize the binary data stored in-memory as binary object as R original objects (matrices, lists, etc.)?
The encryption code I am using is available at: http://pastebin.com/eVfVQYwn
Thanks in advance.

A: (If you aren't interested in learning how to research this type of
problem in the future, skip to "Results", far below.)
Long Story ...
Knowing some things about how the R objects are stored with save
will inform you on how to retrieve it with load. From help(save):
 save(..., list = character(),
      file = stop("'file' must be specified"),
      ascii = FALSE, version = NULL, envir = parent.frame(),
      compress = !ascii, compression_level,
      eval.promises = TRUE, precheck = TRUE)

The default for compress will be !ascii which means compress will
be TRUE, so:

compress: logical or character string specifying whether saving to a
               named file is to use compression.  'TRUE' corresponds to
               'gzip' compression, ...

The key here is that it defaults to 'gzip' compression. From here,
let's look at help(load):

'load' ... can read a compressed file (see 'save') directly from a
  file or from a suitable connection (including a call to
  'url').

(Emphasis added by me.) This implies both that it will take a
connection (that is not an actual file), and that it "forces"
compressed-ness. My typical go-to function for faking file connections
is textConnection, though this does not work with binary files, and
its help page doesn't provide a reference for binary equivalence.
Continued from help(load):

A not-open connection will be opened in mode '"rb"' and closed after
  use. Any connection other than a 'gzfile' or 'gzcon'
  connection will be wrapped in 'gzcon' to allow compressed saves to
  be handled ...

Diving a little tangentially (remember the previous mention of gzip
compression?), help(gzcon):

Compressed output will contain embedded NUL bytes, and so 'con'
  is not permitted to be a 'textConnection' opened with 'open =
  "w"'. Use a writable 'rawConnection' to compress data into
  a variable.

Aha! Now we see that there is a function rawConnection which one
would (correctly) infer is the binary-mode equivalent of
textConnection.
Results (aka "long story short, too late")
Your pastebin code is interesting but unfortunately moot.
Reproducible examples
make things easier for people considering answering your question.
Your problem statement, restated:
set.seed(1234)
fn <- 'test-mjaniec.Rdata'
(myvar1 <- rnorm(5))
##  [1] -1.2070657  0.2774292  1.0844412 -2.3456977  0.4291247
(myvar2 <- sample(letters, 5))
##  [1] "s" "n" "g" "v" "x"
save(myvar1, myvar2, file=fn)
rm(myvar1, myvar2) ## ls() shows they are no longer available

x.raw <- readBin(fn, what=raw(), n=file.info(fn)$size)
head(x.raw)
## [1] 1f 8b 08 00 00 00
## how to access the data stored in `x.raw`?

The answer:
load(rawConnection(x.raw, open='rb'))

(Confirmation:)
myvar1
##  [1] -1.2070657  0.2774292  1.0844412 -2.3456977  0.4291247
myvar2
##  [1] "s" "n" "g" "v" "x"

(It works with your encryption code, too, by the way.)


text:
Q: How can i make signals in django which can differentiate between put and post method? I am using in_built Django user and want to generate notification for each added user but I don't want notification to generate on put request.It should only generate on post request .
My model is...
Models.py
class User(AbstractUser):
    gender= models.CharField(choices=GENDER, max_length=10, null=True, blank=True)
    role= models.CharField(choices=ROLE_CHOICE, max_length=15, null=True, blank=True)
    designation=models.CharField(max_length=225,null=True,blank=True)
    employee_id = models.CharField(max_length=20, default=None, null=True)

class Notification(models.Model):
    text = models.CharField(max_length=225)
    recipient=models.ForeignKey(User,related_name='notification')
    timestamp = models.DateTimeField(null=True,blank=True,auto_now_add=True)
    unread = models.BooleanField(default=True, blank=False)
    send_by= models.ForeignKey(User, null=True,blank=True, related_name='Notification')

and in my signals I have made like....
Signals.py
@receiver(post_save, sender= Any_model)
def comment_recieved(sender,**kwargs):
    obj= kwargs.get('instance')
        recipient=User.objects.get(is_superuser=True)
        Notification.objects.create(
            recipient= recipient,
            comment= obj,
            project=obj.project,
            type="commented",
            send_by=obj.supporter,
            text= "%s has commented on %s" % (obj.supporter, obj.project)
        )
        return None

Now the problem is that everytime you do either a put or post request,it saves the user instance and so it creates a Notification object.I want to create Notification only when new user is created.

A: Suppose you use serializer for DRF view so you could override create() method of your User serializer.
class UserSerializer(serializer.ModelSerializer):
    ...
    def create(self, validated_data):
        user = User.objects.create(**validated_data)
        Notification.objects.create( # fill your fields here )
        return user

But more clear solution is writing custom manager and override create method there which will accept both fields for User and for Notification models:
class UserManager(models.Manager):
    ...
    def create(self, gender, role ... type #and so on):
        user = User(
            gender=gender
            role=role
            ...
            # other fields
            )
        user.save()
        notification = Notification(
                           type=type
                           ..
                           # other fields
                           )
        notification.save()
        return user

class User(models.Model):
    ....
    objects = UserManager()

serializers:
    class UserSerializer(serializer.ModelSerializer):
        ...
        def create(self, validated_data):
            return User.objects.create(
                   gender=validated_data.get('gender')
                   role=validated_data.get('role')
                   ....
                   type = validated_data.get('type')

A: The post_save signal sends an argument called created which is

A boolean; True if a new record was created.

You can use this to differentiate between if a new record is created or just updated.
More info in the docs

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can not boot Boot-Repair live cd I have installed Ubuntu 14.04 and windows 8.1. I can boot both O.S using the BIOS boot options (manually).
I want to select O.S from a grub screen when PC starts. So i tried to use a boot repair live CD to repair grub/boot. The problem is when I select "64-bit session" in the boot repair menu an error appears:

kernel panic at boot: not syncing. No init found

Pastebin: http://paste.ubuntu.com/15368305/

A: As per your boot-repair report(translated to English)
The boot files [ Linux ] are far from the beginning of the disc . Your BIOS could not detect them . You may want to retry after creating a partition / boot ( EXT4 , > 200MB , beginning of the disc ) . This can be done with tools like GParted . Then select this partition through the [ separate / boot partition ] of [Boot Repair ] . ( Https://help.ubuntu.com/community/BootPartition )

If your computer boots directly into Windows , try changing the boot order in the BIOS.
If your BIOS does not support changing the boot order , change the default entry in the Windows boot loader .
For example you can start Windows , then type the following command in a cmd window with administrator privileges :
bcdedit / set { bootmgr } path \ EFI \ ... \ grub * .EFI

I won't take the first point very seriously...but the second one is worth trying
For example you can start Windows , then type the following command in a cmd window with administrator privileges :
bcdedit / set { bootmgr } path \ EFI \ ... \ grub * .EFI

Give this a try.

A: Perhaps you could give it a try with Super GRUB 2 disk.
You can download it from here.
Then install it in a usb using Unetbootin
Now you could restart your system and make sure it is set in the boot option menu.


text:
Q: c++ convert pipe to comma delimited I am trying to convert this pipe delimited file into comma delimited. I need to read the file into an array and then output it in comma delimited into a CSV file. I am having a very hard time with the whole conversion process so I am trying to find the simplest way that I can output the data into the comma file.
This is the input file:
Miles per hour|6,445|being the "second" team |5.54|9.98|6,555.00 "Ending" game| left at "beginning"| Elizabeth, New Jersey|25.25|6.78|987.01 |End at night, or during the day| "Let's go"|65,978.21|0.00|123.45 Left-base night|10/07/1900|||4.07|777.23 "Let's start it"| Start Baseball Game| Starting the new game to win

This is the portion of code I have so far for when the input pipe file is already open:
#include <iostream>
#include <string>

using namespace std;

int main () {

string myArray[5];

   for(int = 0; i<5, i++)
{
  file >> myArray[i];

 while (getline(input, temp, '|')) {
      if (temp.find(",") != string::npos)
         cout << '"' << temp << "\",";
      else
         cout << temp << ',';
}


text:
Q: The usage of articles with nouns modified by an adjective Please help.
1) "I sat into a car. Having sat into a nice car I started home"
2) "I sat into a car. Having sat into the nice car I started home"
3) "I saw a car. A nice car was very clean and shiny"
4) "I saw a car. The nice car was very clean and shiny"

*

*Can they both be used for the second mention?

*If yes, what is the difference in meaning?
P.s. The way I see it - saying "a nice car" is appropriate in 1 and 3, like a way of saying "what was a nice car (referring to the car already introduced)..." or it can also be the first mention of another car.
Saying "the nice car" in 2 and 4 - "what was the only nice car within context" or it can have another meaning - just the second mention of that car, that is not nessessary the only one.
But all of the above are just my guesses and I'd be glad if you could clarify it. Thanks.

A: I have multiple answers as your question has many points. Easiest first:
Forget the bit about the adjective. Seriously. As far as the articles are concerned, it's not relevant.
With sentence (1) and (3) there is no "connection" between the two sentences. Your assumption that it's something like a shortened relative clause is not true. (Example follows later). So, yes, you are talking about two cars, which might or might not be the same. Very confusing for the reader.
Sentence (2) and (4) are ok, because it's clear that you are talking about the same car (just introduced). Still, it would be better if you'd use a demonstrative ("this" car) instead of the article. So:

4) I saw a car. This nice car was very clean and shiny.

Also, it sounds more natural if you move the adjective to the first mentioning of the car. Then, as you already mentioned the car, a pronoun will be enough in the second part:

I saw a nice car. It was very clean and shiny.

If you want to further describe the car (as you suggested), use not "what", but "which". Also, the two sentences should be "closer", so join them:

I saw a nice car, which was very clean and shiny.

Similar line of thought leads to:

I sat in a nice car. Having sat in it I drove home. ->
  Having sat in a nice car, I drove home.


text:
Q: Package the model weights of a trained neural network to make it usable for transfer learning I have trained and evaluated a neural network on a movie's dataset. Basically, I am trying to predict the multi-class dependent variable movie_genre using text inputs like the plot, actors, reviews etc.
The model weights are saved in .h5 format in a local path of my computer. Let's say here C:/Users/Desktop/classification_attention_layer_model.h5.
The model structure is also saved in a separate .json file format in the same path. Let's say here classification_attention_layer_model.json.
What I want is to give the neural network weights to a colleague and use those weights for transfer learning. So for example, create a different neural network with the pre-trained word embeddings that I sent him and use those pre-trained embeddings on top of dense/hidden layers to train his own neural network on movies.
How can I achieve this? I know that one way is to just sent him the .h5 file with the trained embedding weights. But is this a professional way to do it?
I firmly believe that docker can help on this but I don't know how. Or maybe a python package may do the trick.
The only related question I found online is this one How to create a pre-trained weight model similar to Imagenet or Noisy-student?. However, they only explain how to save the model weights which I have already done.
Basically, I want to achieve the methodology of spaCy package when it uses a text to create its word vectors. This task is demonstrated on Kaggle's course NLP exercise 3:
import spacy
import numpy as np

nlp = spacy.load('en_core_web_lg')
review_data = pd.read_csv('../input/nlp-course/yelp_ratings.csv')

vectors = np.array([nlp(review_data.text).vector for idx, review in review_data.iterrows()])

vectors.shape #(100, 300) where 100 rows and 300 are the vectors per row

A: If I were you I would create a small simple package and upload it to PyPI.
You could add your model as part of the package (if it isn't large) using MANIFEST.in as described here.
On the downside, it will take disk space of users, no matter whether they're using your software at this moment or not.
Alternatively (IMO better), upload you weights somewhere and make them downloadable through code, something like:
import yourpackage

backbone = yourpackage.yourmodel.backbone(
    download=True,
    pretrained=True
)

This is how torchvision approaches this problem and it seems to be good solution.
Docker
I see no point in this case, unless your model depends on non pip installable software, which is unlikely.


text:
Q: Difference between CreateObject and New when opening a new excel application What is the difference between the following two statements? I was writing a basic VB.net code which creates a new excel workbook and adds a new sheet. Both seem to be doing the same thing:
Dim oxl As Excel.Application
oxl = New Excel.Application

Dim oxl As Excel.Application
oxl = CreateObject("Excel.Application")

The only thing that I note is that the VB.net editor displays the following message when I am using NEW: "Object initialization can be simplified"
Can anyone pls help?

A: In the sample code posted the early (or static) binding refers to compile time binding (you must add a COM reference for that):
Dim oxl As Excel.Application
oxl = New Excel.Application

And late (or dynamic) binding refers to runtime binding (for example when you use reflection) and doesn't require any COM references.
Dim oxl As Excel.Application
oxl = CreateObject("Excel.Application")

You can read more about early and late binding technologies in the Using early binding and late binding in Automation article.


text:
Q: Is it possibile to completely remove css .ng-invalid while keeping validators with MatFormFields? I'm trying to have a login form with simple Validators.required fields, but I don't want to actually see the error color when .ng-invalid class applies to the input.
Is there an easy way to achieve this or do I really need to ovverride all css classes?

A: You should override the class to render what you want


text:
Q: Script to label emails if it contains specific words in the subject or body on Gmail Update:
Thank you so much endothermic_dragon! You are brilliant! It all works now.
I have created scripts before but never for Gmail. I am having a hard time creating a script to filter emails coming in and label and archive them if they have specific words. We receive about 100 emails daily from various senders relating to a group of companies. Each company has its label. Usually the name of the company is in the subject or body of the email. I am trying to build a script that gets each email, check if the array with subjects or the array with plainBody contains the name of one or more of the labels (each label is the name of a company) in the labels array from getUserLabels(), and if so, assign the respective label(s) to it. I have tried everything, from filter() to forEach() to indexOf() but nothing seems to work. I feel the arrays from getUserLabels() and getInoboxThreads() are 2D, and I'm struggling to work with them. I've rewritten the code multiple times and it got me nowhere. I really hope one of you can shed some light on this.
Example:
Let's suppose we work with Apple, Amazon and Netflix. Each of these companies have their own label.
If an email comes in and has "Apple" in the subject or body, then add label "Apple" to it and archive it. If it has "Amazon" and "Netflix" in the subject or body, then add labels Amazon and Netflix.
Final code:
function labelEmails() {
  var labels=[]
  GmailApp.getUserLabels().forEach(function(label){labels.push(label.getName())})
  var threads = GmailApp.search('is:unread').forEach(function(email){
    email.getMessages().forEach(function(thread){
      //Filter - https://developers.google.com/apps-script/reference/gmail/gmail-message
      //Example used - if body contains 'hi', mark as read.
      labels.forEach(function(label){
        if (thread.getBody().toLowerCase().includes(label.toLowerCase())){
          labelToAssign = GmailApp.getUserLabelByName(label);
          labelToAssign.addToThread(email)
        } else if (thread.getSubject().toLowerCase().includes(label.toLowerCase())) {
           labelToAssign = GmailApp.getUserLabelByName(label);
          labelToAssign.addToThread(email)
          }
      })
    })
    });
}

Some of our labels are abbreviations of the name of the companies, so I also needed a function to handle those. You can check it out below too:
(Companies in the code are random companies, not the real ones)
function labelExceptions() {
  var exceptions = [{exc:'apple', labeln: 'APPL'}, {exc: 'amazon', labeln: 'AMZ'}, {exc: 'Bank of America', labeln: 'BOFA'}]
  var threads = GmailApp.search('is:unread').forEach(function (thread){
    thread.getMessages().forEach(function(message){
      exceptions.forEach(function(exception){
        if (message.getBody().toLowerCase().includes(exception.exc)){
          labeltoAssign = GmailApp.getUserLabelByName(exception.labeln);
          labeltoAssign.addToThread(thread)
        } else if (message.getSubject().toLowerCase().includes(exception.exc)){
          labeltoAssign = GmailApp.getUserLabelByName(exception.labeln);
          labeltoAssign.addToThread(thread)
        }

      })

    })}
 );
  }

Thank you very much!

A: Checked with my gmail, works!
function myFunction() {
  var labels=[]
  GmailApp.getUserLabels().forEach(function(label){labels.push(label.getName())})
  var threads = GmailApp.search('is:unread').forEach(function(email){
    email.getMessages().forEach(function(thread){
      //Filter - https://developers.google.com/apps-script/reference/gmail/gmail-message
      //Example used - if body contains 'hi', mark as read.
      labels.forEach(function(label){
        if (thread.getBody().toLowerCase().includes(label.toLowerCase())){
          email.markRead()
        }
      })
    })
    });
}


text:
Q: Cannot invoke "java.io.DataInputStream.readLine()" because "this.input" is null I've been trying to connect a socket client with a URL. Am I supposed to add the URL's IP in the Windows host file ("C:\Windows\System32\drivers\etc\hosts")?

What is socket?
Sockets allow communication between two different processes on the same or different machines. To be more precise, it's a way to talk to other computers using standard Unix file descriptors. In Unix, every I/O action is done by writing or reading a file descriptor. A file descriptor is just an integer associated with an open file and it can be a network connection, a text file, a terminal, or something else.

But I've got this error:
java.net.UnknownHostException: https://socket.edu.net
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.io.DataInputStream.readLine()" because "this.input" is null

A: I solved the problem. I've changed https://socket.edu.net to socket.edu.net.
Then successfully connected.
EDIT: I restored hosts file and now in its original form and still connected successfully.


text:
Q: c# Regex problems I have this Regex which I'm working on
string addressstart = Regex.Escape("<a href=\"/url?q=");
                string addressend = Regex.Escape("&amp");
                string regAdd = addressstart + @"(.*?)" + addressend;

I'd like it to give me the url from this html

so it should return "https://www.google.com/"
Any ideas Why it isnt working?
thanks!

A: The following regex worked for me. Make sure that you select group 1, since group 0 is always the full string.
@"<a href=\"\/url\?q=(.*?)&amp"

A: As it appear you are looking for the url of google as part of your string.
You might find useful the following pattern which will match it:
https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}

It is to be noted this is a small tweak of the general regex found at: What is a good regular expression to match a URL?
Edit Please see the code below in order to apply this regex and find the value you are looking for:
string input = "";
var regex = new Regex(@"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}");
var output = regex.Match(input).Value; // https://www.google.com

A: The problem is in the "<a href=\"/url?q=" part of the regular expression. The ? is not escaped. It means an optional l. Hence that part of the regular expresion matches either <a href="/urlq= or <a href="/urq=. Neither include the ? character.

A: When parsing HTML, you should consider using some HTML parser, like HtmlAgilityPack, and only after getting the necessary node, apply the regex on the plain text.
If you want to debug your own code, here is a fix:
using System;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        var s = "";
        var pattern = @"<a href=""/url\?q=(.*?)&";
        var result = Regex.Match(s, pattern);
        if (result.Success)
            Console.WriteLine(result.Groups[1].Value);
    }
}

See a DotNetFiddle demo.
Here is an example how how you may extract all  href attribute values that start with /url?q= with HtmlAgilityPack. Install it via Solution > Manage NuGet Packages for Solution... and use
public List<string> HapGetHrefs(string html)
{
    var hrefs = new List<string>();
    HtmlAgilityPack.HtmlDocument hap;
    Uri uriResult;
    if (Uri.TryCreate(html, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp)
    { // html is a URL
        var doc = new HtmlAgilityPack.HtmlWeb();
        hap = doc.Load(uriResult.AbsoluteUri);
    }
    else
    { // html is a string
        hap = new HtmlAgilityPack.HtmlDocument();
        hap.LoadHtml(html);
    }
    var nodes = hap.DocumentNode.SelectNodes("//a[starts-with(@href, '/url?q=')]");
    if (nodes != null)
    {
       foreach (var node in nodes)
       {
           foreach (var attribute in node.Attributes)
               if (attribute.Name == "href")
               {
                   hrefs.Add(attribute.Value);
               }
        }
    }
    return hrefs;
 }

Then, all you need is apply a simpler regex or a couple of simpler string operations.

A: You can use:
(?<=a href="\/url\?q=)[^&]+


text:
Q: Javascript/jQuery beforeunload and unload not firing I have a page where I want my script to let the server know that the user went offline when the browser/tab/page is closed.
$(document).ready(function() {
    // Inform the server that the user went online
    setStatus('online');

    // Inform the server that the user went offline
    $(window).on('beforeunload', function() {
        setStatus('offline');
    });

    // Inform the server that the user went offline
    $(window).on('unload', function() {
        setStatus('offline');
    });
});

async function setStatus(status) {
    let { data } = await axios.post('/status', { status: status });
}

The part where I have setStatus('online'); works but I can never seem to set the status to offline when I close the page/tab/browser.

A: Looking around, I found this really nice answer - I just had to put this on my server.js file:
peer.oniceconnectionstatechange = function() {
    if(peer.iceConnectionState == 'disconnected') {
        console.log('Disconnected');
    }
}

It does take a few seconds before it registers that the peer has dropped but at least it's always firing and that's reliable enough for me.


text:
Q: CRM 2011 SSRS report - using non-FetchXML data source in sub-report I have a SSRS sub-report that uses an XML datasource which works fine in BIDS or when deployed and run from the SSRS server, however once deployed as a report in Microsoft Dynamics CRM 2011 it fails to run when called from CRM as SSRS throws the following exception:
Microsoft.ReportingServices.ReportProcessing.ProcessingAbortedException: An error has occurred during report processing. --->
Microsoft.ReportingServices.DataExtensions.XmlDP.XmlDPException:
The data extension supports Windows Integrated Security and No Credentials (anonymous request) only.

The parent report uses FetchXML to load some data which is then passed into the sub-report as parameters.  CRM automatically passes through UserID/OrganizationID are credentials to any reports, which is correct since the credentials are required in order to call the FetchXML in the parent report, however judging from the exception it would appear to me that the sub-report is also (incorrectly?) inheriting the data source credential settings from the parent reports, despite the sub-report using an entirely different type of data source and credential setting.
If sub-report is published in CRM and is run by itself then it also works fine, but this doesn't meet business needs.  The sub-report must be wrapped in the parent report in order to pass user selectable parameters through.
Are there any methods of overriding this behavior, perhaps some custom code in the sub-report that can force the XML data source to use the 'Do not use credentials' setting?

A: After pulling my hair out for hours over this issue I eventually discovered that it seems to be an issue with CRM caching the initial data source credential settings (which must have been initially incorrect) from when the report is first uploaded.  If you re-upload the RDL on top of an existing report it mustn't update some cache that it must maintain of credential settings.
Deleting the published reports then republishing the sub-report first (XML datasource), then the parent report (decided to go for SQL datasource rather than FetchXML to try and eliminate FetchXML as the issue) works as expected.
Lesson to learn when using CRM SSRS reports: try deleting the reports and trying again!
This is on CRM 2011 UR11.


text:
Q: Fix irregular shape of merged tables in MS Word 2007 I have been looking for the answer to this for quite some time, but to no avail, so I hope someone here will be able to help me.
I have recently exported a document from FineReader 12 to word. The document is basically a 130-page-long table. The table has a regular shape: 5 columns, no merged cells.
However, when I merge individual tables (FineReader splits them by page) into one by deleting the lines between them, the table gets an irregular shape on each joint, like this:
.
Given the sheer number of tables I have, is there a way to reset their shape altogether? So far it seems I have to manually adjust each table's columns to fit the other ones.
I have tried resetting the table and column width, text wrapping etc.; I also selected the entire table and checked, then unchecked the "table header" tick for all.
Converting table to text and back doesn't work, because some cells have paragraph breaks, and that's to be dealt with later.

A: Okay, I was given an answer by Paul Edstein aka macropod at MS Office Forums which I slightly modified and it works like charm now. I paste the solution here as it might save dozens of hours of work for anybody working with OCR and whatnot.
The idea is to make a macro that reformats layout of each table (and each cell if needed), like that:
Sub FixTables()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim Tbl As Table, i As Long
With ActiveDocument
    For Each Tbl In .Tables
        With Tbl
            With .Rows
                .LeftIndent = 0
                .WrapAroundText = False
                .Alignment = wdAlignRowCenter
            End With
            .TopPadding = 0
            .LeftPadding = 0
            .RightPadding = 0
            .BottomPadding = 0
            .AllowAutoFit = False
            .PreferredWidthType = wdPreferredWidthAuto
            If .Uniform Then
                .Columns(1).Width = CentimetersToPoints(1#)
                .Columns(2).Width = CentimetersToPoints(3.75)
                .Columns(3).Width = CentimetersToPoints(3.75)
                .Columns(4).Width = CentimetersToPoints(3.75)
                .Columns(5).Width = CentimetersToPoints(3.75)
            Else
                For i = 1 To .Range.Cells.Count
                    Select Case (i - 1 Mod 5) + 1
                        Case 1: .Range.Cells(i).Width = CentimetersToPoints(1#)
                        Case Else: .Range.Cells(i).Width = CentimetersToPoints(3.75)
                    End Select
                Next
            End If
    End With
    While .Tables.Count > 1
        .Tables(1).Range.Characters.Last.Next.Delete
    Wend
Next
End With
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

The only downside is that while it executes in just a couple of seconds with only 3 tables, it took about 15 minutes to perform the changes on a set of 50 tables. The tweaks to that include temporarily turning off the screen refresh in word and suppressing all alerts (it would otherwise ask to save the changes each time Word ran out of RAM).
Please note that this solution is adapted for 5 colums only, so tweak it accordingly!


text:
Q: How to partition Delta tables efficiently? Looking for efficient partitioning strategies for my dataframe when storing my dataframe in the delta table.
My current dataframe 1.5000.000 rowa it takes 3.5h to move data from dataframe to delta table.
Looking for a more efficient way to do this writing I decided to try different columns of my table as partitioning columns.I searched for the cardinality of my columns and selected the following ones.
column1 = have 3 distinct_values
column2 = have 7 distinct values
column3 = have 26 disctinc values
column4 = have 73 distinc values
column5 = have 143 distinc values
column6 = have 246 distinct values
column7 = have 543 disctinc values
cluster: 64GB, 8 cores
using the folloging code in my notebook
df.write.partitionBy("column_1").format("delta").mode("overwrite").save(partition_1)
..
df.write.partitionBy("column_7").format("delta").mode("overwrite").save(partition7)

Thus, I wanted to see which partitioning strategy would bring better results: a column with high cardinality, one with low cardinality or one in between.
To my surprise this has not had any effect as it has taken practically the same time in all of them with differences of a few minutes but all of them with + 3h.
why have I failed ? is there no advantage to partitioning ?

A: When you use Delta (either Databricks or OSS Delta 1.2.x, better 2.0) then often you may not need to use partitioning at all for following reasons (that aren't applicable for Parquet or other file formats):

*

*Delta supports data skipping that allows to read only necessary files, especially effective when you use it in combination with OPTIMIZE ZORDER BY that will put related data closer to each other.

*Bloom filters allow to skip files even more granularly.

The rules of thumb of using partitioning with Delta lake tables are following:

*

*use it when it will benefit queries, especially when you perform MERGE into the table, because it allows to avoid conflicts between parallel transactions

*when it helps to delete old data (for example partitioning by date)

*when it really benefits your queries. For example, you have data per country, and most of queries will use country as a part of condition.  Or for example, when you partition by date, and querying data based on the time...

In all cases, don't use partitioning for high cardinality columns (hundreds of values) and having too many partition columns because in most cases it lead to creation of small files that are less efficient to read (each file is accessed separately), plus it leads to increased load to the driver as it needs to keep metadata for each of the file.


text:
Q: How to change info on UAC prompt? On Windows Vista, with UAC enabled, everytime a program that requires administrative priviledges starts, a UAC prompt is displayed. In the box, there are two fields - name and author. How can those be customized?

A: You need to sign the application.
http://www.google.com/search?q=authenticode


text:
Q: Global variables and sessions in Developer Studio Now it starts a session for each file you run. Is there any way to run two files using the same session (and the same global variables) in Eclipse Progress Developer Studio 3.7 (without one file running the other)?
Yes I know global variables should be avoided but that's not the topic.

A: You can start the Procedure Editor from Developer Studio by clicking the highlighted button.

The Procedure Editor will contain the currently active file from Eclipse. It is running in the progress process from Developer Studio that is used for compilation of the current project. So all files you start this way will be executed using the same process (as long as you do not restart the OpenEdge AVM).
In the Procedure Editor just hit F2 to execute the file. Note that this will only work for procedure files, not for classes.

A: There is an option in the run configuration to use the project avm instead of starting a new one.
That way subsequent runs will be in the same session.
You'll need to restart the avm to get rid of the context created by those runs

A: Only if you run it from the char or GUI client, and then it would still be:
run prog1.p.
run prog2.p.

so there's now way to do this w/out having a "stub" program which runs the two programs in sequence.


text:
Q: Android drawer with icons always visible Which layout component is the right one for building a drawer menu with icons that are always visible? I don't want to use a SlidingPaneLayout because the main content should not be affected by this.

A: 1. Add CrossFadeSlidingPaneLayout
  public class CrossFadeSlidingPaneLayout extends SlidingPaneLayout {
  private View partialView = null;
  private View fullView = null;

  // helper flag pre honeycomb used in visibility and click response handling
  // helps avoid unnecessary layouts
  private boolean wasOpened = false;

  public CrossFadeSlidingPaneLayout(Context context) {
    super(context);
  }

  public CrossFadeSlidingPaneLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public CrossFadeSlidingPaneLayout(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  protected void onFinishInflate() {
    super.onFinishInflate();

    if (getChildCount() < 1) {
      return;
    }

    View panel = getChildAt(0);
    if (!(panel instanceof ViewGroup)) {
      return;
    }

    ViewGroup viewGroup = (ViewGroup) panel;
    if (viewGroup.getChildCount() != 2) {
      return;
    }
    fullView = viewGroup.getChildAt(0);
    partialView = viewGroup.getChildAt(1);

    super.setPanelSlideListener(crossFadeListener);
  }

  @Override
  public void setPanelSlideListener(final PanelSlideListener listener) {
    if (listener == null) {
      super.setPanelSlideListener(crossFadeListener);
      return;
    }

    super.setPanelSlideListener(new PanelSlideListener() {
      @Override
      public void onPanelSlide(View panel, float slideOffset) {
        crossFadeListener.onPanelSlide(panel, slideOffset);
        listener.onPanelSlide(panel, slideOffset);
      }

      @Override
      public void onPanelOpened(View panel) {
        listener.onPanelOpened(panel);
      }

      @Override
      public void onPanelClosed(View panel) {
        listener.onPanelClosed(panel);
      }
    });
  }

  @Override
  protected void onLayout(boolean changed, int l, int t, int r, int b) {
    super.onLayout(changed, l, t, r, b);

    if (partialView != null) {
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        // "changed" means that views were added or removed
        // we need to move the partial view out of the way in any case (if it's supposed to of course)
        updatePartialViewVisibilityPreHoneycomb(isOpen());
      } else {
        partialView.setVisibility(isOpen() ? View.GONE : VISIBLE);
      }
    }
  }

  private SimplePanelSlideListener crossFadeListener = new SimplePanelSlideListener() {
    @Override
    public void onPanelSlide(View panel, float slideOffset) {
      super.onPanelSlide(panel, slideOffset);
      if (partialView == null || fullView == null) {
        return;
      }

      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        if (slideOffset == 1 && !wasOpened) {
          // the layout was just opened, move the partial view off screen
          updatePartialViewVisibilityPreHoneycomb(true);
          wasOpened = true;
        } else if (slideOffset < 1 && wasOpened) {
          // the layout just started to close, move the partial view back, so it can be shown animating
          updatePartialViewVisibilityPreHoneycomb(false);
          wasOpened = false;
        }
      } else {
        partialView.setVisibility(isOpen() ? View.GONE : VISIBLE);
      }

      ViewHelper.setAlpha(partialView, 1 - slideOffset);
      ViewHelper.setAlpha(fullView, slideOffset);
    }
  };

  private void updatePartialViewVisibilityPreHoneycomb(boolean slidingPaneOpened) {
    // below API 11 the top view must be moved so it does not consume clicks intended for the bottom view
    // this applies curiously even when setting its visibility to GONE
    // this might be due to platform limitations or it may have been introduced by NineOldAndroids library
    if (slidingPaneOpened) {
      partialView.layout(-partialView.getWidth(), 0, 0, partialView.getHeight());
    } else {
      partialView.layout(0, 0, partialView.getWidth(), partialView.getHeight());
    }
  }
}

2. layout of activity
    <com.xxx.CrossFadeSlidingPaneLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/sliding_pane_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:layout_width="@dimen/side_pane_width"
        android:layout_height="match_parent"
        android:background="@color/purple">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:gravity="center_horizontal"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:orientation="horizontal">

                <ImageView
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:layout_marginLeft="7dp"
                    android:background="@drawable/ic_launcher" />

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:text="Your Screen" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:orientation="horizontal">

                <ImageView
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:layout_marginLeft="7dp"
                    android:background="@drawable/ic_launcher" />

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:text="Your Screen" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:orientation="horizontal">

                <ImageView
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:layout_marginLeft="7dp"
                    android:background="@drawable/ic_launcher" />

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:text="Your Screen" />
            </LinearLayout>
        </LinearLayout>

        <LinearLayout
            android:layout_width="55dp"
            android:layout_height="fill_parent"
            android:gravity="center_horizontal"
            android:orientation="vertical">

            <ImageView
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:background="@drawable/ic_launcher" />

            <ImageView
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:background="@drawable/ic_launcher" />

            <ImageView
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:background="@drawable/ic_launcher" />
        </LinearLayout>

    </FrameLayout>

    <TextView
        android:layout_width="@dimen/main_pane_width"
        android:layout_height="match_parent"
        android:layout_marginLeft="@dimen/partial_pane_width"
        android:layout_weight="1"
        android:background="@color/light_blue"
        android:text="@string/pane_2" />
</com.xxx.CrossFadeSlidingPaneLayout>

its done now always menu will be visible :)
Attribution to original project: Github Url


text:
Q: Seed roles in an ASP.NET MVC Core project with Entity Framework I am trying to seed some roles to my identity db context, when I initially create the database.
For that I tried to implement the code like it was stated here:
https://stackoverflow.com/a/29547994/985798
I tried this in the ConfigureServices-method inside my Startup-class:
  public void ConfigureServices(IServiceCollection services)
using this snippet:
var rolestore =
    new Microsoft.AspNetCore.Identity.EntityFrameworkCore.
        RoleStore<Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole>(identityContext);

var roleManager = new Microsoft.AspNetCore.Identity.RoleManager
                  <Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole>(rolestore);

//use rolemanager to insert roles etc.

The problem is, that it seems to not work in an fresh Core-project, created with Visual Studio 2017.
It gives me the following build error:

CS7036    There is no argument given that corresponds to the required
  formal parameter 'roleValidators' of
  'RoleManager.RoleManager(IRoleStore,
  IEnumerable>, ILookupNormalizer,
  IdentityErrorDescriber, ILogger>,
  IHttpContextAccessor)'

Even if I use the other overload (with null values for the other parameters), the RoleManager seems to have no "Create" method anymore.
So, I am stuck at this point. What do I need to do? Has something changed in the ASP.NET MVC Core implementation of the rolemanager? Do I use something wrong?

A: using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

public static class Seed
{
    public static void Initialize(IServiceProvider provider)
    {
        var _context = provider.GetRequiredService<ApplicationDbContext>();
        var userManager = provider.GetRequiredService<UserManager<ApplicationUser>>();
        var roleManager = provider.GetRequiredService<RoleManager<IdentityRole>>();

    }
}

Then below the majority of the code in the in the Configure() in startup.cs
Seed.Initialize(app.ApplicationServices);

HTH (hope that helps).


text:
Q: Problema de linkagem "undefined reference" Estou tentando compilar uma biblioteca dinâmica que usa uma biblioteca estática.
Estou usando o cmake e o problema que estou tendo são erros na linkagem, onde  os métodos da biblioteca estática estão dando erro de "undefined reference".
O que estou tentando compilar é esse projeto i9corp/i9corp-voip-sdk, que usa o pjsip.
Se eu compilo no Linux (Debian) a compilação e linkagem não dão erro e ao final é gerado o meu arquivo.so, porém se eu compilo no Windows (usando o MinGW) da os erros de undefined reference em todos os lugares onde eu tenho chamadas de métodos da biblioteca estática.
Já tentei setar o caminho do meu MinGW na mão (no cmake) para ele achar os includes e libs, mas não mesmo assim não da certo.
No trecho abaixo arquivo completo disponível no github o i9corp-voip-sdk é a minha biblioteca dinâmica e o pjproject é uma biblioteca estática que está no diretório ./third-parties/pjsip as demais bibliotecas wsock32 ws2_32 crypto ssl pthread eu coloquei para tentar resolver o problema, mas não tive sucesso.
Só que seu eu tentar gerar no Windows um uma biblioteca estática no lugar de uma biblioteca dinâmica dá certo. Só da erro se eu tentar gerar a biblioteca dinâmica.
target_link_libraries(i9corp-voip-sdk pjproject wsock32 ws2_32 crypto ssl pthread )


text:
Q: JProfiler : knowing which method is calling for java objects I'm new to JProfiller, I'm using it to know which part of my app is consuming a lot of resources.
I use the live memory and found that those object consumes a lot of memory :

then I select heap walker as mentioned in  a comment of this question, but I cannot find which method or part of my code is calling for those objects
.I tested the Graph, References and Inspections but it doesn't help.

So my question is how to know which part of my code is calling for those java object ?.

A: First, double-click on the row to create a new object set. Then you can to go the "References" view and select "Cumulated incoming references" to explore the incoming references to the entire object set. Or, you can find the path to a GC root for single objects in the "Incoming references".
Alternatively, start with the "Biggest objects" view (without selecting any object set first) to see which objects in your application retain most memory.
A helpful screen cast is available at http://blog.ej-technologies.com/2017/03/finding-memory-leak-with-jprofiler.html


text:
Q: Enquiry about the number of irreducible representations of a finite group In the representation theory of groups, it is a common assertion that the number of irreducible representations of a finite group G over the complex numbers is equal to the number of conjugacy classes of G. I have two quires:
1- Do we still have such a result if the field we are working on is of characteristic zero?
2- Till now the books I read, the authors stated such a fact with either the field of complex numbers $\mathbb{C}$ or the algebraically closed field F; what is significant of requiring algebraically closed field?

A: There are some important represantation theoric properties which are lost when $F$ is not algebraically closed.
Lemma $1$: Let $A$ be a finite dimensional $F$-algebra where $F$ is algebraicly closed and $V$ be an irreducable $A$-module. Then $End_A(V)\cong F$.
Lemma $2$: Let $A$ be a finite dimensional commutative $F$algebra where where $F$ is algebraically closed and $V$ be an irreducible $A$-module. Then $dim_{ F}(V)=1$.
Above lemma says that if $G$ is abelian and $V$ is an $FG$ module where $F$ is algebraicly closed then $dim_{ F}(V)=1$. On the other hand, if $F=\mathbb{R}$ then we can only say that $dim_{ \mathbb R}(V)\leq 2.$
Thus, number of the linear characters of $G$ need not to be equal $|G|$ in that case.
 (Notice that when $G$ is abelian number of the conjugacy classes is $|G|$).
Notice that Mackey's theorem works for fields whose characteristic is zero. Thus the group algebra $FG$ is completely reducible when $F=\mathbb R$ or $F=\mathbb C$. From now on assume characteristic of $F$ is zero.
Now let $V$ be an irreducible $A=FG$ (right) module and $0\neq v\in V$. Since $vA$ is $A$-invariant space, we get $V=vA$ due to the simplicity of $V$. Then $V\cong A/ann(v)$. Since $A$ is completly reducable $A$-modue, $A=Ann(v)\oplus U$ where  $U$ is $A$-submodue of $A$. Then we see that $U$ is isomorphic to $V$, that is, every irreducible $A$-module is isomorphic to a submodule of $A$ (this also show that there are finitely many distinct irreducible $A$-module).
Now suppose that $F=\mathbb C$. There are many ways of showing that the number of the irreducable character of $G$ (equivalently, the number of the irreducable $A$-module up to isomorphism) is equal to the number of conjugacy classes of $G$.
Each author follows a distinct way. Some of them defines the concept of "characters" and "class function" then shows that the set of irreducable characters constiyes a ortanormal base for the spaces of all class functions which has a dimension equal to the number of the conjugacy classes of $G$. (You can read the chapter 15 of "Algebra: A Graduate Course - I. Martin Isaacs". The the theorem you are looking for is Theorem 15.5) Another approach is purely by "represantation theory".
Now assume $F=\mathbb R$ and $G$ is abelian so that $FG$ is a commutative algebra. Since Lemma $2$ is no longer true, the number of the irreducable character of $A$ could be less than the dimension of $A$, which is eqaul to $|G|$, as some of the irreducable $A$ moduel can be of dimension $2$.

A: over $\mathbb{Q}$, there are two irreducible representations of $C_3=\langle c\mid c^3=1\rangle$, the cyclic group of order 3. One representation is the trivial one, the other is given by
$$
c\mapsto\begin{pmatrix}0&-1\\1&-1\end{pmatrix}.
$$
You can understand this by considering the isomorphisms
$$\mathbb{Q}C_3\cong\mathbb{Q}[c]/(c^3-1)\cong\mathbb{Q}[c]/(c-1)\oplus\mathbb{Q}[c]/(c^2+c+1).$$


text:
Q: Trim a wav file I'm trying to trim a file using the code from here
 public static void TrimWavFile(string inPath, string outPath, TimeSpan cutFromStart, TimeSpan cutFromEnd)
 {
    using (WaveFileReader reader = new WaveFileReader(inPath))
    {
        using (WaveFileWriter writer = new WaveFileWriter(outPath, reader.WaveFormat))
        {
            int bytesPerMillisecond = reader.WaveFormat.AverageBytesPerSecond / 1000;

            int startPos = (int)cutFromStart.TotalMilliseconds * bytesPerMillisecond;
            startPos = startPos - startPos % reader.WaveFormat.BlockAlign;

            int endBytes = (int)cutFromEnd.TotalMilliseconds * bytesPerMillisecond;
            endBytes = endBytes - endBytes % reader.WaveFormat.BlockAlign;
            int endPos = (int)reader.Length - endBytes;

            TrimWavFile(reader, writer, startPos, endPos);
        }
    }
}

private static void TrimWavFile(WaveFileReader reader, WaveFileWriter writer, int startPos, int endPos)
{
    reader.Position = startPos;
    byte[] buffer = new byte[1024];
    while (reader.Position < endPos)
    {
        int bytesRequired = (int)(endPos - reader.Position);
        if (bytesRequired > 0)
        {
            int bytesToRead = Math.Min(bytesRequired, buffer.Length);
            int bytesRead = reader.Read(buffer, 0, bytesToRead);
            if (bytesRead > 0)
            {
                writer.WriteData(buffer, 0, bytesRead);
            }
        }
    }
}

I wrote exactly whats in there but when I'm opening the file i trimmed it says he's corrupted.
How does this code works? The while (reader.Position < endPos) is always true and the reader.Position doesn't change.
Edit 1
The else if() are same as the else but i put it just to be sure.
while (reader.Position < end)
        {
            int bytesRequired = (int)(end - reader.Position);
            if (bytesRequired > 0)
            {
                int bytesToRead = Math.Min(bytesRequired, buffer.Length);
                int bytesRead = reader.Read(buffer, 0, bytesToRead);
                if (bytesRead > 0)
                {
                    writer.Write(buffer, 0, bytesRead);
                }
                else if (bytesRead == 0)
                {
                   break;
                }
            }
            else if (bytesRequired <= 0)
            {
                break;
            }
        }

A: you should break out of the while loop if bytesRequired <= 0 or if bytesRead == 0

A: I found the soluton. I had to write writer.Dispose() after it was finished.
Like that:
public static void TrimWavFile(string inPath, string outPath, TimeSpan cutFromStart, TimeSpan cutFromEnd)
 {
    using (WaveFileReader reader = new WaveFileReader(inPath))
    {
        using (WaveFileWriter writer = new WaveFileWriter(outPath, reader.WaveFormat))
        {
            int bytesPerMillisecond = reader.WaveFormat.AverageBytesPerSecond / 1000;

            int startPos = (int)cutFromStart.TotalMilliseconds * bytesPerMillisecond;
            startPos = startPos - startPos % reader.WaveFormat.BlockAlign;

            int endBytes = (int)cutFromEnd.TotalMilliseconds * bytesPerMillisecond;
            endBytes = endBytes - endBytes % reader.WaveFormat.BlockAlign;
            int endPos = (int)reader.Length - endBytes;

            TrimWavFile(reader, writer, startPos, endPos);
            writer.Dispose();
        }
    }

A: The sample code you used it a bit outdated and has some bugs.
Here is an updated version (that works perfectly well for me):
private void Cut()
{
  var filename = @"G:\Voice\Samples\LongAudioFile.wav";
  FileInfo fi = new FileInfo(filename);
  var outputPath = System.IO.Path.Combine(fi.Directory.FullName, string.Format("{0}_Shorter{1}", fi.Name.Replace(fi.Extension, ""), fi.Extension));

  TrimWavFile(filename, outputPath, TimeSpan.FromHours(1));
}

public static void TrimWavFile(string inPath, string outPath, TimeSpan duration)
{
  using (WaveFileReader reader = new WaveFileReader(inPath))
  {
    using (WaveFileWriter writer = new WaveFileWriter(outPath, reader.WaveFormat))
    {
      float bytesPerMillisecond = reader.WaveFormat.AverageBytesPerSecond / 1000f;

      int startPos = 0;
      startPos = startPos - startPos % reader.WaveFormat.BlockAlign;

      int endBytes = (int)Math.Round(duration.TotalMilliseconds * bytesPerMillisecond);
      endBytes = endBytes - endBytes % reader.WaveFormat.BlockAlign;
      int endPos = endBytes;

      TrimWavFile(reader, writer, startPos, endBytes);
    }
  }
}

private static void TrimWavFile(WaveFileReader reader, WaveFileWriter writer, int startPos, int endPos)
{
  reader.Position = startPos;
  byte[] buffer = new byte[reader.BlockAlign * 1024];
  while (reader.Position < endPos)
  {
    int bytesRequired = (int)(endPos - reader.Position);
    if (bytesRequired > 0)
    {
      int bytesToRead = Math.Min(bytesRequired, buffer.Length);
      int bytesRead = reader.Read(buffer, 0, bytesToRead);
      if (bytesRead > 0)
      {
        writer.Write(buffer, 0, bytesRead);
      }
    }
  }
}

Note that in my case I need to get the audio from the start up to a certain point (ex: 1H).
if you want to get a specific section somewhere in the middle, just change:
int startPos = 0;

to
int startBytes = (int)Math.Round(startPoint.TotalMilliseconds * bytesPerMillisecond);
startBytes = startBytes - startBytes % reader.WaveFormat.BlockAlign;
int startPos = startBytes;


text:
Q: Unable to open include file 'inttypes.h' in Borland C++ Builder I'm using Borland C++ Builder, I wrote a class where I had to use this header "inttype.h" because I'm using 'int64_t'. the problem is I have this error telling me it can open this include file:
[C++ Error] RSA.h(3): E2209 Unable to open include file 'inttypes.h'

in Code::Blocks I didn't have this problem, so I thought C++ Builder doesn't have this file, so I added 'inttypes.h' from Code::Blocks directory to my project in C++ Builder but still the same error.
how can I surpass this problem ? or if I can't include this file, what are long integer variables I can use instead of 'int64_t' ?
EDITED:
my C++ Builder version is 6
thanks, I finally found a solution is one could say. instead of using "inttypes.h" I used "stdint.h"
but still wondering, can this stdint.h do all the things inttypes.h can do ?

A: inttypes is a c99 header. probably your compiler does not fully support c99.
you may try #include <cinttypes> which is the c++ variant. or the more basic stdint.h or cstdint


text:
Q: Generated .TLB file output directory I have a compiled c# assembly that I am registering for COM exposure. In order to import my library into some legacy c++ code the .tlb file needs to be in one of my "include" directories.
Instead of adding my bin directory to the include directories of the project that will use it, and since these projects will always be compiled under the same folder structure, I was wondering if, on compile, it was possible to direct my .tlb file to a specific directory.

A: In the Project Properties under the Build Events there is a Post-build events section. Here you can apply any command you'd like, including copy.
Here's some example code that will copy a file form the bin\Debug directory to another directory in the C:\ drive.
copy "$(TargetDir)\filename.tlb" "C:\output directory path\"

A: Use XCOPY in a post-build task.


text:
Q: EJB+EclipseLink or Spring+Hibernate I noticed many projects, that are based on Spring framework use Hibernate for JPA.
But when they base on EJB, they use often EclipseLink.
Is my observation correct?
If yes - why is that?

A: I have worked on a couple EJB projects and multiple Spring ones that all used Hibernate.
From a Spring perspective one reason that most Spring projects use Hibernate is that Spring has always had extremely good integration with Hibernate and is constantly improved to use the latest Hibernate releases. Using Spring and Hibernate just works!!!


text:
Q: Can we link meta.stackoverflow from meta.X.SX? Sometimes it's appropriate on a meta.X.SX site to say "This should be on meta.SO instead".  So there's a sort of hierarchy: parent -> meta -> meta.SO.  Would it make sense to have a link to 'meta.SO' on a meta site's banner (next to 'parent', perhaps)?
(I know that the link "feedback always welcome" points here, but that's not an obvious link to click on for people wanting support or to find out more about the SE network.)


text:
Q: Select from MySQL Pivot Stored Procedure using PHP I am trying to use the MySQL pivot from this site - http://mysql.rjweb.org/doc.php/pivot - to create and select a pivot using MySQL & PHP.  So far I have saved the stored procedure to MySQL and that worked fine.  When I go into the MySQL console on the server and enter the query below I receive the expected data/result.
CALL Pivot('`rates-short`', '`Hotel_Name`', '`CheckIn_Date`',
           '`Discount_Percentage`', "WHERE `Num_Nights` = 1", '');

However, when I call that same SQL statement in PHP, I don't get any data.  Instead I get the text below (from a PHP print_r).  How do I get the pivot data?
Array ( [@stmt] => SELECT GROUP_CONCAT(CONCAT(
     'SUM(IF(`CheckIn_Date` = ', '"', val, '"', ',
            `Discount_Percentage`, 0)) AS ', '"', val, '"')
                SEPARATOR ", ") INTO @sums
    FROM ( SELECT DISTINCT `CheckIn_Date` AS val
               FROM `rates-short`
               WHERE `Num_Nights` = 1
               ORDER BY 1
         ) AS top )

I have tried many different PHP MySQL/MySQLi/stored procedure code variations and they all return the same thing.  Here's what I have at the moment.
<?php
$dbhost = xxx;
$dbuser = xxx;
$dbpass = xxx;
$dbname = xxx;

try {
    $pdo = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    $sql = "CALL Pivot('`rates-short`', '`Hotel_Name`', '`CheckIn_Date`',
          '`Discount_Percentage`', 'WHERE `Num_Nights` = 1', '')";
    $q   = $pdo->query($sql);
    $q->setFetchMode(PDO::FETCH_ASSOC);
}
catch (PDOException $e) {
    die("Error occurred:" . $e->getMessage());
}

while ($r = $q->fetch()) {
    echo count($r);
    print_r($r);
}
?>

A: Sounds like the problem is with "retrieving multiple result sets through PDO".  (The problem will occur with PHP's mysqli interface, too.)  Here are some references:

*

*https://www.php.net/manual/en/pdostatement.nextrowset.php

*https://stackoverflow.com/a/21381133/1766831

*http://www.mysqltutorial.org/mysql-stored-procedures-return-multiple-values/

*https://www.ibm.com/support/knowledgecenter/SSEPGG_11.5.0/com.ibm.swg.im.dbclient.php.doc/doc/t0023501.html


text:
Q: Asus K53SJ upgrade to 8Gb of Ram ussually getting screen glitch I've just upgrade my ASUS K53SJ to 8Gb of RAM (the original is 4Gb), I'm using 2x Elpida 4Gb 1333Mhz.
When I use just single one of RAM, everything works fine, but when I combine and use both of my RAMs, my computer usually freeze like this pic below

And for sure, I can't use it any more, I need to hold the power button to shut it down.
I'm using Windows 8.1 with lastest update, running on Intel SSD 530 120Gb.
Please any1, do you have any idea what happens with my laptop? :(
Thanks in advance and sorry for my English.

UPDATE 1:
Processor: Intel® Core™ i5 2410M
Chipset: Intel® HM65 Express Chipset
Graphic: NVIDIA® GeForce® GT 520M with 1GB DDR3 VRAM
Storage: Intel SSD 530 120Gb + WD 500Gb
Bios: last version

UPDATE 2
I did try to get another DDR3 8Gb instead of 2x4Gb, and seems like everything is running ok until now, so I will close my question here.
The problem may come from the voltage, my new Samsung DDR3L 8Gb (1.35v) seems working perfect with my laptop, it is running very smooth and no conflict.
Thanks.


text:
Q: Regex.IsMatch returns true when shouldn't I have a Regex pattern which should allow all alphanumeric characters, and -, _, . and space
"[A-Za-z0-9-_. ]+"
I am trying to validate a string against this regex using Regex.IsMatch, but it returns true. Why?
string pattern = "[A-Za-z0-9-_. ]+";
string input = "rtgfd&**((&";
bool isMatch = Regex.IsMatch(input, pattern);
// isMatch is true, why?

A: It matches because your string does contain one or more characters in the [A-Za-z0-9-_. ] set. If you want only that, change your pattern to this:
string pattern = "^[A-Za-z0-9-_. ]+$";

It will force the pattern to match from the beginning to the end of the string.


text:
Q: Is there a way to break up a getline? #include <iostream>
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;

const int N = 20;

void instructions()
{cout << "* To quit or print a bill, enter 0 when asked to Enter an item number." << endl;
cout << endl;
cout << "* To cancel orders, enter the item number of the item to cancel" << endl;
cout << "  and then enter the negative of the number of orders to cancel." << endl;
cout << "  (e.g., -3 to cancel 3 orders of the selected item)." << endl;
cout << endl;
cout << "--- MENU --------------------" << endl;
}
int main(int argc, char *argv[])
{

ifstream infile; // init input file
string foods; // food name
float costs; // food cost
string food[N]; // food array
float cost[N]; // cost array
int cnt; // counter
char tab = '\t';

cout << setprecision(2) << fixed; // shows decimal two places
// below if file argument isn't found return error message
if(argc != 2)
{
    cerr << "File not found." << endl;
    return 1;
}

infile.open(argv[1]); // opens the user inputed file
    cnt = 0;// sets up counter for while loop
       infile >> foods >> costs;    // initalizes the while loop

instructions();

// While loop reads in information from input file and uses a count.
while(infile &&  cnt < N)
{

     food[cnt]= foods;
     cost[cnt] = costs;
     cout << cnt << ": " << food[cnt] << tab << cost[cnt] << endl;
     ++cnt;

     infile >> foods >> costs;
}

cout << "Enter item number (0 to print bill): ";
cout << endl << cnt;

return 0;
}

Object: The program reads in a menu file. The name of the food goes to an array and the cost goes to an array. The issue I'm having is that when words have a space in them it throws the whole thing off. I know I need to use a getline, but I'm not exactly sure how to break a getline into name // cost. Can someone help or show some type of example.
Hamburger    1.89
Cheeseburger 2.29
French Fries 1.59
Onion Rings  1.59
Soda         1.29
Iced Tea     1.29

A: You can use std::getline() in a loop to read each line, then use std::find_if() to find first digit of that line. That's the position where to split the string. I'll leave it to you to trim the trailing whitespace from the food name.
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <cctype>

int main()
{
    using namespace std;

    istringstream is(
R"(Hamburger    1.89
Cheeseburger 2.29
French Fries 1.59
Onion Rings  1.59
Soda         1.29
Iced Tea     1.29
)");

    string s;
    while( getline( is, s ) )
    {
        auto it = find_if( begin( s ), end( s ), []( char c ){ return isdigit( c ); } );
        if( it != end( s ) )
        {
            string name( begin( s ), it );
            string price( it, end( s ) );
            cout << "\nFood: " << name << "\nPrice: " << price << endl;
        }
    }
}

Live Demo.
More robust solution
As commenter noted, the above solution doesn't work if food name contains digits. To fix that we can use reverse_iterator to parse each line in reverse. The reverse_iterator will be obtained by calling free functions crbegin() (const reverse begin) and crend() (const reverse end).
If your version of STL doesn't provide these yet, you can replace them by the related std::string methods line.crbegin() and line.crend() (remove the c if even these are not available).
The first token found in reverse will be our price. From the "reverse end" of the price we parse further backwards to skip the whitespace between name and price.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <cctype>

int main()
{
    using namespace std;

    istringstream is(
R"(Hamburger    1.89
Cheeseburger 2.29
French Fries 1.59
Onion Rings  1.59
Soda 24      1.29
Iced Tea     free
)");

    string line;
    while( getline( is, line ) )
    {
        auto itLineRevEnd = crend( line );

        // Find end (reverse begin) of price token.
        auto itPriceRevBegin = find_if( crbegin( line ), itLineRevEnd, []( char c ){ return ! isspace( c ); } );
        if( itPriceRevBegin != itLineRevEnd )
        {
            // Find begin (reverse end) of price token.
            auto itPriceRevEnd = find_if( itPriceRevBegin, itLineRevEnd, []( char c ){ return isspace( c ); } );
            if( itPriceRevEnd != itLineRevEnd )
            {
                // Find end (reverse begin) of name.
                auto itNameRevBegin = find_if( itPriceRevEnd, itLineRevEnd, []( char c ){ return ! isspace( c ); } );
                if( itNameRevBegin != itLineRevEnd )
                {
                    // Call reverse_iterator::base() to turn them into forward iterators (otherwise strings would be reversed).
                    string name( itLineRevEnd.base(), itNameRevBegin.base() );
                    string price( itPriceRevEnd.base(), itPriceRevBegin.base() );

                    cout << "\nFood: \"" << name << "\"";
                    cout << "\nPrice: ";

                    try
                    {
                        double priceNum = stod( price );
                        cout << priceNum << endl;
                    }
                    catch( std::exception& e )
                    {
                        // Conversion error or out-of-range.
                        cout << "ERROR" << endl;
                    }
                }
            }
        }
    }
}

Live Demo.
Output:
Food: "Hamburger"
Price: 1.89

Food: "Cheeseburger"
Price: 2.29

Food: "French Fries"
Price: 1.59

Food: "Onion Rings"
Price: 1.59

Food: "Soda 24"
Price: 1.29

Food: "Iced Tea"
Price: ERROR


text:
Q: How does MEF know which parts to import? Currently I use unity and prism.
If I want to put stuff into unity i do it at the module level.
How do I do it with MEF?
I see that I add exports to the class, but how does MEF know to add these?  Does it do it by class library?  is there a way to link it to modules?

A: MEFContrib has a "MEF + Unity Integration" project you should look at. Here's a blog post about it:
http://pwlodek.blogspot.com/2009/05/unity-mef-integration-layer.html
It makes MEF aware of Unity and vice-versa. Pretty nice.
As for "How does MEF work", I would suggest watching this excellent video:
http://channel9.msdn.com/Shows/SilverlightTV/Silverlight-TV-Episode-4-3-Steps-to-MEF-Export-Import-Compose
It shows all of the component parts of MEF and how they work together.


text:
Q: get stderr and stdout to string in ShellExecute function I want to get the stderr and the stdout from excusing commands in console to x string in order to do some codes in certain stderr and stdout cases
case WM_CREATE:
            ShellExecute(0,
                         "open",
                         "cmd.exe",
                         "/C ipconfig > x",
                         0, SW_HIDE);
break;

that out result to x file also I think it is not recording stderr as it leaves the x file empty on excusing adb command

A: @CodyGray, thank you for trying to help, I found the solution is to just add "2>&1" this will catch stderr and stdout like this
ShellExecute(0,
                         "open",
                         "cmd.exe",
                         "/C ipconfig > buffer.txt 2>&1",
                         0, SW_HIDE);

the solution is more simpler than what you have mentioned just need to find out how to redirect it to string


text:
Q: Redirect to Parent URL from callback after using window.open I'm trying to redirect the callback URL back to the parent window that is calling window.open.  Currently the callback URL is opening inside the child window spawned from the parent.
Parent Window => Opens child window for authentication => user authenticates and is redirected to this child window. How do I redirect to the Parent Window?
Here is the call to window.open
newwindow = window.open(response.data.auth_url,'Etsy','height=800,width=1000');
if (window.focus) {
    newwindow.focus()
}

Any idea how to accomplish this?

A: To communicate between windows use Postmessage
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
Your scenario might be that the child window sends a message to the parent window that in turn closes the child window and redirects to the final url.

A: Here's the solution I came up with if anyone else runs into this issue.
In my angularJS Controller file I check for the two pieces of info I need from the callback URL:
if ($state.params.oauth_token && $state.params.oauth_verifier) {

    /* This closes the child window */
    $window.close();

    var params = {
        oauth_token: $state.params.oauth_token,
        oauth_verifier: $state.params.oauth_verifier
    };

    /* process the info ... */

}

I also poll to see when the callback URL is made and redirect the parent window
win = window.open(response.data.auth_url,'Etsy','height=800,width=1000');

var pollTimer = window.setInterval(function() {
    try {
        if (win.document.URL.indexOf(response.data.callback_url) != -1) {

            window.clearInterval(pollTimer);

            $state.go("etsy.connected");

         }
     } catch(e) {
           // Error Handling
     }
}, 500);


text:
Q: How to add a list or array of strings as a column to a Spark Dataframe So, I have n number of strings that I can keep either in an array or in a list like this:
val checks = Array("check1", "check2", "check3", "check4", "check5")
val checks: List[String] = List("check1", "check2", "check3", "check4", "check5")

Now, I have a spark dataframe df and I want to add a column with the values present in this List/Array. (It is guaranteed that the number of items in my List/Array will be exactly equal to the number of rows in the dataframe, i.e n)
I tried doing:
df.withColumn("Value", checks)
But that didn't work. What would be the best way to achieve this?

A: You need to add it as an array column as follows:
val df2 = df.withColumn("Value", array(checks.map(lit):_*))

If you want a single value for each row, you can get the array element:
val df2 = df.withColumn("Value", array(checks.map(lit):_*))
            .withColumn("rn", row_number().over(Window.orderBy(lit(1))) - 1)
            .withColumn("Value", expr("Value[rn]"))
            .drop("rn")


text:
Q: How to use ajax to display php code when button is clicked So I have this code here,
<button type="button">Click Me</button>


text:
Q: Is having a fragment with every activity a good practice (based on Android Studio)? In the new Android Studio, every time I create an activity from the wizard it will create the following structure:
public class LoginActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_login, container, false);
            return rootView;
        }
    }

}

Notice there's the activity and it contains a fragment place holder. Is this considered a good practice? is it because if you wanted in the future to support tablets or replace fragment then you could (and thats why its the new default in Android studio?).

A: Generally speaking, yes, you should try to use fragments as much as possible, so that you can have different layouts for different size / aspect ratio devices.
And yes, that's why Android Studio generates code that way by default.
However, like any good rule, there are exceptions. Sometimes, an activity is simple, and will not differ on different devices. In that case, a fragment doesn't necessarily make sense.
In short, use fragments by default. Go with just an activity in the few cases where it makes sense you in your project.


text:
Q: Mapping DTO to Entity with ModelMapper including exceptions I am having a DTO (OpeningHoursPeriodDTO) and an Entity (OpeningHoursPeriod), which I want to map using ModelMapper.
As long I throw no exception inside the converter method all is working fine as expected.
Here the code of the converter:
modelMapper
        .createTypeMap(OpeningHoursPeriodDTO.class, OpeningHoursPeriod.class)
        .setConverter(converter -> {
            OpeningHoursPeriodDTO openingHoursPeriodDTO = converter.getSource();
            if (openingHoursPeriodDTO == null) {
                return null;
            }

            if (openingHoursPeriodDTO.getOpen() == null || openingHoursPeriodDTO.getClose() == null) {
                throw new BadRequestException("Opening hours and closing hours must be present");
            }

            if (!Objects.equals(
                    openingHoursPeriodDTO.getOpen().getDay(),
                    openingHoursPeriodDTO.getClose().getDay())) {
                throw new BadRequestException("Opening and close day for a period must be for the same day");
            }

            return OpeningHoursPeriod.builder()
                    .id(openingHoursPeriodDTO.getId())
                    .day(openingHoursPeriodDTO.getOpen().getDay())
                    .openTime(LocalTime.parse(openingHoursPeriodDTO.getOpen().getTime(), TIME_FORMATTER))
                    .closeTime(LocalTime.parse(openingHoursPeriodDTO.getClose().getTime(), TIME_FORMATTER))
                    .build();
        });

The problem is that if it happens to throw an Exception, I get a 500 Status Code in my Spring Boot application, although the status code of the BadRequestException should be 400.
Any Idea how to best handle such converter exceptions?

A: You could add @ResponseStatus to your exception:
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
}

This will generate a 400 when this exception is thrown.
But there are various other options to handle exceptions in REST Controllers. Have a look here:
https://www.baeldung.com/exception-handling-for-rest-with-spring


text:
Q: Cannot connect to FTPS at the same machine I need to create FTPS server for code testing purpose. I did such thing in IIS on port 990, generated a self-signed certificate and tried to connect via WinSCP at the same machine (All programs hosted locally). I created new session with my machine IP, username, 990 port number, chose FTP protocol, implicit encryption TLS/SSL and input my test password.
When I try to login I get communicate "Tls connection established waiting for welcome message" and a password prompt appears. After entering the test password I get only "Access denied" and nothing else.
When I tried do the same in filezilla I got only
"Connecting to server [myIp]:990...
Connected, waiting for authentication
Connection to server closed.
Trying to reconnect in 5 seconds" repeatedly.
My machine's operating system is Windows 10. Does anyone have an idea of what's going on? This is my log file after my login attempt:
`. 2019-06-17 17:24:59.256 --------------------------------------------------------------------------
. 2019-06-17 17:24:59.256 WinSCP Wersja 5.15.1 (Build 9407) (OS 10.0.18362 - Windows 10 Enterprise)
. 2019-06-17 17:24:59.256 Configuration: HKCU\Software\Martin Prikryl\WinSCP 2\
. 2019-06-17 17:24:59.256 Log level: Normal
. 2019-06-17 17:24:59.256 Local account: XXXXXX
. 2019-06-17 17:24:59.256 Working directory: C:\Program Files (x86)\WinSCP
. 2019-06-17 17:24:59.256 Process ID: 11024
. 2019-06-17 17:24:59.257 Command-line: "C:\Program Files (x86)\WinSCP\WinSCP.exe"
. 2019-06-17 17:24:59.257 Time zone: Current: GMT+2, Standard: GMT+1 (Środkowoeuropejski czas stand.), DST: GMT+2 (Środkowoeuropejski czas letni), DST Start: 31.03.2019, DST End: 27.10.2019
. 2019-06-17 17:24:59.257 Login time: poniedziałek, 17 czerwiec 2019 17:24:59
. 2019-06-17 17:24:59.257 --------------------------------------------------------------------------
. 2019-06-17 17:24:59.257 Session name: user@xxx.xxx.xx.xxx (Site)
. 2019-06-17 17:24:59.257 Host name: xx.xx.xx.xxx (Port: 990)
. 2019-06-17 17:24:59.257 User name: user (Password: No, Key file: No, Passphrase: No)
. 2019-06-17 17:24:59.257 Transfer Protocol: FTP
. 2019-06-17 17:24:59.257 Ping type: Dummy, Ping interval: 30 sec; Timeout: 15 sec
. 2019-06-17 17:24:59.257 Disable Nagle: No
. 2019-06-17 17:24:59.257 Proxy: None
. 2019-06-17 17:24:59.257 Send buffer: 262144
. 2019-06-17 17:24:59.257 UTF: Auto
. 2019-06-17 17:24:59.257 FTPS: Implicit TLS/SSL [Client certificate: No]
. 2019-06-17 17:24:59.257 FTP: Passive: Yes [Force IP: Auto]; MLSD: Auto [List all: Auto]; HOST: Auto
. 2019-06-17 17:24:59.257 Session reuse: Yes
. 2019-06-17 17:24:59.257 TLS/SSL versions: TLSv1.0-TLSv1.2
. 2019-06-17 17:24:59.257 Local directory: default, Remote directory: C:\ftpstest, Update: Yes, Cache: Yes
. 2019-06-17 17:24:59.257 Cache directory changes: Yes, Permanent: Yes
. 2019-06-17 17:24:59.257 Recycle bin: Delete to: No, Overwritten to: No, Bin path:
. 2019-06-17 17:24:59.257 Timezone offset: 0h 0m
. 2019-06-17 17:24:59.257 --------------------------------------------------------------------------
. 2019-06-17 17:24:59.321 Połączanie do xxx.xxx.xx.xxx:990...
. 2019-06-17 17:24:59.321 Połączono z xxx.xxx.xx.xxx:990, negocjowanie połączenia TLS...
. 2019-06-17 17:24:59.321 Verifying certificate for "" with fingerprint 7e:ea:df:4b:d7:47:0e:92:b9:37:b6:a0:05:03:3e:89:90:86:50:a8 and 20 failures
. 2019-06-17 17:24:59.321 Certificate for "" matches cached fingerprint and failures
. 2019-06-17 17:24:59.321 Using TLSv1.2, cipher TLSv1/SSLv3: AES256-GCM-SHA384, 2048 bit RSA, AES256-GCM-SHA384       TLSv1.2 Kx=RSA      Au=RSA  Enc=AESGCM(256) Mac=AEAD
. 2019-06-17 17:24:59.342 Połączenie TLS nawiązane. Czekam na wiadomość powitalną...
< 2019-06-17 17:24:59.342 220 Microsoft FTP Service
> 2019-06-17 17:24:59.342 USER user
< 2019-06-17 17:24:59.342 331 Password required
> 2019-06-17 17:25:03.247 PASS ***
< 2019-06-17 17:25:03.584 530-User cannot log in.
< 2019-06-17 17:25:03.584  Win32 error:
< 2019-06-17 17:25:03.584  Error details: An error occurred during the authentication process.
< 2019-06-17 17:25:03.584 530 End
. 2019-06-17 17:25:03.584 Połączenie nie powiodło się.
. 2019-06-17 17:25:03.606 Password prompt (last login attempt failed)`


text:
Q: ¿Cómo mando informacion de ASHX a HTML? Tengo una página HTML en la cual mando a llamar un Handler de ASHX, pero quiero que lo que trae el Handler de la Base de Datos se despliegue en el HTML dentro de una etiqueta

Tengo este código:
public class Titulo : IHttpHandler
{
    #region IHttpHandler Members

    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        //write your handler implementation here.
        ;

        string Order = context.Request.QueryString["Order"];

        string IdOrder = "0";

        switch (Order)
        {
            /*Pagina Index Portada Perfil -------*/
            case "1":
                { IdOrder = "1"; Title(context, IdOrder); }
                break;
            case "2":
                { IdOrder = "2"; Title(context, IdOrder); }
                break;
            case "3":
                { IdOrder = "3"; Title(context, IdOrder); }
                break;
            case "4":
                { IdOrder = "4"; Title(context, IdOrder); }
                break;
            case "5":
                { IdOrder = "5"; Title(context, IdOrder); }
                break;
        }
    }
    public void Title(HttpContext context, string Id)
    {
        /* Hace la conexion */

        bool flag = false;

        string Identificador = Id;

        using (SqlConnection conexion = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Aviso"].ToString()))
        {
            /* abre la connexion */

            conexion.Open();
            /*Ejecuta el stored procedure */
            using (SqlCommand orden = new SqlCommand("EXEC dbo.PROC_AVISO_Avisos " + Identificador.ToString(), conexion))
            {
                flag = true;
                using (SqlDataReader lector = orden.ExecuteReader())
                {
                    while (lector.Read())
                    {
                        string Titulo = lector[0].ToString(); //Titulo
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(Titulo);
                    }
                    lector.Close();
                }
            }
            conexion.Close();
        }
    }

En la parte de lector[0].ToString(); si me trae la información, pero no sé la forma en la que pueda poner esa información dentro del HTML

A: Si usas jQuery es muy sencillo llamar al handler ashx y volcar el contenido devuelto en un elemento HTML.

        $(function() {
            $('.title').load('/Titulo.ashx');
        });

Este ejemplo llama al handler Titulo.ashx y muestra su contenido en el span decorado con la clase "title".
Por supuesto deberás reemplazar la url "/Titulo.ashx" por la ruta de tu handler.

A: Dado que estas usando un Handler asumo que el resultado se debe hacer tras una acción o evento de tu pagina y de manera asíncrona.
para esto puedes usa la libreria JQuery y usar Ajax en donde pasas la url del archivo .ashx y la respuesta se retorna en un CallBack, adicionalmente si quieres enviar datos desde el HTML usas la propiedad Data asi:
$.ajax({
         url: 'Handlers/titulo.ashx',
         data: { identificador:'valor'//parametros opcionales
         dataType: 'text',
         type: 'POST',
         error: function () {console.log('sucedio un error'); },
        //en este punto usas tu resultado del backend
         success: function (respuestaTitulo) {
respuestaTitulo
}
});

esta fracción de codigo puede ir por ejemplo en el evento click de un botón.
espero te sirva.

A: Puedes usar variables de sesión, se trabajan desde el Code Behind, y pueden ser de cualquier tipo, ya sea un dato primitivo o una clase (hecha por ti o de las que trae ya C#)
Aquí te dejo un ejemplo de como instanciar una variable de sesión:
Session["nombreVarSession"] = new DataTable(); //un DataTable por ejemplo

Después para recuperarlo al otro lado simplemente accedes a la variable de sesión y le haces un casteo.
DataTable nombreVariable = (DataTable)Session["nombreVarSession"];


text:
Q: Active Reports winforms viewer control hosted in WPF Window There is currently not an available WPF viewer for Active Reports 6.   I was attempting to use a host control to display the viewer in a interop host but I'm not having much luck.  Has anyone else attempted this successfully?  I can't even get the wrapper Viewer control to add to the project toolbox as a custom control at this point.  I'm hoping to avoid recreating the wheel.

A: The existing ActiveReports Viewer works fine in WPF. You can use the below XAML to host it in WPF:
<Window x:Class="ARViewerHostedInWpf.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:arv="clr-namespace:DataDynamics.ActiveReports.Viewer;assembly=ActiveReports.Viewer6"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
    <Grid>
        <WindowsFormsHost Name="windowsFormsHost1">
            <arv:Viewer x:Name="ARViewer" Dock="Fill" />
        </WindowsFormsHost>
    </Grid>
</Window>

The following code in the code-behind of the XAML file will connect a report to the viewer in the XAML above and run it:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        NewActiveReport1 rpt = new NewActiveReport1();
        this.ARViewer.Document = rpt.Document;
        rpt.Run();
    }
}

I'm using the currently available version of ActiveReports 6 to test this.
Hope this helps!
Scott Willeke
GrapeCity


text:
Q: Custom ITaskHost on non windows system I'm trying to register a custom ITaskHost in a HostServices to be accessed during the build process with the Task.HostObject Property.
HostServices hostServices = new HostServices();
string prjPath = "/mnt/devel/CrowIDE/build/Debug/netcoreapp3.1/src/CustomCrowIDE.targets"
hostServices.RegisterHostObject(prjPath, "CustomBeforeBuild", "HookTask", this);
ProjectInstance pi = BuildManager.DefaultBuildManager.GetProjectInstanceForBuild (project);
BuildRequestData request = new BuildRequestData (pi, new string[] { target }, hostServices);
BuildResult result = BuildManager.DefaultBuildManager.Build (solution.buildParams, request);

But the HostObjet property of my custom task stays null.
I've read that ITaskHost are com object on windows that have to be registered in the ROT table, but here on linux, is it possible to bypass this constraints?

A: I've found another solution to forward result to the hosting application using the ILogger and the possibility to raise custom events with CustomBuildEventArgs.
The trick is to use reflexion in the logger to bypass isolation.


text:
Q: Is it possible to put notes in the tool bar of Pycharm/Other tools A suggestion, oftentimes I switch between editors depending on the task I am working on but I find that the often used keyboard shortcuts that I become trained to use for one editor starts to mess up my ability to use the keyboard shortcuts for another editor. So I thought that there is so much space at the top of the application near the toolbar to put down notes for shortcuts I use very often for that application.
For example, opening a resource in

*

*Pycharm is Ctrl+Shift+N

*Eclipse is Ctrl+Shift+R

*Vscode/Visual Studio is Ctrl+P
Anyways switching between editors and forgetting what keys does what becomes a bit of mental cost at some point and then shifting through various combinations become ineffective and creates frustration. It would be easier if I could just add the action "text" and shortcut "text" near the top of the IDE. Curious if such a feature exists in Pycharm or any other tool?
Unfortunately, the alternative I could do is edit all tools to key bind specifically to my specifications which maybe an option if I ever can get a good set of key binds I prefer along side with the config files I would need to do it.

A: Well this is an old question, but still answering. No, there is no such feature in PyCharm to do such a thing as stated in the question.
But a solution to the problem is to use Find Action whose shortcut key is Ctrl+Shift+A. Or even simpler, one can press Shift twice and then go in the Actions menu. After this one has to just search the action one wants to perform, and also this menu shows the shortcut key for actions.
Also, PyCharm's GUI is vast, so one need not necessarily use keyboard shortcuts (but yeah, this is not useful if work speed matters a lot)


text:
Q: Proving that if $m \in \mathbb{Z}$, then $\left]m,m+1\right[ = \emptyset$ in $\mathbb{Z}$. Using the fact that $\mathbb{Z}$ is an ordered ring.
Is this the same as proving that $n>m \Leftrightarrow n \geq m+1$ (again, in $\mathbb{Z}$)? I take it that it is, but, I also have trouble proving that.
I'd appreciate any sort of guidance or hints.


text:
Q: How to render OSM data in correct order? I am rendering data from OSM. There are various styles for different features(city road, highway, country road, walking path..). In order for a highway to be rendered above a simple road, it has to be rendered last, otherwise the roads would look like they lay above the highway. Of course this applies in general to all objects, not just roads.
So I wonder how can I determine the proper order? Using the area of the feature usually works for polygons, but even then not always. The OSM has a gazzilion of tags so trying to figure this out via trial and error would take ages. I'm sure there is some guideline or prepared set of rules for this somewhere but I haven't found it yet.

A: As to highways specifically, the most common way to render them at large scales (1:1 to +/- 1:50k) is to use the OSM 'layer' key (https://wiki.openstreetmap.org/wiki/Key:layer). Layer defines the relative vertical position of crossing but unconnected highway elements, e.g. a secondary road viaduct over a motorway, or motorway flyovers at a major highway junction.
Valid Wiki documented values are -5 to +5, and should cater for even the most exotic highway junction. However, sometimes people falsely use values outside this range, e.g. as a substitute for the OSM 'level' key (https://wiki.openstreetmap.org/wiki/Key:level). This is wrong, but you should reckon with this fact and deal with it. I usually default values outside the range to the maximum values. E.g. a false value of 'layer=11' is set to 'layer=5' in code.
As to the stacking of all other features: except for the already mentioned tip of reviewing some of the existing styles, which should give you a basis to work from, there is no substitute for "old fashioned" cartography... If you're unwilling to invest time in styling and cartography, then you should really reconsider your choice of OSM as datasource for your mapping needs, and maybe get some commercial or government sourced datasets with pre-configured layering and styling.

A: You can sort lines in the order of importance but as you can see through the data, things doesn't always mantain the same logic.
For example, using the same downloaded data you will find this (correct order of elements):

...or this (lower and secondary road over the highway):

So, what I can figure it out from your post is that you need to stablish an order of importance of roads and show the main ones over the secondary ones. In this case, highways always over the others, independently from the aerial view.
You can do that in two steps:

*

*Create a new attribute that defines the order or importance of the road (you decide your order):

*Sort (using MMQGIS for instance) by that new attribute.

Now if you apply the same style to this new sorted layers you will get those highways always on top (even if It is not the real aerial view...):


text:
Q: Laravel Query Builder MIN method I've this code below (Laravel 5 Query Builder), that should return the list of the posts having the id under the specified id and the minimum id founded.
As you can see the query use the take in order to limit the result, the value passed is an integer.
The problem is that the postList variable contain correctly the requested values but the firstPostID return the minumum founded in the db and not the minumum that the query i'm expecting to obtain.
$q = DB::table('posts')
            ->select('posts.id', 'posts.title', 'posts.created_at', 'users.name AS creatorName')
                ->join('users', 'users.id', '=', 'posts.creatorid_ext')
                ->take(Config::get('generals.history_posts_number'))
                ->where('posts.id', '<', $id)->orderBy('posts.id', 'desc');

        $postsList   = $q->get();

        $firstPostID = $q->min('posts.id');

This is what i get

{
   "firstid": 1,
   "posts": [
      {
         "created_at": "2015-03-01 12:00:00",
         "creatorName": "XXXX",
         "id": 6,
         "title": "this is the sixth title"
      },
      {
         "created_at": "2015-03-01 11:00:00",
         "creatorName": "XXX",
         "id": 5,
         "title": "this is the fifth title"
      },
      {
         "created_at": "2015-03-01 10:00:00",
         "creatorName": "XXX",
         "id": 4,
         "title": "this is the fourth title"
      },
      {
         "created_at": "2015-03-01 09:00:00",
         "creatorName": "XXX",
         "id": 3,
         "title": "this is the tirhd title"
      }
   ]
}

This is what i want to get

{
   "firstid": 3,
   "posts": [
      {
         "created_at": "2015-03-01 12:00:00",
         "creatorName": "XXX",
         "id": 6,
         "title": "this is the sixth title"
      },
      {
         "created_at": "2015-03-01 11:00:00",
         "creatorName": "XXX",
         "id": 5,
         "title": "this is the fifth title"
      },
      {
         "created_at": "2015-03-01 10:00:00",
         "creatorName": "XXX",
         "id": 4,
         "title": "this is the fourth title"
      },
      {
         "created_at": "2015-03-01 09:00:00",
         "creatorName": "XXX",
         "id": 3,
         "title": "this is the tirhd title"
      }
   ]
}

Many Thanks for your help


text:
Q: Replace a list in prolog I want to add a element to a list and replace it with my list.
So i wrote
initialstate(0,[],[[1,0],[2,3],[1,2],[1,3]]).
add(X,L2,[X|L2]).

I would like to make something like that...
?- initialstate(_,List,_),add(4,List,List)

and replace me the initialstate to this one
initial_state(0,[4],[[1,0],[2,3],[1,2],[1,3]]).

The maining question for me it's how to replace the list inside the indetifiers "initialstate".
I am new in prolog...Please help me... and sorry if it is something stupid.

A: once provided the appropriate declaration
:- dynamic initialstate/3.

you could update your DB in this way
?- retract(initialstate(A,B,C)), assertz(initialstate(A,[4|B],C)).

A: If you want to change a list you get a different list. So you need a different name for it.
Prolog is not an imperative language but more a descriptive one. This means: you do not say do this and this. You say this is like that and when this is the case this is true/false in files (knowledge). Then you start the interpreter, consult the knowledge and ask questions wether something is true.
Writing A = B means that A is always B.
?- initialstate(_,List,_),add(4,List,List)

means initialstate of a List is when 4 added to the list is the list itself.
This is not true. if 4 is added there should be a 4 where no 4 was before.
You can do this:
append4(List, ListWithFourInside) :- append(List, [4], ListWithFourInside).

Which reads like when I append 4 to a list I get a list with 4 inside.
It can be done shorter if you want the 4 in the beginning
add4(List, ListWithFourInside) :- [4 | List] = ListWithFourInside.

or even shorter:
add4(List, [4|List]).