text:
Q: Custom NLog target with async writing NLog allows me to write a custom target. I want to log to my database using Entity Framework Core.
In NLog.Targets.Target there is this:
protected virtual void Write(LogEventInfo logEvent);

However my code is async, so I must do:
protected override async Task WriteAsync(LogEventInfo logEvent)
{
    await WriteToEfContext(logEvent);
    // and so on...
}

But there is no Task WriteAsync version of the write method.
How do I write a custom target, with async support?

A: Update AsyncTaskTarget with NLog 4.6:
public class MyCustomTarget : AsyncTaskTarget
{
     protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken token)
     {
          return await MyLogMethodAsync(logEvent.LogEvent).ConfigureAwait(false);
     }
}

See also: https://github.com/NLog/NLog/wiki/How-to-write-a-custom-async-target
Previous Answer:
If order of LogEvents are not important and correct flush is not important, then you can do the following:
public class MyCustomTarget : TargetWithLayout
{
    protected override async void Write(AsyncLogEventInfo logEvent)
    {
        try
        {
           await MyLogMethodAsync(logEvent.LogEvent).ConfigureAwait(false);
           logEvent.Continuation(null);
        }
        catch (Exception ex)
        {
           logEvent.Continuation(ex);
        }
    }
}

Implemented an abstract class, that ensures correct ordering (and doesn't exhaust the threadpool):
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using NLog.Common;

/// <summary>
/// Abstract Target with async Task support
/// </summary>
public abstract class AsyncTaskTarget : Target
{
    private readonly CancellationTokenSource _cancelTokenSource;
    private readonly Queue<AsyncLogEventInfo> _requestQueue;
    private readonly Action _taskStartNext;
    private readonly Action<Task, object> _taskCompletion;
    private Task _previousTask;

    /// <summary>
    /// Constructor
    /// </summary>
    protected AsyncTaskTarget()
    {
        _taskStartNext = TaskStartNext;
        _taskCompletion = TaskCompletion;
        _cancelTokenSource = new CancellationTokenSource();
        _requestQueue = new Queue<AsyncLogEventInfo>(10000);
    }

    /// <summary>
    /// Override this to create the actual logging task
    /// <example>
    /// Example of how to override this method, and call custom async method
    /// <code>
    /// protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken token)
    /// {
    ///    return CustomWriteAsync(logEvent, token);
    /// }
    ///
    /// private async Task CustomWriteAsync(LogEventInfo logEvent, CancellationToken token)
    /// {
    ///     await MyLogMethodAsync(logEvent, token).ConfigureAwait(false);
    /// }
    /// </code></example>
    /// </summary>
    /// <param name="logEvent">The log event.</param>
    /// <param name="cancellationToken">The cancellation token</param>
    /// <returns></returns>
    protected abstract Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken);

    /// <summary>
    /// Schedules the LogEventInfo for async writing
    /// </summary>
    /// <param name="logEvent">The log event.</param>
    protected override void Write(AsyncLogEventInfo logEvent)
    {
        if (_cancelTokenSource.IsCancellationRequested)
        {
            logEvent.Continuation(null);
            return;
        }

        this.MergeEventProperties(logEvent.LogEvent);
        this.PrecalculateVolatileLayouts(logEvent.LogEvent);

        _requestQueue.Enqueue(logEvent);
        if (_previousTask == null)
        {
            _previousTask = Task.Factory.StartNew(_taskStartNext, _cancelTokenSource.Token, TaskCreationOptions.None, TaskScheduler.Default);
        }
    }

    /// <summary>
    /// Schedules notification of when all messages has been written
    /// </summary>
    /// <param name="asyncContinuation"></param>
    protected override void FlushAsync(AsyncContinuation asyncContinuation)
    {
        if (_previousTask == null)
        {
            InternalLogger.Debug("{0} Flushing Nothing", this.Name);
            asyncContinuation(null);
        }
        else
        {
            InternalLogger.Debug("{0} Flushing {1} items", this.Name, _requestQueue.Count + 1);
            _requestQueue.Enqueue(new AsyncLogEventInfo(null, asyncContinuation));
        }
    }

    /// <summary>
    /// Closes Target by updating CancellationToken
    /// </summary>
    protected override void CloseTarget()
    {
        _cancelTokenSource.Cancel();
        _requestQueue.Clear();
        _previousTask = null;
        base.CloseTarget();
    }

    /// <summary>
    /// Releases any managed resources
    /// </summary>
    /// <param name="disposing"></param>
    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
        if (disposing)
            _cancelTokenSource.Dispose();
    }

    private void TaskStartNext()
    {
        AsyncLogEventInfo logEvent;
        do
        {
            lock (this.SyncRoot)
            {
                if (_requestQueue.Count == 0)
                {
                    _previousTask = null;
                    break;
                }

                logEvent = _requestQueue.Dequeue();
            }
        } while (!TaskCreation(logEvent));
    }

    private bool TaskCreation(AsyncLogEventInfo logEvent)
    {
        try
        {
            if (_cancelTokenSource.IsCancellationRequested)
            {
                logEvent.Continuation(null);
                return false;
            }

            if (logEvent.LogEvent == null)
            {
                InternalLogger.Debug("{0} Flush Completed", this.Name);
                logEvent.Continuation(null);
                return false;
            }

            var newTask = WriteAsyncTask(logEvent.LogEvent, _cancelTokenSource.Token);
            if (newTask == null)
            {
                InternalLogger.Debug("{0} WriteAsync returned null", this.Name);
            }
            else
            {
                lock (this.SyncRoot)
                {
                    _previousTask = newTask;
                    _previousTask.ContinueWith(_taskCompletion, logEvent.Continuation, _cancelTokenSource.Token);
                    if (_previousTask.Status == TaskStatus.Created)
                        _previousTask.Start(TaskScheduler.Default);
                }
                return true;
            }
        }
        catch (Exception ex)
        {
            try
            {
                InternalLogger.Error(ex, "{0} WriteAsync failed on creation", this.Name);
                logEvent.Continuation(ex);
            }
            catch
            {
                // Don't wanna die
            }
        }
        return false;
    }

    private void TaskCompletion(Task completedTask, object continuation)
    {
        try
        {
            if (completedTask.IsCanceled)
            {
                if (completedTask.Exception != null)
                    InternalLogger.Warn(completedTask.Exception, "{0} WriteAsync was cancelled", this.Name);
                else
                    InternalLogger.Info("{0} WriteAsync was cancelled", this.Name);
            }
            else if (completedTask.Exception != null)
            {
                InternalLogger.Warn(completedTask.Exception, "{0} WriteAsync failed on completion", this.Name);
            }
            ((AsyncContinuation)continuation)(completedTask.Exception);
        }
        finally
        {
            TaskStartNext();
        }
    }
}

A: There is WriteAsyncLogEvent
public void WriteAsyncLogEvent(
    AsyncLogEventInfo logEvent
)

Look at the usage in the tests section, for example ConsoleTargetTests
try
{
    var exceptions = new List<Exception>();
    target.Initialize(null);
    target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message1").WithContinuation(exceptions.Add));
    target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message2").WithContinuation(exceptions.Add));
    target.WriteAsyncLogEvents(
        new LogEventInfo(LogLevel.Info, "Logger1", "message3").WithContinuation(exceptions.Add),
        new LogEventInfo(LogLevel.Info, "Logger2", "message4").WithContinuation(exceptions.Add),
        new LogEventInfo(LogLevel.Info, "Logger2", "message5").WithContinuation(exceptions.Add),
        new LogEventInfo(LogLevel.Info, "Logger1", "message6").WithContinuation(exceptions.Add));
    Assert.Equal(6, exceptions.Count);
    target.Close();
}
finally
{
    Console.SetOut(oldConsoleOutWriter);
}

Look also at the wiki section Asynchronous processing and wrapper targets for more details

Because asynchronous processing is a common scenario, NLog supports a
  shorthand notation to enable it for all targets without the need to
  specify explicit wrappers. You can simply set async="true" on targets
  element and all your targets within that element will be wrapped with
  the AsyncWrapper target.

<nlog>
  <targets async="true">
    <!-- all targets in this section will automatically be asynchronous -->
  </targets>
</nlog>


text:
Q: Why Isn't Image Displaying From SDCard? I'm a noob to android development and I am trying to display an image from the SDCard in an ImageButton.  I have the permission READ_EXTERNAL_STORAGE in my manifest and I am using the aFileChooser library to find the files on my sdcard. When I click my imagebutton it allows me to select my desired image but doesn't display the image in the image button.  Instead the ImageButton disappears completely. I don't get an error, but the ImageButton goes blanks.  Any help is greatly appreciated.
private void showChooser() {
        // Use the GET_CONTENT intent from the utility class
        Intent target = FileUtils.createGetContentIntent();
        // Create the chooser Intent
        Intent intent = Intent.createChooser(
                target, getString(R.string.chooser_title));
        try {
            startActivityForResult(intent, REQUEST_CODE);
        } catch (ActivityNotFoundException e) {
            // The reason for the existence of aFileChooser
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case REQUEST_CODE:
            // If the file selection was successful
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    // Get the URI of the selected file
                    final Uri uri = data.getData();

                    try {
                        // Create a file instance from the URI
                        final File file = FileUtils.getFile(uri);
                        Toast.makeText(RegisterActivity.this,"File Selected: "+file.getAbsolutePath(), Toast.LENGTH_LONG).show();
                        Log.e("File Path", file.getAbsolutePath());// Returns /external/images/media/1830
                        Log.e("BMP NULL", bmp.toString()); //Throws NullPointerException
                        Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath());//Seems to work fine here
                        userpic.setImageBitmap(bmp);  //ImageButton disappears/goes blank here.
                    } catch (Exception e) {
                        Log.e("FileSelectorTestActivity", "File select error", e);
                    }
                }
            }
            break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

A: For aFileChooser Android plugin , when you club it to your program, you need to add activity.
You haven't added following code in manifest
<activity
            android:name="com.ipaulpro.afilechooser.FileChooserActivity"
            android:exported="false"
            android:icon="@drawable/ic_chooser"
            android:label="@string/choose_file"
            android:theme="@style/ChooserTheme" >
            <intent-filter>
                <action android:name="android.intent.action.GET_CONTENT" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.OPENABLE" />

                <data android:mimeType="*/*" />
            </intent-filter>
