text:
Q: How to subplot a dictionary of dataframes I would like to subplot 16 dataframes from a dictionary, but I tried with for loop but I don't how to finish my code with my DictDataFrame:
DataFrameDict.keys() :
dict_keys([1, 10, 20, 30, 40, 47, 100, 15, 25, 35, 45, 50, 5, 105, 55, 0])

DataFrameDict[0]:

date_time   id  value   Duration_datetime   Duration(Min)

So I would like to subplot each column Duration(Min) for each dataframe from dictionary but I don't know how to deals with : DataFrameDict[key]['Duration(Min)']
fig = plt.figure()
fig, ax = plt.subplots(nrows=4, ncols=4)

for i in range(4):
    for j in range(4):
        subplot = ax[i, j]

plt.show()

A: Try flatten the axes array and loop with zip:
fig = plt.figure()
fig, axes = plt.subplots(nrows=4, ncols=4)

for (key, data), ax in zip(DataFrameDict.items(), axes.ravel()):
    data['Duration (Min)'].plot(ax=ax)

    ax.set_title(f'Data for {key}')

plt.show()

A: *

*Using .ravel to flatten the axes array is fairly common.

*

*See the answer to this question for a thorough explanation.

*math.ceil will ensure there are enough rows, when the number of items to plot is not evenly divisible by the number of columns.

*This for-loop iterates through the enumerated dict keys, using idx to index the correct value from ax_array, and using the key to plot each dataframe.

*pandas.DataFrame.plot is used to plot the dataframe.

import pandas as pd
import numpy as np  # for test data
import math

# test data
rows = 10
keys = sorted([1, 10, 20, 30, 40, 47, 100, 15, 25, 35, 45, 50, 5, 105, 55, 0])
df_dict = {key: pd.DataFrame({'a': np.random.randint(0, 10, size=(rows)), 'b': np.random.randint(15, 25, size=(rows)), 'Duration(Min)': np.random.randint(30, 40, size=(rows))}) for key in keys}

# determine number of rows, given the number of columns
cols = 4
rows = math.ceil(len(keys) / cols)

# create the figure with multiple axes
fig, axes = plt.subplots(nrows=rows, ncols=cols, figsize=(16, 16))

# convert the axes from a 4x4 array to a 16x1 array
ax_array = axes.ravel()

# iterate through the dataframe dictionary keys and use enumerate
for idx, key in enumerate(keys):
    df_dict[key]['Duration(Min)'].plot(ax=ax_array[idx], ylabel='Value', title=f'DataFrame: {key}')
plt.tight_layout()
plt.show()


text:
Q: Selection.Find within a range I am not familiar with Word VBA and am having a problem with Selection.Find.
I want to replace commas by decimal points in a range of cells in a table. However I can only get Selection.Find to replace either all commas in the document or only the first comma in the range.
What I would like is something like Selection.Replace What:=".", Replacement:="," in Excel, but Word does not support that.
Suggestions very gratefully received!
CJ
Sub Replace_Percent_Separator()
'Correct percent separator in row 6, table 2

Dim PcentCells As Range

Path = "C:\xxx\Word\"
file = Dir(Path & "*.docx")

Application.DisplayAlerts = False
Application.ScreenUpdating = False

Do While file <> ""

    Documents.Open Filename:=Path & file

    With ActiveDocument

        Set PcentCells = .Range(Start:=.Tables(2).Cell(6, 2).Range.Start, _
            End:=.Tables(2).Cell(6, 10).Range.End)
        PcentCells.Select

        With Selection.Find
            .Text = ","
            .Replacement.Text = "."
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
            .Execute Replace:=wdReplaceAll '<-- replaces throughout document
            '.Execute Replace:=wdReplaceOne '<-- replaces in first cell but no other cells
        End With

    End With

    ActiveDocument.Save

    ActiveDocument.Close

    file = Dir()

Loop

Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub

A: Given your problem description, your code can be reduced to:
Sub Replace_Percent_Separator()
'Correct percent separator in row 6, table 2
file = Dir("C:\xxx\Word\*.docx")

Do While file <> ""
  Documents.Open FileName:=Path & file, AddToRecentFiles:=False, Visible:=False
  With ActiveDocument
    With .Tables(2).Row(6).Range.Find
      .Text = ","
      .Replacement.Text = "."
      .Forward = True
      .Wrap = wdFindStop
      .Format = False
      .Execute Replace:=wdReplaceAll
    End With
    .Close SaveChanges:=True
  End With
  file = Dir()
Loop

End Sub

As can be seen, there is no need to select anything and, by using wdFindStop instead of wdFindContinue, the Find/Replace stops where it should.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to get old location from corelocation - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

locations array last object holds new location, How to get the previous location?

A: You should create and use a mutable array of previous locations that were updated from previous calls to "locationManager: didUpdateLocations:".
According to the Apple documentation, the only time that "locations" array passed in via the delegate method will have more than one entry will be "If update events were deferred or if multiple events arrived before they could be delivered, the array may contain additional entries."

A: Get updated location in this method
func locationManager(_ manager: CLLocationManager,didUpdateLocations locations: [CLLocation])
 {
   guard let mostRecentLocation = locations.last else { return }
   print(mostRecentLocation)
 }


text:
Q: Flutter : Disable Previous Stepper Click I am using Stepper Widget to make Change PinCode Form. Everything is okay, but i don't know how to disable previous stepper click.
Example :

*

*Step 1 Input Old PinCode.

*Step 2 Input New Pincode.

I don't want to go back to step 1 if i am in step 2 by clicking the Stepper.
 How can i solve this ?

Here's my source Code :
Form(
        key: _formKey,
        child: Stepper(
          steps: steps(),
          currentStep: currStep,
          onStepContinue: () {
            setState(() {
              if (formKeys[currStep].currentState.validate()) {
                if (currStep < steps().length - 1) {
                  currStep += 1;
                } else if (steps().length == 2) {
                  print('Done');
                } else {
                  currStep = 0;
                }
              }
            });
          },
          onStepTapped: (step) {
            setState(() {
              currStep = step;
              print(step);
            });
          },
        ),
      ),
 List<Step> steps() {
    return [
      Step(
        title: const Text('Enter Previous PinCode'),
        isActive: currStep == 0 ? true : false,
        state: StepState.indexed,
        content: Form(
          key: formKeys[0],
          child: TextFormField(
            autofocus: true,
            keyboardType: TextInputType.number,
            validator: (value) {
              if (value.isEmpty || value != userModelHive.pinCodeNumber) {
                return 'PinCode Invalid';
              }
              return null;
            },
          ),
        ),
      ),
      Step(
        title: const Text('Enter New PinCode'),
        isActive: true,
        state: StepState.indexed,
        content: Form(
          key: formKeys[1],
          child: TextFormField(
            autofocus: true,
            keyboardType: TextInputType.number,
            validator: (value) {
              if (value.isEmpty) {
                return 'Provided PinCode';
              } else if (value.length < 4 || value.length > 6) {
                return "More than 4 Less than 6";
              }
              return null;
            },
          ),
        ),
      ),
    ];
  }

A: just check for the step variable in the onStepTapped weather it is previous or not..if it is the previous step then don't call setState
Stepper(
    steps:steps(),
    currentStep:currentStep,
    onStepTapped:(step){
      if(step>currentStep){
        setState((){
            currentStep=step;
        });
      }
    }
)

A: You can use the state parameter in Stepper.
state: _currentStep >= 1? StepState.disabled : StepState.complete

StepState.disabled will make it not clickable.

A: I'm not aware of any way of doing this which is supported out of the box by the Stepper widget. My proposed approach will be something like:
//List of already visited steps indexes
List<int> alreadyVisitedStepsIndexes = [];

// Your form
Stepper(
  steps: steps,
  currentStep: currStep,
  onStepTapped: (step) {
   // I'm not sure if step is already the index of it
   // if that's the case this code can be simplified

   var indexOfSelectedStep = steps.indexOf(step);
   if(!alreadyVisitedStepsIndexes.contains(indexOfSelectedStep)){
     alreadyVisitedStepsIndexes.add(indexOfSelectedStep);
     setState(() {
       currStep = step;
     });
   }
  },
)


text:
Q: Seraching for an alternative to annotatorjs.org following situation:
I have a website and would like customers to be able to annotate that like it is possible in google docs. Means: Mark a text and do a comment. I have already searched a lot and found http://annotatorjs.org/ which would be perfect for my needs but the problem is that development seems to have stopped back in 2016 and i don´t want to use components that are already not developed anymore by the date of implementation.
Does anyone have an idea ? I really searched a lot but i mostly find picture annotations which are not what i´m searching for.
Software as a service would also be an option.
Thanks, Christoph


text:
Q: Custom image name on iOS I'm developing an iPhone application, which has similar functionality to Camera Roll. In full size mode (e.g. viewing selected image in full size), I want to display the picture name (image file name).
The problem here: If the user changes the picture name on their PC and upload the picture back to their iPhone, I'm still getting original file name (e.g. "IMG_xxx), while I would like to get the name given by user. If I go to MyPictures on my iPhone, I do see user custom names.
How I can get a custom image name?
Thanks!

A: simple answer is No. You cannot do what are requesting.
In your app you can call an image whatever you want but once you save it to iPhone/iPad camera roll then it is renamed automatically by iOS. We developers have no control over that behavior.
Now if you were to save that picture in your apps document dir and some how let the user download / upload those pics using iTunes file sharing then perhaps that may work for you.


text:
Q: When NOT to use HTTP Connection Pooling? In my Java application, I am using a single object of RestTemplate for calling one HTTP endpoint. The resttemplate is a default one (instantiated by new RestTemplate() at the time of application start up) and so it doesn't has any connection pooling. Since the frequency of its usage is very less (about 50 calls per day), I am of the opinion that connection pooling should not be used as it will add to the overhead. Am I correct in my assumption?
Is there any standard use-case where HTTP connection-pooling should not be used?


