text:
Q: How do I split split from specific character to specific character I have a file.txt with urls such as:
asd.com/abc.xyz?b=21
asd.com/abc.xyz?a=1&c=2
asd.com/abc.xyz?a=12&d=21
asd.com/abc.xy?b=21
asd.com/abc.xy?a=1&c=2
asd.com/abc.xy?a=12&d=21
I need a result like:
asd.com/abc.xyz?a=&b=&c=&d=
asd.com/abc.xy?a=&b=&c=&d=
As it can be seen i want each parameter of specific url to be linked to only one.
I have written a code to seperate by ? and remove everything after ? and then removed the duplicate but my code completely removes the a, b, c and d from the urls

lines_seen = set() # holds lines already seen
outfile = open("out.txt", "w")
actualout = open("output.txt", "w")

for line in open("txt", "r"):
    line = line.split("?", 1)[0]
    outfile.write(line+"\n")
outfile.close()

for line in open("out.txt", "r"):
    if line not in lines_seen: # not a duplicate
        actualout.write(line)
        lines_seen.add(line)

actualout.close()

A: *

*Split on ?

*Group by first part of the url

*Concatenate all second parts of the url for the same group

Sidenote: I strongly advise you to use with contexts to encapsulate calls to open().
from itertools import groupby
from operator import itemgetter

with open('txt', 'r'), open('output.txt', 'w') as in_file, out_file:
    for bareurl,g in groupby((line.split('?') for line in sorted(in_file)), itemgetter(0)):
        out_file.write( ''.join([bareurl,
                                 '?',
                                 '&'.join(spliturl[1] for spliturl in g),
                                 '\n'])
                      )

# OUTPUT:
# asd.com/abc.xy?a=1&c=2&a=12&d=21&b=21
# asd.com/abc.xyz?a=1&c=2&a=12&d=21&b=21

If you want to keep only the last value of each parameter, to avoid supplying more than one value per parameter in a url, you could build a dict mapping parameters to their values:
from itertools import groupby
from operator import itemgetter

with open('txt', 'r'), open('output.txt', 'w') as in_file, out_file:
    for bareurl,g in groupby((line.split('?') for line in sorted(in_file)), key=itemgetter(0)):
        d = dict(e.split('=') for spliturl in g for e in spliturl[1].split('&'))
        out_file.write( ''.join([bareurl,
                                 '?',
                                 '&'.join(f'{k}={v}' for k,v in d),
                                 '\n'])
                      )

# OUTPUT:
# asd.com/abc.xy?a=12&c=2&d=21&b=21
# asd.com/abc.xyz?a=12&c=2&d=21&b=21


text:
Q: Superfish menu arrow drop-down indicator for non-link item I am using Superfish in Joomla for my menu and I want to add a "text separator" menu item as the parent for list of drop-down items, so the separator item is not a link, but when hovered it shows the children items i.e.:

About

Mission

Staff

However, when I do this Superfish does not add the arrow image indicating that there are child items to the Separator.
The html that is output for a parent item that is a regular link is:

About
 »

Our Values

The html that is output for the parent item that is a text separator is:

Projects

About Our Projects

What is missing is the  ». I thought that maybe I could force it to apply to the parent text separator as well as the parent link menu item by modifying the default_separator.php file in the module's tmpl folder, but so far no luck.

redpajama_set_name: RedPajamaStackExchange


text:
Q: powershell script to get the status of failed jobs which are running in the application reading the json file from a odata query uri I need to have filtered data from a odata query formatted in json file, i wanted to use the powershell script to read out that json file and get the results of the failed status jobs
below is the example uri:
https://app.name.com//odata/ScheduledJobs?$format=json&$expand=Application($select=Id,Name,AssetId;$expand=Asset($select=Id,Name)),JobType,JobInstances($filter=StartTime+eq+null;$orderby=NextRunTime+asc;$top=1),CompletedJobs($orderby=StartTime+desc;$top=1;$expand=State;$select=Id,StateId,StartTime,EndTime)&$top=20&$orderby=ScheduleStart&$filter=Enabled+eq+true&$count=true

when I tried to use the powershell script as below to convert it to csv i get the following message, i do not know how to proceed further, please help me, i am a beginner at powershell scripting.
Get-Content -Path 'C:\Users\username\Downloads\ScheduledJobs1.json'
    ConvertFrom-Json |
    Select-Object -expand results |
    ConvertTo-Csv -NoTypeInformation |
    Set-Content 'C:\Users\username\Downloads\sai.csv'

please tell me how can I get results of the failed status jobs in the application and get that information in a tabular format...

A: I am not in a position to test this right now. But try using Export-csv instead of set-content.
Get-Content -Path 'C:\Users\username\Downloads\ScheduledJobs1.json'
    ConvertFrom-Json |
    Select-Object -expand results |
    Export-csv 'C:\Users\username\Downloads\sai.csv' -NoTypeInformation


text:
Q: Need help downloading a file using java in my app, it tries but quickly disappears I am trying to download a zip file and save it to the sdcard.
I have a button with the id "download"
When I click the button, the dialog shows up and quickly disapears.
Here's what the code section looks like.
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;

public void download(View view) {
    switch (view.getId()) {
        case R.id.download:
            startDownload();
    }
}

private void startDownload() {
    String url = "https://mydownloadurl";
    new DownloadFileAsync().execute(url);
}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading file..");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            return mProgressDialog;

        default:
            return null;
    }
}

class DownloadFileAsync extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected String doInBackground(String... aurl) {
        int count;
        try {
            URL url = new URL(aurl[0]);
            URLConnection conexion = url.openConnection();
            conexion.connect();
            int lenghtOfFile = conexion.getContentLength();
            Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream("/sdcard/mydownload.zip");
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress("" + (int)((total * 100) / lenghtOfFile));
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
        }
        catch (Exception e) {
        }
        return null;
    }

    protected void onProgressUpdate(String... progress) {
        Log.d("ANDRO_ASYNC",progress[0]);
        mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

And the only thing that shows in the logcat is

17586-17586/com.tyler.myapp D/qdmemalloc: ion: Mapped buffer base:0x6da9b000 size:1892352 offset:0 fd:47
  17586-17586/com.tyler.myapp D/qdmemalloc: ion: Mapped buffer base:0x4002a000 size:4096 offset:0 fd:52
  17586-17586/com.tyler.myapp D/OpenGLRenderer: Flushing caches (mode 0)
  17586-17586/com.tyler.myapp D/qdmemalloc: ion: Unmapping buffer  base:0x6da9b000 size:1892352
  17586-17586/com.tyler.myapp D/qdmemalloc: ion: Unmapping buffer  base:0x4002a000 size:4096
  596-5470/system_process W/InputMethodManagerService: Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@42942fe8 attribute=null, token = android.os.BinderProxy@41dab9b0, pid=17586, inputType=0x(null)

A: Your code is probably throwing an exception in doInBackground(). In your catch block you should log the exception so you can see what the problem is. You can do so like this:
Log.e("Downloader - doInBackground()", "Error while downloading", e);
Also, did you specify WRITE_EXTERNAL_STORAGE permission in your AndroidManifest.xml?


text:
Q: How do I stop the setInterval() function? How can I stop the interval using the same button I used to start the interval?
function slideShow() {
   'use strict';
    var pics = ['IMG_2135.jpg', 'IMG_2125.jpg', 'IMG_2119.jpg', 'IMG_2118.jpg'];
    var output = document.getElementById('output');
    output = pics[Math.floor(Math.random() * pics.length)];
    document.getElementById('image').src = output;
}
button.onclick = function () { setInterval(slideShow, 2000); }

A: var interval;
button.onclick = function () {
   interval = setInterval(slideShow, 2000); // assigned to a variable
}

You definitely need a variable to be assigned to the setInterval, which can be stopped using
clearInterval(interval);

How can I stop the interval using the same button I used to start the
  interval?

You do this by setting up a boolean check flag like
var isRecursiveOn = true;  // by default it will be true
var interval;
    button.onclick = function () {
       if  (isRecursionOn) {  // check the flag
            isRecursiveOn = false;
            interval = setInterval(slideShow, 2000); // assigned to a variable
       } else {
           clearInterval(interval);
           isRecursiveOn = true; //reset it
       }
    }


text:
Q: Not able to activate trigger send in sales cloud using cloud connect I have created a trigger send on the lead object using marketing cloud connect but when I am activating the trigger it is giving me alert,

Before activating a triggered send the appropriate Apex Trigger must be created for the following object: LEAD. Please refer to Marketing Cloud Help for more information.

For that, I have added a trigger,
if(Trigger.isAfter && Trigger.isInsert){
    et4ae5.triggerUtility.automate('Lead');
}

after this also I am still facing the same issue.

A: I had the same issue and it was really annoying to make it running.
It seems like the connector checks for the same naming convention which is provided in the documentation. My problem was, we have one trigger per sObject so the code was recognised in our trigger template.
At the end, I had to deploy a separate trigger only for that propose. Below is the is the code.
trigger Trig_Lead on Lead (after insert, after update)
{
    if (!Test.isRunningTest())
    {
        et4ae5.triggerUtility.automate('Lead');
    }
}

Also, the trigger needs to have a code coverage which also doesn't make sense when you by pass the deployment with a condition (!Test.isRunningTest()). But it was the only way and after the deployment I had to run the test class which then give me a code coverage of 50%. Finally, I was able to activate it.
Maybe the connector version might be important as well, my current version was (210.1.1)
Wish you good luck.
Best
Yoonsang


text:
Q: Android - How to use a search query result to populate a listview in a ListActivity I am trying to start a project but the first part requires me to figure out how to populate a listview using the results of a search query.  I was looking at the SearchManager in Android to create an intent to submit a search, but I could not find an example that showed how the results get returned and how to then do the other thing I need to do, to use the say first 10 results to populate a listview.  I know how to do the rest of what I want to do, but this first part has me stuck.

A: Look at this example : http://developer.android.com/guide/components/loaders.html#example
It uses a Loader when the text in the Search input changes. When the text changes, the loader is restarted with getLoaderManager().restartLoader(0, null, this); , and when the loader finishes searching, it updates the Adapter :
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    mAdapter.swapCursor(data);

Before that, we already set the adapter for the class, which is a ListFragment, so that the list in the screen is linked to the adapter and its content :
mAdapter = new SimpleCursorAdapter(getActivity(),
            android.R.layout.simple_list_item_2, null,
            new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },
            new int[] { android.R.id.text1, android.R.id.text2 }, 0);
setListAdapter(mAdapter);