</activity>

A: i can help you with a solution without fileChooser...
hope it will help
only check if data != NULL,
and send a request code!
public final int SELECT_PICTURE = 324234; //some value

first
...
        ContentValues values = new ContentValues();
        String title = "blabla";
        String descritpion = "blabla";
        values.put(MediaStore.Images.Media.TITLE, title);
        values.put(MediaStore.Images.Media.DESCRIPTION, descritpion);
        imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(takePhotoIntent, SELECT_PICTURE);

...
then
if (requestCode == SELECT_PICTURE && data != null)
    try {
                    // !!! could be every format!!!
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                    if (cursor == null) {
                        Toast.makeText(getApplicationContext(),"imageunguilty", Toast.LENGTH_SHORT).show();
                        break;
                    }
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    File src = new File(picturePath);
                    Bitmap b = decodeFile(src.getAbsolutePath());
                    //here recommended to resize your bitmap due to OutOfMemoryError!!!
                    if (b != null) {
                        // UpdatePicture

                    } else {
                        Toast.makeText(getApplicationContext(), "no image selected?", Toast.LENGTH_SHORT).show();
                    }
                } catch (OutOfMemoryError e) {
                    Log.e("Pictures", "" + e.getMessage());
                }

in your code
    Log.e("BMP NULL", bmp.toString()); //Throws NullPointerException
because bmp is not defined before!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I show a row in SSRS when no data is available? My code in the first text box in a tablix row is as follows:
=IIF(CountRows("DataSet") = 0, "Row Label", (IIF(RowNumber("ThisTablix") = 1, "Row Label", "")))

My understanding of the logic is that:

*

*If the number of rows returned in the data set "DataSet" is 0, then the row should appear with a text box that says "Row Label"

*If data is available in "DataSet" then if this is the first row in the tablix, the textbox should say "Row Label".

However when I attempt to run the report without any data, the row does not seem to be appearing.
Any pointers would be appreciated.

A: I think your point 1 is incorrect.  If zero rows are returned, your textbox will never be evaluated.  Look for the NoRowsMessage property, and set it.  Also see this question.


text:
Q: CRYPT_INTEGER_BLOB to decimal string How can i convert the SerialNumber member of a CERT_INFO structure to a string representation in base 10 preferable using C/C++
The SerialNumber is CRYPT_INTEGER_BLOB with contains two members the length, and an array of bytes.
For cases where the SerialNumber has a maximum if 8 bytes is easy to copy the bytes to a long long and then use standard ostream operator to convert this to a string in base 10, but not sure how can i deal with case that the serial number contains more that 8 bytes, according to X509 spec CAs should handle up to 20 bytes.

A: If efficiency is not an issue you could use a biginteger implementation (such as this one: https://mattmccutchen.net/bigint/) and build the integer up from the byte array by doing something like this:
void print_dec(const char *byte_array, const size_t len)
{
    BigInteger a = 0;

    for (int i = 0; i < len; i++) {
        const char &byte = byte_array[i];

        for (int bit = 7; bit >= 0; bit--) {
            a = a*2 + ((byte >> bit) & 0x01);
        }
    }

    std::cout << a << '\n' << std::endl;
}

(This code is untested)

A: CryptBinaryToString:
DWORD len = 1024;
auto sn = new wchar_t[len];
CryptBinaryToString(
    pCertContext->pCertInfo->SerialNumber.pbData,
    pCertContext->pCertInfo->SerialNumber.cbData,
    CRYPT_STRING_HEXRAW,
    sn,
    &len);

The result can be like this b910cfe1ba35ecd2.


text:
Q: Theorems only valid for huge numbers I am trying to find a theorem that is valid only for very large numbers.
Example:
There are numbers which have more than 100 distinct factors.
Above theorem satisfies this condition, but it is a trivial one. What I would like is not a trivial one just for the purpose of being for huge numbers. I mean the huge number part should be a side effect rather than main focus.
I want to use it to show that even if you use brute force, trying up to hundred digit numbers, it may still not be successful proof.
Thank you


text:
Q: Permalinks randomly break and start getting 404 I'm working on a Wordpress instance with some plugins.
Everything works great after it starts serving 404 code. Seems to be random because everything works fine and in some moment the rewrite rules seems to break and the links stops working.
Sometimes it is happening when I update a content (we are using custom content types with this plugin https://wordpress.org/plugins/custom-content-type-manager/) but sometimes without touch anything (for example a weekend in the middle of the night).
We have been checking all the solutions we found but nothing works. The htaccess has the correct permissions and it is rewriting well the urls.
After debuging Wordpress, the problem seems to be that for some reason, it is reseting the rewrite rules to other than the correct ones (here you can find both dumps, the one when the site serves 404 first, and the second one with the correct rules https://es.forums.wordpress.org/topic/permalinks-error-404?replies=5#post-53705).
Also, we check what was the wp-cron running but we didn't find any plugin that touch the rules (I am not sure if WP doed anything with the rules periodically).
Thanks in advance.
Germán

A: I'm seeing this with a multisite install. It seems to correspond to codebase changes in WP core.


text:
Q: Inflate fragment just once So, I have this code inside a setOnClickListener:
helpFragment = HelpFragment.newInstance()
            supportFragmentManager
                .beginTransaction() // Começar a transição
                .replace(R.id.container, helpFragment)
                .addToBackStack(helpFragment.toString())
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                .commit() // Aplicar as alterações
}

But the problem is, every time I click the button a new instance of the fragment is instantiated. With that, for example, if I click 10 times in the button, I will have 9 fragments added to backstack and 1 visible. How can I create just one instance of the fragment? I have tried:
if (helpFragment == null)

But that obviously doesn't work...

A: Adding a Fragment to the back stack will retain fragments in the stack so that you can navigate back when needed.
You can still use the back stack but you have to check if the fragment is already added so that you don't have duplicated instances of the fragment in the stack.
E.g.
val helpFragment = HelpFragment.newInstance()
val isInBackstack = supportFragmentManager.findFragmentByTag(helpFragment.toString())
if (!isInBackstack) {
    supportFragmentManager
        .beginTransaction() // Começar a transição
        .replace(R.id.container, helpFragment)
        .addToBackStack(helpFragment.toString())
        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
        .commit() // Aplicar as alterações
}

A: If you use addToBackStack, it'll always save the fragments to the backstack. Remove that line to not add the fragment to backstack. addToBackStack is used when there are multiple changes to the transaction, then all the changes are added in stack, and pressing back button will then restore those transactions one by one.
helpFragment = HelpFragment.newInstance()
            supportFragmentManager
                .beginTransaction() // Começar a transição
                .replace(R.id.container, helpFragment)
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                .commit() // Aplicar as alterações
}

A: It is better to see whole codebase of your problem. You can solve it with Kotlin's lazy. Check out this topic


text:
Q: Deezer sdk android : seek with the TrackPlayer class I initialized my TrackPlayer like this :
trackPlayer = new TrackPlayer((Application) context.getApplicationContext(), deezerConnect, new WifiAndMobileNetworkStateChecker());
trackPlayer.playTrack(trackId);

Then, I want to seek into the track with this code :
if (trackPlayer != null && trackPlayer.isAllowedToSeek()) {
trackPlayer.seek(newPositionInMs);
}

I get this error :
java.lang.IllegalStateException: Unable to retrieve AudioTrack pointer for getSampleRate()
            at android.media.AudioTrack.native_get_playback_rate(Native Method)

If everyone can help me,
Thanks

A: This issue might happen if you try to seek too soon. When you call playTrack(), the player needs to fetch the requested track information, and download the track, which means that the player might not be initialised yet when you call the seek method.
You might want to wait for the player  to be in the READY or PLAYING state before seeking.
To do so, just add a PlayerStateChangedListener on your player.


text:
Q: XCode 8 enable indexing I tried the following two commands in the terminal window with sudo and also restarting the machine and Xcode, and indexing didn't turn on.
defaults delete com.apple.dt.XCode IDEIndexDisable

and
defaults write com.apple.dt.XCode IDEIndexDisable 0

I have a swift project and indexing does not turn on when I clean the project.  What am I doing wrong?


text:
Q: Can k-means clustering error ever increase? I have implemented k-means clustering algorithm for 20-dimensional histograms.  It seems to be working well on 2-dimensional histograms.
Occassionally, the sum of squared errors will increase slightly after an iteration.  Is this normal, or a sign of an underlying bug?
If it is possible to increase the SSE, can anyone provide an example that I can visualise?

A: The assignment must not increase.
Seems as if you have a bug somewhere. Maybe you are using something other than squared Euclidean distance?
SSE = sum of squared errors, not sum of distances or something else based on distances.


text:
Q: How can I call a concrete Coffeecript function from html I have an app that uses HTML, and Coffeescript in the frontend. I recently made it possible to change the language thanks to i18next.
Now I have some buttons that change my window.userLang to the different languages, but the user has to refresh some elements of the app to see it translated.
My problem comes because I need the translations made without refreshing the HTML.
In the app, I use Craftyjs, so what I need to know is how can (if possible) from HTML file, call a function that it's defined in Craftyjs.
The function I want to call is: Crafty.scene("main").
Thanks all!

A: Create a global name space defined above where your scripts are included. Then in your javascript you can define the functions you need as fields on that namespace.
<script>
  var MySweetWebApp = {};
</script>
<script src="..."></script>

... Inside JS file ....
MySweetWebApp.Crafty = { ... }

... From Anywhere ...
MySweetWebApp.Crafty.scene('main');


text:
Q: How to make a loop repeat another loop? The code below gives you a number close to pi when you run the program. It takes the user input for the number of darts you want thrown per trial, and uses that to come up with the number close to pi. I need to make the code run for a specific number of trials, but can't seem to make it work. How do I do this?
    System.out.print("How many darts per trial? ");
    int darts = in.nextInt();
    System.out.print("How many trials? ");
    int trials = in.nextInt();

    //The code below this represents 1 trial
    for(int i = 0; i < darts; i++)
    {
        xInt[i] = (Math.random() * (upper - lower)) + lower;
        yInt[i] = (Math.random() * (upper - lower)) + lower;
        c2[i] = Math.pow(xInt[i], 2) + Math.pow(yInt[i], 2);
        c[i] = Math.sqrt(c2[i]);

        if(c[i] <= 1)
        {
            hits++;
        }
    }
    double answer = 4 * ((double)hits / (double)darts);
    System.out.println(answer);

If I added the for-loop for the trials (see below), then it adds up all of the answers and prints the sum
for(int n = 0; n < trials; n++)
    {
        for(int i = 0; i < darts; i++)
        {
            xInt[i] = (Math.random() * (upper - lower)) + lower;
            yInt[i] = (Math.random() * (upper - lower)) + lower;
            c2[i] = Math.pow(xInt[i], 2) + Math.pow(yInt[i], 2);
            c[i] = Math.sqrt(c2[i]);
            if(c[i] <= 1)
                hits++;
        }
    }

    double answer = 4 * ((double)hits / (double)darts);
    System.out.println(answer);

It should print out something like this when you are finished.
Trial [1]: pi = 3.11341744
Trial [2]: pi = 3.04824237
Trial [3]: pi = 3.33281081
Trial [4]: pi = 3.40901039

A: You need to reset the number of hits for each trial by adding a hits=0; right after the trials for loop
Furthermore move your calculation and print statement inside the for loop.
Like this:
for(int n = 0; n < trials; n++)
{
    hits=0;
    for(int i = 0; i < darts; i++)
    {
        xInt[i] = (Math.random() * (upper - lower)) + lower;
        yInt[i] = (Math.random() * (upper - lower)) + lower;
        c2[i] = Math.pow(xInt[i], 2) + Math.pow(yInt[i], 2);
        c[i] = Math.sqrt(c2[i]);
        if(c[i] <= 1)
            hits++;
    }
    double answer = 4 * ((double)hits / (double)darts);
    System.out.println(answer);
}

This should fix it if i'm understanding you correctly.


text:
Q: bash unzip retaining partial directory structure Clients submit large (1.5gigs, >10,000 files) zip file with their directory structure from clients OUTPUT directory.
I want to bash unzip to my INPUT directory, preserving their directory structure also, BUT NOT ENTIRE directory structure.
Example, if their zip file contains the files:
/home/base/data/output/able/file1.xml
/home/base/data/output/able/file2.xml
/home/base/data/output/able/file3.xml
/home/base/data/output/baker/file1.xml
/home/base/data/output/baker/file2.xml
/home/base/data/output/baker/file3.xml
/home/base/data/output/charlie/file1.xml
/home/base/data/output/charlie/file2.xml
/home/base/data/output/charlie/file3.xml
(this goes on for thousands of files in about a dozen unique directories)

I want to unzip them to my INPUT directory as below:
../input/able/file1.xml
../input/able/file2.xml
../input/able/file3.xml
../input/baker/file1.xml
../input/baker/file2.xml
../input/baker/file3.xml
../input/charlie/file1.xml
../input/charlie/file2.xml
../input/charlie/file3.xml

So far I tried:
unzip BIGFILE.zip   /output/   input   --(*) before and after /output/

which does unzip all xml files with the directory structure of able/baker/charlie, etc.
HOWEVER, it also unpacks the entire file structure BEFORE /output:
../input/home/base/data/output/able/file1.xml
../input/home/base/data/output/able/file2.xml
../input/home/base/data/output/able/file3.xml
../input/home/base/data/output/baker/file1.xml
../input/home/base/data/output/baker/file2.xml
../input/home/base/data/output/baker/file3.xml
../input/home/base/data/output/charlie/file1.xml
../input/home/base/data/output/charlie/file2.xml
../input/home/base/data/output/charile/file3.xml

Probably can't be done in a one liner, but haven't found any scripts that would read in the partial directory a couple thousand files, then unzip them to a specific directory.
Any thoughts?


text:
Q: SQL Server Agent Job Next Run DateTime Stuck In The Past The job is enabled, the schedule is enabled, the agent service is running, but the job is not running as it is supposed to. Looking in the Job Activity Monitor, it shows a Next Run that is actually in the past.
Running the job manually will cause the Next Run to advance to the correct scheduled time for a new run, but when the time comes, the job still won't run.
How is this odd issue fixed?

A: This happened because you did a mass disable and then re-enable by updating the enabled flag in msdb.dbo.sysjobs after a massive outage; instead of doing things the right way and using the stored procedure,
sp_update_job.
All of the jobs that were enabled one-by-one via the GUI worked fine, it was just those mass enabled that were a problem. Doing a quick disable then enable resolved all the issues.
See link for further info:
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-update-job-transact-sql?redirectedfrom=MSDN&view=sql-server-ver15
Syntax:
EXEC dbo.sp_update_job  @job_name = N'[Your Job's Name HERE]',
@enabled = 0 --- This disables, set to 1 to enable;