text:
Q: How to improve and optimize Python Code for compiling images to Word file and saving as PDF Background: I am new to Python, and just trying to automate my mundane tasks.
It's my first time writing a program using python (this program is executed via the command prompt, it's not a GUI yet). So, what happens is I have a picture file (Has a random file name, I'm manually renaming this to "receipt.jpg", by the way, so it can conform to the code) and a PDF file ("SOA.pdf", also renaming this manually). I convert the pdf to image, insert the two images in a Word document, then save the document.
Here then is the question. Can anyone check the code I wrote and make some recommendations on how to improve it? I feel like I repeated a lot of code, and just changed a single letter.
Also, I can't straight up convert the Word file directly to PDF since Microsoft's Azure Information Protection is on, and have to manually click "Internal".
Sorry for the long question. Here's the code:
#import libraries
from lib2to3.pytree import convert
from docx import Document
from docx.shared import Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
from PIL import Image
from pdf2image import convert_from_path
#from docx2pdf import convert

#convert SOA.pdf to JPEG image named SOA.jpg
images = convert_from_path('SOA.pdf')
for i in range(len(images)):
    images[i].save('SOA.jpg', 'JPEG')

#store receipt.jpg as picture1, and SOA.jpg as picture2
picture1 = "receipt.jpg"
picture2 = "SOA.jpg"

#Access the properties of the pictures
img1 = Image.open(picture1)
img2 = Image.open(picture2)

#Store widths and heights of images to variables
width1 = img1.width
height1 = img1.height

width2 = img2.width
height2 = img2.height

#Create a document
document = Document ()

#Insert the picture1 into the document, width and height are calculated
document.add_picture(picture1,width=Inches(width1/260),height=Inches(height1/260))

#Center picture1
last_paragraph = document.paragraphs[-1]
last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

#Insert the picture2 into the document, width and height are calculated
document.add_picture(picture2,width=Inches(width2/260),height=Inches(height2/260))

#Center picture2
last_paragraph1 = document.paragraphs[-2]
last_paragraph1.alignment = WD_ALIGN_PARAGRAPH.CENTER

#Save the document as word file (.docx)
document.save('Receipt and SOA.docx')

#convert ('Receipt and SOA.docx','Receipt and SOA.pdf')

Thanks a lot!

A: I'd add a function add_picture to simplify the code and remove the duplication. Something like this:
def add_picture(document, picture):
  img = Image.open(picture)

  #!todo: Check that this file exists. I.e. that next actions with img are correct

  #Store widths and heights of images to variables
  width = img.width
  height = img.height

  #Insert the picture1 into the document, width and height are calculated
  document.add_picture(picture, width=Inches(width/260), height=Inches(height/260))

  #Center picture
  last_paragraph = document.paragraphs[-1]
  last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

In this case you'll call this function twice:
#Create a document
document = Document ()

add_picture(document, "receipt.jpg")
add_picture(document, "SOA.jpg")

May be you will prefer to add one more function – get_img_size(picture):
def get_img_size(picture):
      img = Image.open(picture)

      #!todo: Check that this file exists. I.e. that next actions with img are correct

      return img.width, img.height

After this your add_picture will be even simpler.
Also I'd extract the constant 260 to the very beginning of your code. It is right to avoid duplication of constants. So, I'd put something like img_size=260 somewhere upper.


text:
Q: Can I compress HTTP Requests using GZIP? I am communicating to a Tomcat Server using a Java ME application on my mobile device.
I was wondering if I could compress my requests/responses using Gzip to reduce the number of bytes sent over the network.

A: You can compress the content of an HTTP request or response, but not the headers.  See section 3.6 of the HTTP 1.1 spec, and the later section that describes the Content-Encoding header.
EDIT:  The flip side of this is that there is no guarantee that an HTTP server side will accept any particular compression format.  And depending on the quality of the server-side implementation of HTTP, it might not even recognize that the request content has been compressed.  So you don't want to do this unless you know that the server-side supports compressed request content.

A: Since you are using Tomcat, consider the possibility of putting an instance of Apache HTTP Server in front of the Tomcat server.
This can be done using the mod_jk module for Apache HTTP Server. Once you have done that, you can use mod_gzip/mod_deflate in Apache.
Of course, your client should have the ability to handle the compressed responses, for this to work. If you force your client to work with compressed responses, the client will end up displaying gibberish, since it would have been (usually) expecting plain text responses. You will find the definite indicator of the client's capability to handle compressed responses, in the client's Accept-Encoding headers.
This can be done programatically, using a servlet or a servlet filter that writes to a ZipOutputStream or GZipOutputStream, if you want to avoid the introduction of the Apache HTTP Server in the network. You will find some pointers on how to do this at the OReilly OnJava.com site.

A: Modern phones have so much CPU power and the network is relatively slow so compression makes perfect sense. It's quite easy to do also.
On the J2ME side, you do something like this (assuming you use HttpConnection),
  hc.setRequestProperty("Accept-Encoding", "gzip, deflate");
  if (hc.getResponseCode() == HttpConnection.HTTP_OK) {
      InputStream in = hc.openInputStream();
      if ("gzip".equals(hc.getEncoding()))
         in = new GZIPInputStream(in);
  ...

We use GZIPInputStream from tinyline but I am sure there are others,
http://www.tinyline.com/utils/index.html
On the server side, it's all built-in. Just add following attributes to the Connector in server.xml on Tomcat,
<Connector
compression="on"
compressionMinSize="2048"
compressableMimeType="text/html,application/json"
... />

A: On the server side, you can enable it as described here, but the mobile application will need a library that can decompress gzip, such as this one. Might be a bit of work to get it working though...


text:
Q: jQuery reset count on key press after partial postback I have a TextBox inside an asp.net UpdatePanel that records the number of key presses with some jquery
$(document).on("keypress", "#TextBox",function()   {
    $("#KeyPressCount").val(i += 1);
});

I do a partial postback after a button click inside the UpdatePanel and the jquery re-binds as expected and continues counting the key presses.
Now if I wanted to reset the count after the partial postback how would I go about doing that?
So if it had counted 20 key presses then a postback occurred it would reset to 0 and start counting again.
Any advice is appreciated.

A: you can do it like this
$(document).on("keypress", "#TextBox",function()   {
    var $keypress = $("#KeyPressCount");
    // if i==20 the set it to 0 or else add 1
    $keypress.val($keypress.val() >= 20 ? 0 : $keypress.val() += 1);
});

A: var keyPresses = 0;

$(document).on("keypress", "#TextBox",function()   {
    $("#KeyPressCount").val(keyPresses += 1);
});

Now all you need to do is update the value of keyPresses to 0 in the function that performs the postback.


text:
Q: Regular expressions in C# to detect more than one space between words I need to use regular expressions in C# to validate a TextBox. I need to add this role in ValidationExpress for a Validation Control in ASP.NET. Regular expressions should not allow this:

*

*more that ONE space between words

*considering also beginning and end of the string

Any ideas?

A: No need for regexps.
if (string.StartsWith(" ") || string.EndsWith(" ") || string.Contains("  ")) throw...

A: I believe you want:
 if (myText.Split(" ", StringSplitOptions.RemoveEmptyEntries).Length !=
     myText.Split(" ").Length)
 {
    //String contains multiple spaces
 }

As you've now said you DO want regexes I'd use
 @"\s\s+"

to match two or more whitespaces or:
 @"\ \ +"

to match two or more spaces.

A: If you are limited to validating a string, try the following pattern (example):
^[ ]?([^ ]+[ ])*[^ ]*$

It doesn't allow strings with two spaces anywhere in the string. This pattern ignores tabs and newlines, by the way. I've picked [ ] so you can see the spaces, but a simple space is the same. \s may not be right for you. For one, it might match a windows new line, \r\n.
Similarly, you can use a negative lookahead (example):
^(?!.*[ ]{2})

If you're using a client side validator you need to match from start to end, so use the pattern (?!.*[ ]{2}).*. It implicitly adds ^...$ around your pattern.
Either way, consider using a custom validator and writing a simple line of code to negate searching for two spaces. Here's how it's done. First, look at the documentation add a JavaScript function to your page:
function noTwoSpaces(source, arguments) {
    arguments.IsValid = (arguments.Value.indexOf('  ') == -1);
}

Next, add the CustomValidator control to use it:
<asp:CustomValidator ID="CustomValidator1" runat="server"
    ControlToValidate="TextBox1" Display="Dynamic" ErrorMessage=":-("
    ClientValidationFunction="noTwoSpaces"></asp:CustomValidator>

And that's it. Much easier than an elusive regex.

A: var rex = new Regex(@"\s{2,}");
Edit: Didn't see the start/end of the string.
        string poo = "a b";
        string poo1 = "a  b";
        string poo2 = "a   b";
        string poo3 = "a    b";
        string poo4 = " a  b";
        string poo5 = "a   b ";
        string poo6 = " a    b ";
        string poo7 = " a b ";
        var rex = new Regex(@"^\s{0}.\s{0,1}.\s{0}$");

        Console.WriteLine(rex.IsMatch(poo));
        Console.WriteLine(rex.IsMatch(poo1));
        Console.WriteLine(rex.IsMatch(poo2));
        Console.WriteLine(rex.IsMatch(poo3));
        Console.WriteLine(rex.IsMatch(poo4));
        Console.WriteLine(rex.IsMatch(poo5));
        Console.WriteLine(rex.IsMatch(poo6));
        Console.WriteLine(rex.IsMatch(poo7));

This returns:

True
False
False
False
False
False
False
False
Since the only valid string is the first one.

A: If you want to use regex, use this:
 {2,}

(NB: There is a space before the brackets).

A: Can be done without regex, but imho it's less obvious to not use regex:
\s{2,} or \s\s+ if .NET doesn't support the match-min-max syntax (I don't recall).

A: How about something like
string s = " tada  bling zap  ";
Regex reg = new Regex(@"\s\s+");
MatchCollection m = reg.Matches(s);

A: For beginning and ending no white spaces ^[^\s](.*\s.*)+[^\s]$
Mary bought a shoe match
MarySqeezeIntoAshoe no match


text:
Q: Update Symfony bundle with composer ignoring the minimum-stability setting I installed the payum/payum-bundle with composer (using the PHP Storm Plugin).
I couldn't install a version newer to 2.0.1 because the newer version seems not to be marked as stable (minimum-stability in composer.lock is "stable").
I too installed the payum/paypal-express-checkout-nvp bundle to add paypay express support.
I set everything up, created a controller to test it and ended up getting the error
Attempted to load trait "GatewayAwareTrait" from namespace "Payum\Core".
Did you forget a "use" statement for another namespace?

According to this (closed) issue the problem seems to be that payum/core is at version 1.2.8 but should be at least 1.3
https://github.com/Payum/PayumBundle/issues/367
Obviously the payum/bundle installation in version 2.0.1 installed the core-part with 1.2.8.
Now... How can I force composer to update the payum/core to at least 1.3?
What I need to do is either tell composer to ignore the minimum-stability for this single bundle or to set the minimum-stability to something less then stable (which I assume not being the best idea especialy when not permanently following all dev branches of all used packages) and a hint on how then to update the payum/core part.
Any hints are very wellcome - I am stuck here...

A: Your assumption is wrong, the version 2.1.0 of payum/payum-bundle is marked as stable.
In order to find out why you don't install it, we need your content of composer.json.
Did you run composer update in order to try to update to the latest packages of everything?

A: Since 1.3.0 Payum require a virtual package http client. You must add one of its implementations as a package, after that composer will allow you to upgrade payum.
The doc suggest you to install php-http/guzzle6-adapter but you can choose any other implementations of the client.
Do
php composer.phar update payum/core php-http/guzzle6-adapter


text:
Q: Register application to launch when USB item is connected to PC I created an Android application I would like to automatically open when USB item running Android gets connected to the PC.
Is it possible to register my application to handle USB connection? How do I do that?

A: You can listen for the Intent.ACTION_UMS_CONNECTED (usb mass storage mode started) or Intent.ACTION_POWER_CONNECTED (the phone is charging now) broadcasts with a BroadcastReceiver.
Note that both do not exactly tell you that you are connected to a computer. The charge broadcast might be as well fired when a normal charger is connected. The USB broadcast is a good indicator that you have something like a pc on the other end of the wire, but it's no guarantee. The user can also just connect the phone to the computer without entering mass storage mode.
As far as I know there is no intent that tells you for sure that you are connected to a computer (I can see that it's hard to detect without an application on the pc). You may want to read the intent class documentation and see if you can find a broadcast that I didn't see yet.

A: In your Manifest.xml, add this:
<receiver android:name=".BattStatusShow">
    <intent-filter>
        <action android:name="android.intent.action.ums_connected" />
    </intent-filter>
</receiver>

Then have your battery status class extend BroadcastReceiver, since your registered it for USB messages in the Manifest file.
public class BattStatusShow extends BroadcastReceiver{
  if (intent.getAction().equalsIgnoreCase( "android.intent.action.UMS_CONNECTED")) {
    //do stuff here, like signal the view of your app it needs to do something
  }
}

You don't give much information about what your application, but if it is only a battery display application, programming a PC host application to talk to your Android app seems overkill. If you want to do more, look at how the Nokia PC station app interacts with Nokia and emulate the behavior.

A: You can open any application from your mobile even if it is connected to PC via USB.
Visit the below link know about detecting USB connected or detached and Register a Broadcast Receiver for the same and launch your application from the Receiver using appropriate intent.
http://developer.android.com/guide/topics/usb/accessory.html


text:
Q: Pass data from caller to popup window on Internet Explorer I'm trying to pass the scope among other values to the child window. Currently, it works as expected on Chrome, but in internet explorer doesn't. Is there a way around ?
var  templateUrl = "/someviewpage";

  var wOptions$ = 'menubar=no, toolbar=no, location=0, status=no,
  resizable=no,scrollbars=no,top=175,toolbar=yes,scrollbars=no,resizable=no,width=800,height =' +
  window.innerHeight;

  var fname$ = 'mike',lname$ = 'jackson';
   var dataDto$ = {
                fname: fname$,
                lname: lname$,
                parentScope: $scope
            };
  var openUploadWindow$ = $window.open(templateUrl, 'coolpopup', wOptions$);

  openUploadWindow$.data = dataDto$;

A: Question had been asked and answered here: angularjs-issue-passing-data-to-a-new-browser-window-on-internet-explorer
Final code looks like this:
var  templateUrl = "/someviewpage";

  var wOptions$ = 'menubar=no, toolbar=no, location=0, status=no,
  resizable=no,scrollbars=no,top=175,toolbar=yes,scrollbars=no,resizable=no,width=800,height =' +
  window.innerHeight;

  var fname$ = 'mike',lname$ = 'jackson';
   var dataDto$ = {
                fname: fname$,
                lname: lname$,
                parentScope: $scope
            };

   $window.data = dataDto$;
  var openUploadWindow$ = $window.open(templateUrl, 'coolpopup', wOptions$);

Inside popup window js:
console.log(window.opener.data);


text:
Q: BLE advertising with different PHY used I'd like to ask question about BLE 5.0 advertising. If there are several PHY which can be utilized (Long Range - 125kbps or 500kbps, 1M, 2M), I wonder what PHY is used when device is sending advertising messages on these three advertising channels?
Are all used at once? So if I configure device at Long Range PHY, is it advertising using 125kbps/500kbps and is it only using this rate and modulation? Or does it work the way, devices are using only 1M and only when connection is established, they switch to the other rate & modulation?
Thank you very much. I'm just beginning with BLE standard and there is a lot to learn.
Radim

A: Generally speaking, the normal 1M PHY is used by default for advertising/scanning and connection. This is to retain compatibility with pre Bluetooth v5.0 devices. The device can then take advantage of the 2M, 500kbps, 125kbps through the following mechanisms:-
1- Connection: Once a connection is established, your device can request to switch to a different PHY. This is done by sending a request to the remote device and the remote device should accept this request (if it supports different PHYs). If this happens, only the chosen PHY would be used then. In other words, if the connection is switched to 2M PHY, all the packet exchange will be occurring on the 2M modulation and the 1M/500kbps/125kbps will not be used (see Bluetooth Core Specification v5.2, Vol 4, Part E, section 7.8.49: LE Set PHY Command).
2- Advertising: One of the new features of Bluetooth v5 is the availability of primary advertising channels (these are the default 3 advertising channels that have been used by BLE since version 4.0) and secondary advertising channels (these are the 37 data channels which Bluetooth v5 devices can utilise for advertising). When advertising, your device can choose the PHYs for the primary and secondary channels. For primary advertising channels, you are only allowed to choose between 1M or CODED PHY. For secondary advertising channels, your device can choose 1M, 2M, or CODED PHY. This means that your device can be advertising on 1M and CODED PHY simultaneously (see Bluetooth Core Specification v5.2, Vol 4, Part E, section 7.8.53: LE Set Extended Advertising Parameters command).
3- Scanning: Likewise, when performing a scan for devices, your device can choose the PHY that it wants to perform the scan/advert on for both primary and secondary channels. This means that the device can be performing scans on different channels simultaneously.

So to answer your questions:-

*

*I wonder what PHY is used when device is sending advertising messages on these three advertising channels?

Th used PHY depends on the device's preference. It is usually 1MPHY by default, but the device can switch to CODED PHY for its primary advertising channels, or to 2M/CODED PHY for its secondary advertising channels.

*

*Are all used at once?

For connections you can only have 1 PHY modulation. For advertising/scanning you can have two types of modulation if you are taking advantage of both primary and secondary channels (e.g. you can be advertising on the 1M PHY on your primary channels and also advertising on the CODED PHY on the secondary channels).

*

*So if I configure device at Long Range PHY, is it advertising using 125kbps/500kbps and is it only using this rate and modulation?

If you are only using primary advertising channels then yes, it will only be using this rate and modulation. If you are using both primary and secondary channels, you can have two modulations.

*

*Or does it work the way, devices are using only 1M and only when connection is established, they switch to the other rate & modulation?

No, the connection can be established on any PHY if both devices support connection establishment on different PHYs.
Below are some useful links:-

*

*How to work with BLE Codec 1MPHY, 2MPHY and CODED PHY on nRF52

*Bluetooth PHY - How it Works and How to Leverage it

*Bluetooth 5 Long-Range (Coded PHY)


text:
Q: Apollo federation throws error: marked @external but is not defined on the base service of i'm using apollo federation and meet with error, when trying to make something similar to computed fields (https://www.apollographql.com/docs/federation/entities/#extending-an-entity-with-computed-fields-advanced):
Error: A valid schema couldn't be composed. The following composition errors were found:client-api-gateway_1
[Payments MS] User.parentId -> marked @external but parentId is not defined on the base service of User (Users MS)

I have two services: Users and Payments. In users service i store information about users, and in payments information about payments connected to user.
Users service graph:
type User @key(fields: "id") {
        id: Int!
        name: String!
        surname: String!
        type: USER_TYPE!
        parentId: Int
    }

Payments service graph:
type UserSubscriptionInfo {
     nextChargeAmount: Int
     ......etc
}

extend type User @key(fields: "id") {
     id: Int! @external
     parentId: Int @external
     subscription: UserSubscriptionInfo @requires(fields: "parentId")
}

Based on parentId from User type i would like to get subscription, by extending User type.

A: Make sure you put both graphql schemas in the same gateway. In my app there was 2 different gateways and i put them in 2 different gateways. Above code is working perfectly.

A: Check also if the extended class has @GqlKey('id') in its class
For example :

@ObjectType({
  description: 'Extended Class',
})
@GqlKey('id') // <- Check if this extention exist
export class ClassName{
  @Field(() => ID)
  @Expose()
  id: string;
  ...
}


text:
Q: Android, How to fit message in Facebook dialog? After two days of searching finally I could integrate Facebook SDK into my application. My problem is when I set bundle and show dialog interface, some parts of lines are out of screen. This is my code:
        private void postFacebookMessage() {
            Log.i(TAG, "Try to post message");

            token = mFacebook.getAccessToken();
            Log.i("token", "" + token);

            Bundle parameters = new Bundle();
            parameters.putString("access_token", token);
            parameters.putString("message", "This is test message.");
            parameters.putString("name", "Chef Astro");
            parameters.putString("link", "http://www.astrogempak.com.my");
            parameters.putString("caption", message);
            parameters.putString("description", "");
            parameters.putString("picture","http://a1.mzstatic.com/us/r30/Purple/v4/2d/7d/c3/2d7dc3ed-9e32-cd7b-adba-2a31637a8cf0/mzl.toeyydsk.175x175-75.jpg");

    //      mAsyncRunner.request("me/feed", parameters, "POST", new WallPostRequestListener(), null);
            mFacebook.dialog(FacebookActivity.this, "feed", parameters, new SampleDialogListener());
    }

I put message in description but result is same. How to fit message inside dialog?


text:
Q: Proving that $\mathbb{Q}$ adjoin the square root of every prime is an infinite extension How would one show that $[\mathbb{Q}(\sqrt2, \sqrt3,...,\sqrt{p_n},...)]=\infty$? I know that we want to show there is no finite basis over the rationals, but I'm not sure how one would determine that such a basis does not exist.

A: Kummer theory tells us that as $ 2$, $3,\ldots,{p_n}$
generate a subgroup of order $2^n$ in $\Bbb Q^*/(\Bbb Q^*)^2$ then the
extension field $K_n=\Bbb Q(\sqrt2,\ldots,\sqrt {p_n})$ has degree $2^n$
over $\Bbb Q$. So your field contains subfields of arbitrarily large degree
over $\Bbb Q$.


text:
Q: What are some better ways to unstack a large data frame in R? I would like to reshape a data frame of dimensions 103740 x 4 into wide format, i.e., to go from the first block of text below to the second.  The following function works well enough when applied to part of the data frame but it exhausts my machine's available memory when applied to the full data frame:
reshape(analysis1[1:8], idvar=c("name", "sire_name"),
        timevar = "course", direction = "wide")[, -c(1,2)]

What are some better ways to unstack this data frame?
           name sire_name        course appearance
1      A Beetoo   Bahhare       Kempton          0
2      A Beetoo   Bahhare     Lingfield          9
3      A Beetoo   Bahhare     Southwell          0
4      A Beetoo   Bahhare Wolverhampton          0
5 A Bid In Time  Danetime       Kempton          0
6 A Bid In Time  Danetime     Lingfield          3
7 A Bid In Time  Danetime     Southwell          2
8 A Bid In Time  Danetime Wolverhampton          2
...

  Kempton Lingfield Southwell Wolverhampton
1       0         9         0             0
5       0         3         2             2
...

I've tried moving the data frame into a data table, but just doing this alone doesn't seem to help.

A: When you want it very simple like this reshaping in base R would be most efficient.  I'd just make a matrix out of appearance, cast it to a data.frame type, and name the columns.
newDF <- data.frame( matrix(oldDF$appearance, ncol = 4, byrow = TRUE) )
names(newDF) <- oldDF$course[1:4]

Now, if you don't have the frame sorted just as you've presented it and maybe even have more values in the course column the following is more robust...
oldDF <- oldDF[ order(oldDF$course), ]
s <- sort(unique(oldDF$course))
newDF <- data.frame( matrix(oldDF$appearance, ncol = length(s)) )
names(newDF) <- s

(you can add other columns to the order function to break ties if you wish)
One of the great advantages of the many commands that can be used to reshape your data and is that they are robust to the order of the data, missing cells, etc.  However, this also makes them generally quite slow when you've got a straightforward reshape on a very large data.frame object.


text:
Q: Create row values in a column with data from previous row in Python Pandas I am trying to create a new column in which the value in the first row is 0 and from the second row, it should do a calculation as mentioned below which is
ColumnA[This row] = (ColumnA[Last row] * 13 + ColumnB[This row])/14

I am using the python pandas shift function but it doesn't seem to be producing the intended result.
test  = np.array([ 1, 5, 3, 20, 2, 6, 9, 8, 7])
test = pd.DataFrame(test, columns = ['ABC'])
test.loc[test['ABC'] == 1, 'a'] = 0
test['a'] = (test['a'].shift()*13 + test['ABC'])/14

I am trying to create a column that looks like this

ABC
a

1
0

5
0.3571

3
0.5459

20
1.9355

2
1.9401

6
2.2301

9
2.7137

8
3.0913

7
3.3705

But actually what I am getting by running the above code is this

ABC
a

1
nan

2
0

3
nan

4
nan

5
nan

6
nan

7
nan

8
nan

9
nan

A: test  = np.array([ 1, 2, 3, 4, 5, 6, 7, 8, 9])
test = pd.DataFrame(test, columns = ['ABC'])
test["res"] = test["ABC"]
test.iloc[0]['res'] = 0                        # Initialize the first row as 0
test["res"] = test.res + test.res.shift()
test["res"] = test.res.fillna(0).astype(int)   # test.res.shift() introduces a nan and we replace it with a 0 and convert the column data type to int

A: Try:
test["a"] = (test["ABC"].shift().cumsum() + test["ABC"].shift()).fillna(0)
print(test)

Prints:
   ABC     a
0    1   0.0
1    2   2.0
2    3   5.0
3    4   9.0
4    5  14.0
5    6  20.0
6    7  27.0
7    8  35.0
8    9  44.0

A: Let's try a for loop
import pandas as pd

df = pd.DataFrame({'ABC': [1, 5, 3, 20, 2, 6, 9, 8, 7]})

lst = [0]
res = 0
for i, row in df.iloc[1:].iterrows():
    res = ((res * 13) + row['ABC']) / 14
    lst.append(res)

df['a'] = pd.Series(lst)
print(df)

Output:
   ABC         a
0    1  0.000000
1    5  0.357143
2    3  0.545918
3   20  1.935496
4    2  1.940103
5    6  2.230096
6    9  2.713660
7    8  3.091256
8    7  3.370452


text:
Q: TypeScript Error - Redux Middleware property 0 I get the following errors when setting up middleware. Using Redux observable/Redux toolkit.
Any inputs on why this is happenening?
Following below repo set-up.
https://github.com/beast911/react-redux-observables-typescript
import systemReducer, {
  getInfoStart,
  getInfoSuccess,
  getInfoFailed,
  addInfoStart,
  addInfoSuccess,
  addInfoFailed,
  editInfoStart,
  editInfoSuccess,
  editInfoFailed,
  deleteInfoStart,
  deleteInfoSuccess,
  deleteInfoFailed,
  completeInfoStart,
  completeInfoSuccess,
  completeInfoFailed,
} from "./system/slice";

import {
  combineReducers,
  configureStore,
  getDefaultMiddleware,
} from "@reduxjs/toolkit";
import { createBrowserHistory } from "history";
import { combineEpics, createEpicMiddleware } from "redux-observable";
import {
  getInfoEpic,
  addInfoEpic,
  completeInfoEpic,
  deleteInfoEpic,
  editInfoEpic,
} from "./system/epics";
import { ActionType } from "typesafe-actions";
import {
  connectRouter,
  routerMiddleware,
  RouterState,
} from "connected-react-router";

type SystemActionsWithPayload =
  | typeof getInfoStart
  | typeof getInfoSuccess
  | typeof getInfoFailed
  | typeof addInfoStart
  | typeof addInfoSuccess
  | typeof addInfoFailed
  | typeof editInfoStart
  | typeof editInfoSuccess
  | typeof editInfoFailed
  | typeof deleteInfoStart
  | typeof deleteInfoSuccess
  | typeof deleteInfoFailed
  | typeof completeInfoStart
  | typeof completeInfoSuccess
  | typeof completeInfoFailed;

type SystemActions = ActionType<SystemActionsWithPayload>;

type finalActions = SystemActions;

const epics = combineEpics(
  getInfoEpic,
  addInfoEpic,
  completeInfoEpic,
  deleteInfoEpic,
  editInfoEpic
);

export const history = createBrowserHistory<RouterState>();
export const rootReducer = combineReducers({
  router: connectRouter(history),
  system: systemReducer,
});
export type RootState = ReturnType<typeof rootReducer>;
const epicMiddleware = createEpicMiddleware<
  finalActions, // input actions
  finalActions, // output actions
  RootState
>();

function configureAppStore(initialState?: any) {
  // configure middlewares
  const middlewares = [routerMiddleware(history), epicMiddleware];
  // create store
  return configureStore<RootState>({
    reducer: rootReducer,
    middleware: middlewares,
    preloadedState: initialState,
  });
}

export const store = configureAppStore();
epicMiddleware.run(epics);

Type 'Middleware<{}, any, Dispatch>[]' is not assignable to type '[ThunkMiddleware<CombinedState<{ router: RouterState<RouterState>; system: TaskState; }>, AnyAction, null> | ThunkMiddleware<...>] | ((getDefaultMiddleware: CurriedGetDefaultMiddleware<...>) => [...]) | undefined'.
Property '0' is missing in type 'Middleware<{}, any, Dispatch>[]' but required in type '[ThunkMiddleware<CombinedState<{ router: RouterState<RouterState>; system: TaskState; }>, AnyAction, null> | ThunkMiddleware<...>]'

A: Most Redux Toolkit apis should not be called with manually specified generics.
By calling return configureStore<RootState>(... you actually erase all information about middlewares from your store. Skip the generic, just call return configureStore(... and let TypeScript infer the correct types from usage.


text:
Q: Sorting an array of information from another array output from SQL I need to be retrieve multiple unique values from an array set of data. Currently they are extracted as follows :
while($row1 = mysql_fetch_array($result1))
    {

     echo    "
".
             "".$row1[0]           . "	".
             "".$row1[1]           . "	".
             "".$row1[2]           . "	".
             "".$row1[3]           . "	".
             "".$row1[4]           . "	".
             "".$row1[5]           . "	".
             "".$row1[6]           . "	".
             "".$row1[7]           . "	".
//$row1[8] is the number of hours
             "".$row1[8]           . "	".
//$row1[9] is the user
             "".$row1[9]           . "	";
             }

As commented above, I need to accumulate the hours per user. However, I have problem sorting the array as the user value has to be unique in the array whereas the number has to keep stacking.
Really confused now. Appreciate any help offered.
EDIT : $row1[8] is an integer yes.
The sample data output table ( sorry no image) will be as follows :
------------------------------------------------------------------------------------------
Users |Telephone | Address | Postal Code | Hobbies | Interest| FB |Twitter | Insta | Hours
------------------------------------------------------------------------------------------
John  | 92238726 | SG      | 345322      | Running | Movies  |  1 |   0    | 0     |  5
Tom  | 922382134 | MY      | 345212      | Soccer | Movies  |  1 |   0    | 0      |  8
Jerry | 92238726 | SG      | 342122      | stamps | Nil  |  0 |   1    | 0      |   5
John  | 92238726 | SG      | 345322      | Running | Movies  |  1 |   0    | 0     |  12
Jerry | 92238726 | SG      | 342122      | stamps | Nil  |  0 |   1    | 0      |   2

Based on the output above which was extracted with the mysql_fetch_array, I'd like to sort the information to something like the following :
Users | Total Hours
John  |    17
Tom   |     8
Jerry |    7

SQL CODE :
"select DISTINCT jl.refno, jl.logno, jl.attendee, jl.jobsummary, FROM_UNIXTIME(jl.date, '%d/%m/%y') AS 'Date-In', from_unixtime(jl.dateout + (15*3600), '%d/%m/%y') AS 'Date-Out', @timein := (left(jl.timein,2)*60+right(jl.timein,2)) AS 'Time-In', @timeout := (left(jl.timeout,2)*60+right(timeout,2)) AS 'Time-Out', @temp := ((dateout -date)* 24 * 60) + @timeout - @timein AS 'temp', us.username from joblog jl, projects proj, users us where jl.project ='{$value}' AND proj.id ='{$value}' AND jl.staff = us.id"

A: Since you are using MySQL anyway, I recommend you to do it with an SQL. It's cleaner.
Edit your query to:
SELECT users, SUM(hours) as total FROM userTable GROUP BY users ORDER BY total DESC;

UPDATE - PHP Edition:
You can do it like this in PHP.
$counters = array();
while ($row1 = mysql_fetch_array($result1)) {
    $counters[$row1[9]] += $rows1[8];
}

arsort($counters);

foreach ($counters as $name => $total) {
   // do your output here
}

A:     <?php

function totalHours($user){
$result=mysql_query("select sum(hours) as total  from table_name where users='".$user."'");
$row=mysql_fetch_array($result);
return $row['total'];
    }

$result=mysql_query("select * from table_name group by users");
echo "
";
echo "

User
Total Hours

";

while($row1 = mysql_fetch_array($result1))
    {

 echo    "
".
         "".$row1[0]. "	".
        "".totalHours($row1[0]). "
";

         }

        echo "
";
?>


text:
Q: Is it acceptable to replace 2 parallel 100uF capacitors for LM2596 with two 220uF capacitors I have a printer motherboard with the LM2596 IC. The older version of the motherboard had one 100uF capacitor at the output pin of LM2596 but LM2596 recommends that 220uF be used. Because a cheap 100uF capacitor was used, there were issues with the printer such as temperature fluctuating.
People that had issues replaced the 100uF with 220uF and the issues were solved. I had the-same issue then opened up the device to replace the capacitor. After making this post, I realized that the motherboard version I have came with a supposed fix for this issue. The new motherboard uses two 100uF  in parallel to fix the issue. Those two 100uF parallel capacitors should only give 200uF not the recommended 220uF. Even with this fix, I still get temperature fluctuating sometimes.
Is there a problem if I replace the two 100uF parallel capacitors with two 220uF? Is this going to cause a problem? I mean, that would be 440uF.
If that's going to be a problem, how about removing the two 100uF parallel capacitors and put just one 220uF?
Most post I found also mentioned that the a poor quality capacitor is used for  LM2596 IC is used and this should be replace so that's why I feel like I have to replace those caps with a high quality one.

A: I assume that the output terminal of which you speak is not merely a DC power supply. I assume that it serves a control function, in addition to powering something.
If so, then it's hard to say what the effect of bulking up to 440 μF might be. At least two modes of failure are possible:

*

*The output signal at 440 μF might be unusably sluggish. The printer thus might not respond. Reducing the capacitance to 200 μF or 220 μF again would fix this problem.

*The 440 μF might draw too much current at the output, storing too much energy too fast. This would not harm the capacitor but it might render the board permanently useless.

Fortunately, #2 is unlikely. Even #1 is fairly unlikely.
Let's talk about #1. The output has an output resistance Rout, and the lower, the better; but for this kind of electronics, unfortunately, it's probably fairly high. The off-board load—that is, whatever it is that the output drives—will have a variable impedance, which means that it draws a variable current, which is why you have a capacitor tapped to a point between: the capacitor supplies the variable current so that the board's other electronics do not have to. The bigger the capacitor, the better it can supply the variable current, so that's good. Regrettably, the bigger the capacitor, the longer the period the output shall want to switch from low to high or high to low.
Switching is not instantaneous. The larger the capacitance, the slower the switch.
The time needed to switch will be approximately t = [-ln(Vmargin/VCC)][Rout][C], where probably 1.0 < -ln (Vmargin/VCC) < 1.5 and where C is your capacitance.
Regarding scenario #2, the potential problem there is that the board's electronics supplying the output must generate switching heat in proportion to the capacitance C. The heating rate dQ/dt will not change, but because the time t is longer, extra heat will be generated each time the output switches low to high or high to low.
Fortunately, outputs like these tend to be designed to handle a lot of switching. Even more fortunate (if you wish to call it fortune) is that #1 limits the effective switching rate. So #1 counteracts #2 to a significant degree.
I hope that some of that makes sense. If you wish to make some extremely rough calculations, then you might assume that Rout = 1.0 kilohm. (For better calculations, construct a voltage divider to measure Rout by Thévenin's technique.)
If you want my recommendation, though, I would be inclined to leave the 200 μF alone, unless you just wish to experiment and do not mind the risk. Otherwise, @StainlessSteelRat is right: "Hard to see a manufacturer changing a design without correcting a known problem."
You say that your version of the board has a supposed fix, but isn't it more likely that the supposed fix is just a fix?


text:
Q: Download file and the user decides where to locate it I have this problem, I am looking for how to download an AWS Bucket file, but not download it on the client and decide where to save it, which is not working.
$S3Options =
[
    'version' => 'latest',
    'region' => 'us-east-1',
    'credentials' =>[
        'key' => 'xxxxxxx',
        'secret' => 'xxxxxxxx'
    ],
    'scheme' => 'http'
];

$s3 =  new Aws\S3\S3Client($S3Options);

$getFile = $s3->getObject(
    [
        'Key' => 'xxxx/'.$archivo[1],
        'Bucket' => 'xxxxxxx',

    ]);

$getFile = $getFile->toArray();
file_put_contents($archivo[1],$getFile['Body']);

A: First, file_put_contents would save the file to the server instead of the client. You need to directly display the content to client. The easiest way is echo:
echo $getFile['Body'];

To force the user download a file (instead of showing it on browser), you need to provide a header that a browser does not know how to handle directly.
$S3Options =  [
    'version' => 'latest',
    'region' => 'us-east-1',
    'credentials' =>[
        'key' => 'xxxxxxx',
        'secret' => 'xxxxxxxx'
    ],
    'scheme' => 'http',
];

$s3 = new Aws\S3\S3Client($S3Options);

$getFile = $s3->getObject([
    'Key' => 'xxxx/'.$archivo[1],
    'Bucket' => 'xxxxxxx',
]);

$getFile = $getFile->toArray();

// ** Add header call here **
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream'); // this is the most important line
header('Content-Transfer-Encoding: binary');
// ** header end **

echo $getFile['Body'];

Now the browser will know to download the file instead of showing, but it does not guarantee the browser would prompt user for the save location.
The download behaviour differs between browsers. And most browser also give user options for it to "save to default location without asking". If the user set their browser to save without asking, he would never get a dialog.


text:
Q: Python reserved keyword as argument does not work (although it should?) This code
def get_recent_tracks(username, fromuts):
    print(fromuts)
    recent_tracks = lastfm_network.get_user(username).get_recent_tracks(**{'from':fromuts})
    for i, track in enumerate(recent_tracks):
        printable = track_only(track)
        print(str(i + 1) + " " + printable)
    return recent_tracks

results in
get_recent_tracks() got an unexpected keyword argument 'from'

The print() function returns the correct result.
I learned several programming languages in my youth. Unfortunately, my youth being some 30 years ago, Python was not one of them. What I need is a working equivalent of
recent_tracks = lastfm_network.get_user(username).get_recent_tracks(from=fromuts)

For other params like limit=20 the code works just fine.

A: There's nothing strictly wrong with the format of your code.  That code will get around the problem of from being a Python keyword, and it is doing so. So you've gotten past that problem.  The problem now is more fundamental and has nothing to do with the fact that from is a keyword...
The problem is simply that the get_recent_tracks method does not accept a named parameter with the name from.  You'd expect this, because it would be hard for it to define such a parameter, and it wouldn't make sense for it to do so knowing that calling it with such a named parameter would be problematic.  Read the docs for the method and supply it with the correct parameters, and you won't have an issue.
UPDATE:  Collecting information from comments, the issue seems to be that the OP was assuming a one-to-one mapping between the names and existence of each of the parameters to the HTTP API call that underlies the get_recent_tracks Python method. Here are the docs for each of these APIs:

Python: https://hexdocs.pm/elixirfm/0.1.2/Elixirfm.User.html#get_recent_tracks/2

HTTP: https://last.fm/api/show/user.getRecentTracks

According to @Dierk, the OP, the equivalent parameter exists in the Python API and has the name time_from.  This isn't reflected in the documentation referenced above.  I notice that in that same documentation, there is the comment "start and end times not implemented yet" for another method in the API.  So maybe this documentation is outdated, and support for the "time" parameters has since been added to the API.


text:
Q: How to properly obtain value from an element type? I have the following HTML and TS code and I get the following error. I am trying to fix it but without any further progress. Could you please help me? I am new to TS and web-development.
Error:
Property 'value' does not exist on type 'Element'

// TS CODE
const elInput = document.querySelector(`#chat-form-input`)

// add onkeypress listener
document.onkeypress = function (e) {

    // use e.keyCode
    if (e.key === 'Enter') {
      // code for enter
      console.log(elInput)
      console.log(elInput.value) //error
    }
}

          <input type="text" placeholder="search"/>

        +

        <input id="chat-form-input" type="text" placeholder="Type a message!"/>


text:
Q: Дублируются значения при использовании нескольких JOIN (извлечение данных при нескольких связях многие ко многим) PostgreSQL Уже 3 вопрос по одному SQL запросу, но постоянно возникают новые проблемы =).
Входные данные: PostgreSQL. Есть 5 таблиц: products, colors, sizes, products_to_colors, products_to_sizes. Связь многие ко многим - каждый продукт может иметь несколько цветов и несколько размеров. Каждый цвет и размер может быть у нескольких продуктов. Связь между цветами, размерами и продуктами реализована с помощью 2 таблиц products_to_colors, products_to_sizes.
Поля в таблицах:

*

*products - id, name (остальные не имеют значение, упрощаем задачу =) )

*colors - id, color (в color указывается сам цвет, например, зелёный)

*colors - id, size (в size указывается сам размер, например, XL)

*products_to_colors - id, color_id, product_id

*products_to_colors - id, size_id, product_id
Мне нужно достать данные из этих таблиц и получить модели товаров. Пробовал использовать такой запрос:
SELECT
    products.*,
    string_agg(colors.color, ',') AS colors,
    string_agg(sizes.size, ',') AS sizes
FROM products
    LEFT JOIN products_to_colors ON products.id = products_to_colors.product_id
    LEFT JOIN colors ON colors.id = products_to_colors.color_id
    LEFT JOIN products_to_sizes ON products.id = products_to_sizes.product_id
    LEFT JOIN sizes ON sizes.id = products_to_sizes.size_id
GROUP BY products.id

В ответе от postgres значения sizes и colors продублированы, т.е.:
"id": 4,
"name": "test",
"colors": "белый,желтый,белый,желтый",
"sizes": "38,38,48,48"

Почему это происходит и как я могу это исправить?
P.S. Ещё есть таблицы images с картинками (связь многие к одному - 1 товар, несколько картинок.), и products_to_products (в ней сохраняются похожие продукты). Их тоже буду использовать в запросе, пробовал их тоже в запросе использовать, тогда значения выводятся по 4 раза, а не по 2

A: Вы умножаете между собой записи из products_to_colors и products_to_sizes, отсда и повторы. Делайте оба подзапросами примерно так:
(select string_agg(colors.color, ',')
 from products_to_colors
 JOIN colors ON colors.id = products_to_colors.color_id
 where products.id = products_to_colors.product_id) as colors


text:
Q: Why is "/public" still in the URL? I have a folder structure like this:
.cpanel/
public_html/
public_ftp/
..

and a laravel project inside the public_html directory like this:
app/
bootstrap/
public/
vendor/
composer.json
artisan
..

The problem was that when I entered the url like www.example.com, it would redirect to www.example.com/public.
I found a rewrite rule that allowed me to put in www.example.com and it would just show public/index.php without the "/public" part:
 RewriteEngine on
 RewriteCond %{HTTP_HOST} ^(www.)?example.com$
 RewriteCond %{REQUEST_URI} !^/subfolder/
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ /subfolder/$1
 RewriteCond %{HTTP_HOST} ^(www.)?example.com$
 RewriteRule ^(/)?$ subfolder/index.php [L]

It worked for the index page, but when I try to go to any of the routes, "/public" shows back up in the URL.
Why does this rewrite rule work for the index page and not for any of the routes?  What rewrite rule will work for all of the pages to remove "/public" from the URL?

A: In your local environment, rename public to public_html
Copy the project into the parent folder so that the laravel public folder is now the public_html
.cpanel/
app/
bootstrap/
vendor/
composer.json
artisan
public_html/
public_ftp/
..

DONT try to fudge it with .htaccess because you will leave your .env file exposed in your server root folder.  This is a big security issue if you do.

A: This should work:

*

*Rename the server.php file in your Laravel root directory to index.php

*Copy the .htaccess file from your /public directory to your Laravel root directory.


text:
Q: Unable to load any webpages I have trouble using the Internet using Wifi on my Windows 8 laptop.
It first happened about 2 days ago, everything was fine in the morning, but I was unable to connect to any webpages in the evening. There was the yellow error triangle icon over my wifi icon in the task tray, and it says "No Internet Access". I tried connecting directly to my router using a LAN cable, but still no Internet access. I thought it might be my NordVPN, and I uninstalled the NordVPN TAP, closed the NordVPN program, restarted the PC, and was able to connect to the Internet again.
Today, I was initially able to use the Internet (the pages loaded slower than usual, but they eventually loaded). However, after about an hour, I suddenly could not load any pages anymore. My Wifi is still connected to the Internet, but I couldn't access any websites.
The things I tried were

*

*Uninstall another program called "Tap for NordVPN". Not sure why there were 2 TAP programs, but this one has a different icon. It was
an orange icon instead of NordVPN's blue icon.

*Uninstall the last few things I installed - Oracle VirtualBox, Npcap.

*I tried to uninstall Wireshark, but couldn't because dumpcap.exe was still in use. I couldn't kill dumpcap.exe using wmic, taskkill or PowerShell's kill, getting either the errors Access is denied or No running instance.

*I tried to uninstall NordVPN (though this has been running for a couple of years now), but the window stayed at "Loading" for a long time after I clicked "Uninstall" from the Control Panel.

*Remove NordVPN from startup list

*After each one, I would restart the laptop.

At this point, I can ping 8.8.8.8, but if I ping www.google.com, there is no response, no error message, just nothing. After some googling, I though it might have to do with my DNS client, as ipconfig /displaydns, ipconfig /flushdns and ipconfig /registerdns would return errors. The service was indeed disabled, so I restarted it, and ran the 3 dns commands, which were successful this time.
Still, I couldn't load any webpages, so I renewed my DHCP lease, and ran the 3 dns commands again. Still nothing. I can ping and even tracert 8.8.8.8, but not dns.google. I can also connect to my tablet using Airdroid using its IP address. I don't know what else I can try.
BTW, a few days before all of this, I had to reboot my laptop a couple of times after DPC_WATCHDOG_VIOLATION errors, suddenly when I was browsing some webpages. Not sure if that's related.


text:
Q: Mockserver expectation not active Context is a Junit test, setup with Spring-boot, Mockserver and Camel.
Problem is that mocked response of the verified request is not matched during the test.
The logs :
INFO 1841843 --- [erver-EventLog4] org.mockserver.log.MockServerEventLog    : 8087 received request:

  {
    "method" : "GET",
    "path" : "/api/installation/organizations",
    "headers" : {
      "content-length" : [ "0" ],
      "User-Agent" : [ "Java/11.0.13" ],
      "Host" : [ "localhost:8087" ],
      "Connection" : [ "keep-alive" ],
      "Accept" : [ "application/json" ]
    },
    "keepAlive" : true,
    "secure" : false
  }

INFO 1841843 --- [erver-EventLog4] org.mockserver.log.MockServerEventLog    : 8087 no expectation for:

  {
    "method" : "GET",
    "path" : "/api/installation/organizations",
    "headers" : {
      "content-length" : [ "0" ],
      "User-Agent" : [ "Java/11.0.13" ],
      "Host" : [ "localhost:8087" ],
      "Connection" : [ "keep-alive" ],
      "Accept" : [ "application/json" ]
    },
    "keepAlive" : true,
    "secure" : false
  }

 returning response:

  {
    "statusCode" : 404,
    "reasonPhrase" : "Not Found"
  }

INFO 1841843 --- [           main] b.h.c.route.CsvRouteBuilderTest          : Started CsvRouteBuilderTest in 6.17 seconds (JVM running for 8.32)
INFO 1841843 --- [erver-EventLog4] org.mockserver.log.MockServerEventLog    : retrieved requests and responses in json that match:

  { }

DEBUG 1841843 --- [           main] b.h.c.route.CsvRouteBuilderTest          : RecordedRequestsAndResponses: 12
INFO 1841843 --- [erver-EventLog4] org.mockserver.log.MockServerEventLog    : 8087 retrieved 0 active expectations in json that match:

  { }

DEBUG 1841843 --- [           main] b.h.c.route.CsvRouteBuilderTest          : activeExpectations: 0
INFO 1841843 --- [erver-EventLog4] org.mockserver.log.MockServerEventLog    : retrieved recorded expectations in json that match:

  { }

DEBUG 1841843 --- [           main] b.h.c.route.CsvRouteBuilderTest          : recordedExpectations: 0
INFO 1841843 --- [erver-EventLog4] org.mockserver.log.MockServerEventLog    : 8087 verifying requests that match:

  {
    "httpRequest" : {
      "method" : "GET",
      "path" : "/api/installation/organizations"
    },
    "times" : {
      "atLeast" : 1
    }
  }

INFO 1841843 --- [erver-EventLog4] org.mockserver.log.MockServerEventLog    : request:

  {
    "method" : "GET",
    "path" : "/api/installation/organizations"
  }

 found at least once

And the code :
@ExtendWith(MockServerExtension.class)
@MockServerSettings(ports = {8087})
@SpringBootTest
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
@DisableJmx
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class CsvRouteBuilderTest {

    @Autowired
    ProducerTemplate producerTemplate;

    private MockServerClient mockServerClient;

    @BeforeEach
    public void beforeEachLifecyleMethod(MockServerClient client) {
        mockServerClient = client;
    }

    @Before
    public void setupMocks() {
        mockServerClient
            .when(
                request().withMethod("GET").withPath(HDConnectProxyRestTemplate.URI_GET_INSTALLATION_ORGANIZATIONS)
                    .withHeader(Header.header("Accept", MediaType.APPLICATION_JSON.toString())))
            .respond(
                response("{data}").withContentType(MediaType.APPLICATION_JSON));
    }

What did I miss ? I can see that both Camel and Mockserver are running at the moment of the test. But the mocked response should be triggered.

A: I found out that spring-boot's context is starting the Camel logic before the unit test itself.
So, at the test, the Camel route was already running, and the mock-server expectations were not available.
In order to properly test this situation, I needed to :

*

*First prevent the Camel route to start (for example with the Route.configure() method),

*Initialize the mocks and their expectations (@Before each test),

*Then, specifically enable the Camel route, during the Junit test.

A: As the MockServerExtension starts the mock server thanks to the BeforeAllCallback, another way could be to initialize the mocker server beforeAll as next:
@BeforeAll
static void setupMocks(MockServerClient mockServerClient) {
    mockServerClient
        .when(
            request().withMethod("GET").withPath(HDConnectProxyRestTemplate.URI_GET_INSTALLATION_ORGANIZATIONS)
                .withHeader(Header.header("Accept", MediaType.APPLICATION_JSON.toString())))
        .respond(
            response("{data}").withContentType(MediaType.APPLICATION_JSON));
}

This way your mock server will be configured before the start up of Camel.


text:
Q: Variable 'dateFormatter' used before being initialized in iOS Swift I am using NSDateFormatter in my project using Swift language.
I am getting following error:

Variable 'dateFormatter' used before being initialized

My code:
var date : NSDate = (NSDate.date())

var dateFormatter : NSDateFormatter

dateFormatter.dateFormat = "dd:mm:yyyy HH:mm:ss zzz"

A: Change just one line.
You not initialise the NSDateFormatter
change below line:
var dateFormatter : NSDateFormatter = NSDateFormatter()

Complete code:
var date : NSDate = (NSDate.date())

var dateFormatter : NSDateFormatter = NSDateFormatter()

dateFormatter.dateFormat = "dd:mm:yyyy HH:mm:ss zzz"

A: First you need to initialise, then you won't get error.
In Swift, initilization completes with ().
var dateFormatter = NSDateFormatter()

A: New usage would be:
        let date = Date()
        let formatter = DateFormatter()
        formatter.dateFormat = "MM.dd.yy" // or whatever format
        let dateStr = formatter.string(from: date)


text:
Q: Received :org.springframework.transaction.CannotCreateTransactionException I am making a JPA application in eclipse.I have designed the service layer with spring.I have
used "HibernatePersistence" as persistence provider.
Below is my persistence layer:
    @MappedSuperclass
    public class BaseEntity implements Serializable{

    /**
     *
     */
    @Transient
    private static final long serialVersionUID = -2265881632984808864L;

   @Id
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   @Column(name="ID",nullable=false,updatable=false)
   private Long id;
   /**
   * @return the id
   */
   public Long getId() {
    return id;
    }
   /**
    * @param id the id to set
   */
   public void setId(Long id) {
    this.id = id;
  }
 }

package com.edfx.jpapp.persist.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;

@Entity
@Table(name = "Customer", schema = "customerdb")
public class Customer extends BaseEntity {

/**
 *
 */
@Transient
private static final long serialVersionUID = 1443119926544372161L;

@Column(name = "CUSTOMER_NAME", nullable = false, length = 30)
private String customerName;
@Column(name = "CUSTOMER_ADDRESS", nullable = false, length = 25)
private String customerAddress;

/**
 * @return the customerName
 */
public String getCustomerName() {
    return customerName;
}

/**
 * @param customerName
 *            the customerName to set
 */
public void setCustomerName(String customerName) {
    this.customerName = customerName;
}

/**
 * @return the customerAddress
 */
public String getCustomerAddress() {
    return customerAddress;
}

/**
 * @param customerAddress
 *            the customerAddress to set
 */
public void setCustomerAddress(String customerAddress) {
    this.customerAddress = customerAddress;
}

/**
 * @return the serialversionuid
 */
public static long getSerialversionuid() {
    return serialVersionUID;
}
  }

here is my DAO layer
package com.edfx.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.edfx.jpapp.dao.CustomerDAO;
import com.edfx.jpapp.persist.entity.Customer;

public class CustomerDAOImpl implements CustomerDAO {

 @PersistenceContext(unitName="customerUnit")
  private EntityManager entityManager;

/**
 * @return the entityManager
 */
  public EntityManager getEntityManager() {
    return entityManager;
  }

/**
 * @param entityManager
 *            the entityManager to set
  */
  public void setEntityManager(EntityManager entityManager) {
    this.entityManager = entityManager;
  }

  @Override
  public void insertCustomer(Customer customer) {
    entityManager.persist(customer);
   }

   @Override
   public List<Customer> getAllCustomer() {

    return entityManager.createQuery("select c from customer c",
            Customer.class).getResultList();
    }
    }

 here is the service layer

package com.edfx.jpapp.service.impl;

import java.util.ArrayList;
import java.util.List;
import org.dozer.Mapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.edfx.jpapp.dto.CustomerDTO;
import com.edfx.jpapp.persist.entity.Customer;
import com.edfx.jpapp.service.CustomerService;
import com.edfx.jpapp.service.base.BaseService;

 @Transactional
 public class CustomerServiceImpl extends BaseService implements CustomerService {

@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
@Override
public void insertCustomer(CustomerDTO customerDTO) {
    Customer customer = getBeanMapper().map(customerDTO, Customer.class);
    getDaoProvider().getCustomerDAO().insertCustomer(customer);
}

@Transactional(readOnly = true)
@Override
public List<CustomerDTO> getAllCustomer() {
    Mapper mapper = getBeanMapper();
    ArrayList<CustomerDTO> customerDTOs = new ArrayList<CustomerDTO>();
    List<Customer> customers = getDaoProvider().getCustomerDAO()
            .getAllCustomer();
    for (Customer customer : customers) {
        CustomerDTO customerDTO = mapper.map(customer, CustomerDTO.class);
        customerDTOs.add(customerDTO);
    }
    return customerDTOs;
}
 }

I have placed my persistence.xml file under META-INF Folder: and it is as follows
   <?xml version="1.0" encoding="UTF-8"?>
   <persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
 <persistence-unit name="customerUnit"
    transaction-type="JTA">
     <provider>org.hibernate.ejb.HibernatePersistence</provider>
     <jta-data-source>java:/jBossCustomerMysql</jta-data-source>
     <class>com.edfx.jpapp.persist.entity.Customer</class>
     <validation-mode>NONE</validation-mode>
     <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
        <property name="hibernate.hbm2ddl.auto" value="update"/>
     </properties>
 </persistence-unit>

I have used JTA DataSource and I have configured the JNDI in jboss standalone.xml file
  as follows:
         <datasource jta="true" jndi-name="java:/jBossCustomerMysql" pool-name="jBossCustomerMysql" enabled="true" use-ccm="false">
                <connection-url>jdbc:mysql://localhost:3306/customerdb</connection-url>
                <driver-class>com.mysql.jdbc.Driver</driver-class>
                <driver>mysql</driver>
                <security>
                    <user-name>root</user-name>
                    <password>root</password>
                </security>
                <validation>
                    <validate-on-match>false</validate-on-match>
                    <background-validation>false</background-validation>
                </validation>
                <statement>
                    <share-prepared-statements>false</share-prepared-statements>
                </statement>
            </datasource>

well when I ran the application my Tables got created in database.But when I try to insert a customer from xhtml page then I got the exception::
13:52:37,227 SEVERE [javax.faces.event] (http-localhost-127.0.0.1-8087-2) Received 'org.springframework.transaction.CannotCreateTransactionException' when invoking action  listener '#{customerController.addCustomer}' for component 'j_idt9'
13:52:37,227 SEVERE [javax.faces.event] (http-localhost-127.0.0.1-8087-2) org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.NullPointerException
 at  org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:427)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:329)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy22.insertCustomer(Unknown Source)
at com.edfx.jpapp.web.controller.CustomerController.addCustomer(CustomerController.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.el.parser.AstValue.invoke(AstValue.java:262)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:148)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:769)

Below is my spring configuration file:
 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="customerUnit" />
    <property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
    <property name="packagesToScan" value="com.edfx.jpapp.persist.entity" />
  </bean>
</beans>

anther one is transactionConfig.xml file:
 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

 <bean id="transactionInterceptor" abstract="true"
     class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <property name="transactionManager" ref="transactionManager" />
    <property name="transactionAttributeSource">
    <bean           class="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource" />
      </property>
      </bean>

     <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
       <property name="entityManagerFactory" ref="entityManagerFactory" />
     </bean>
  </beans>

can anyone give any solution to this??????

A: I have found the solution.I need to add the following piece of code to my persistence.xml file.
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform"/>


text:
Q: Методы уже определены в *.obj + интерфейс Нужно было реализовать интерфейс используя только элементы модульного программирования
Ошибка что метод уже определен в другом объекте
//main cpp
#include "Container.h"
using namespace std;
int main()
{
    setlocale(LC_ALL, "RUS");
    typedef void* Cont;
    Cont l = cont_allocate();
    Cont A = cont_allocate();
    //cont_add(l, (void*)1);

    system("pause");
}

//container.h
#pragma once
#include <iostream>
using namespace std;

typedef void(*cont_handle)(void* data);
void* cont_allocate();          // Создает пустой контейнер
void  cont_release(void* cont); // Удаляет контейнер
void  cont_add(void* cont, void* data); // Добавляет элемент в  конец контейнера
void  cont_insert(void* cont, int pos, void* data); // Вставляет элемент в позицию pos
int   cont_size(void* cont);    // Возвращает размер контейнера
void* cont_get(void* cont, int pos);    // Возвращает данные в позиции pos
void* cont_replace(void* cont, int pos, void* data);    // Заменяет данные в    позиции pos.  Возвращает старые данные.
void* cont_remove(void* cont, int pos); // Удаляет данные из позиции pos. Возвращает удаленные данные.
void  cont_foreach(void* cont, cont_handle proc);   // Перебирает все элементы контейнера по порядку.
void  cont_foreach_reverse(void* cont, cont_handle proc);   //Перебирает все элементы контейнера в обратном порядке.

//ListArray.cpp
struct list
{
    int field; // поле данных
    list *next; // указатель на следующий элемент
    list *prev; // указатель на предыдущий элемент

};

void* cont_allocate()
{
    setlocale(LC_ALL, "RUS");
    list *lst;
    // выделение памяти под корень списка
    lst = (list*)malloc(sizeof(list));
    lst->next = NULL; // указатель на следующий узел
    lst->prev = NULL;
    std::cout << "dq";
    return lst;
}

//DinamicArray.cpp
#include "Container.h"

struct Darray
{
public:
    int size; // поле данных
    void* arr;
};

void* cont_allocate()
{
    Darray *drr;
    setlocale(LC_ALL, "RUS");
    drr = (Darray*)malloc(sizeof(Darray*));
    cout << "da";
    return drr;
}

A: У вас нарушено ODR (правило одного определения), присутствуют две реализации функции со следующей сигнатурой void* cont_allocate(); у которой внешнее связывание, чтобы сделать связывание для функции внутренним (то есть чтобы видимость была в пределе одной единицы трансляции) можно поместить функцию в анонимный namespace или сделать её static.
для определения в пределах одной единицы трансляции:

*

*с анонимным namespace:
namespace
{
  void* cont_allocate()
  {
  }
}

*static
static void* cont_allocate()
{
}

если хотите функции с одинаковыми сигнатурами, но чтобы было внешнее связывание можно поместить их в разные неанонимные пространства имён


text:
Q: what is the mysql host name in 1freehosting I know this is a noob question.But i could not figure out the solution by any means so i am posting it here.
I have been learning php and mysql using my local machine and xampp.Now i have decided to put my works online. .So i choose one of the free hosting services like 1freehosting.I have created a mysql user like the following :
username : u377815502_root,
database : u377815502_login,
password : ********

To connect to my mysql on the webhost, i provide the following information to my php pdo connection.
'mysql'=>array('host'=>'localhost',
                       'username'=>'u377815502_root',
                       'password'=>'********',
                       'db'=>'u377815502_login'
                       ),

my question is am i doing it right?should i keep 'host' as 'localhost'? i am not sure!
when i try to visit my site i am getting the following error :

SQLSTATE[28000] [1045] Access denied for user
  'u377815502_root'@'localhost' (using password: YES)

A: i created my own account on the host you mentioned and the host name is "mysql.1freehosting.com" without quotes obviously !! enjoy :D


text:
Q: Error in Shipping Magento I am facing error Sorry, no quotes are available for this order at this time.I am using Webshopapps Matrix extension for shipping and import the shipping charges through csv(see below image of csv).For simple i have weights like (5000,0.5000).Can someone tell me why i got this error.Thanks in advance

A: There could be a number of reasons. Firstly, there is no value for the "Delivery Type", so you need to fill this out, i.e. "Standard Delivery", "Next Day Delivery" or whatever.
Could you then also tell us about the product. What is it's weight? From memory, if the weight is 0, it will be ignored.
If you have more than one store, you will need to upload the csv to each store too.


text:
Q: Qt-Creator doesn't create a .pro file
I want to connect Qt with Sqlite. Everyone on YouTube says that we need to type QT += core gui sql inside of .pro file, but the problem is that after I created a Qt Widget Application I haven't found the .pro file. Probably the problem is connected with using CMake, but I cannot change to qmake, because our lecturer told us to use CMake in our coursework. I wish the problem is not that hard, and beautiful community is able to help me.

A: Since you created a CMake-based project, the corresponding project file is called CMakeLists.txt, not a .pro file.
The corresponding command to QT += sql for linking against the Qt Sql module, is find_package(Qt5 COMPONENTS Sql REQUIRED) for CMake projects.
See also the Get Started with CMake documentation from the Qt documentation.


text:
Q: is there a way to introduce cost for one class in h2o.glm in R? I am using h2o.glm to carry out a prediction. The model requirement is as many true positives as possible at the cost of many false positives.
In terms of accuracy or (AUC) the result of h2o.glm is pretty good, however, due to the requirements, I need to play with the cost matrix. C5.0 has a way to introduce cost matrix, for example.
I read the documentation
https://www.rdocumentation.org/packages/h2o/versions/3.8.1.3/topics/h2o.glm
and checked many other resources and did not come across with a solution.
Perhaps some of you tried it. I would appreciate a hint.


text:
Q: --disable -shared in gcc compiler I am new to this site.The compiler i have using is --disable -shared.but i need to create .so file.while creating .so file i am getting this error
error: no memory region specified for loadable section
How should i overcome this error.
root@coinel-PC:/home/coinel/Desktop/linux-cortexm-1.10.0# arm-uclinuxeabi-gcc -v
Using built-in specs.
Target: arm-uclinuxeabi
Configured with: /scratch/julian/2010q1-release-uclinux-lite/src/gcc-4.4-2010q1/configure --build=i686-pc-linux-gnu --host=i686-pc-linux-gnu --target=arm-uclinuxeabi --enable-threads --disable-libmudflap --disable-libssp --disable-libstdcxx-pch --enable-extra-sgxxlite-multilibs --with-gnu-as --with-gnu-ld --with-specs='%{O2:%{!fno-remove-local-statics: -fremove-local-statics}} %{O*:%{O|O0|O1|O2|Os:;:%{!fno-remove-local-statics: -fremove-local-statics}}}' --enable-languages=c,c++ --disable-shared --disable-lto --with-pkgversion='Sourcery G++ Lite 2010q1-189' --with-bugurl=https://support.codesourcery.com/GNUToolchain/ --disable-nls --prefix=/opt/codesourcery --with-sysroot=/opt/codesourcery/arm-uclinuxeabi/libc --with-build-sysroot=/scratch/julian/2010q1-release-uclinux-lite/install/arm-uclinuxeabi/libc --with-gmp=/scratch/julian/2010q1-release-uclinux-lite/obj/host-libs-2010q1-189-arm-uclinuxeabi-i686-pc-linux-gnu/usr --with-mpfr=/scratch/julian/2010q1-release-uclinux-lite/obj/host-libs-2010q1-189-arm-uclinuxeabi-i686-pc-linux-gnu/usr --with-ppl=/scratch/julian/2010q1-release-uclinux-lite/obj/host-libs-2010q1-189-arm-uclinuxeabi-i686-pc-linux-gnu/usr --with-host-libstdcxx='-static-libgcc -Wl,-Bstatic,-lstdc++,-Bdynamic -lm' --with-cloog=/scratch/julian/2010q1-release-uclinux-lite/obj/host-libs-2010q1-189-arm-uclinuxeabi-i686-pc-linux-gnu/usr --disable-libgomp --enable-poison-system-directories --with-build-time-tools=/scratch/julian/2010q1-release-uclinux-lite/install/arm-uclinuxeabi/bin --with-build-time-tools=/scratch/julian/2010q1-release-uclinux-lite/install/arm-uclinuxeabi/bin
Thread model: single
gcc version 4.4.1 (Sourcery G++ Lite 2010q1-189)
root@coinel-PC:/home/coinel/Desktop/linux-cortexm-1.10.0#

A: Build the compiler from source with -enable-shared. – bmargulies


text:
Q: Django - How to filter children of a nested queryset? I have this model called Menu which has a many-to-many relationship with another model called category. Both this models have a field called is_active which indicates that menu or category is available or not.
Alright, then I have an api called RestaurantMenus, which returns all active menus for a restaurant with their categories extended, the response is something like this:
Menu 1
     Category 1
     Category 2
Menu 2
     Category 3
Menu 3
     Category 4
     Category 5
     Category 6

Now what I try to achieve is to only seriliaze those menus and categories which are active (is_active = True). To filter active menus is simple but to filter its children is what I'm struggling with.
My Models:
class Category(models.Model):
    menu = models.ForeignKey(Menu, related_name='categories', on_delete=models.CASCADE)
    name = models.CharField(max_length=200)

class Menu(models.Model):
    name = models.CharField(max_length=200)

My Serializers:
class CategorySerializer(serializers.ModelSerializer):

    class Meta:
        model = Category
        fields = "__all__"

class MenuSerializer(serializers.ModelSerializer):
    categories = CategorySerializer(many=True, read_only=True)

    class Meta:
        model = Menu
        fields = "__all__"

P.S. Category model itself has a many-to-many relationship with another model Called Item, which has an is_active field too. I want the same effect for those too but I cut it from the question cause I think the process should be the same. So actually the api response is something like this:
Menu 1
     Category 1
          Item 1
          Item 2
          Item 3
     Category 2
          Item 4

A: Using a SerializerMethodField is pretty straightforward.
You can filter inside get_< attribute >, you serialize the queryset and return the data from this serialized queryset.
class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = "__all__"

class MenuSerializer(serializers.ModelSerializer):
    categories = serializers.SerializerMethodField('get_categories')

    def get_categories(self, menu):
        qs = Category.objects.filter(menu=menu, is_active=True)
        serializer = CategorySerializer(qs, many=True)
        return serializer.data

    class Meta:
        model = Menu
        fields = "__all__"

If you have a third nested class, you can just apply the same simple logic to CategorySerializer using a get_items and ItemSerializer.
This approach lets you filter Menu objects to check is_active = True on your views.py since this is business logic.

A: I assume you define your models like this
Menu
    is_active
    categories: ManyToManyField (related_name='menus')

Category
    is_active
    items: ManyToManyField (related_name='categories')

Item
    is_active

E.g.
def get_categories():
    active_category_qs = Category.objects.filter(is_active=True)
    active_menu_qs = Menu.objects.filter(is_active=True,
    categories__in=active_category_qs)
    categories = []

    for menu in active_menu_qs.iterator():
        for category in menu.categories.all():
            if category.id not in [
                    obj_target["id"] for obj_target in categories
            ]:
                category_data = CategorySerializer(category).data # just get the data of category object
                categories.append(category_data)
    return categories

A: You can try like this using list_serializer_class:
class FilterActiveListSerializer(serializers.ListSerializer):
    def to_representation(self, data):
        data = data.filter(is_active=True)
        return super(FilterActiveListSerializer, self).to_representation(data)

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        list_serializer_class = FilterActiveListSerializer

class CategorySerializer(serializers.ModelSerializer):
    items = ItemSerializer(many=True, read_only=True)
    class Meta:
        model = Category
        list_serializer_class = FilterActiveListSerializer

class MenuSerializer(serializers.ModelSerializer):
    categories = CategorySerializer(many=True, read_only=True)
    class Meta:
        model = Menu

A: try this:
class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model  = Category
        fields = "__all__"

class MenuSerializer(serializers.ModelSerializer):
    category     = SerializerMethodField()

    def get_category(self,instance):
        qs = Category.objects.filter(menu__id=instance.id)
        data = CategorySerializer(qs,many=True).data
        return data

    class Meta:
        model  = Menu
        fields = "__all__"

A: Here you can use Django Prefetch objects. This lets you define queryset to choose the set objects from.
So, you would write your Menu retrieval query something like this:
from django.db.models import Prefetch

menus = Menu.objects.filter(is_active=True).prefetch_related(Prefetch('categories', queryset=Category.objects.filter(is_active=True)))

To add category items as well to the result set, use the following query:
menus = Menu.objects.filter(is_active=True).prefetch_related(Prefetch('categories', queryset=Category.objects.filter(is_active=True)), Prefetch('categories__items', queryset=Item.objects.filter(is_active=True))))