text:
Q: ionic two tabs full width I have a view in Ionic with TABS that I want to make their content 50%+50% of the width of the screen, the current result is as follows (theres some margin on the sides):
http://play.ionic.io/app/e59562e15d95
In the view with three tabs, you can see that the tabs are indeed full width.:
http://play.ionic.io/app/637826dbec6c

A: Check this :http://play.ionic.io/app/35f4dc56d51e
Make a class
.full-width-tab{
  max-width:100% !important;
}

Add it to tabs item

    One

    Two


text:
Q: Which value should isControlling have in ice4j Agent? In all the ice4j examples (for example) the agent is set to setControlling(true) for one site and setControlling(false) for the other site.
Which value must I set if the other site is a browser? I can modify it only on the Java site in this case. Or is there an equivalent in JavaScript? Can I derive this from a SDP offer or answer? Depends this on the attribute a=setup:active and a=setup:passive?


text:
Q: Specify class of link_to in embedded ruby How would I specify the :class => "" here?:

<%= link_to "#" current_user  %>

TY

A:
<%= link_to "#", current_user, :class => "class-name"  %>

A: Check following,
 <%= link_to "Articles", articles_path, :id => "news", :class => "article" %>
   # => Articles

For more information, check:- http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to


text:
Q: SwiftUI + ScrollView not able to add views if it's exceed view height I am trying to show all the properties of the Text component in a single view. Showing Text with different styles and fonts. For that I am adding multiple Text components in a single view.
To make it possible I am using the ScrollView component and adding all Text components in it.
At some point, it won't allow me to add one more component in the scrollView and showing different errors each time.
Code:
struct TextClass: View {
    var body: some View {
        GeometryReader { geometry in
            ScrollView(.vertical, showsIndicators: false) {
                Text("This is suppose to be a really long text that can go on to multiple lines. By default, it could go more than one lines.").padding()

                Text("This is only one line regardless of how long the sentence is")
                    .padding()
                    .lineLimit(1)
                Text("Hello Swift - LargeTitle").font(.largeTitle).padding()
                Text("Hello Swift - Title").font(.title).padding()
                Text("Hello Swift - Headline").font(.headline).padding()
                Text("Hello Swift - SubHeadline").font(.subheadline).padding()
                Text("Hello Swift - body").font(.body).padding()
                Text("Hello Swift- callout").font(.callout).padding()
                Text("Hello Swift- Footnote").font(.footnote).padding()

                Text("Font Weight - Ultralight").fontWeight(.ultraLight).padding()
                Text("Font Weight - Thin").fontWeight(.thin).padding()
    //            Text("Font Weight - light").fontWeight(.light).padding()
    //            Text("Font Weight - Regular").fontWeight(.regular).padding()
            }.frame(width: geometry.size.width)
        }
    }
}

struct TextClass_Previews: PreviewProvider {
    static var previews: some View {
        TextClass()
    }
}

It shows error like:

If I comment line
Text("Font Weight - Thin").fontWeight(.thin).padding()

the error is gone.
It seems that it only allows me to add 10 Text component in this situation If I add more than that it gives me an error.
Is it a bug? is it a common behavior in SwiftUI? What is the benefit of scrollView if it won't allow adding more components?

A: You need to use Group as you can't have more than 10 elements inside a view
struct TextClass: View {
    var body: some View {
        GeometryReader { geometry in
            ScrollView(.vertical, showsIndicators: false) {
                    Group {
                            Text("This is suppose to be a really long text that can go on to multiple lines. By default, it could go more than one lines.").padding()
                            Text("This is only one line regardless of how long the sentence is")
                                .padding()
                                .lineLimit(1)
                            Text("Hello Swift - LargeTitle").font(.largeTitle).padding()
                            Text("Hello Swift - Title").font(.title).padding()
                            Text("Hello Swift - Headline").font(.headline).padding()
                            Text("Hello Swift - SubHeadline").font(.subheadline).padding()
                            Text("Hello Swift - body").font(.body).padding()
                    }
                    Group {
                            Text("Font Weight - Ultralight").fontWeight(.ultraLight).padding()
                            Text("Font Weight - Thin").fontWeight(.thin).padding()
                            Text("Font Weight - light").fontWeight(.light).padding()
                            Text("Font Weight - Regular").fontWeight(.regular).padding()
                    }
            }.frame(width: geometry.size.width)
        }
    }
}


text:
Q: Why does my menu close automatically when I just open it? When I want to open the menu in the mobile version, it then closes the menu automatically while it must remain open.
My site is on Bootstrap 4.4.1.
CSS and HTML code:

.navbar{
    background: #707071;
}

.navbar .navbar-collapse {
    text-align: center;
}

.navbar-nav.navbar-center {
    position: absolute;
    left: 50%;
    transform: translatex(-50%);
}
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="./css/style.css">

    <title>Home</title>

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

        </button>

                    WERK

                    OVER

                    CONTACT

I hope someone can help me out to resolve this problem! Thank you in advance!

A: check your js file make sure they are updated .. cdn linked with snippet
remove     position: absolute from navbar-nav and only add
.navbar-center {
    text-align: center;
}

in your css it will dispay you navigation in center .

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home (current)

        Link

        Disabled

A: Your    .navbar-nav.navbar-center class seems to be messing with it. Particularly the position: absolute style. Removing the custom definition of this class resolves the issue

.navbar{
    background: #707071;
}

.navbar .navbar-collapse {
    text-align: center;
}
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="./css/style.css">

    <title>Home</title>

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

        </button>

                    WERK

                    OVER

                    CONTACT


text:
Q: How to uniquely identify which PCB is plugged in / connected I am designing a board (Main PCB) into which any one of about 60 slightly different boards (Peripheral PCB) may be connected/plugged-in.
The challenge I'm facing is to autonomously identify which of the Peripheral boards is plugged in at any given time.

*

*The Main PCB has a microcontroller available to do some processing.

*However, to minimize part count, the Peripheral PCBs each have only a (unique) sensor, and no intelligence -- i.e., no microcontroller on board, e.g., to send information via digital pins or I2C -- as of now .

*Both boards are open to design changes, although the inter-connector pin count leaves me at the moment with only two more free pins available to use for any further modification.
What is the simplest, least expensive way (< $1 USD) I can modify the circuits to let the Main PCB identify which of the Peripheral PCBs is plugged in?
Will I have to add a microcontroller to each Peripheral PCB, or is there a smarter way?
ADC reading of a unique voltage divider on each Peripheral board seemed like a good start but for such a large number of different boards to be identified, this does not seem like a very reliable strategy.

A: You could use two resistors with a common to ground to give group and number within the group. 10 x 10 should be no problem with fractional-cent 1% resistors. I wouldn't bother with dividers- put the other resistor on the board doing the reading.
Another option would be an I2C EEPROM. That would use your two pins, no worries about voltage drop to the ground, and could be easily reprogrammed if you need to re-jig a board to be another variant. A 24C01 1K bit EEPROM costs about 20 cents in small quantity, so it's not extravagant, and you could accommodate serial numbers and batch numbers, production date as well as board identification, if so desired.

A: The tiny 6-pin microcontrollers are very inexpensive (e.g., PIC10F200 is $0.40 to $0.50, depending on quantity), and would provide the most flexibility. You could identify the peripheral type as well as give each one a unique serial number. This would require power, ground, and at least one contact for communication.
You could also go with something like the Maxim DS2401 1-Wire Silicon Serial Number ($0.50 to $0.60 in quantity). This would only require one contact plus ground.
The cheapest I2C EEPROMs are on the order of $0.20 in quantity. These would require power, ground and 2 contacts for communication.

A: Two free pins gives you two voltage dividers. For 60 boards you need 8 voltages each. Even the crappiest ADC in the world is capable of more than 3 bits.


text:
Q: Is it possible to parse Queries in MongoDB to get more specific results? I want to get time greater than 2:00 and less than 8:00 in my mongoDb. However, my data looks like this:
{"time": "4:35"}
The colon prevents me from making queries like "db.collection.find( { time: { $gt: 2, $lt: 8 } } )" Is there some way to query this? (Perhaps parse 4:35 into 435 without changing the inner data)

A: if you just wanted to search for the time between 2 and 8 then you could probably try this:
db.collection.find( { time: { $gt: "2:00", $lt: "8:00" } } )

This is what i have done to test this. I have inserted few data to the collections and here is the the list:

db.time.find({},{"_id":0})
  { "mytime" : "4:35" }
  { "mytime" : "1:35" }
  { "mytime" : "6:35" }
  { "mytime" : "8:35" }
  { "mytime" : "10:35" }
  { "mytime" : "10:10" }

db.time.find( { mytime: { $gt: "2:00", $lt: "8:00" } }, {"_id":0} )
    { "mytime" : "4:35" }
    { "mytime" : "6:35" }

A: Storing times as strings is a bad idea. Unfortunately MongoDB has no dedicated time-only data type, but there are two alternatives which are not as bad as using strings:

*

*use a BSON Date. When storing the year, month and day would be counter-productive, set all these to the same value (the start of the epoch, Jan 1st 1970, would be an option).

*use an integer, and have it represent the number of minutes or seconds since midnight. Do the conversion on the application-layer.


text:
Q: Symfony2 > MappingException: Class ...\Entity\User does not exist I am trying to get my user authentication working from the database. I have followed the instruction from the cookbook and set up a user entity. My bundle is registered in appKernel and I have used the bundle before. The only thing that changed is the new Entity\User.php and the changes in security.yml. I am sure that this is something silly, but for the life of me I cannot figure out what I am doing wrong. When I execute cache:clear, I get the following:

When browsing to app_dev.php:

Extract from app\src\MyFreelancer\PortalBundle\Entity\User.php
<?php
namespace MyFreelancer\PortalBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
use JMS\Serializer\Annotation as Ser;
use Gedmo\Mapping\Annotation as Gedmo;

use Symfony\Component\Security\Core\User\Role;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;

/**
 * User
 *
 * @ORM\Entity
 * @ORM\Table(name="users")
 * @Ser\ExclusionPolicy("all")
 */