Don't update system tables directly next time.


text:
Q: What's the density of primes by this measure, as a value of the Zeta function or otherwise? If we define the morphism from the positive integers to the interval $(0,1]$ as follows:
$f(x)=\left(\frac{1}{x+1},\frac{1}{x}\right]$
Then we can measure the density of any set of positive integers as a proportion of the whole, e.g. the odd numbers as follows:
$\displaystyle\sum_{x = 1}^{\infty} \left(\frac{1}{2x-1}-\frac{1}{2x}\right)=\ln{2}$
Obviously the even numbers have density $1-\ln{2}$ and every set of multiples of some integer has measure less than $1$, with the set only being fully closed if we include the point at infinity in our sum.
I presume this is a known measure?
What is the density of the prime numbers by this measure?
$\displaystyle\sum_{p\in\text{prime}} \left(\frac{1}{p}-\frac{1}{p+1}\right)\approx0.3302$
It looks to simplify to $\displaystyle\sum_{p\in\text{prime}}\frac{1}{p(p+1)}$
It looks like this has something to do with the relationship of the Zeta function to the distribution of primes.  I imagine this sum over primes can be translated into an Euler product, a Dirichlet series and ultimately into a value of the Zeta function but I'm struggling to see how to proceed further.

A: Use the geometric series $$\frac{1}{p+1} = \frac{1}{p} \frac{1}{1+\frac1p} = \sum_{k=1}^\infty \frac{(-1)^{k+1}}{p^{k}}$$ thus $$\sum_p \frac{1}{p}-\frac{1}{p+1} = \sum_{k=2}^\infty (-1)^{k} P(k) \\= \sum_{k=2}^\infty (-1)^{k} \sum_{n=1}^\infty \frac{\mu(n)}{n} \log \zeta(nk)=\sum_{m=1}^\infty (\frac{\mu(m)}{m}-a_m) \log \zeta(m)$$ where $a_m = \sum_{d | m} (-1)^{m/d+1} \frac{\mu(d)}{d}=\prod_{p^k \| m} a_{p^k}$ and $P(s) = \sum_p p^{-s} = \sum_{n=1}^\infty \frac{\mu(n)}{n} \log \zeta(ns)$


text:
Q: SIP 408:Request Timeout while creating account in zoiper I have downloaded zoiper220-linux.tar.gz and unzipped It but when I am trying to create account in it shows
SIP 408: Request timeout error
I have been trying this for days
Thanks in advance

A: You have to first register in soft phone with the username and password set in sip.conf
For more details check the link


text:
Q: C# 7.0 case pattern matching on generic parameter Is there a reason for not being able to handle a generic variable by the type pattern? Please consider the code:
public static int CompareValues<T>(T left, T right)
{
  switch (left)
  {
    case IComparable<T> comparableDif:
      return comparableDif.CompareTo(right);
    case System.Numerics.Complex c:
      return c.Magnitude
        .CompareTo(((System.Numerics.Complex)(object)right).Magnitude);
    default:
      throw new ArgumentException("unsupported type");
  }
}

The first match on the IComparable interface is ok, but the second one does not compile. Why do I have to use this boxing workaround?
case object o when o is System.Numerics.Complex:
  return ((System.Numerics.Complex)o).Magnitude
    .CompareTo(((System.Numerics.Complex)(object)right).Magnitude);

A: This is a consequence of how pattern matching in C# 7.0 is defined: for your type pattern to compile, a cast from T to Complex would have to exist, but it does not. The C# team realized it was a mistake to require this, so this issue was fixed in C# 7.1.