This should solve your problem.
Note: I have not tested the code so you might need to make some modifications.

A: item_instance = Item.objects.filter(is_active = True, category__is_active=True)

you will get all active items that have an active category using this.
fetch all items and create JSON data from them.
upvote if it helps


text:
Q: SQL Query where a field will be default 0, or 1 When the category is Null or equal to the most servere id for the group I have the following SQL Statement,
SELECT DISTINCT
    Mem.MemberID, Mem.LastName + ', ' + Mem.FirstName AS Name,
    MIN(MD.DiagnosisID) OVER(PARTITION BY  Mem.MemberID) AS 'Most Severe Diagnosis'
    ,MIN(Diag.DiagnosisDescription) OVER(PARTITION BY  Mem.MemberID) AS 'Most Severe Diagnosis Description'
    ,dc.DiagnosisCategoryID, dc.CategoryDescription, dc.CategoryScore,
    MIN(ISNULL(DC.DiagnosisCategoryID,1)) OVER(PARTITION BY  Mem.MemberID) AS 'Most Severe Category'
FROM
    Member AS Mem
LEFT OUTER JOIN
    MemberDiagnosis AS MD ON Mem.MemberID = MD.MemberID
LEFT OUTER JOIN
    Diagnosis AS Diag ON MD.DiagnosisID = Diag.DiagnosisID