class User implements AdvancedUserInterface, \Serializable
{
    /**
    * @var integer
    *
    * @ORM\Column(name="id", type="integer")
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    * @Ser\Expose
    */
    private $id;
...

Extract from security.yml (which is causing the problem):
    providers:
    main:
        entity:
            class: MyFreelancer\PortalBundle\Entity\User,
            property: username

As you can see, the entity exists in the correct file structure, the namespace is defined in the entity file, the class is defined as an entity and the Bundle is registered. I do not know what I'm missing.

A: As per jperovic's comment, it was just a case of removing the ',' from security.yml. Really silly mistake that I just didn't pick up on.


text:
Q: F4 search add into smart table ui5 I have tried to configure F4 search filed into smart table in UI5. I could't achieve it.
How do I configure F4 search (smart field) in smart table SAP UI5

A: Actually F4 works in SmartFilterBar fields, check the sample here.
The Fiori word for F4 SearchHelp (SHLP) is: Value Help
You can provide a descriptor called annotation.xml in your UI to configure Value Helps. You can tell for each Entity Property an EntitySet, a collection to browse from when you want to select values.
In manifest.json you can assign annotation to model and tell the location of the annotation file:
"mainService": {
  "uri": <yourServiceUri>,
  "type": "OData",
  "settings": {
    "odataVersion": "2.0",
    "localUri": "localService/metadata.xml",
    "annotations": [
      "annotation0"
    ]
  }
},
"annotation0": {
  "type": "ODataAnnotation",
  "uri": "./annotation0.xml"
}


text:
Q: Pandas filter using multiple conditions and ignore entries that contain duplicates of substring I have a dataframe derived from a massive list of market tickers from a crypto exchange.
The list includes ALL combos yet I only need the tickers that are vs USD stablecoins.
The 1st 15 entries of the original dataframe...
           Asset            Price
0   1INCHBTC      0.00009650
1   1INCHBUSD     5.74340000
2   1INCHUSDT     5.74050000
3   AAVEBKRW      164167.00000000
4   AAVEBNB       0.77600000
5   AAVEBTC       0.00615200
6   AAVEBUSD      365.00200000
7   AAVEDOWNUSDT  2.02505200
8   AAVEETH       0.17212000
9   AAVEUPUSDT    81.89500000
10  AAVEUSDT      365.57600000
11  ACMBTC        0.00018420
12  ACMBUSD       10.91700000
13  ACMUSDT       10.89500000
14  ADAAUD        1.59600000

Now...there are many USD stablecoins, however not every ticker has a pair with one.
So I used the most popular ones in order to make sure every asset has at least one match.
df = df.loc[(df.Asset.str[-3:] == 'DAI')|
            (df.Asset.str[-4:] == 'USDT')|
            (df.Asset.str[-4:] == 'BUSD')|
            (df.Asset.str[-4:] == 'TUSD')]

The 1st 15 entries of the new but 'messy' dataframe...
           Asset         Price
0   1INCHBUSD     5.74340000
1   1INCHUSDT     5.74050000
2   AAVEBUSD      365.00200000
3   AAVEDOWNUSDT  2.02505200
4   AAVEUPUSDT    81.89500000
5   AAVEUSDT      365.57600000
6   ACMBUSD       10.91700000
7   ACMUSDT       10.89500000
8   ADABUSD       1.21439000
9   ADADOWNUSDT   3.46482700
10  ADATUSD       1.21284000
11  ADAUPUSDT     76.12900000
12  ADAUSDT       1.21394000
13  AERGOBUSD     0.43012000
14  AIONBUSD      0.07210000

How do i filter/merge entries in this dataframe so that it removes duplicates?
I also need the substring to be removed at the end, so I'm left with just the asset and the USD price.
It should look something like this...
           Asset         Price
0   1INCH         5.74340000
2   AAVE          365.00200000
3   AAVEDOWN      2.02505200
4   AAVEUP        81.89500000
6   ACM           10.91700000
8   ADA           1.21439000
9   ADADOWN       3.46482700
11  ADAUP         76.12900000
13  AERGO         0.43012000
14  AION          0.07210000

This is for a portfolio tracker.
Also if there is a better way to do this without the middle step I'm all ears.

A: According your expected output, you want to remove duplicates but keep first item:
df.Asset = df.Asset.str.replace(r"(DAI|USDT|BUSD|TUSD)$", "")
df = df.drop_duplicates(subset="Asset", keep="first")
print(df)

Prints:
       Asset       Price
0      1INCH    5.743400
2       AAVE  365.002000
3   AAVEDOWN    2.025052
4     AAVEUP   81.895000
6        ACM   10.917000
8        ADA    1.214390
9    ADADOWN    3.464827
11     ADAUP   76.129000
13     AERGO    0.430120
14      AION    0.072100

EDIT: To group and average:
df.Asset = df.Asset.str.replace(r"(DAI|USDT|BUSD|TUSD)$", "")
df = df.groupby("Asset")["Price"].mean().reset_index()
print(df)

Prints:
      Asset       Price
0     1INCH    5.741950
1      AAVE  365.289000
2  AAVEDOWN    2.025052
3    AAVEUP   81.895000
4       ACM   10.906000
5       ADA    1.213723
6   ADADOWN    3.464827
7     ADAUP   76.129000
8     AERGO    0.430120
9      AION    0.072100

A: Just do
con1 = df.Asset.str[-3:] == 'DAI'
con2 = df.Asset.str[-4:] == 'USDT'
con3 = df.Asset.str[-4:] == 'BUSD'
con4 = df.Asset.str[-4:] == 'TUSD'

df['new'] = np.select(['con1','con2','con3','con4'],
                      ['DAI','USDT','BUSD','TUSD'])
out = df[con1 | con2 | con3 | con4].groupby('new').head(1)

or
df[con1 | con2 | con3 | con4].drop_duplicates('new')


text:
Q: Video file time length in minute while uploading to server in Spring or J2EE I want to save time length of the video files having several extension(mp4, wav, flv etc) in to database while uploading to server when submitting the page. But I did not find the how to get the length of the uploading video? I tried this code but it only works for audio files.
      File f = new File(fileName);
      Bitstream m_bitstream = new Bitstream(inputStream);
      Header m_header = m_bitstream.readFrame();
      int mediaLength = (int)f.length();
      int nTotalMS = 0;
      if (mediaLength != AudioSystem.NOT_SPECIFIED) {
         nTotalMS = Math.round(m_header.total_ms(mediaLength));
      }

Can you please help me?

A: Please refere to this post for "wav" files
How to learn .wav duration in Java media frame work?
For mp3 files please refere to:
How do I get a mp3 file's total time in Java?
For mp4 please refer to:
Is there a Java API for mp4 files?


text:
Q: Inequality of expansion of $\| \ \ \|$ The following is from a proof of a paper
Distributed subgradient Methods for Multi-Agent Optimization, Nedic & Ozdaglar - Lemma 5

Note:  $y(k+1)=y(k)-\frac{\alpha}{m}\sum_{j=1}^md_j(k)$
The picture simply did the expansion of the following:
$\|y(k+1)-x\|^2=\|(\ \ y(k)-\frac{\alpha}{m}\sum_{j=1}^md_j(k)\ \ ) - x\|^2 = \|(y(k)-x) - \frac{\alpha}{m}\sum_{j=1}^md_j(k)\|^2$
No other specific assumption required.

My question is the last term of (24), it seems that the author did the following:

$\|\sum_{j=1}^md_j(k)\|^2\leq \sum_{j=1}^m\|d_j(k)\|^2$
I do not think this is correct. (This is not convex function type)

Recall:
$\|\|^2$ is a convex function, so  $\|\theta x + (1-\theta)y\|^2\leq \theta\|x\|^2+(1-\theta)\|y\|^2 = \|x\|^2+\|y\|^2$


text:
Q: Pandas can't read hdf5 file created with h5py I get pandas error when I try to read HDF5 format files that I have created with h5py. I wonder if I am just doing something wrong?
import h5py
import numpy as np
import pandas as pd
h5_file = h5py.File('test.h5', 'w')
h5_file.create_dataset('zeros', data=np.zeros(shape=(3, 5)), dtype='f')
h5_file.close()
pd_file = pd.read_hdf('test.h5', 'zeros')

gives an error:
TypeError: cannot create a storer if the object is not existing nor a value are passed
I tried to specify key set to '/zeros' (as I would do it with h5py when reading the file) with no luck.
If I use pandas.HDFStore to read it in, I get an empty store back:
store = pd.HDFStore('test.h5')
>>> store
<class 'pandas.io.pytables.HDFStore'>
File path: test.h5
Empty

I have no troubles reading just created file back with h5py:
h5_back = h5py.File('test.h5', 'r')
h5_back['/zeros']
<HDF5 dataset "zeros": shape (3, 5), type "<f4">

Using these versions:
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin

pd.__version__
'0.16.2'
h5py.__version__
'2.5.0'

Many thanks in advance,
Masha

A: I've worked a little on the pytables module in pandas.io and from what I know pandas interaction with HDF files is limited to specific structures that pandas understands.  To see what these look like, you can try
import pandas as pd
import numpy as np
pd.Series(np.zeros((3,5),dtype=np.float32).to_hdf('test.h5','test')

If you open 'test.h5' in HDFView, you will see a path /test with 4 items that are needed to recreate the DataFrame.

So I think your only option for reading in NumPy arrays is to read them in directly and then  convert these to Pandas objects.


text:
Q: trying to plot histogram on realtime basis with set of data from a sensor using txt file Trying to plot histogram from data provided by a sensor using txt file. The file has continuously running data, It should take the data from first line but it should exclude some values in the start of the data and plot the graph then move to the next line want to do this on realtime basis. Tried few things but didn't work. I get an error could not convert string to float: '27/12/2018-14:35:30'.
    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib
    with open('load.txt', 'r') as fx:
        for line in fx:
            counter = True
            line = line.split(',')
            for thing in line:
                if counter:
                    counter = False
                else:
                    print(thing)
    f= np.loadtxt('load.txt', delimiter=',', unpack= True)

    bins = [0,50,100,150,200]
    plt.hist(f, histtype = 'bar', bins = bins, rwidth=1, color='c')
    plt.xlabel('x values')
    plt.ylabel('y values')
    plt.title('OPC_N3 Histogram')
    #plt.legend()
    plt.show()

data: but it should exclude the initial values eg. in the first block of data it should take values from the first 0 and so on with the next blocks and plot histogram as the output one by one for each block of data
27/12/2018
14:35:30,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,29,27,114,1,8,95,231,137,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,0,4,60
27/12/2018-14:36:40,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,78,12,114,1,72,97,93,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,0,74,100
27/12/2018-14:37:51,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,78,12,114,1,172,97,156,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,0,223,60
27/12/2018-14:39:02,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,78,12,114,1,1,98,185,126,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,0,130,60
27/12/2018-14:40:13,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,78,12,114,1,48,98,234,125,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,0,197,182

A: Well As I can see, the problem with float is that you givenit a 1st thing, which should be ignored as I did in my code, the thing you might want to do is to use threading for your file, but in that case, you will be removing the line from 1st file and adding it to an a backup file, the best thing about threading is that it allows you to run it basicly nonstop and even errors should not be able to stop the program
Here is a similar problem as you have now Python multiprocess/multithreading to speed up file copying
P.S if you choose an answer, please mark question as answered , thank you :)

A: Add this line after the split
line=line.apply(lambda x: x[-1:])

Good luck man!


text:
Q: Temporal aberration. Shape of telescope mirror large enough that light transit time is significant Suppose a parabolic mirror of a telescope is large enough (or equivalently that the camera exposure time is short enough) that you need to take into account the transit time of the light signal from hitting the mirror to reaching the focal point.
What shape should the mirror be to have the same effect as a parabolic mirror that doesn't take into account light transit time ?
Added after comments:
Suppose you want to view surface details on an exoplanet with an array of space mirrors spanning millions or even billions of km, also redirecting photons towards a detector at a focal point. The property to preserve is photons from an event on the exoplanet arriving at the focal point at the same time.
If the transit time from hitting the mirror to reaching the focus is long enough then given that objects aren't ideal or at infinity, then any discrepancy at all in arrival times is magnified by the huge transit-time so if the object being viewed changes fast it can change significantly during the discrepancy.
In talking about shutter speed I was thinking about viewing an object whose properties change very quickly (say clouds moving on a giant exoplanet). If there is a discrepancy in the time it takes for photons leaving the object to reach the focal point and the object changes during that time then the image would be blurred (temporally aberrated).
As Ross Millikan points out distances to the focus point should be the same, so I was misunderstanding things, however looking at Wikipedia exact focus only exists for point sources otherwise there is coma aberration. The article also says there is something called bestform or aplantic lenses to minimise this, but you can't apply a lense to an array of mirrors spanning billions of km, so the original question stands but with a changed understanding.

A: As Willie Wong points out, this is not an issue for a parabolic mirror.  In fact, another way to think about optical focus is that it makes constructive interference at the image point.  This means that all light rays coming from the subject take the same travel time to reach the focus or else the interference wouldn't be constructive.
Note that shutter speed doesn't matter unless you are thinking about exposing different parts of the sensor at different times (like the old 35mm curtain cameras) and the subject is moving.  Focus is focus for any shutter speed.


text:
Q: PHP Define var = one or other (aka: $var=($a||$b);) Is there a way to define a php variable to be one or the other just like you would do var x = (y||z) in javascript?
Get the size of the screen, current web page and browser window.

var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

i'm sending a post variable and i want to store it for a later use in a session. What i want to accomplish is to set $x to the value of $_POST['x'], if any exist, then check and use $_SESSION['x'] if it exist and leave $x undefined if neither of them are set;
$x = ($_POST['x'] || $_SESSION['x');

According to http://php.net/manual/en/language.operators.logical.php

$a = 0 || 'avacado'; print "A: $a\n";
will print:
A: 1
in PHP -- as opposed to printing "A: avacado" as it would in a
  language like Perl or JavaScript.
This means you can't use the '||' operator to set a default value:
$a = $fruit || 'apple';
instead, you have to use the '?:' operator:
$a = ($fruit ? $fruit : 'apple');

so i had to go with an extra if encapsulating the ?: operation like so:
if($_POST['x'] || $_SESSION['x']){
  $x = ($_POST['x']?$_POST['x']:$_SESSION['x']);
}

or the equivalent also working:
if($_POST['x']){
  $x=$_POST['x'];
}elseif($_SESSION['x']){
  $x=$_SESSION['x'];
}

I didn't test theses but i presume they would work as well:
$x = ($_POST['x']?$_POST['x']:
       ($_SESSION['x']?$_SESSION['x']:null)
     );

for more variables i would go for a function (not tested):
function mvar(){
  foreach(func_get_args() as $v){
    if(isset($v)){
      return $v;
    }
  } return false;
}

$x=mvar($_POST['x'],$_SESSION['x']);

Any simple way to achieve the same in php?
EDIT for clarification: in the case we want to use many variables $x=($a||$b||$c||$d);

A: Yes you need to use simple ternary operator which you have used within your example along with some other functions of PHP like as of isset or empty functions of PHP. So your variable $x will be assigned values respectively
Example
$x = (!empty($_POST['x'])) ? $_POST['x'] : (!empty($_SESSION['x'])) ? $_SESSION['x'] : NULL;

So the above function depicts that if your $_POST['x'] is set than the value of
$x = $_POST['x'];

else it'll check for the next value of $_SESSION if its set then the value of $x will be
$x = $_SESSION['x'];

else the final value'll be
$x = null;// you can set your predefined value instead of null

$x = (!empty($a)) ? $a : (!empty($b)) ? $b : (!empty($c)) ? $c : (!empty($d)) ? $d : null;

If you need a function then you can simply achieve it as
$a = '';
$b = 'hello';
$c = '';
$d = 'post';

function getX(){
    $args = func_get_args();
    $counter = 1;
    return current(array_filter($args,function($c) use (&$counter){ if(!empty($c) && $counter++ == 1){return $c;} }));
}

$x = getX($a, $b, $c, $d);
echo $x;

A: A simpler approach is to create a function that can accept variables.
 public function getFirstValid(&...$params){
    foreach($params as $param){
        if (isset($param)){
            return $param;
        }
    }
    return null;
 }

and then to initialize a variable i would do...
var $x = getFirstValid($_POST["x"],$_SESSION["y"],$_POST["z");

the result will be that the var x will be assign the first variable that is set or is set to null if none of the variables pass are set.
explanation:
function getFirstValid accepts a variable number of variable pointers(&...) and loops through each checking if it is set, the first variable encountered that is set will be returned.

A: Update
I've managed to create a function for you that achieves exactly what you desire, allowing infinite arguements being supplied and fetching as you desire:
function _vars() {
    $args = func_get_args();
    // loop through until we find one that isn't empty
    foreach($args as &$item) {
        // if empty
        if(empty($item)) {
            // remove the item from the array
            unset($item);
        } else {
            // return the first found item that exists
            return $item;
        }
    }
    // return false if nothing found
    return false;
}

To understand the function above, simply read the comments above.
Usage:
$a = _vars($_POST['x'], $_SESSION['x']);

And here is your:
Example

It is a very simply ternary operation. You simply need to check the post first and then check the session after:
$a = (isset($_POST['x']) && !empty($_POST['x']) ?
        $_POST['x']
        :
        (isset($_SESSION['x']) && !empty($_SESSION['x']) ? $_SESSION['x'] : null)
    );

A: PHP 7 solution:
The ?? operator.
$x = expr1 ?? expr2

*

*The value of $x is expr1 if expr1 exists, and is not NULL.

*If expr1 does not exist, or is NULL, the value of $x is expr2.

https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

A: It would be simple -
$x = (!empty($_POST['x']) ? $_POST['x'] :
          (!empty($_SESSION['x']) ? $_SESSION['x'] : null)
     );


text:
Q: Javascript check how function is invoked is there a way to check how some function is called (and change the output according to that) ?
I have some object that should have the string "," as separator when concatenated, how can i overload toString function in a way that it put separator between two strings?
For example alert ( a + b ) when "a" and "b" are my object will invoke their toString() functions.
Now i would that the first invocation should sees that the caller function ( the plus ) will concatenate the toString() of my object and so put separator (eg : "," ).
The second invocation on the other hand should sees that it is the second operator of the function plus, so even if this function is still concatenating my object the "b".toString() is a simple toString().
If a.toString() = "foo" and b.toString() = "bar" , i would that ( a + b ) will equal to "foo.bar" and not "foo.bar."
Is there a way to achieve this behaviour ?

A: I myself am also obsessed with beautiful syntax.
  // How wonderful, if this:
cursorPosition + playerPosition + targetPosition

  // Could output to something like this:
"(14:68), (22:56), (76:32)"

It's a nice idea, but I don't think it's practical. The best-practice solution is nearly as wonderfully simple:
display(cursorPosition, playerPosition, targetPosition)
"(14:68), (22:56), (76:32)"

Importantly, with this technique (defining a display function), toString acts conventionally -- which means you don't need to worry about your comma stuff toying with your conventional use of toString:
console.log("Your location is " +playerPosition+ " and the target is " +targetPosition+" which is far away");
"Your location is (22:56) and the target is (76:32) which is far away"

In my opinion, the situation should be handled this way:
function Position(x,y){
  this.x = x ?x :0;
  this.y = y ?y :0;
}
Position.prototype.toString = function(){  return '(' +this.x+ ':' +this.y+ ')'  };

var pos1 = new Position(22,40);
var pos2 = new Position(18,24);
var pos3 = new Position(84,46);
var pos4 = new Position(32,64);

function display(){
  var tests = [];
  for (var i=0; i<arguments.length; i+=1)
    tests.push( arguments[i].toString() );
  return tests.join(', ');
}

console.log(display( pos1, pos2, pos3, pos4 ));

Which outputs:
(22:40), (18:24), (84:46), (32:64)


text:
Q: Random walk on a sphere: statistics of the solid angle? Consider a random path on the surface of a 2-sphere, made of N discrete points (each picked with a uniform distribution across the surface). The path connects two successive points by the shortest line between them, and we connect the last point to the first one to make a closed path.
My question is, what is the statistics of the solid angle subtended by this path? I expect the mean to be zero, but I have no idea for the standard deviation.

A: Here are important tracks. But it's not a complete solution.
As any solid angle is measured by the corresponding area, we need to use the formula for the area of a triangular triangle. Afterwards, there will be a summation process. Let $A,B,C$ be the angles of the triangle, we have
$$area=A+B+C-\pi$$
(angular excess: see Girard's theorem here).
But we must be able to compute these angles.
This is done by using this formula:
$$\cos c=\cos a\cos b+\sin a\sin b\cos C \ \ \iff \ \ \cos C=\dfrac{\cos c-\cos a\cos b}{\sin a\sin b}$$
and the 2 other formulas obtained by circular permutation:
$$\cos A=\dfrac{\cos a-\cos b\cos c}{\sin b\sin a} \ \ \text{and} \ \ \cos B=\dfrac{\cos b-\cos c\cos a}{\sin c\sin b}$$
When the path $M_1M_2\cdots M_nM_1$ is completed, one computes the sum of areas:
$$\Delta=s_1 \times area(M_1M_2M_3)+ s_2 \times area(M_1M_3M_4)+ \cdots + s_{n-2} \times  area(M_1M_{n-1}M_{n})\tag{1}$$
where the sign $s_k$ is $+$ if the triangle is positively oriented, $-$ otherwise.
(1) defines a random variable.
The mathematical expectation of $\Delta$ is the sum of the mathematical expectations of the triangular areas, which are clearly $0$ because there is a balance between the positive and negative areas.
The variance of $\Delta$, assuming mutual independence between the different areas, is the sum of variances of the triangle's areas:
$$E(area(M_1M_kM_{k+1})^{\color{red}{2}})$$
... which have to be computed by taking into account the variances and expectancies of sides lengths $\cos a, \cos b, \cos c$, themselves functions of the number $N$ of points "dropped" on the sphere, which doesn'tt look very easy to do, because we have to take as well into account the shortest path limitation. But I think rather good approximations can be obtained by taking a uniform enough distribution of points on the sphere.
Remark: Given a number $N$ of points on the sphere, set apart exceptional values of $N$, it is not possible to have an even distribution of points on the sphere, for example with $N=5$, but we can get rather close to it.


text:
Q: Is there a way to test if a control is Edit or RichEdit? Basically, I have written a program in C# that grabs text and the current caret position from any window handle using user32.dll. After manipulating the text, the program sets the text of the control to the new string and also resets the caret position.
The issue I am running into is that EM_GETSEL returns an caret position for RichEdit controls based on the number of CR+LF proceeding the caret position.
Edit controls treat these as two characters, while RichEdit controls treat them as one "character".
Is there anyway that I can detect which of these two a control may be by windows messages?
Or is there a better way that I can detect caret position for unmanaged controls?

A: Your observation is imprecise.
Rich Edit does not count CRLF as 1 character, but it does not use CRLF (\r\n) for a newline, but only LF (\n). You will see that when you examine the text content of the Rich Edit. Line breaks are returned as \n only, not \r\n.
You can see the same behaviour in the .net Winforms RichEdit control:
    var before = "Line1\r\nLine2";
    richTextBox1.Text = before;
    var after = richTextBox1.Text;

    MessageBox.Show(string.Format("Before: {0} After: {1}", before.Length, after.Length));

This will show "Before: 12 After: 11". The line break \r\n in the text is converted to \n when the text is assigned to the rich edit.

A: Alright everyone, thank you for your help! This explanation is a little off the cuff, so bear with me.
I had a breakthrough today, and I was able to determine a simple way to tell the difference between an Edit or RichEdit control.
Since we know that WM_GETTEXT returns the original string, and EM_GETSEL will be off by 1 for every newline, all we have to do is check for the following:

*

*Are we off of the the first line (line 0)?

*If we are greater than line zero, use EM_LINEINDEX (I use a loop here to increase
wParam and I'll explain why in just a second) to get a substring
from character 0 to EM_LINEINDEX

*Check if that substring
contains a \r (If not, then you have a wordwrap somewhere. This is
why I use the loop in step 2)

*Once you find a substring \r, does that
substring also contain \n?

Again, this works because even EM_LINEINDEX is off by 1 character in a RichEdit against WM_GETTEXT and therefore a substring from character 0 until the EM_LINEINDEX after your first newline will not contain a \n if your control is a RichEdit.


text:
Q: retrieve a json result from a https site How can I retrieve a JSON result from a HTTPS site?
I prefer a method to no need any DLL.
It show this error:

Error connecting with SSL.error:1409442E:SSL routines:ssl3_read_bytes:tlsv1 alert protocol version.

I'm using Delphi Tokyo 10.2.
function GetUrlContent(s: string): string;
var
  IdHTTP1: TIdHTTP;
begin
  IdHTTP1 := TIdHTTP.Create;
  try
    Result := IdHTTP1.Get(s);
  finally
    IdHTTP1.Free;
  end;
end;

procedure GetData;
var
  mydata, ordername: string;
begin
  ordername := 'https://www.bitstamp.net/api/ticker/';
  mydata := GetUrlContent(ordername);
  DBMemo7.Text := mydata;
end;

I've also tried this, but it still gets the annoying SSL error:
function GetURLAsStrin1(const aurl:  string): string;
var
  res, req: String;
  sList: TStringList;
  IdHttp: TIdHttp;
begin
  IdHttp := TIdHttp.Create (nil);
  try
    IdHttp.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(IdHttp);

    req := aurl;
    res := IdHttp.Get (req);

    result := res;
  finally
    idHttp.Free;
  end;

A: By default, TIdSSLIOHandlerSocketOpenSSL enables only TLS 1.0.  Most likely, the site in question does not support TLS 1.0 anymore.  Try enabling TLS 1.1 and 1.2, eg:
function GetUrlContent(url: string): string;
var
  IdHTTP1: TIdHTTP;
begin
  IdHTTP1 := TIdHTTP.Create;
  try
    IO := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP1);
    IO.SSLOptions.SSLVersions := [sslvTLSv1, sslvTLSv1_1, sslvTLSv1_2] // <-- add this!
    IdHttp.IOHandler := IO;
    Result := IdHTTP1.Get(url);
  finally
    IdHTTP1.Free;
  end;
end;

A: For newer delphi versions, I would recommend using the in-built HttpClient class. It does not require any external DLLs, and works for both http or https out of the box.
uses
  System.Net.HttpClient;

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
  Memo1.Text := GetUrlContent('https://www.bitstamp.net/api/ticker/');
end;

function TForm1.GetUrlContent(Url: string): string;
var
  HttpClient: THttpClient;
  Response: IHttpResponse;
begin
  HttpClient := THTTPClient.Create;
  try
    Response := HttpClient.Get(URL);
    Result := Response.ContentAsString();
  finally
    HttpClient.Free;
  end;
end;


text:
Q: Need to overlap subarray of a array at particular indexes Generate another array from the following array based on the index supplied thru another array selected.
The following array
array =[`0: Array(2)
    0:
      disable: false
      label: "label0"
    1:
      disable: false
      label: "label1"

1: Array(2)
    0:
      disable: false
      label: "label0"
    1:
      disable: true
      label: "label1"

2: Array(2)
    0:
      disable: true
      label: "label0"
    1:
      disable: false
      label: "label1"

3: Array(2)
    0:
      disable: false
      label: "label0"
    1:
      disable: true
      label: "label1"]

Now, When array selected = [2,3]. The disable true data array should be given priority. Then the resultant array should be
`0:
  disable: true
  label: "label0"
1:
  disable: true
  label: "label1" `

Similarly When array selected = [0,1]
Then, the resultant should be
   0:
      disable: false
      label: "label0"
    1:
      disable: true
Edit:label: "label1"

Edit : I am sorry I forgot to mention that. So far I have tried following

checked=[2,3]
 arrayData=[

   [
      {
         "label": "label1",

         "disable": true
      },
      {
         "label": "label2",

         "disable": false
      },

   ],
   [
      {
         "label": "label1",

         "disable": false
      },
      {
         "label": "label2",

         "disable": false
      },

   ],
   [
      {
         "label": "label1",

         "disable": true
      },
      {
         "label": "label2",

         "disable": false
      },

   ]
]

const result=this.checked
                  .map(indexAtArrayData => {

                 const element = this.arrayData[indexAtArrayData];
                   const resData=[]
                    if (element) {
                      for (var i=0;i<element.length;i++) {
                        resData[i]={label:element[i].label};

                        if (element[i].disable || typeof resData[i]['disable'] == 'undefined') {
                            resData[i].disable=element[i].disable;
                        }
                      }
                      return resData;
                    }
                  });console.log(result);

I have tried the above code and achieved the result but I am looking for a neater way of doing so.

A: You could get a copy of the first wanted array with objects and update disable if necessary.

var array = [[{ disable: false, label: "label0" }, { disable: false, label: "label1" }], [{ disable: false, label: "label0" }, { disable: true, label: "label1" }], [{ disable: true, label: "label0" }, { disable: false, label: "label1" }], [{ disable: false, label: "label0" }, { disable: true, label: "label1" }]],
    selected = [2, 3],
    result = selected.reduce((r, i) => {
        if (!r) {
            return array[i].map(o => Object.assign({}, o));                   // take copy
        }
        array[i].forEach((o, j) => r[j].disable = r[j].disable || o.disable); // update disable
        return r;
    }, undefined);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: If I understand this correctly the selected array represents indices of the original array and at each selected element of the original array you want to select the first element set to disabled and the first element else.
This is how a solution would look like:
selectedArray
  .map(indexAtArrayData => {
    const element = arrayData[indexAtArrayData];
    if (element) {
      for (let entry of element) {
        if (entry.disable) {
          return entry;
        }
      }
      return element[0];
    }
  });

A: function processData(arr, selected) {
  let processedArray = [];
  selected.map(index => {
    const element = arr[index];
    if (element) {
      for (let entry of element) {
        let processedEntry = {
          label: entry.label
        };

        if (entry.disable || entry.disable === undefined) {
          processedEntry.disable = true;
        }

        processedArray.push(processedEntry);
      }
    }
  });

return processedArray;
}

Here is the link to jsfiddle


text:
Q: Modifying the /sys/devices/system/memory/ directory of Sysfs in Linux Kernel I am working on my course homework for modifying the memory directory of Sysfs in Linux Kernel. I am seeking help from people here after taking permission from my prof. Here's what I exactly want to do.
Background: If I have a 4 GB RAM I can have 4 X 1 GB DIMMS or 2X 2GB DIMMS on my motherboard. NUMA is supported in Linux by dividing this 4GB physical memory into many chunks with specific starting and ending physical address for each chunk. The 'devices' directory in Sysfs contains the global device hierarchy. This contains every physical device that has been discovered by the bus types registered with the kernel. Hence the details regarding the memory chunks are stored in the path '/sys/devices/system/memory/' of Linux Kernel. In this directory, we have a file called 'block_size_bytes' which decides how many parts my RAM can be split into. For example in my system it is 8000000 and hence the RAM is split into 32 memory folders from memory0 to memory43. Every 'memoryX' directory will have a file called 'state' which represents the online/offline state of the memory chunk. I can toggle between online/offline if I want to 'switch off' that particular chunk off memory.
So here's what I exactly want to do:
I want to modify this whole directory structure into 4 directories. Why 4? Because, I have 4 X 1GB DIMMS on my motherboard, so I want reduce these 32 memory chunks in to to 4 big chunks so that I can control whichever DIMM I want by toggling it's 'state' online/offline. So Basically I want to change the state of the memory on DIMM level.
That's pretty much my problem description.
My approach: I have read through the sysfs file system and tried to look up the kernel modules which are responsible for organizing the 'memory' directory of sysfs. I want to find the module and edit it as per my requirement and compile that module. It got increasingly difficult to find the specific documentation regarding this topic which lead me to ask this question. All I could find was that there this C programming file '/lib/modules/3.8.0-19-generic/source/drivers/base/memory.c' which has methods for setting the 'state' of the memory chunks, showing the starting and ending physical address of each memory section and many other methods. But I am not able to figure out where exactly these methods are being called or which module is utilizing this C file to set all the attributes.
Could you please let me know which exact module I need to look for? If you find my approach wrong, could you please point me in the right direction?
Thanks in advance :)

A: I just answer to this part of the question :

But I am not able to figure out where exactly these methods are being called or which module is utilizing this C file to set all the attributes.

You can use lxr to search in the kernel tree.
Here an exemple with show_mem_state function.


text:
Q: Partition Keys & Data Modeling in ScyllaDB In Scylla, data is stored by partition key. If I query a large table with many partition keys, is it equivalent to executing multiple queries against the table? For example, suppose I have the following table:
key1 : val1
key2 : val2
key3 : val3

Where each of the 3 keys (key1..3) is a different partition key.
If I execute the following query against the table:
SELECT * from table.

Scylla, will presumably need to execute this query 3 times - on 3 different partitions since each row is stored on a different partition. It seems inefficient, as it means the query will be executed once per partition. Suppose the data was partitioned into 100 partitions (100 keys), will the query need to be executed 100 times to complete? (and by extension, the query will only be as fast as the slowest server?)
If this is true, then querying 1 row from 3 separate tables (e.g, where each row has a different partition key), should have identical performance as when querying 3 rows from one table where each of 3 three rows has a different partition key? In other words, whether the data is modeled as part of one table or multiple tables, doesn't really matter. What matters is whether two or more rows share the same partition key?
What happens when we query 3 different tables were each row has the same partition key, is this as efficient as querying 3 rows from one table where all of the rows have the same partition key?
Any guidance in evaluating performance expectations in the 3 scenarios described above would be very helpful.
Thanks!

A: As you noted, the query SELECT * FROM table is not a query in an individual partition, but rather a whole-table scan. A whole-table scan is "costly" in the sense that it will need to read all the data in the table (if you run it to completion), but it is not as inefficient as you thought it might be:
Scylla or Cassandra do not begin such a query by looking for the list of extant partition keys - and then querying each of those individually. Instead, Scylla and Cassandra have a deterministic order for the partition keys, so-called "token" order (you can think of the partition key's "token" as a hash function). Individual server nodes hold contiguous ranges of these tokens, so scanning the entire table is achieved by scanning each of these contiguous token ranges (also called "vnodes") - each of which is implemented efficiently by an individual node efficiently reading data sequentially from its own disk. So you can have a million or even a billion partitions, and SELECT * FROM table for reading the entire table will still involve mostly-sequential reads from disk - not a million or billion seeks to individual partitions.
Another comment I feel compelled to make is that if you are thinking about having just 3 partitions, and worrying about increasing the number to 100, you are misunderstanding data modeling in Scylla (and Cassandra). In fact, having 100 partitions is still too few. You should have a lot more than 100 partitions. The more, the better. The reason is that if you have only a few huge partitions, the data will not be evently distributed between nodes and shards (CPUs). If you have just 3 partitions and 100 CPUs, since each partition is owned by one CPU (in Cassandra, one server), you'll only have 3 out of the 100 CPUs working, which is certainly not a good idea. Having a million partitions is much better than having just 3.

A: In the future, please try to ask only one question per question.
SELECT * from table

Without the ability to determine an exact partition, the driver will choose a node in the cluster to send the query.  This node becomes a "coordinator" for this query.  It then sends requests out to each node in the cluster, and builds the result set.  Once complete, the coordinator returns the result set back to the driver.  In this particular case, it has to poll all nodes in the cluster to find only 3 rows...not terribly efficient.
This is why unbound queries really aren't a good idea in the Cassandra/Scylla world, as that one node becomes responsible for polling the data from all of the other nodes.  In a large cluster, large data scenario, it is not unheard of for a node acting as a coordinator to slow down, or even crash.

If this is true, then querying 1 row from 3 separate tables (e.g, where each row has a different partition key), should have identical performance

I assume from reading this, that a partition key is being provided as a part of each query's WHERE clause.  Querying a single, specific row from 3 separate tables will be faster.  Basically, it won't need to exhaustively check every node in the cluster.  The driver can simply hash the three partition keys, and know exactly where to go to get the data.  The three queries will perform even faster in this scenario if the driver is using a token-aware load balancing policy, as there is no need for a single node to act as coordinator, skipping one network trip.

What happens when we query 3 different tables were each row has the same partition key, is this as efficient as querying 3 rows from one table where all of the rows have the same partition key?

This will perform similarly to previous scenario, where three distinct queries will be run.  The fact that they all go to the same partition shouldn't make much of a difference, other than the same nodes will be used to serve the data.
For additional reference, here's a link to a Fault Tolerance diagram from Scylla's docs.  It provides more, visual detail on the paths of read and write operations, as well as the effects of replication factor, consistency level, and multiple nodes.


text:
Q: Align text in navigation bar Problem with aligning text in nav bar
Hi there
i have a problem with aligning my text in a navigation bar. I need the last text to move to the right of the bar so it stays with my search bar, and the other to stay on the left
But Im having issues getting this done, any help maybe?

A: You can use flex for this and just apply  "margin-left: auto" to the last list item. Note that I got the basic layout (nav to the left and search to the right with flex (using flex-grow and flex-shrink repsectively).
The inside the nav - applying the flex styling to layout the list items and then on the :last-child using margin-left to force it to the right away from teh other list items.
UPDATE - following comments from OP - have amended it to have a second nav-list to the right of the search input. Much easier to split the list than trying to get the layout using float etc.

header {
  display: flex;
  align-items: center;
}

nav {
  flex-grow: 1
}

.nav-list {
  display: flex;
  align-items: center;
  list-style: none;
  padding: 0;
  margin: 0;
}

.nav-list li {
 padding: 4px 16px;
}

.search-wrapper {
  flex-shrink: 0;
   padding: 0 16px;
 )

Home

About

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

Contact


text:
Q: Gunicorn gevent workers vs Uvicorn ASGI I'm currently developing a service in Django which makes use of a slow external API (takes about 10s to get a response), which means the connections to my server are kept open waiting for the external API to respond, and occupying worker time/resources.
I know I can use gunicorn's thread or gevent workers to add concurrency, but can't seem to grasp the exact difference between using gunicorn with gevent workers and uvicorn (or any other server) with the asgi interface.
What would be the criteria for using one over the other?
Django still doesn't fully support async/await views. Would it be better if I just stick with gevent workers?

A: Gunicorn has a pre-fork worker model
A pre-fork worker model basically means a master creates forks which handle each request. A fork is a completely separate *nix process (Source).
Uvicorn is a ASGI server running uvloop
Python async needs a event loop for it to use it's async features. And uvloop is an alternative to the asyncio loop. So if you're having async calls in your code you could use uvloop internally or use uvicorn as your ASGI server. Note: You still have just a single event loop. You can choose to use gunicorn and uvicorn to have multiple workers and use uvloop.
In your django application it makes sense to use uvloop internally (if you choose to) and use gunicorn as your ASGI.


text:
Q: Running a function on thread gives an error I am trying to run a function "generate_model" on thread which takes three arguments.
def thread_for_generate_model(Thread):
    def __init__(self, name, job_id, boolean_string, Batch_size):
        self.name = name
        self.job_id = job_id
        self.boolean_string = boolean_string
        self.Batch_size = Batch_size

    def run(self):
        LOGGER.info("vector model create started for job_id: %s on thread %s", self.job_id, self.name)
        generate_model(self.job_id, self.boolean_string, self.Batch_size)
        LOGGER.info("vector model created for job_id: %s", self.job_id)

def main():
     ....
     thread_for_generate_model("Thread_for_vectormodel", job_id, generate_search_string(job_id,keywords), 5000).start()
     # I am trying to run this function on a thread
     # generate_model(job_id, generate_search_string(job_id,keywords), 5000)
     ....

I got an error ,
TypeError: thread_for_generate_model() takes 1 positional argument but 4 were given

by solution in the link, I have modified as below by adding an additional parameter
 def run(self, event=  None)

but still has the same error. how to rectify it?

A: Code below should do what you are trying to do - I have just added a few dummy functions etc. to get the code not throw syntax error or undefined functions/variables etc.. This is roughly the structure you can follow.
As pointed out in the comments - use def something to define a method. and class Something to define a class.
from threading import Thread
import logging
import time

LOGGER = logging.getLogger()
logging.basicConfig()

class thread_for_generate_model(Thread):
    def __init__(self, name, job_id, boolean_string, Batch_size):
        Thread.__init__(self)
        self.name = name
        self.job_id = job_id
        self.boolean_string = boolean_string
        self.Batch_size = Batch_size

    def run(self):
        LOGGER.info("vector model create started for job_id: %s on thread %s", self.job_id, self.name)
        generate_model(self.job_id, self.boolean_string, self.Batch_size)
        LOGGER.info("vector model created for job_id: %s", self.job_id)

def generate_search_string(job_id, keywords):
    return False

def generate_model(job_id, string, batch_size):
    while True:
        time.sleep(1)
def main():

    job_id = 0
    keywords = ['a', 'b']
    thread_for_generate_model("Thread_for_vectormodel", job_id, generate_search_string(job_id,keywords), 5000).start()
    # I am trying to run this function on a thread
    # generate_model(job_id, generate_search_string(job_id,keywords), 5000)

if __name__ == '__main__':
        main()


text:
Q: KQL group by or summarize count by see the rest of the columns I would like to ask your help with a kql query:
DeviceEvents
| distinct InitiatingProcessAccountUpn,DeviceName,DeviceId
| join DeviceTvmSoftwareVulnerabilities on $left.DeviceId == $right.DeviceId
| summarize count() by SoftwareName, DeviceId

The problem is I used summarize count by there are many software versions and I just want to see the version of the software from each machine, and it did the tick but I can not re-add the missing columns from the table.
I tried to rejoin with the same table but wasn't successfull.
What I would like to see is from one machine one software.
Now, if I have this, I can see the name of the software and ID but I want to see in the final report the rest column as well.
Do you have any idea what I can do better?
Thanks

A: you can use take_any:
summarize take_any(SomeOtherColumns)

Or you could add the other column as a grouping key and then do another summarize and aggregate it somehow (also take_any(), max(), arg_max(), make_list() etc)


text:
Q: How to make a lua file? I wanna try to make a ".exe" file using lua code.
I've tried lua.org but i don't understand anything about it.
i've followed tutorials but they all don't help.
It would help me alot if there was a setup file that does all the setup and
lets me able to make .lua files.
Thank you for trying to help!

A: There's nothing built in to Lua that will let you do this, so you need to either write some C code yourself or use a third-party tool. If you want to go the third-party route, https://github.com/PG1003/dogfood is an example of such a tool.


text:
Q: Express routes are conflicting I have the following express routes defined:
// Questions Routes
app.route('/questions')
    .get(questions.list)
    .post(users.requiresLogin, questions.create);

app.route('/questions/:questionId')
    .get(questions.read)
    .put(users.requiresLogin, questions.hasAuthorization, questions.update)
    .delete(users.requiresLogin, questions.hasAuthorization, questions.delete);

app.route('/questions/list/:page')
            .get(questions.questionList);

app.route('/questions/count/')
            .get(questions.count);

Along with this callback trigger for the questionId route parameter:
app.param('questionId', questions.questionByID);

The expected behavior was to have /questions/count requests route to the count method in a controller, but it is instead being routed to the questionByID method and I'm seeing this error:
CastError: Cast to ObjectId failed for value "count" at path "_id"
...
at exports.questionByID (/path/controllers/questions.server.controller.js:137:56)
...

I think this appears because mongoose is trying to convert the literal "count" from the route to an ObjectId type, which would make sense if I was using the /questions/:questionId route but it doesn't if I'm using /questions/count to make the request.
These are the two relevant methods in questions.server.controller.js
exports.count = function (req, res) {
    console.log('attempting to count these damn questions!');
    Question.count({}, function (err, count) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            console.log(count);
            res.jsonp(count);
        }
    });
};

/**
 * Question middleware
 */
exports.questionByID = function (req, res, next, id) {
    Question.findById(id).populate('user', 'displayName').exec(function (err, question) {
        if (err) return next(err);
        if (!question) return next(new Error('Failed to load Question ' + id));
        req.question = question;
        next();
    });
};

I've fixed it by setting the route to:
app.route('/questionscount')
            .get(questions.count);

But it looks bad and I don't want to do it like that, does anyone know why this is happening?
Thanks in advance.

A: Since express evaluates the routes in addition order, you should put the more specific routes first. In your example it just evaluates "count" as the questionId parameter because it matches the expression.
If you put the app.route('/questions/count/') route before the
app.route('/questions/:questionId') it should work.

A: If count and question_id have diffirence you can put  Regex to route for distinguish them


text:
Q: How to assert org.slf4j.Logger statements with junit? How can I validate log statements from a org.slf4j.Logger with junit in a spring-boot-test?
@Service
public class MyService {
    private final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(this.getClass());

    public void run() {
        LOGGER.info("running");
    }
}

@SpringBootTest
public class MyTest {
    @Autowired
    private MyService service;

    @Test
    public void test() {
        service.run();

        //TODO how to validate log statement?
    }
}

A: If the underlying SLF4J is Log4j 2.x, as your tags might implicate, you can use a ListAppender, which is contained in the log4j-core's test-jar.

A: I found a solution with Springs @ExtendWith(OutputCaptureExtension.class):
@SpringBootTest
@TestPropertySource(properties = "logging.level.root=INFO")
public class LogServiceTest {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Test
    @ExtendWith(OutputCaptureExtension.class)
    public void testLogging(CapturedOutput capture) {
        logger.info("junit"); //can be replaced with any service call that logs
        assertThat(capture.getOut()).contains("junit");
    }
}

It requires the follow="true" option on your log4j config:
<Console name="CONSOLE" target="SYSTEM_OUT" follow="true">


text:
Q: How can I get computed CSS excluding the browser specifics? I am trying to get all computed css properties without the browser specifics through javascript/jQuery.
Is there a way to do that?
Thank you

A: Yes, here is a cross-browser example:

*

*http://www.quirksmode.org/dom/getstyles.html
The example is quite old. You probably want to reverse it to use getComputedStyle in preference to currentStyle.


text:
Q: 'pie' function in MATLAB gives "undefined function 'cos'" error I wrote a function, wins_plot, to read the scoreboard from a file and store the player's name, number of plays, wins, & losses. I stored all those using struct. I loop over the file, store each line in line, textscan for everything I need from line, and then iterate i (initially == 1) as I go to expand my array of structures. A snippet from the code to represent what I am saying:
c = textscan(line, '%s %s %d %d %d');

  player(i).firstName = c{1};
  player(i).lastName = c{2};
  player(i).plays = c{3};
  player(i).wins = c{4};
  player(i).losses = c{5};

After all the file has been scanned and stored, I then write this code to extract the number of wins of each player and store it in X and then finally use the pie function to represent the values in X
for n=1:(i-1)
    X(n) = player(n).wins;
end
pie(X);

I get a wall of error after:

Undefined function 'cos' for input arguments of type 'int32'.
Error in pol2cart (line 22) x = r.*cos(th);
Error in pie (line 99)
      [xtext,ytext] = pol2cart(theta0 + x(i)*pi,1.2);
Error in wins_plot (line 30) pie(X);

I have no clue what might be wrong. Any help would be greatly appreciated. Please keep in mind that I only just started learning MATLAB today so my knowledge of it is very limited (and I have R2013a). Thank you in advance!

A: The numbers got read as int32, but when you call pie, it requires them to be double to do the computation. So, when you call pie, try casting the values to double. Try this,
pie(double(X));


text:
Q: convert txt to xml then style with xslt with c# I'm very new c# and xml
I'm trying to convert a txt file to XML, then with a button apply an XSLT to the XML with C# (and display it in the program)
I have managed to convert the txt file to XML (although it only takes 1 lot of data), but cannot figure out how to apply the XSLT to the XML.
Is there some way to insert the stylesheet link into the XML () or is this what "XSLcompiledTransform" is meant to do ?
Below is the c# that I have been testing -
    private void button1_Click(object sender, EventArgs e)
    {
        string filePath = "authors.xml";

        dataSet1.ReadXml(filePath);

        dataGridView1.DataSource = dataSet1;
        dataGridView1.DataMember = "authors";
    }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void button2_Click(object sender, EventArgs e)
    {
        String[] data = File.ReadAllLines("TextFile.txt");

        XElement authors =
            new XElement("authors",
             new XElement("title", data[0]),
             new XElement("Released", data[1]),
             new XElement("Price", data[2]));

        authors.Save("authors.Xml");
    }

    private void button3_Click(object sender, EventArgs e)
    {
        try
        {

            // Generating a temporary HTML file
            string outfile = Path.GetTempFileName().Replace(".tmp", ".html");

            // Creating the XslCompiledTransform object
            XslCompiledTransform transform = new XslCompiledTransform();

            // Loading the stylesheet file from the textbox
            transform.Load("authors.xslt");

            // Transforming the XML file and storing output in HTML file
            transform.Transform("authors.xml", outfile);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void button4_Click(object sender, EventArgs e)
    {
        // Create a reader that contains the style sheet.
        XmlReader reader = XmlReader.Create("authors.xslt");
        reader.ReadToDescendant("xsl:stylesheet");

        // Load the style sheet.
        XslCompiledTransform xslt = new XslCompiledTransform();
        xslt.Load(reader);

    }

    private void button5_Click(object sender, EventArgs e)
    {
        string filePath = "authors.xml";

        string[] lines = File.ReadAllLines(filePath);

        textBox1.Text = System.IO.File.ReadAllText(filePath);
    }
}
}


text:
Q: UIScrollView: Content first appears too low Before posting a lot of code I want to ensure it's not a commonly known issue (independent of the specific code) so first I'll explain my problem in general:
In the storyboard I created a UIViewController, added a UIScrollView as well as another UIView (hierarchical subviews). I need the scroll view to push the content up when the keyboard appears so the textfield stays visible. When running the app everything works fine besides the fact, that the content appears closer to the bottom of the screen than defined in my storyboard. As soon as I tapped the textfield the content is scrolled up (by adjusting scrollView.contentInset and scrollView.scrollIndicatorInsets to (0.0, 0.0, keyboardSize!.height, 0.0)) and its position is like expected. When pressing the return key, the keyboard disappears, the content scrolls down again (by adjusting scrollView.contentInset and scrollView.scrollIndicatorInsets to (0.0, 0.0, 0.0, 0.0)) but now everything is like I want it to be and like it was defined in the storyboard.
Trying to understand what's happening I also let print out to the console some of the y points in viewDidLoad(), keyboardDidShow and keyBoardDidHide but when comparing those, they're all the same. What did I miss out? Do you need to see some specific part of my code?

A: It works as desired when setting up
viewDidAppear(animated: Bool) {
    scrollView.contentInset = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)
    scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)
}

Any comments concerning other/better solutions are welcome!

A: I just had this issue - I messed around with all the solutions above, finally found the fix.
For me, I just had to flip the right switch in the ViewController constructor:
public ViewController ()
{
    AutomaticallyAdjustsScrollViewInsets = false;
}

I'm suspecting the results would be similar for LoadView(), ViewWillAppear(), etc...

A: Can you check that:

*

*edgesForExtendedLayout contains the upper edge

*automaticallyAdjustsScrollViewInsets is set on your view
controller?

A: This one will work even better, without visibly "bumping" the first item on the view, but doing so before it is shown to the user:
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    scrollView.contentInset = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0);
    scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0);
}


text:
Q: Lerna bootstrap does not link local dependencies? What is the proper way of working with lerna and local dependencies?

I have configured two modules in a mono repo to use lerna with a local dependency. I expected that
$ lerna bootstrap
$ lerna run test

would be sufficient to download all external dependencies, link a local dependency and execute and pass all tests in all modules.
Expected Behavior
As per the lerna bootstrap documentation:

*Symlink together all Lerna packages that are dependencies of each other.

Thus, I expected that lerna bootstrap would create a symlink in module-b/node_modules below that points to module-a (which then would allow the tests to be executed and pass).
Current Behavior
No linking occurs, which cause the tests to fail:

lerna ERR! yarn run test exited 1 in 'module-b'
  lerna ERR! yarn run test stdout:
  yarn run v1.19.1
  $ jest
  info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
lerna ERR! yarn run test stderr:
  FAIL ./import.test.js
    ● Test suite failed to run
Cannot find module 'module-a' from 'import.test.js'

> 1 | const moduleA = require('module-a');
    | ^
  2 |
  3 | test('should import module-a', () => {
  4 |   moduleA();

  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:259:17)
  at Object.<anonymous> (import.test.js:1:1)

Steps to Reproduce

*

*Create the folder structure below

*Copy the files inlined to their corresponding directory

*Execute $ lerna bootstrap followed by $ lerna run test
project-root
   + packages
   |       + module-a
   |       |      + package.json
   |       |      + index.js
   |       |
   |       + module-b
   |       |      + package.json
   |       |      + import.test.js
   |
   +  lerna.json

packages/module-a/package.json
{
  "name": "module-a",
  "version": "1.0.0",
  "private": true,
  "main": "index.js",
  "scripts": {
    "test": "echo \"Test passed in module-a\""
  }
}

packages/module-a/index.js
module.exports = () => console.log('Log in module-a');

packages/module-b/package.json
{
  "name": "module-b",
  "version": "1.0.0",
  "private": true,
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "dependencies": {
    "module-a": "file:../module-a"
  },
  "devDependencies": {
    "jest": "^24.9.0"
  }
}

packages/module-b/import.test.js
const moduleA = require('module-a');

test('should import module-a', () => {
  moduleA();
});

lerna.json
{
  "npmClient": "yarn",
  "packages": [
    "packages/*"
  ],
  "version": "independent"
}

Observation
Executing lerna link --force-local does not change status quo, the test still fails because the module-b/node_modules/ still does not contain a reference to module-a.
Remark
I cannot use yarn workspaces together with lerna because module-b is an Electron app and the electron builder expects its dependencies to be installed in the packages/module-b/node_modules/ folder.
Environment

*

*lerna --version 3.18.4

*npm --version 6.11.3

*yarn --version 1.19.1

*node --version v12.12.0

*macOS Mojave 10.14.6

A: I have tried your implementation.
Using file:../module-a in packages/module-b/package.json does not work for me.
You can go around it easily by using writing a version number for module-a (it does not matter which since we will force-local)
{
  "name": "module-b",
  "version": "1.0.0",
  "private": true,
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "dependencies": {
    "module-a": "1.0.0"
  },
  "devDependencies": {
    "jest": "^24.9.0"
  }
}

At the root of your project:
Bootstrap and link for local version:
npx lerna bootstrap --force-local
Run tests:
npx lerna run test

A: for me its worked, and installed packages in node_module folder
npx lerna exec -- npm install


text:
Q: Need to get information about video when user tap on Iframe embedded on WKWebView As in image, I have blog that contain video and what I want is when ever user tapped on it I need total video information like duration, title, etc.

A: Because the interaction you are trying to observe is occurring in the context of the web browser and not the context of UIKit, your best bet is to inject JavaScript into the page to interact with DOM content.  (I am not qualified to tell you how the JavaScript might work).
To get results back, WKWebView has:
func evaluateJavaScript(_, in:, in:, completionHandler:)

and
func callAsyncJavaScript(_, arguments:, in:, in:, completionHandler:)


text:
Q: How to properly store name of directories into a linked list? I'm trying to store the names of directories and sub directories in a linked list. When I display them using printf, the names are listed correctly, but when I try to store them in a linked list they do not appear correctly.
Every thing works when when I'm just printing, but results differ when I store the strings into a linked list and displaying it.
void ls_r(char *path) {
    DIR *dir;
    struct dirent *file;
    struct stat buf;
    char *temp;
    t_list *list;

    if (!(dir = opendir(path)))
        return;
    list = NULL;
    while ((file = readdir(dir)) != NULL) {
        if (file->d_name[0] != '.') {
            temp = strdup(path);
            strcat(temp, "/");
            strcat(temp, file->d_name);
            stat(temp, &buf);
            if (buf.st_mode && S_ISDIR(buf.st_mode)) {
                ft_list_insert(&list, temp);
                printf("%s\n", temp);
                ls_r(temp);
            }
        }
    }
    ft_print_list(list, "\n");
}

printf result:
./file3
./file3/file32
./file3/file33
./file3/file31
./file3/file31/file311
./file3/file31/file313
./file3/file31/file312
./file2
./file1
./file1/file11
./file1/file12
./file1/file13

linked list result:
./file3/file31/f .@��
./file3/file31/f�-@��
./file3/file31/f./file3/file31
./file3/file33
./file3/file32./file1/file13
./file1/file12
./file1/file11./file1
./file2
./file3

A: These statements
        temp = strdup(path);
        strcat(temp, "/");
        strcat(temp, file->d_name);

are invalid.
You have to reserve enough space to contain the concatenation of strings path, "/", and file->d_name.
So use for example
temp = malloc( strlen( path ) + sizeof( ( char )'/' ) + strlen( file->d_name ) + sizeof( ( char )'\0' ) );

and then copy the strings into the allocated memory.
strcpy( temp, path );
strcat(temp, "/");
strcat(temp, file->d_name);

Also it is possible that the function ft_list_insert the code of which is not shown does not correctly insert a node in the list.

A: Your code has undefined behavior because you copy extra characters at the end of the string allocated by strdup. You must allocate enough space for the complete string.
Note also that you have a memory leak for all entries that are not directories, and you should free the list before returning too. The path should be freed too if ft_list_insert() duplicates it.
Also testing buf.st_mode seems useless, but testing for stat failure is necessary to avoid reading uninitialized contents of the buf structure.
Here is a modified version with a utility function:
char *makepath(const char *dir, const char *name) {
    size_t len1 = strlen(dir);
    size_t len2 = strlen(name);
    // allocate extra space for '/' and '\0'
    size size = len1 + len2 + 2;
    char *p = malloc(size);
    if (p != NULL) {
        // copy the directory part
        memcpy(p, dir, len1);
        if (len1 > 0 && dir[len - 1] != '/') {
            // only append a path separator if needed
            p[len1++] = '/';
        }
        // copy the filename and its null terminator
        memcpy(p + len1, name, len2 + 1);
    }
    return p;
}

void ls_r(const char *path) {
    DIR *dir;
    struct dirent *file;
    struct stat buf;
    char *temp;
    t_list *list;

    if (!(dir = opendir(path)))
        return;
    list = NULL;
    while ((file = readdir(dir)) != NULL) {
        if (file->d_name[0] != '.') {
            temp = makepath(path, file->d_name);
            if (temp != NULL && !stat(temp, &buf) && S_ISDIR(buf.st_mode)) {
                ft_list_insert(&list, temp);
                printf("%s\n", temp);
                ls_r(temp);
            } else {
                free(temp);
            }
        }
    }
    ft_print_list(list, "\n");
    ft_free_list(list);  // assuming ft_free_list() also frees the list payload
}

A: Here is the working code:
Changes: (Done on top of @chqrlie changes)

*

*Added main function to call ls_r() function.

*Allocated heap memory for "char *temp" before writing actual path to the same memory location.

*Added singly linked list utility functions to maintain the directory list.

*removed ft_print_list(list, "\n"); call from ls_r() as it getting called recursively. Moved the same call with different function name (print_list()) to the main function.

Basically, you need to take care of memory allocations and deallocations properly. Otherwise, you encounter these kind of problems.
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>

/* directory node structure */
struct dir_node
{
    char *path;
    struct dir_node *next;
};

typedef struct dir_node dnode;

/* Global pointers, these can be moved to main() function
 * and can be passed to the required functions.
 * To do that you will have to use double pointers(pointer to pointer).
 * Just for understanding making these as global.
 */

dnode *newnode,*temp;
dnode *list = NULL, *last = NULL;

/*
 * Creating new node.
 */
dnode* create_node(char* path)
{
    newnode = (dnode *)malloc(sizeof(dnode));
    if (newnode == NULL)
    {
        printf("\nMemory was not allocated");
        return NULL;
    }
    else
    {
        int path_len = strlen(path);
        //make sure we have received valid path.
        if(path_len <= 0)
        {
            free(newnode);
            newnode=NULL;
            return NULL;
        }
        newnode->path = path;
        newnode->next = NULL;
        return newnode;
    }
}
/*
 * Insert new node at the end of the list.
 */
void insert_node(char* path)
{
    newnode = create_node(path);
    if(newnode == NULL)
    {
        //Something went wrong.
        //Either path is invalid or memory is not allocated properly.
        return;
    }
    if (list == last && last == NULL)
    {
        //First node in the list.
        list = last = newnode;
        list->next = NULL;
        last->next = NULL;
    }
    else
    {
        last->next = newnode;
        last = newnode;
        last->next = NULL;
    }
}
/*
 * Print the list.
 */
void print_list()
{
    temp=list;
    while(temp!=NULL)
    {
        printf("%s\n",temp->path);
        temp=temp->next;
    }
    printf("\n");

}
/*
 * Clear the list.
 */
void clear_list()
{
    dnode* current = list;
    dnode* next;

    while (current != NULL)
    {
        next = current->next;
        if(current->path != NULL)
        {
            free(current->path);
            current->path=NULL;
        }
        free(current);
        current = next;
    }
    list = NULL;
    temp=list;
}
char *create_path(const char *dir, const char *name) {
    size_t len1 = strlen(dir);
    size_t len2 = strlen(name);
    // allocate extra space for '/' and '\0'
    size_t size = len1 + len2 + 2;
    char *p = (char *)malloc(sizeof(char)*size);
    if (p != NULL) {
        // copy the directory part
        memcpy(p, dir, len1);
        if (len1 > 0 && dir[len1 - 1] != '/') {
            // add a path separator if needed
            p[len1++] = '/';
        }
        // copy the filename and its null terminator
        memcpy(p + len1, name, len2 + 1);
    }
    return p;
}

void ls_r(const char *path) {
    DIR *dir;
    struct dirent *file;
    struct stat buf;
    char *temp=NULL;

    if (!(dir = opendir(path)))
        return;
    while ((file = readdir(dir)) != NULL) {
        if (file->d_name[0] != '.') {
            temp = create_path(path, file->d_name);
            if (temp != NULL && !stat(temp, &buf) && S_ISDIR(buf.st_mode)) {
                printf("%s\n", temp);
                insert_node(temp);
                ls_r(temp);
            } else {
                free(temp);
            }
        }
    }
}
int main()
{
    ls_r("/work/Workspace/");
    printf(".....Directory list:....\n");
    print_list();
    clear_list();
    printf(".....Directory list after clearing:....\n");
    print_list();
    printf("...done....\n");
    return 0;
}


text:
Q: Can I fit enough useful A / B testing data into 30MB or 100MB of Redis on Heroku? Ok this question is admittedly coming from an interest in not spending money I don't have to. And I know it's hard to "estimate" this kind of thing. But maybe someone out there feels they have a confident ballpark figure they could offer.
I want to start doing A/B testing in my ruby on rails app hosted on heroku. I have several gems/libraries to choose from to implement the A/B tests.
Split, the gem that seems to be most full-featured only uses a Redis data store, whereas others use a SQL store, but seem not as solid. I feel a bit gun-shy of using Redis, increasing the complexity of my stack, and possibly incurring $10 - $50 per month just for A/B testing.
The Redis Cloud add-on offers 30MB on the free tier and 100MB at $10/mo. I'm having trouble visualizing what kind of usefulness I can get out of the free tier or the 100MB tier.
I'd rather not implement the A/B testing in my app (investing in a certain API / config setup), only to find that I can't afford it.
So to phrase my question in the (over) simplest way possible. How many months of data could I expect to be able to collect with 5-10 A/B tests on 30MB (and/or 100MB) of Redis?