text:
Q: Downgrading Elastic Search from 7 to 6? I am trying to downgrade Elastic Search from 7 to 6 as the application I am using only works on 6.
When I install 6 I get boosted to 7 for some reason:
{
  "name" : "activecollab-v6",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "D7qs_zqTTX6Rv8AiE_ioqw",
  "version" : {
    "number" : "7.1.0",
    "build_flavor" : "default",
    "build_type" : "deb",
    "build_hash" : "606a173",
    "build_date" : "2019-05-16T00:43:15.323135Z",
    "build_snapshot" : false,
    "lucene_version" : "8.0.0",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

How do I ensure I am downgraded? The following is my install recipe and below that is the recipe report which shows that elastic search is installed too.
# Install Elastic Search

echo ">> Installing Elastic GPG Key"
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -

echo ">> Install apt-transport-https"
apt install apt-transport-https

echo ">> Adding deb package"
echo "deb https://artifacts.elastic.co/packages/6.x/apt stable main" | sudo tee -a /etc/apt/sources.list.d/elastic-6.x.list

echo ">> Updating apt"
apt update

echo ">> Installing Java and Elastic Search"
apt -y install default-jre elasticsearch

echo ">> Java Installed"
echo ">> Elastic Search Installed"

echo ">> Scheduling Elasticsearch"
/bin/systemctl daemon-reload
/bin/systemctl enable elasticsearch.service

echo ">> Starting Elasticsearch"
systemctl start elasticsearch.service

echo ">> Running on port 9200. Make sure to add a firewall rule if you need external access."
echo ">> You can check the status by running 'curl 'http://localhost:9200'. Note: may take a few seconds before elasticsearch is fully started."

Recipe Report
>> Installing Elastic GPG Key
Warning: apt-key output should not be parsed (stdout is not a terminal)
OK
>> Install apt-transport-https

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

Reading package lists...
Building dependency tree...
Reading state information...
apt-transport-https is already the newest version (1.6.10).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
>> Adding deb package
deb https://artifacts.elastic.co/packages/6.x/apt stable main
>> Updating apt

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

Get:1 http://ppa.launchpad.net/chris-lea/redis-server/ubuntu bionic InRelease [15.4 kB]
Get:2 http://mirrors.digitalocean.com/ubuntu bionic InRelease [242 kB]
Get:3 http://security.ubuntu.com/ubuntu bionic-security InRelease [88.7 kB]
Get:4 http://archive.ubuntu.com/ubuntu bionic InRelease [242 kB]
Get:5 http://ppa.launchpad.net/nginx/development/ubuntu bionic InRelease [15.4 kB]
Get:6 http://ppa.launchpad.net/ondrej/apache2/ubuntu bionic InRelease [20.7 kB]
Get:7 http://ppa.launchpad.net/ondrej/php/ubuntu bionic InRelease [20.8 kB]
Get:8 http://ppa.launchpad.net/webupd8team/java/ubuntu bionic InRelease [15.4 kB]
Get:9 https://deb.nodesource.com/node_10.x bionic InRelease [4584 B]
Hit:10 https://repos.sonar.digitalocean.com/apt main InRelease
Get:11 http://mirrors.digitalocean.com/ubuntu bionic-updates InRelease [88.7 kB]
Get:12 http://mirrors.digitalocean.com/ubuntu bionic-backports InRelease [74.6 kB]
Ign:13 https://artifacts.elastic.co/packages/6.x/apt stable InRelease
Get:14 http://ppa.launchpad.net/chris-lea/redis-server/ubuntu bionic/main amd64 Packages [1004 B]
Get:15 http://ppa.launchpad.net/chris-lea/redis-server/ubuntu bionic/main Translation-en [584 B]
Ign:16 https://artifacts.elastic.co/packages/7.x/apt stable InRelease
Get:17 https://artifacts.elastic.co/packages/6.x/apt stable Release [5116 B]
Get:18 https://artifacts.elastic.co/packages/7.x/apt stable Release [5116 B]
Get:19 https://artifacts.elastic.co/packages/6.x/apt stable Release.gpg [473 B]
Get:20 https://artifacts.elastic.co/packages/7.x/apt stable Release.gpg [473 B]
Get:21 http://security.ubuntu.com/ubuntu bionic-security/main amd64 Packages [349 kB]
Get:22 http://security.ubuntu.com/ubuntu bionic-security/main Translation-en [125 kB]
Get:23 http://security.ubuntu.com/ubuntu bionic-security/restricted amd64 Packages [4296 B]
Get:24 http://security.ubuntu.com/ubuntu bionic-security/restricted Translation-en [2192 B]
Get:25 http://security.ubuntu.com/ubuntu bionic-security/universe amd64 Packages [245 kB]
Get:26 http://security.ubuntu.com/ubuntu bionic-security/universe Translation-en [140 kB]
Get:27 http://security.ubuntu.com/ubuntu bionic-security/multiverse amd64 Packages [4004 B]
Get:28 http://security.ubuntu.com/ubuntu bionic-security/multiverse Translation-en [2060 B]
Get:29 http://archive.ubuntu.com/ubuntu bionic/universe amd64 Packages [8570 kB]
Get:30 http://archive.ubuntu.com/ubuntu bionic/universe Translation-en [4941 kB]
Get:31 http://ppa.launchpad.net/nginx/development/ubuntu bionic/main amd64 Packages [4264 B]
Get:32 http://ppa.launchpad.net/nginx/development/ubuntu bionic/main Translation-en [4328 B]
Get:33 http://ppa.launchpad.net/ondrej/apache2/ubuntu bionic/main amd64 Packages [8528 B]
Get:34 http://ppa.launchpad.net/ondrej/apache2/ubuntu bionic/main Translation-en [4052 B]
Get:35 http://ppa.launchpad.net/ondrej/php/ubuntu bionic/main amd64 Packages [45.1 kB]
Get:36 http://ppa.launchpad.net/ondrej/php/ubuntu bionic/main Translation-en [22.1 kB]
Get:37 http://mirrors.digitalocean.com/ubuntu bionic/main amd64 Packages [1019 kB]
Get:38 http://mirrors.digitalocean.com/ubuntu bionic/main Translation-en [516 kB]
Get:39 http://mirrors.digitalocean.com/ubuntu bionic/restricted amd64 Packages [9184 B]
Get:40 http://mirrors.digitalocean.com/ubuntu bionic/restricted Translation-en [3584 B]
Get:41 http://mirrors.digitalocean.com/ubuntu bionic/universe amd64 Packages [8570 kB]
Get:42 https://deb.nodesource.com/node_10.x bionic/main amd64 Packages [767 B]
Get:43 http://mirrors.digitalocean.com/ubuntu bionic/universe Translation-en [4941 kB]
Get:44 http://mirrors.digitalocean.com/ubuntu bionic/multiverse amd64 Packages [151 kB]
Get:45 http://mirrors.digitalocean.com/ubuntu bionic/multiverse Translation-en [108 kB]
Get:46 http://mirrors.digitalocean.com/ubuntu bionic-updates/main amd64 Packages [618 kB]
Get:47 http://mirrors.digitalocean.com/ubuntu bionic-updates/main Translation-en [229 kB]
Get:48 http://mirrors.digitalocean.com/ubuntu bionic-updates/restricted amd64 Packages [6996 B]
Get:49 http://mirrors.digitalocean.com/ubuntu bionic-updates/restricted Translation-en [3076 B]
Get:50 http://mirrors.digitalocean.com/ubuntu bionic-updates/universe amd64 Packages [937 kB]
Get:51 http://mirrors.digitalocean.com/ubuntu bionic-updates/universe Translation-en [274 kB]
Get:52 http://mirrors.digitalocean.com/ubuntu bionic-updates/multiverse amd64 Packages [6644 B]
Get:53 http://mirrors.digitalocean.com/ubuntu bionic-updates/multiverse Translation-en [3556 B]
Get:54 http://mirrors.digitalocean.com/ubuntu bionic-backports/main amd64 Packages [1024 B]
Get:55 http://mirrors.digitalocean.com/ubuntu bionic-backports/main Translation-en [448 B]
Get:56 http://mirrors.digitalocean.com/ubuntu bionic-backports/universe amd64 Packages [3496 B]
Get:57 http://mirrors.digitalocean.com/ubuntu bionic-backports/universe Translation-en [1604 B]
Get:58 https://artifacts.elastic.co/packages/6.x/apt stable/main amd64 Packages [49.1 kB]
Get:59 https://artifacts.elastic.co/packages/7.x/apt stable/main amd64 Packages [6534 B]
Fetched 32.8 MB in 8s (4196 kB/s)
Reading package lists...
Building dependency tree...
Reading state information...
7 packages can be upgraded. Run 'apt list --upgradable' to see them.
W: Target Packages (main/binary-amd64/Packages) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:2
W: Target Packages (main/binary-all/Packages) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:2
W: Target Translations (main/i18n/Translation-en) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:2
W: Target CNF (main/cnf/Commands-amd64) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:2
W: Target CNF (main/cnf/Commands-all) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:2
W: Target Packages (main/binary-amd64/Packages) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:3
W: Target Packages (main/binary-all/Packages) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:3
W: Target Translations (main/i18n/Translation-en) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:3
W: Target CNF (main/cnf/Commands-amd64) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:3
W: Target CNF (main/cnf/Commands-all) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:3
W: Target Packages (main/binary-amd64/Packages) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:4
W: Target Packages (main/binary-all/Packages) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:4
W: Target Translations (main/i18n/Translation-en) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:4
W: Target CNF (main/cnf/Commands-amd64) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:4
W: Target CNF (main/cnf/Commands-all) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:4
W: Target Packages (main/binary-amd64/Packages) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:2
W: Target Packages (main/binary-all/Packages) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:2
W: Target Translations (main/i18n/Translation-en) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:2
W: Target CNF (main/cnf/Commands-amd64) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:2
W: Target CNF (main/cnf/Commands-all) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:2
W: Target Packages (main/binary-amd64/Packages) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:3
W: Target Packages (main/binary-all/Packages) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:3
W: Target Translations (main/i18n/Translation-en) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:3
W: Target CNF (main/cnf/Commands-amd64) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:3
W: Target CNF (main/cnf/Commands-all) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:3
W: Target Packages (main/binary-amd64/Packages) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:4
W: Target Packages (main/binary-all/Packages) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:4
W: Target Translations (main/i18n/Translation-en) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:4
W: Target CNF (main/cnf/Commands-amd64) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:4
W: Target CNF (main/cnf/Commands-all) is configured multiple times in /etc/apt/sources.list.d/elastic-6.x.list:1 and /etc/apt/sources.list.d/elastic-6.x.list:4
>> Installing Java and Elastic Search

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

Reading package lists...
Building dependency tree...
Reading state information...
default-jre is already the newest version (2:1.11-68ubuntu1~18.04.1).
The following NEW packages will be installed:
  elasticsearch
0 upgraded, 1 newly installed, 0 to remove and 7 not upgraded.
Need to get 347 MB of archives.
After this operation, 572 MB of additional disk space will be used.
Get:1 https://artifacts.elastic.co/packages/7.x/apt stable/main amd64 elasticsearch amd64 7.1.0 [347 MB]
debconf: unable to initialize frontend: Dialog
debconf: (TERM is not set, so the dialog frontend is not usable.)
debconf: falling back to frontend: Readline
debconf: unable to initialize frontend: Readline
debconf: (This frontend requires a controlling tty.)
debconf: falling back to frontend: Teletype
dpkg-preconfigure: unable to re-open stdin:
Fetched 347 MB in 6s (57.1 MB/s)
Selecting previously unselected package elasticsearch.
(Reading database ...
(Reading database ... 5%
(Reading database ... 10%
(Reading database ... 15%
(Reading database ... 20%
(Reading database ... 25%
(Reading database ... 30%
(Reading database ... 35%
(Reading database ... 40%
(Reading database ... 45%
(Reading database ... 50%
(Reading database ... 55%
(Reading database ... 60%
(Reading database ... 65%
(Reading database ... 70%
(Reading database ... 75%
(Reading database ... 80%
(Reading database ... 85%
(Reading database ... 90%
(Reading database ... 95%
(Reading database ... 100%
(Reading database ... 91269 files and directories currently installed.)
Preparing to unpack .../elasticsearch_7.1.0_amd64.deb ...
Creating elasticsearch group... OK
Creating elasticsearch user... OK
Unpacking elasticsearch (7.1.0) ...
Processing triggers for ureadahead (0.100.0-21) ...
Setting up elasticsearch (7.1.0) ...
Created elasticsearch keystore in /etc/elasticsearch
Processing triggers for systemd (237-3ubuntu10.21) ...
Processing triggers for ureadahead (0.100.0-21) ...
>> Java Installed
>> Elastic Search Installed
>> Scheduling Elasticsearch
Synchronizing state of elasticsearch.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install enable elasticsearch
Created symlink /etc/systemd/system/multi-user.target.wants/elasticsearch.service → /usr/lib/systemd/system/elasticsearch.service.
>> Starting Elasticsearch
>> Running on port 9200. Make sure to add a firewall rule if you need external access.
>> You can check the status by running 'curl 'http://localhost:9200'. Note: may take a few seconds before elasticsearch is fully started.
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0

A: *

*There is no downgrade. Purge the install and start over.

*The DEB repository looks correct. Have you always had it like that? Because this cannot get you version 7.x.

Update:
I can see the line Get:59 https://artifacts.elastic.co/packages/7.x/apt stable/main amd64 Packages [6534 B] in your output, so you have added both the 6.x and the 7.x repository. Remove the 7.x repo (/etc/apt/sources.list.d/elastic-7.x.list), purge, and install again.
Alternatively you could purge elasticsearch and specify the version to install: sudo apt-get install elasticsearch=6.8.0. I think this is the version number you could pick, but you can verify what is available with apt-cache policy elasticsearch.

A: I was in the same position to downgrade the elasticsearch from 7 to 6 without losing the data. The easy trick I did was, removed the existing elasticsearch, and installed a new one. It worked for me. I would like to give you steps to downgrade. I was using ubuntu server. Hence,

*

*Stop the running server. sudo service elasticsearch stop

*Remove the elasticsearch: sudo apt-get remove elasticsearch

*Install the elasticsearch version 6.x

Installation reference link: Install elasticsearch in ubuntu
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
sudo apt-get install apt-transport-https
echo "deb https://artifacts.elastic.co/packages/6.x/apt stable main" | sudo tee -a /etc/apt/sources.list.d/elastic-6.x.list
sudo apt-get update && sudo apt-get install elasticsearch

Elasticsearch may start automatically. You can check the status: sudo service elasticsearch status. If it says failed then  you can restart it with: sudo service elasticsearch restart or sudo systemctl restart elasticsearch. It should restart the elasticsearch server.
Done.
Warning!

I can't guarantee that the data will be there. Hence, make sure to backup your data before doing this step. Yes, it is true that I didn't lose my data.


text:
Q: Let d1 and d2 be two metrices on X . Then $d(x,y)= d1(x,y)*d2(x,y)$ $x, y\in X$ is also metric on X? I'm able to solve three properties of metric such as

*

*$d(x,y)\geq 0$ for all $x, y \in X $

*$d(x,y)=0$ iff $x=y$

*$d(x,y)= d(y,x)$ for all $x, y \in X $
But facing problem to solve triangle inequality.
Please help me. Thanks in advance.

A: Certainly false. Try to show that the square of the usual metric on the real line is not a metric.

A: $|0-\frac12|^2 + |\frac12 - 1|^2 = \frac12 < 1 = |0-1|^2$ so $d_1 = d_2$ equal to the standard distance on $\Bbb R$ already gives a counterexample to the triangle inequality.


text:
Q: How to exclude certain files from authentication checks when using HttpAuthenticationMechanism When using our own implementation of HttpAuthenticationMechanism how does one prevent authentication checks being triggered for certain file types?
Eg. we do not want our Authentication bean to be triggered for static resource requests such as .js / .css files
Using Wildfly 26 (Java EE8)
UPDATE:
Have tried specifying static files in web.xml with no <auth-constraint> defined which is how the spec says this should be done, but I am still finding that validateRequest is firing for these files
<security-constraint>
    <web-resource-collection>
        <web-resource-name>Static Content</web-resource-name>
        <url-pattern>/jsJawrPath/*</url-pattern>
        <url-pattern>/cssJawrPath/*</url-pattern>
        <url-pattern>/javax.faces.resource/*</url-pattern>
        <url-pattern>/images/*</url-pattern>
        <url-pattern>/resources/*</url-pattern>
    </web-resource-collection>
</security-constraint>

Our authentication bean
@RequestScoped
@AutoApplySession
public class CustomAuthentication implements Serializable, HttpAuthenticationMechanism {

/**
 *
 */
private static final long serialVersionUID = 1L;

@Inject private Logger log;

/**
 * Note: this method is called for all requests (including public) to determine if authentication is required
 */
@Override
public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response,
        HttpMessageContext httpMessageContext) throws AuthenticationException {

    log.debug("Validating request {}",request.getRequestURI());

    //Authentication logic...

}

}
Then in the logs...
[10:44:30.476] DEBUG (com.myapp.security.CustomAuthentication)  Validating request /jsJawrPath/jawr_generator.js

FURTHER INFO:
The reason I am trying to deactivate HttpAuthenticationMechanism is I am trying to implement the Weld performance suggestions at the end of this article https://weld.cdi-spec.org/news/2016/10/25/tip3-performance/ to deactivate CDI contexts for static files, but when I add the org.jboss.weld.context.mapping param I get the Context is not active because HttpAuthenticationMechanism is trying to invoke validateRequest method.


text:
Q: Videos streaming on react Console log returns a 404 on the home page and param error when click on video Home.js

import React, {
  Component
} from "react";
import {
  Link
} from "react-router-dom";
import Header from "./Header";
import Footer from "./Footer";

export default class Home extends Component {
  constructor() {
    super();
    this.state = {
      videos: [],
    };
  }

  async componentDidMount() {
    try {
      const response = await fetch("http://localhost:4000/videos");
      const data = await response.json();
      this.setState({
        videos: [...data]
      });
    } catch (error) {
      console.log(error);
    }
  }

  render() {
    return ( <
      div className = "App-header" >
      <
      Header / >
      <
      div className = "container" >
      <
      div className = "row" > {
        this.state.videos.map((video) => ( <
          div className = "col-md-4"
          key = {
            video.id
          } >
          <
          Link to = {
            `/player/${video.id}`
          } >
          <
          div className = "card border-0" >
          <
          img src = {
            `http://localhost:4000${video.poster}`
          }
          alt = {
            video.name
          }
          /> <
          div className = "card-body" >
          <
          p > {
            video.name
          }
 <
          p > {
            video.duration
          }
 <
          /div> <
          /div> <
          /Link> <
          /div>
        ))
      } <
      /div> <
      /div> <
      Footer / >
      <
      /div>
    );
  }
}

Player.js

import React, { Component } from "react";
import Header from "./Header";
import Footer from "./Footer";
import { useParams } from "react-router-dom";

export default class Player extends Component {
  constructor(props) {
    super();
    this.state = {
      videoId: this.match.params.id,
      videoData: {},
    };
  }

  async componentDidMount() {
    try {
      const res = await fetch(
        `http://localhost:4000/video/${this.state.videoId}/data`
      );
      const data = await res.json();
      this.setState({ videoData: data });
    } catch (error) {
      console.log(error);
    }
  }

  render() {
    return (

        <video controls muted autoPlay>
          <source
            src={`http://localhost:4000/video/${this.state.videoId}`}
            type="video/mp4"
          ></source>
          <track
            label="English"
            kind="captions"
            srcLang="en"
            src={`http://localhost:4000/video/${this.state.videoId}/caption`}
            default
          ></track>
        </video>

{this.state.videoData.name}

    );
  }
}

server(app.js)

const express = require("express");
const fs = require("fs");
const thumbsupply = require("thumbsupply");
const cors = require("cors");

const videos = [
  {
    id: 0,
    poster: "/video/0/poster",
    duration: "3 mins",
    name: "Sample 1",
  },
  {
    id: 1,
    poster: "/video/1/poster",
    duration: "4 mins",
    name: "Sample 2",
  },
  {
    id: 2,
    poster: "/video/2/poster",
    duration: "2 mins",
    name: "Sample 3",
  },
];
const app = express();

app.use(cors());
app.get("/videos", (req, res) => res.json(videos));

app.get("/video/:id/data", (req, res) => {
  const id = parseInt(req.params.id, 10);
  res.json(videos[id]);
});

app.get("/video/:id", (req, res) => {
  const path = `assets/${req.params.id}.mp4`;
  const stat = fs.statSync(path);
  const fileSize = stat.size;
  const range = req.headers.range;
  if (range) {
    const parts = range.replace(/bytes=/, "").split("-");
    const start = parseInt(parts[0], 10);
    const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
    const chunksize = end - start + 1;
    const file = fs.createReadStream(path, { start, end });
    const head = {
      "Content-Range": `bytes ${start}-${end}/${fileSize}`,
      "Accept-Ranges": "bytes",
      "Content-Length": chunksize,
      "Content-Type": "video/mp4",
    };
    res.writeHead(206, head);
    file.pipe(res);
  } else {
    console.log("no range", range);
    const head = {
      "Content-Length": fileSize,
      "Content-Type": "video/mp4",
    };
    res.writeHead(200, head);
    fs.createReadStream(path).pipe(res);
  }
});

app.listen(4000, () => {
  console.log("Listening on port 4000");
});

In the console
on the Home page[The files are not found][1]
Player[When I click on one sample][2]
I would really like to know how to work around this. And when i play one video directly from the serve it has no errors.
[1]: https://i.stack.imgur.com/rH7jc.png
[2]: https://i.stack.imgur.com/TdSZI.png


text:
Q: mp4 video loading forever and does not open of Samsung TV I have two mp4 files one is working on Samsung TV and the second one is not working, it keep loading forever
I have checked the codec of both and the are the same , the only change is the bitrate is different, could that be the reason of not being able to play the video on TV
and if yes how to solve t using vlc program or any ffmpeg code that convert it


text:
Q: WordPress country list gone after installing this plugin https://wordpress.org/plugins/wc-china-checkout/, all my country list gone and only left China.
I try to deactive this plugin at still don't get back other country list.
How can I fix this without install new WordPress?

A: When you have installed the WC China Checkout Plugin, Selling location(s) option has change to only specific country and country will set as China. When you deactivated the plugin, the option was not changed. So we manually have to change that options in WP Backend.
Follow the following steps:
In wordpress backend, go to Woocommerce->Settings and in this page Selling location(s) under General options title.
In Selling location(s), change the dropdown as Sell to all countries


text:
Q: Trying to duel boot linux/windows with each OS on a different HD I'll try to do my best to explain the situation. So I want to boot linux/windows, but duel boot not just boot from the current hd.
Something I noticed when I went into the BIOS settings. I'm not sure if this is something that is causing this issue or what, but I can only one have one of the HD in the boot priority list at a time.
I have to go to boot options and go to Hard Drive BBS Priorities to switch to the other hard drive. Now when I switch the other one can't be in the main Boot Priority list. I have no clue as to why it is doing this.
I was told by a friend and through some research a "grub" screen should appear when I boot. What is a grub screen and could the reason above be why I don't see it?

A: The last time I installed ubuntu with windows it gave an option for dual boot. It would flash on the screen and allow you to choose which operating system to start. I believe you have an installation issue. Try reinstalling ensure you choose the dual boot options. All else fails you can load ubuntu on a USB drive and run it from there.


text:
Q: Find element by HTML in Cypress I've started implementing Cypress for some regression tests, and I'm trying to find a particular element in a list of elements. The elements are in this format:

    <input>

[navigation text]

On a single page, there are several of these. I'd like to try and target a specific on by the [navigation text], but it is possible for them to have similar text. My main example is one with "Profiles" and a second one with "Membership Profiles". So, doing cy.contains("Profiles") will give me the "Membership Profiles" element instead of "Profiles".
Please keep in mind, this is used in a function, like this:
Cypress.Commands.add('goTo', (places) =>
{
    // Navigate to the places
});

Where "places" is an array of pages to navigate to. So, I don't know the exact text I'm looking for in the function to say something like and !text === 'Membership Profiles'.
Does anyone know how I can grab the elements by the html content? This is the function I came up with:
Cypress.Commands.add('goTo', (places) =>
{
    for (let i = 0; i < places.length; i++)
    {
        let place = places[i];
        let navLinks = Cypress.$('.navigationIcon').toArray();
        navLinks.some((link) =>
        {
            if (link.innerHTML.includes(`>${place.name}</div>`))
            {
                cy.wrap(link).click();
                return true;
            }
        });
    }
});

but this is moving onto the next outer for loop iteration too fast and the second time through the navLinks variable pulls the same elements from the previous iteration.
Does Cypress have something built in to let me search by HTML? I've been looking around the documentation, but I can't find anything.

A: I came up with this, I haven't tested it but I believe it will do what you're after.
Cypress.Commands.add('goTo', place => {
  cy.get("div.navigationIcon > div > div").then($navs => {
    var $desiredNav = $navs.find($nav => {
      return $nav.text() == place;
    });

    cy.wrap($desiredNav).click();
});

To make it work with your places array, I'd do this, or the for loop could be placed in your tests:
Cypress.Commands.add('goToPlaces', places => {
  for (let i = 0; i < places.length; i++)
  {
    cy.goTo(places[i]);
  }
});

A: Thanks to Brendan's answer, I was able to get something working:
Cypress.Commands.add('navigateTo', (places) =>
{
    for (let i = 0; i < places.length; i++)
    {
        cy.goTo(places[i]);
    }
});

Cypress.Commands.add('goTo', (place) =>
{
    cy.log(`Navigating to ${place.name}`);

    cy.get('div.navigationIcon > div > div').then(($navLinks) =>
    {
        for (let i = 0; i < $navLinks.length; i++)
        {
            let $link = Cypress.$($navLinks[i]);
            if ($link.text().trim() === place.name)
            {
                // Click the link
                cy.wrap($link).click();
                break;
            }
        }

        // Ensure the url changed
        cy.url().should('include', place.uri);
    });
});

Note:
I pass in an array to the navigateTo function, like this:
cy.navigateTo([
    { name: 'Setup', uri: '#Setup:'},
    { name: 'Profiles', uri: '#Profiles:'},
    { name: 'Addresses', uri: '#Addresses:'}
]);

So that it'll navigate to the page, and then validate the move via the URL

A: Would this work for you?
cy.get('.navigationIcon .navigationText:contains("[navigation text]")')


text:
Q: Filtering numpy arrays I have two numpy arrays (plot_x and plot_y) of the same length where plot_y is calculated based off on the values of plot_x. I want to filter the first array plot_x such that 0.1<=plot_x<=10 and filter the second array plot_y such that it contains the values that corresponds to the values in plot_x so that I can plot them in a graph. How do I do that? Thank you in advance.

A: Filtering the data using Numpy-module is one of the basic operation, one of the simplest way is :
LOGIC :
1. Define Masking Matrix which we will use to filter the data.
condn = np.logical_and(X<5, X>0)

2. Using subscription operator [] we can access desired data with condition masking-matrix should follow Broadcasting-Properties.
X_u = X[condn]
Y_u = Y[condn]

CODE :
import numpy as np

X = np.array([-1, -3, 1,-5, 2, 3,-6, 4, 5,-9, 6, 7, 8])
Y = np.array([i**3 for i in X])

condn = np.logical_and(X<5, X>0)
# for shortcut you can use => condn = (X<5) & (X>0)

X_u = X[condn]
Y_u = Y[condn]
print(X_u)
print(Y_u)

OUTPUT :
[1 2 3 4]
[ 1  8 27 64]


text:
Q: How do I link in all of PyTorch with a pybind11 .so? I have a pybind11 c++ project which uses the pytorch c++ api:
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <math.h>
#include <torch/torch.h>

...

void f()
{
...
   torch::Tensor dynamic_parameters = torch::full({1}, /*value=*/0.5, torch::dtype(torch::kFloat64).requires_grad(true));
   torch::optim::SGD optimizer({dynamic_parameters}, /*lr=*/0.01);
...
}

PYBIND11_MODULE(reson8, m)
{
    m.def("my_function", &my_function, "");
}

I use distutils to compile this into a .so that can be imported in Python:
from distutils.core import setup, Extension

def configuration(parent_package='', top_path=None):
      import numpy
      from numpy.distutils.misc_util import Configuration
      from numpy.distutils.misc_util import get_info

      #Necessary for the half-float d-type.
      info = get_info('npymath')

      config = Configuration('',
                             parent_package,
                             top_path)
      config.add_extension('reson8',
                           ['reson8.cpp'],
                           extra_info=info,
                           include_dirs=["/home/ian/anaconda3/lib/python3.7/site-packages/pybind11/include",
                                          "/home/ian/anaconda3/lib/python3.8/site-packages/pybind11/include",
                                          "/home/ian/dev/hedgey/Engine/lib/libtorch/include",
                                          "/home/ian/dev/hedgey/Engine/lib/libtorch/include/torch/csrc/api/include"])

      return config

if __name__ == "__main__":
      from numpy.distutils.core import setup
      setup(configuration=configuration)

It compiles with no error, but on running "import reson8" in python I get this error:
importerror: undefined symbol: _ZTVN5torch5optim9OptimizerE

I'm unsure if it's whether pytorch hasn't been linked into my so (although the .so is 10mb which is rather large if it doesn't include pytorch, but maybe all pybind11 .so files are large.)
How can I solve this issue?

A: I eventually found I needed to use the Anaconda version of torchlib rather than my own, as well as using Torch's CppExtension.  Here is my working setup.py:
from distutils.core import setup, Extension
from torch.utils.cpp_extension import BuildExtension, CppExtension

def configuration(parent_package='', top_path=None):
      import numpy
      from numpy.distutils.misc_util import Configuration
      from numpy.distutils.misc_util import get_info

      #Necessary for the half-float d-type.
      info = get_info('npymath')

      config = Configuration('',
                             parent_package,
                             top_path)

      config.ext_modules.append(CppExtension(
                name='reson8',
                sources=['reson8.cpp'],
                extra_info=info,
                extra_compile_args=['-g', '-D_GLIBCXX_USE_CXX11_ABI=0'],
                extra_ldflags=['-ltorch_python'],
                include_dirs=["/home/ian/anaconda3/lib/python3.7/site-packages/pybind11/include",
                                          "/home/ian/anaconda3/lib/python3.8/site-packages/pybind11/include",
                                          "/home/ian/anaconda3/lib"
                                          ]
                                ))

      return config

if __name__ == "__main__":
      from numpy.distutils.core import setup
      setup(configuration=configuration)


text:
Q: Incoming SMS contents I wish I could get the contents of an incoming sms but its not working ..
In fact, no toast will appear, and nothing appears in the log, I think the myreceiver is not initialized ...
So here is the manifest, the onCreate the first activity, and my receiver java file : Manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.locateit.antholife.locateit">

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

<receiver android:name=".MyReceiver">
    android:enabled="true"
    android:exported="true" >
    <intent-filter android:priority="999">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

<application
    android:allowBackup="true"
    android:icon="@mipmap/locate"
    android:label="@string/app_nameprincipal"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <supports-screens
        android:anyDensity="true"
        android:largeScreens="true"
        android:normalScreens="true"
        android:resizeable="true"
        android:smallScreens="true"
        android:xlargeScreens="true" />

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Main2Activity"
        android:label="@string/title_activity_main2"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".Changelog"
        android:label="@string/title_activity_changelog"
        android:theme="@style/AppTheme.NoActionBar" />

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="AIzaSyBfmF3WWxsPhufZR5keiDNRy-33hJI1rvM" />

    <activity
        android:name=".lequipe"
        android:label="@string/nomequipe" />
    <activity
        android:name=".Setting"
        android:label="@string/title_activity_setting" />
    <activity android:name=".MDPinterne" />
    <activity android:name=".Bluetooth"></activity>
</application>

</manifest>

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

    ActionBar actionBar = getSupportActionBar();
    actionBar.hide();
    MyReceiver sms = new MyReceiver();
    Log.v("aha3", "smslancer");

and java file :
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}

@Override
public void onReceive(Context context, Intent intent) {

    Bundle extra = intent.getExtras();
    if (extra != null) {
        Object[] pdus = (Object[]) extra.get("pdus");
        final SmsMessage[] messages = new SmsMessage[pdus.length];
        for (int i = 0; i < pdus.length; i++) {
            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
        }
        if (messages.length > -1) {
            Log.v("Ch", "Marche1");
            for (int i = 0; i < messages.length; i++) {
                Log.v("Ch", "Marche2");
                final String messageBody = messages[i].getMessageBody();
                final String phoneNumber = messages[i].getDisplayOriginatingAddress();
                Toast.makeText(context, "Expéditeur:" + phoneNumber, Toast.LENGTH_LONG).show();
                Toast.makeText(context, "Message : " + messageBody, Toast.LENGTH_LONG).show();
            }
        }
    }

}

}

A: Move your receiver XML in your manifest to within the application tags.
<application
android:allowBackup="true"
android:icon="@mipmap/locate"
android:label="@string/app_nameprincipal"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

.......
<receiver android:name=".MyReceiver">
android:enabled="true"
android:exported="true" >
<intent-filter android:priority="999">
    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>


text:
Q: Display a td element on next line in the same tr I want to make a table which looks like this
------------------------------------------------------------------------------------
| Column 1                   | Column 2           | Column 3        | Column 4     |
| Long Text                                                                        |
------------------------------------------------------------------------------------
| Column 1                   | Column 2           | Column 3        | Column 4     |
| Long Text                                                                        |
------------------------------------------------------------------------------------

The td "Long Text" shares the same tr with Column 1,2,3 and 4. How can I force the td to move to "next line" in the same tr?
I tried to put a {display:block} attribute in the td of "Long Text" by following this way http://jsfiddle.net/hDsts/. However, it doesn't work.
Are there good solutions for this?

A:

    Col1
    Col2
    Col3
    Col4

    Verrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrry long text ?

    Col1
    Col2
    Col3
    Col4

    Verrrrryyy LONG

Like this ?
You have rowspan and colspan.
rowspan does this:
+----------------------+------+------+------+
| Col1                 | Col2 | Col3 | Col4 |
+                      +------+------+------+
|                      | x    | x    | x    |
+                      +------+------+------+
|                      | Col2 | Col3 | Col4 |
+                      +------+------+------+
|                      |      | x    | x    |
+----------------------+------+------+------+

A: you can use colspan attribute like this

        Column 1
        Column 2
        Column 3
        Column 4

        Long text

        Column 1
        Column 2
        Column 3
        Column 4

        Long text

and the css for the border
td {
    border: 1px dotted;
}

fiddle

A: You can use the HTML tag rowspan.
http://www.htmlcodetutorial.com/tables/index_famsupp_30.html


text:
Q: How i can pass an object to an attribute of an object? I have this code in reducer:
export const getSerieSuccess = (state = INITIAL_STATE, action) => {
   return {
      ...state,
      isLoadding: false,
      serie: action.serie   //action.serie is a object with id, name, genre e status
   }
}

I want to know if i do serie: action.serie, i am passing a value or a reference. I did this like:
export const getSerieSuccess = (state = INITIAL_STATE, action) => {
const serie = {...action.serie};
   return {
      ...state,
      isLoadding: false,
      serie
   }
}

How wai is better working with functional programming?

A: You can use both variants as long as the payload of the action is not further referenced and will not be mutated/changed.
Good:
store.dispatch(new SomeAction({a: b: {
  c: 1234
}));

Bad (because you pass a reference and change it afterwards):
let value = new SomeAction({a: b: {
  c: 1234
});
store.dispatch(value);
value.a.b.c = 44543; // bad

setTimeout(_ => (value.a.b.c = 5555), 5000); // bad

Note: if you want to make it really save (no reference passing) you could make a copy of the passed value inside of the action.


text:
Q: Get Object nested structure as string path Consider the following set of classes. There are two things I would like to achieve.

*

*Get the string representation of the path of the current property. For example totalAsset.BuildingAsset.HistoricalBuildingAsset.Path should return "TotalAsset.BuildingAsset.HistoricalBuildingAsset"

*Given a path "TotalAsset.BuildingAsset.HistoricalBuildingAsset" and a value "100", I want to use the path to retrieve the property and change its value.

Code Example:
public abstract class Field
{
    private string _path = string.Empty;

    public double Value {get;set;}

    public string Path
    {
        get
        {
            //Code probably goes here
            throw new NotImplementedException();

        }
        protected set { _path = value; }
    }
}

public sealed class TotalAsset : Field
{
    public TotalAsset(BuildingAsset buildingAsset)
    {
        Path = "TotalAsset";
        BuildingAsset = buildingAsset;
    }

    public BuildingAsset BuildingAsset { get; private set; }
}

public sealed class BuildingAsset : Field
{
    public HistoricalBuildingAsset HistoricalBuildingAsset { get; private set; }
    public BuildingAsset(HistoricalBuildingAsset historicalBuildingAsset)
    {
        Path = "BuildingAsset";
        this.HistoricalBuildingAsset = historicalBuildingAsset;
    }
}

public sealed class HistoricalBuildingAsset : Field
{

    public HistoricalBuildingAsset()
    {
        Path = "HistoricalBuildingAsset";
    }
}

[TestClass]
public class TestPath
{
    [TestMethod]
    public void MethodTestPath()
    {
        var historicalBuildingAsset = new HistoricalBuildingAsset();
        var buildingAsset = new BuildingAsset(historicalBuildingAsset);
        var totalAsset = new TotalAsset(buildingAsset);

        Assert.AreEqual("TotalAsset.BuildingAsset.HistoricalBuildingAsset", totalAsset.BuildingAsset.HistoricalBuildingAsset.Path);
    }
}

A: Wouldn't this be easily solved using polymorphism?
Based on your question, it seems like your Path property has an inmutable value, thus you should be able to solve your issue like the following code:
public class A
{
     public virtual string Path
     {
         get { return "A"; }
     }
}

public class B : A
{
     public override string Path
     {
         get { return base.Path + ".B"; }
     }
}

public class C : B
{
     public override string Path
     {
         get { return base.Path + ".C"; }
     }
}

A a = new A();
Console.WriteLine(a.Path); // Prints "A"

B b = new B();
Console.WriteLine(b.Path); // Prints "A.B"

C c = new C();
Console.WriteLine(c.Path); // Prints "A.B.C"

Update v1.1: Recursive approach (now includes getting a property value and setting a property value by a given object path)
Because you want to leave your model as is and go with the composition way, this is the piece of "magic" to dynamically get the whole path. Note that I've required a new FullPath property in order to avoid an infinite loop during path calculation (you can also try it in a DotNetFiddle):
using System;
using System.Linq;
using System.Reflection;

public abstract class Field
{
    public double Value
    {
        get;
        set;
    }

    public string Path
    {
        get;
        protected set;
    }

    public string FullPath
    {
        get
        {
            return BuildPath(this);
        }
    }

    /// <summary>
    /// Recursively-builds a dot-separated full path of associated fields
    /// </summary>
    /// <param name="field">Optional, it's a reference to current associated field </param>
    /// <param name="path">Optional, provided when this method enters to the first associated </param>
    /// <returns>The whole dot-separated full path of associations to Field</returns>
    private string BuildPath(Field field, string path = "")
    {
        // Top-level path won't start with dot
        if (path != string.Empty)
        {
            path += '.';
        }

        path += field.Path;

        // This will look for a property which is of type Field
        PropertyInfo fieldProperty = field.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                                .SingleOrDefault(prop => prop.PropertyType.IsSubclassOf(typeof(Field)));

        // If current field has a property of type Field...
        if (fieldProperty != null)
        {
            // ...we'll get its value and we'll start a recursion to find the next Field.Path
            path = BuildPath((Field)fieldProperty.GetValue(field, null), path);
        }

        return path;
    }

    /// <summary>
    /// Recursively sets a value to an associated field property
    /// </summary>
    /// <param name="path">The whole path to the property</param>
    /// <param name="value">The value to set</param>
    /// <param name="associatedField">Optional, it's a reference to current associated field</param>
    public void SetByPath(string path, object value, Field associatedField = null)
    {
        if (string.IsNullOrEmpty(path.Trim()))
        {
            throw new ArgumentException("Path cannot be null or empty");
        }

        string[] pathParts = path.Split('.');

        if (associatedField == null)
        {
            associatedField = this;
        }

        // This will look for a property which is of type Field
        PropertyInfo property = associatedField.GetType().GetProperty(pathParts[0], BindingFlags.Public | BindingFlags.Instance);

        if (property == null)
        {
            throw new ArgumentException("A property in the path wasn't found", "path");
        }

        object propertyValue = property.GetValue(associatedField, null);

        // If property value isn't a Field, then it's the last part in the path
        // and it's the property to set
        if (!propertyValue.GetType().IsSubclassOf(typeof(Field)))
        {
            property.SetValue(associatedField, value);
        }
        else
        {
            // ... otherwise, we navigate to the next associated field, removing the first
            // part in the path, so the next call will look for the next property...
            SetByPath(string.Join(".", pathParts.Skip(1)), value, (Field)propertyValue);
        }
    }

    /// <summary>
    /// Recursively gets a value from an associated field property
    /// </summary>
    /// <param name="path">The whole path to the property</param>
    /// <param name="associatedField">Optional, it's a reference to current associated field</param>
    /// <typeparam name="T">The type of the property from which the value is going to be obtained</typeparam>
    public T GetByPath<T>(string path, Field associatedField = null)
    {
        if (string.IsNullOrEmpty(path.Trim()))
        {
            throw new ArgumentException("Path cannot be null or empty");
        }

        string[] pathParts = path.Split('.');

        if (associatedField == null)
        {
            associatedField = this;
        }

        // This will look for a property which is of type Field
        PropertyInfo property = associatedField.GetType().GetProperty(pathParts[0], BindingFlags.Public | BindingFlags.Instance);

        if (property == null)
        {
            throw new ArgumentException("A property in the path wasn't found", "path");
        }

        object propertyValue = property.GetValue(associatedField, null);

        // If property value isn't a Field, then it's the last part in the path
        // and it's the property to set
        if (!propertyValue.GetType().IsSubclassOf(typeof(Field)))
        {
            return (T)property.GetValue(associatedField, null);
        }
        else
        {
            // ... otherwise, we navigate to the next associated field, removing the first
            // part in the path, so the next call will look for the next property...
            return GetByPath<T>(string.Join(".", pathParts.Skip(1)), (Field)propertyValue);
        }
    }
}

public sealed class TotalAsset : Field
{
    public TotalAsset(BuildingAsset buildingAsset)
    {
        Path = "TotalAsset";
        BuildingAsset = buildingAsset;
    }

    public BuildingAsset BuildingAsset
    {
        get;
        private set;
    }
}

public sealed class BuildingAsset : Field
{
    public HistoricalBuildingAsset HistoricalBuildingAsset
    {
        get;
        private set;
    }

    public BuildingAsset(HistoricalBuildingAsset historicalBuildingAsset)
    {
        Path = "BuildingAsset";
        this.HistoricalBuildingAsset = historicalBuildingAsset;
    }
}

public sealed class HistoricalBuildingAsset : Field
{
    public HistoricalBuildingAsset()
    {
        Path = "HistoricalBuildingAsset";
    }

    public int Age
    {
        get;
        set;
    }
}

public class Program
{
    public static void Main()
    {
        TotalAsset total = new TotalAsset(new BuildingAsset(new HistoricalBuildingAsset()));

        // Prints "TotalAsset.BuildingAsset.HistoricalBuildingAsset"
        Console.WriteLine(total.FullPath);

        total.SetByPath("BuildingAsset.HistoricalBuildingAsset.Age", 300);

        // Prints "300" as expected!
        Console.WriteLine(total.GetByPath<int>("BuildingAsset.HistoricalBuildingAsset.Age"));
    }
}

A: You can re-use the existing .net framework Binding pattern and codebase. Your description of what you want to do sounds mightily like MVVM binding to me. The use of Binding in WPF is explained here http://msdn.microsoft.com/en-us/library/ms752347(v=vs.110).aspx.
Using System.Windows.Data.Binding gives you an extensible framework for getting data into and out of object graphs using relative and absolute string paths to nominate the class members and collection indexes.


text:
Q: Card Data/fetcher/ previewer API configuration for a php website on Magic the Gathering I would define myself as a junior PHP developer (as have written small  scripts occasionally). A week ago I started a new project to make a website for magic the gathering (card game) where users write and publish their articles on the game or tournaments.
Normally it wouldn't be a problem because if there is any external source, it could by hyperlinked and the problem is solved.
But in this case in articles users have to discuss about MTG cards, upload decklists and stuff like that and can't put hyperlinks for these things and neither create a database for all cards as only 3 months new cards are published with new set release.
What I am looking for is a 3rd party code integration into my project where user typing a string such as "[card_data]NAME OF CARD[card_data]" have a card preview by clicking on it.
There are several websites like:
https://www.mtggoldfish.com/articles/instant-deck-tech-five-color-birds-modern
https://www.channelfireball.com/all-strategy/articles/
and several other website.
I couldn't try anything because I don't know the procedure to call an API in php script, tutorials on youtube, or w3schools are very simple and often they are about facebook and google apis .
There are websites that have APi available for mtg cards data such as https://docs.magicthegathering.io/
https://scryfall.com/docs/api
https://www.echomtg.com/api/
But I am missing the part of integration them in my website.
I would like to have something like in this example where "Wasteland" is a card and by hovering on it or clicking on it there should be a card preview:
Of course, the easiest way to make Wasteland useless is never to play any land at all

A: I found a really easy and simple solution to the problem above. I'll use tooltips of https://deckbox.org/help/tooltips


text:
Q: How can I compare two directories to update a log file in BASH? I am attempting to compare two directories and then update the log file after determining what files are different between the two, but I keep getting error messages saying that it expects an integer result in the line [ if $userinput -eq $userinput.log ]. Is there a way to compare these two that I am missing? Here is the script I have written.
userinput=$1
if [ ! -d "$userinput" ];
then
        echo "Usage: dirlog.sh directory_name" 1>&2
        exit 0
else
        if [ ! -f "$userinput.log" ];
        then
                ls -l > $userinput.log
                echo ".logfile created for $userinput"
        elif [ -f "$userinput.log" ];
        then
                if [ $userinput -eq $userinput.log  ]; #if they are different
                then
                        differences=diff -rq $userinput $userinput.log
                        for file in $differences
                        do
                                echo "$file missing from directory $userinput"
                        done
                else
                        echo "no files missing from directory $userinput"
                fi
                #Update this no matter what
                ls -l > $userinput.log
                echo "logfile updated for directory $userinput"
        fi
fi

A: You can compare two directories with the diff -r command. This will show you all files that differ, which files are missing from one directory to another. The --brief option or --summary option will simply list the differences and not the content of the files.
Now, about your if [ $userinput -eq $userinput.log  ];...
In shell, a variable could hold numeric or could hold alphanumeric data. Let's take something like this:
foo="0456"
bar="456"

In the above, $foo and $bar could be strings or numbers. If I think of them as numbers, they're equal. However, if they are strings, they're not equal.
Here's another example:
foo="123"
bar="45"

Which is greater? Again, it depends whether $foo and $bar are being treated as strings or numbers. If I treat them numerically $foo is greater. However, if I treat them as text strings, $bar is greater because the first character of $bar which is 4 comes after the first character of $foo, 1.
So, how does bash know whether I want numeric or string comparison? Simple, Bash provides me with two different sets of comparison operators. One is for strings and one is for text:
                    String   Numeric
                    ------   -------
Equals                =       -eq
Greater Than          >       -gt
Less Than             <       -lt
Not equals           !=       -ne
Greater Than/Equals  >=       -ge
Less Than/Equals     <=       -le

In your case, you want to compare two strings and you're using -eq. This is why you're getting the error that the -eq operator expects numeric results. By the way, if you're using Bash or Kornshell, you should go ahead and use the doubled square brackets [[ ... ]]. These are less error prone and have a few more nice features such as pattern matching:
if [[ $userinput == "$userinput.log" ]]

However, I really recommend you to use he diff -r --brief command for comparing two directories.


text:
Q: how to send multiple records in single http request and how to receive in the other end in android? In my android application multiple records should be updated to Mysql database.
I can able to it for single record but stuck in updating the multiple records.
below is my code for sending single record how to do it for multiple records.
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();

nameValuePair.add(new BasicNameValuePair("appname", appName));
nameValuePair.add(new BasicNameValuePair("start_time", startTime));
nameValuePair.add(new BasicNameValuePair("end_time", endTime));
 try{

     HttpClient httpclient = new DefaultHttpClient();
     HttpPost httppost = new HttpPost("http://192.168.1.24/file_data_insert.php");
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     HttpResponse response = httpclient.execute(httppost);
     HttpEntity entity = response.getEntity();
     is = entity.getContent();
    }
catch(Exception e){
     Log.e("log_tag", "Error in http connection"+e.toString())
}

A: I would wrap your database  with  rest service ( say with CXF,  pico web remoting, whatever you prefer )  and return JSON document from it.  It can be parsed to objects easily


text:
Q: VB.NET Datagrid Calculations (Visual Studio 2010) In the datagrid table: calculate the difference between two columns with the result in third column (performed automatically during runtime). Null value is 0 in budget and cost columns. Budget - Cost = Difference. I am using Visual Studio 2010. If anyone knows how to do this in the designer, please let me know.Otherwise...
Budget = column7
Cost = column8
Difference = column 9

The budget column  less the cost column = difference column for all rows. Could someone please provide me with some code? I have trashed mine...not even worth posting.

A: Assuming you are using windowsforms:
Create a dataset using the designer
Create a datatable with three columns: budget, cost and a calculated column, difference.
Instantiate the  datatable and fill it.
Bind the datatable to your datagridview

A: You can create a database using Access or sql, then on your vb form at the top click data...add datasource, and then follow instructions.


text:
Q: Hyperbolic structure on surfaces with boundary I have following two questions
1) Let $S$ be a compact oriented surface with (non-empty) boundary. Also assume that the Euler characteristic of $S$ is negative (Thus, $S$ is not disk or annulus). Then is it possible to put a hyperbolic metric on $S$  such that every boundary component becomes a geodesic?
2) In above case, what is the universal cover? Is it a subset of the unit disk with hyperbolic metric?

A: The answers to both questions are positive.
1) If the Euler characteristic of $S$ is negative, then you can find a pants decomposition (where some of the pants boundary components are glued together, while the others are boundary components of $S$). Then you can put hyperbolic metrics on each pair of pants, while prescribing the lengths of the boundary component, so that you can glue them into a hyperbolic metric of $S$ (and you have parameters left for the gluing, just like for a closed surface).
2) You can always, by gluing additional pants, consider $S$ endowed with a hyperbolic metric constructed as above, as a subsurface with geodesic boundary of a closed hyperbolic surface $\bar S$. Then the universal cover of $\bar S$ is the Poincaré disc, and the boundary components of $S$ lift to complete geodesics. The universal cover of $S$ is then one of the connected components of the complement of these complete geodesics.