LEFT OUTER JOIN
    DiagnosisCategoryMap AS Map ON Map.DiagnosisID = Diag.DiagnosisID
LEFT OUTER JOIN
    DiagnosisCategory AS DC ON DC.DiagnosisCategoryID = Map.DiagnosisCategoryID
ORDER BY Name

That returns the following table,
ID|NAME       |MOST SEVERE DIAG|DIAG DESCPTION |CatId|Cat DESC  |SCORE|Is Most Severe|
--+-----------+----------------+---------------+-----+----------+-----+--------------+
2 |Smith, Jack|NULL            |NULL           |NULL |NULL      |NULL |1             |
1 |Smith, John|2               |Test Diagnosis2|2    |Category B|20   |2             |
1 |Smith, John|2               |Test Diagnosis2|3    |Category C|30   |2             |
3 |Smyth, Will|3               |Test Diagnosis3|3    |Category C|30   |3             |
--+-----------+----------------+---------------+-----+----------+-----+--------------+

In Column 'Is Most Severe', how can I set it default to 0, or 1 if the CatId Is the most servere or null. So in the above table, the last column would have the data; 1 1 0 1.

A: Use a CASE expression:
SELECT DISTINCT
    Mem.MemberID,
    Mem.LastName + ', ' + Mem.FirstName AS Name,
    MIN(MD.DiagnosisID) OVER(PARTITION BY Mem.MemberID) AS 'Most Severe Diagnosis',
    MIN(Diag.DiagnosisDescription) OVER(PARTITION BY Mem.MemberID) AS 'Most Severe Diagnosis Description',
    dc.DiagnosisCategoryID,
    dc.CategoryDescription,
    dc.CategoryScore,
    CASE WHEN dc.DiagnosisCategoryID = MIN(MD.DiagnosisID) OVER(PARTITION BY Mem.MemberID) OR
        dc.DiagnosisCategoryID IS NULL
         THEN 1 ELSE 0 END AS 'Is Most Severe'
FROM
    Member AS Mem
LEFT OUTER JOIN
    MemberDiagnosis AS MD ON Mem.MemberID = MD.MemberID
LEFT OUTER JOIN
    Diagnosis AS Diag ON MD.DiagnosisID = Diag.DiagnosisID
LEFT OUTER JOIN
    DiagnosisCategoryMap AS Map ON Map.DiagnosisID = Diag.DiagnosisID
LEFT OUTER JOIN
    DiagnosisCategory AS DC ON DC.DiagnosisCategoryID = Map.DiagnosisCategoryID
ORDER BY
    Name;


text:
Q: Ngx-Datatable sorting by date column doesn't work I have the next code:
<ngx-datatable
 class="material"
 [rows]="rows"
 [columnMode]="'force'"
 [headerHeight]="50"
 [footerHeight]="50"
 [sorts]="[{prop: 'name', dir: 'desc'}]"
 [limit]="3">
 <ngx-datatable-column name="Name">
   <ng-template let-row="row" ngx-datatable-cell-template>
    {{row.name}}
    </ng-template>
  </ngx-datatable-column>
  <ngx-datatable-column name="Date">
    <ng-template let-row="row" ngx-datatable-cell-template>
       {{row.date}}
    </ng-template>
  </ngx-datatable-column>
</ngx-datatable>

I need sort by date format ("dd/mm/yyyy") and ("hh:mm:ss dd/mm/yyyy"). I understand that this table is just sorting by string format, but when I sort by date doesn't work correctly.
Someone kind who can help me. Maybe I have to create an specific sorting or comparation. How I should do it?
Thanks!

A: Ngx-tables can sort by date, but you need to specify that this is date,
Here is small chunk of code that handles Date sorting
if (a instanceof Date && b instanceof Date) {
    if (a < b) return -1;
    if (a > b) return 1;
}

taken from ngx-datatable repository.
You can try to put pipe on your date, so angular will do your work.
<ng-template let-row="row" ngx-datatable-cell-template>
   {{row.date | date}}
</ng-template>