text:
Q: How to apply InStr to match header name with array of names? My macro is supposed to match header name with array of names.

*

*if true, omit it

*if not, set value from second row to the last row as Customer

Initially, I had the customer value on the "Else" part but the macro did the other way around as supposed - only changed cells on array values. It doesn't make sense to me, as I've though that I've set my InStr function to positive output however I've put the instruction on match part
Out of 70 variables, did 67 positively as intended, 3 variables were named Customer and in few of them it doesn't went from 2nd to last, but for instance only second, or only few of them.
Sub test2()

    Dim HeaderRow As Range
    Dim HeaderName As String

    HeaderName = Join(Array("ID", "GENDER", "REVENUE"))

    Set HeaderRow = Range(Cells(1, 1), Cells(1, 1).End(xlToRight))

    For Each Header In HeaderRow

        Debug.Print Header
        Debug.Print HeaderName
        If InStr(1, HeaderName, Header.Value, vbTextCompare) = 0 Then
            Range(Cells(2, Header.Column).Address, Cells(Cells(Rows.Count, Header.Column).End(xlUp).Row, Header.Column).Address).Value2 = "Customer"
        Else

        End If

    Next Header

End Sub

For example that column BD is what it is supposed to be, all these columns have gaps but BD, BF, BG, BO are good (1-59 rows on that particular file, rest are not).
Plus something mentioned earlier - sometimes header is set to customer and first row, nothing else.

New HeaderRow gives me mismatch, when i change to ws.Range initially it gets only first column, like that is not drag xlToLeft

A: Just loop through all worksheets For Each ws In ThisWorkbook.Worksheets and make sure all Range, Cells, Rows and Colums objects are referenced with the worksheet like ws.Range etc.
Option Explicit

Public Sub test2()

    Dim ws As Worksheet
    For Each ws In ThisWorkbook.Worksheets 'loop all worksheets
        Dim HeaderName As String
        HeaderName = Join(Array("ID", "GENDER", "REVENUE"))

        Dim HeaderRow As Range
        Set HeaderRow = ws.Range(ws.Cells(1, 1), ws.Cells(1, 1).End(xlToRight))

        Dim Header As Variant
        For Each Header In HeaderRow
            Debug.Print Header
            Debug.Print HeaderName

            If InStr(1, HeaderName, Header.Value, vbTextCompare) = 0 Then
                ws.Range(ws.Cells(2, Header.Column), ws.Cells(ws.Rows.Count, Header.Column).End(xlUp)).Value2 = "Customer"
            End If
        Next Header
    Next ws

End Sub

Note that the Range object can take Cells as argument and does not need an Address therefore you can shorten this
Range(Cells(2, Header.Column).Address, Cells(Cells(Rows.Count, Header.Column).End(xlUp).Row, Header.Column).Address).Value2 = "Customer"

to
Range(Cells(2, Header.Column), Cells(Rows.Count, Header.Column).End(xlUp)).Value2 = "Customer"

Thoughts according comments
If your header changed that means ws.Cells(ws.Rows.Count, Header.Column).End(xlUp) ends up at the header because there is no data below. So this range
ws.Range(ws.Cells(2, Header.Column), ws.Cells(ws.Rows.Count, Header.Column).End(xlUp)).Value2 = "Customer"

is actually going from row 2 to row 1. To prevent this, you need to split it up and test:
Dim LastCellInCol As Range
Set LastCellInCol = ws.Cells(ws.Rows.Count, Header.Column).End(xlUp)

If LastCellInCol.Row >= 2 Then 'only change if there is data in the column
    ws.Range(ws.Cells(2, Header.Column), LastCellInCol).Value2 = "Customer"
End If

If blanks should be filled until the very last row of all columns
Option Explicit

Public Sub test2()

    Dim ws As Worksheet
    For Each ws In ThisWorkbook.Worksheets 'loop all worksheets
        Dim HeaderName As String
        HeaderName = Join(Array("ID", "GENDER", "REVENUE"))

        Dim LastUsedCell As Range  'find last used cell of ALL columns
        Set LastUsedCell = Nothing 'initialize (because inside loop)
        Set LastUsedCell = ws.UsedRange.Find("*", , , , xlByRows, xlPrevious)

        If Not LastUsedCell Is Nothing Then 'prevent error on empty sheets
            Dim HeaderRow As Range
            Set HeaderRow = ws.Range(ws.Cells(1, 1), ws.Cells(1, ws.Cells.Columns.Count).End(xlToLeft))

            Dim Header As Variant
            For Each Header In HeaderRow
                If InStr(1, HeaderName, Header.Value, vbTextCompare) = 0 Then
                    ws.Range(ws.Cells(2, Header.Column), ws.Cells(LastUsedCell.Row, Header.Column)).Value2 = "Customer"
                End If
            Next Header
        End If
    Next ws

End Sub


text:
Q: DataTable copy exception I have DataTable, there are a lot of threads to fill this table(for each column), so I had many troubles. Now every thread suppose to work with Copy of table, but when I call
                MainTableCopy = new DataTable();
                lock (MainTable)
                    MainTableCopy = MainTable.Copy();

it throws an exception like "The column "MName" is constrained by uniqueness. The value of "Item 12" already exists."
MainTable have same settings and every value in "MName" is unique.
What I'm doing wrong? Where MainTableCopy take clone of row, that unique in MainTable?
P.S. I know I can just make copy row by row, but in this case I want to understand, what exactly happens.
Threads to fill table
                DataTable MainTableCopy = new DataTable();
                lock (MainTable)
                    MainTableCopy = MainTable.Copy();

                foreach (DataRow row in MainTableCopy.Rows)
                {
                    //Getting info
                    DataRow Drw = null;
                    while (Drw == null)
                        Drw = MainTable.Rows.Find(name);
                        lock (Drw)
                        {
                            Drw.SetField("MProfit", 0);
                            //Fill data
                        }
                 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loop over files in tar.gz I have files.tar.gz with a bunch of csv files inside, each having a header. I want to loop over the csv files and process them one at a time. If I just zcat | tar -xO them all, then I won't be able to identify the start of each file, and thus its header.
How can I loop over the files in the archive one at a time, and pipe them individually to a processing command?

A: The GNU tar utility can extract individual file from an archive to stdout with
tar -O -x -z -f archive.tgz file
Here is a loop that might solve your problem, assuming running tar for each file is not prohibitively slow.
tar tzf files.tar.gz | while IFS= read -r f ; do
   echo ">>> Processing file $f"
   tar Oxzf files.tar.gz "$f" | head | cat -n ;
done

command | while IFS= read -r line is a BASH pattern. Clearing the IFS variable is necessary for the code to work correctly when there are spaces in the file names.


text:
Q: Private Class Variables in Python? I'd like to be able to extend a class without inheriting one of the class variables.
Given this scenario:
class A:
    aliases=['a','ay']

class B(A):
    pass

print(B.aliases)

I would rather get an error that B has not defined the aliases variable rather than have B accidentally called ay.
One could imagine a solution where aliases becomes a member of the instantiated object (self.aliases) and is set in __init__ but I really want to be able to access the aliases using the cls object rather than an instance of the class.
Any suggestions?

A: Python does not have REALY private attributes. But you can define it with a double underscore (__):
class A:
    __aliases=['a','ay']

class B(A):
    pass

print(B.__aliases) # yields AttributeError

But you still will be able to access it with:
print(B._A__aliases)

A: This is kindof a ganky work around but here you go:
class K:
    def __init__(self):
        self.mems = dir(self)

def defaultMembers():
    k = K()
    return(k.mems)

class A:
    aliases=['a','ay']

class B(A):
    def __init__(self):
        for k in set(dir(self))-set(defaultMembers()):
            print("removing "+k)
            setattr(self, k, None)

a = A()
b = B()
print(b.aliases)
#None
print(a.aliases)
#['a','ay']

I guess all you really need is the setattr(self, "aliases", None) still this results in a None and not a non-variable. Unfortunately calsses don't support deletion because I tried to use del first.


text:
Q: Query works several times slower when comparing BIT column with 0 instead of 1 I use a view based on a complex query with 17 joins (both inner and left/right outer) and subqueries. All view rows are shown in about 5 seconds.
SELECT * FROM a_view;

One of the view columns has type BIT. And when I filter view rows comparing it with 1, a query works again about 5 seconds.
SELECT * FROM a_view WHERE c = 1;

But when I compare this BIT column with 0, a query works about 50 seconds (10 times slower).
SELECT * FROM a_view WHERE c = 0;

This query which returns the same result rows works as expected about 10 seconds:
SELECT * FROM a_view
EXCEPT
SELECT * FROM a_view WHERE c = 1;

So I wonder why comparing with 0 or 'FALSE' takes so much time? Any ideas, please.
Sorting on this BIT field is fast. Filtering by other columns is fast too.

A: I know this is a very old question, but if anyone is still looking for a solution, you may try this. I encountered the same issue recently, and it was on a relatively simple query, just 3 tables in a join, biggest of them with just over 1000 rows. Unfortunately I didn't have privileges to view exec plan, so I had to improvise.
select * from subquery_x;

very fast, finished basically instantly (returned just about 500 rows) as it should
select * from subquery_x where column_x = 1

dtto, very fast, column_x is a not null bit column
select * from subquery_x where column_x = 0
select * from subquery_x where column_x != 1

should return around 300 rows, both is very, very slow, in fact it took several minutes !!
simple (but weird) solution - convert the column in where clause to tinyint
select * from subquery_x where convert(tinyint,column_x) = 0

I know this might have some performance side effects, but it worked like a charm, comparing converted column value to 1 was also very fast, so I let it like that (it was used in a report with the compared value being provided as a parameter)
If anyone knows why this happens, let us know, I suspect it's a bug, but who knows, might as well be a nasty feature :-)

A: the SQL Server sql engine places the whole SQL query of the view inside the SQL statement you wrote on the view and then tries to optimize it.
This could lead to a situation where with c=0, the statistics of the tables used show that there are much more rows matching that predicate than with c=1. For example, with c=1, a table which contains the c field which is the center of the joins might return just 5 matching rows, which leads to a much different execution plan than if the table returns 1 million rows (which is for example the situation for c=0).
So examine the execution plans for both. Also examine the server profiler results for both, as with c=0, it might be there are much more reads than with c=1, and much more results being returned than with c=1. Returning all rows might take a while so this too might be the reason the query is slower.

A: Usually there is more than one way to execute a query involving joins.  All modern RDBMSs search through different join plans looking for the best plan by estimating costs (CPU and disk access times) for each.
The problem is, each additional join in a query multiplies the number of possible plans by an increasing number, resulting in double-factorial (worse than exponential) growth in the number of plans to consider as the number of joins increases.  For that reason, the DB has to limit the search somewhere, meaning suboptimal plans inevitably get chosen for queries involving many joins.
For reference, PostgreSQL stops evaluating all possible plans after 12 joins by default.  SQL Server will have a similar limit for sure.  17 joins would take (2 * 13) * (2 * 14) * (2 * 15) * (2 * 16) * (2 * 17) times as long to evaluate -- it's more than enough to overwhelm any RDBMS that has ever existed, or ever will.
There is also the fact to consider that DBs estimate costs based on crude statistics, such as the number of distinct values in a column and/or a list of the 10 most common values in a column.  This all adds up to the fact that, as the number of joins goes up, the likelihood of choosing the best (or even a reasonable) join strategy goes way down.
Why do you need to join 17 tables?  Is there no way you can simplify your DB schema?

A: Similar to horcic.roman's solution... I cast the value or column to BIT for a large increase in speed.
myColumn = CAST(1 AS BIT)

CAST(myColumn AS BIT) = 1

Obviously quite strange given that the column is BIT NOT NULL.

A: slow :
select * from bigTable where column = 1
slow
select * from bigTable where column = cast(1 as bit)
fast :
declare @b as bit = 1
select * from bigTable where column = @b


text:
Q: ARC Semantic Issue Objective-c I am creating an ios application in objective-c with xcode and came across a strange error.
the code is:
#import "LAAppDelegate.h"
#import "Reachability.h"

@implementation LAAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:    (NSDictionary *)launchOptions
{
    NetworkStatus networkStatus =
        [[Reachability reachabilityForInternetConnection]
         currentReachabilityStatus];
    if (networkStatus == NotReachable) {
        UIAlertView *alert = [[UIAlertView alloc]
        initWithTite:@"Network Unavailable"
        message:@"Lazuli requires an internet connection"
        delegate:nil
        cancelButtonTitle:@"Ignore"
        otherButtonTitles:nil];
    [alert show];

    }

   // Override point for customization after application launch.
   return YES;
}

I keep getting the error:  "No visible @interface for 'UIAlertView' declares the selector 'initWithTite:message:delegate:cancelButtonTitle:otherButtonTitles:' "
I am a beginner and need help!

A: You have a typo in your method call. It's initWithTitle..., not initWithTite...


text:
Q: Set HSQLDB data type in hibernate configuration files? I am trying to create an in-memory DB using HSQLDB 2.2.5. We are also using Hibernate. The problem is that our Domain Objects are annotated for Oracle. We generate the HBM files from the POJOs. Hence I am getting "type not found or user lack privileges: NUMBER" errors when I attempt to run against HSQLDB. HSQL 2.2.5 doesn't support NUMBER, only NUMERIC.
Is there any way in the hibernate configuration file or hibernate.properties to tell HSQL to treat NUMBER as NUMERIC?

A: Well, this version of HSQLDB supports the Oracle syntax compatibility and accepts MUMBER in this mode, plust many other Oracle-specific features. See the Guide for details.
http://hsqldb.org/doc/2.0/guide/deployment-chapt.html#N14266


text:
Q: RecyclerView becomes empty after coming back to a destroyed activity I have a recyclerview that reads from a Firebase database a list of people and displays them on the layout. When I access to the activity for the first time it goes everything as expected, but when I finish the activity with the BackButton and when I try to access again to that activity, the recyclerview becomes empty.
Note that I try to add programmatically the people by using a Listener for a SingleValueEvent.
    class myActivity : AppCompatActivity() {

    private var index = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_fisio)

        Firebase.database.setPersistenceEnabled(true)
        val database = Firebase.database("mydatabase")
        val myRef = database.getReference("People")

        val peopleList = ArrayList<MyPeopleListAdapter.MyPeopleItem>()

        val code = intent.getStringExtra("key")

        val recview = findViewById<RecyclerView>(R.id.recyclerViewF)
        recview.layoutManager = LinearLayoutManager(this)

        val adapter = MyPeopleListAdapter(peopleList)
        recview.adapter = adapter
        recview.setHasFixedSize(true)

        myRef.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {

                val ref = snapshot.child(code.toString()).getValue<Map<String, *>>()

                val peopleListRef = snapshot.child(code.toString()).child("PeopleList")

                peopleListRef.children.forEach {
                    val hash = it.getValue<Map<String,*>>()
                    val pId = it.key
                    val pFull = hash!!["Name"].toString()
                    val pEmail = hash["Email"].toString()
                    val pPic = hash["Pic"].toString()
                    val pS = hash["S"].toString()

                    peopleList.add(index, MyPeopleListAdapter.MyPeopleItem(
                        pId.toString(),
                        pPic,
                        pFull,
                        pEmail,
                        pS))

                    adapter.notifyItemInserted(index)

                    index += 1

                }

            }

            override fun onCancelled(error: DatabaseError) {
                println(error.message)
            }
        })
    }

    override fun onBackPressed() {
        super.onBackPressed()

        finish()
    }
}

A: The problem was that the recycler view didn't had a scrollToPosition() method implemented. So after the adapter is notified, the scroll method is called and the code becomes:
// ...

    adapter.notifyItemInserted(index)
    recview.scrollToPosition(0)

// ...


text:
Q: template specialization with default parameters The following code compiles. Anyone can explain why? I've been digging the standard to figure out why it's legal.
template <bool B, typename T = void> struct enable_if { };
template <typename T> struct enable_if<true, T> {
    typedef T type;
};
template <typename T, typename Enable = void> struct A;
template <typename T> struct A<T, typename enable_if<(sizeof(T) <= ~0ULL)>::type> {
    void f() { }
};
int main() {
    A<int> a;
    a.f();
}

At the statement:
A<int> a;

As there's only one template paramerter "int", the compiler should go to use the primary template, which is:
template <typename T, typename Enable = void> struct A;

which is undefined, thus causing an error.

A: From § 14.5.5.1

1 When a class template is used in a context that requires an
instantiation of the class, it is necessary to determine whether the
instantiation is to be generated using the primary template or one of
the partial specializations. This is done by matching the template
arguments of the class template specialization with the template
argument lists of the partial specializations.
— If exactly one matching specialization is found, the instantiation is generated from
that specialization.

A: Let's try to figure out what's going on here:
// definition of enable_if, second parameter is defaulted to void
template <bool B, typename T = void>
struct enable_if { };

// specialization of enable_if, if first parameter is true,
// enable_if has a typedef for the second parameter
template <typename T>
struct enable_if<true, T> {
    typedef T type;
};

// definition of struct A, second parameter defaults to void
template <typename T, typename Enable = void>
struct A;

// specialization of struct A, second parameter
// is obtained from the enable_if::type typedef
// the first parameter of enable_if is true if the size of T
// is smaller than the max long long (~0 --> all F)
template <typename T>
struct A<T, typename enable_if<(sizeof(T) <= ~0ULL)>::type> {
    void f() { }
};

int main() {
    // So we attempt the specialization for struct A<int,enable_if...>
    // The expression of enable_if evaluates to...
    // (sizeof(int) <= ~0ULL) == true
    // ... so it applies the specialization of enable_if<true,void>
    //     (second parameter is void because none is provided, so it
    //     uses the default.
    // so the enable_if template is valid (selected the specialization)
    // and that means that the struct A<int,enable_if> specialization
    // is valid too, so it is selected.
    A<int> a;
    a.f();
}

A: The compiler uses the template A<int, enable_if<true>:::type > when you declare A<int> since sizeof(int) <= ~0ULL evaluates to true.
There is no problem with enable_if<true>::type because the compiler is able to use enable_if<true, true>::type.

A: When you consider your enable_if:
template <bool B, typename T = void> struct enable_if{ };

template <typename T> struct enable_if<true, T>
{
    typedef T type;
};

in
void test_EnableIf
{
 static_assert(
   std::is_same<
     enable_if<(sizeof(int) > 0)>::type,
     void>::value, "test_EnableIf failed." );
}

the result (type) is void, as no type was specified (as second
template parameter). The specialization of enable_if is selected
because of the boolean expression being true, and the default
parameter is selected (from primary template) because no other was
provided, and hence type is void, but NOTE that the definition
of type does exist (as the specialization was selected).
Now, in your definition of A...
template <typename T, typename Enable = void> struct A;
template <typename T>
struct A<T, typename enable_if<
  (sizeof(T) <= ~0ULL)>::type>
{
    void f() { }
};

...because type does exist in enable_if, it is a better match, which causes the specialization to be selected, and hence compiles.
A trivial example which amounts to the same thing is the following:
template <class T, class U = void>
struct X;

template <class T>
struct X<T,void>
{
  static int foo(){ return 0; }
};

int main()
{
  return X<int>::foo();
}


text:
Q: Copy contents of text file and copy it to another This is what my professor provided me in his own words.
"Write a program that copies the contents of a text file specified by the user and copies it to another text file "copy.txt".  No line in the file is expected to be longer than 256 characters."
Here is the code I devised so far with his info:
#include <stdio.h>
#include <io.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>

int main ( void )
{
   char filename[256]="";       //Storing File Path/Name of Image to Display
   static const char file2name[] = "C:\\Users\\Rael Jason\\Desktop\\Rael's iPod\\Codeblocks\\copy.txt";
   FILE *file;
   FILE *write;
   printf("Please enter the full path of the text file you want to copy text: ");
   scanf("%s",&filename);
   file = fopen ( filename, "r" );
   file = fopen (file2name, "r" );

   if ( file != NULL )
   {
      char line [ 256 ]; /* or other suitable maximum line size */
      char linec [256]; // copy of line

      while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
      {

         fputs ( line, stdout ); /* write the line */
         strcpy(linec, line);

         fprintf (write , linec);
         fprintf (write , "\n");
      }
      fclose (write);
      fclose ( file );
   }
   else
   {
      perror ( filename ); /* why didn't the file open? */
   }
   return 0;
}

I just can't seem to get the file writing done right? Can you please help?

A: You had the copy and paste issue as mentioned by stacker. And there no need to add an extra newline character. Try the following code.
            #include <stdio.h>
            #include <io.h>
            #include <stdlib.h>
            #include <conio.h>
            #include <string.h>

            int main ( void )
            {
               char filename[256]="";       //Storing File Path/Name of Image to Display
              static const char file2name[] = "C:\\Users\\Rael Jason\\Desktop\\Rael's iPod\\Codeblocks\\copy.txt"; Copy File
               FILE *file;
               FILE *write;
               char line [ 256 ]; /* or other suitable maximum line size */
               char linec [256]; // copy of line

               printf("Please enter the full path of the text file you want to copy text: ");
               scanf("%s",&filename);                       // Enter source file
               file = fopen ( filename, "r" );
               write = fopen (file2name, "w" );

               if ( file != NULL )
               {

                  while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
                  {

                 fputs ( line, stdout ); /* write the line */
                 strcpy(linec, line);

                 fprintf (write , linec);
                // fprintf (write , "\n");         // No need to give \n
                  }
                  fclose (write);
                  fclose ( file );
               }
               else
               {
                  perror ( filename ); /* why didn't the file open? */
               }
               return 0;
            }

A: If this is the code you executed then there are some problem with it.

*

*you are using same FILE pointer file to open both the source and destination file.

*you are opening the destination file in read mode it should be opened in write mode.


text:
Q: C# Merge lists together I want to merge the fields of songDetails and savedSongs together. How do I do this?
I have heard of .Zip() but I am unsure on how to use it.
    [HttpPost]
    public ActionResult Upload(IEnumerable<UploadedSong> songDetails)
    {
        IEnumerable<UploadedSong> savedSongs = (IEnumerable<UploadedSong>)(Session["UserSongs"]);

        return View();
    }

Edit:
songDetails and savedSongs have string fields: Category, AlbumName, BandName, however in songDetails these have data. So I want to merge these non-null data fields with the savedSongs null fields in the same index.

A: The way ZIP works is similar to the Aggregate method. To be honest, I don't think that is what you want.
I will show you why with an example how ZIP works. Given the A & B are arrays of integers.
var A = new [] { 1, 3 };
var B = new [] { 2, 4 };

Zipping A & B won't produce:
C = {1, 2, 3 ,4};

ZIP in C# simple returns one value after looking at two values. Here is what you can do with ZIP in .Net 4.0;
Let's say we have the following functions:
Max & Min and use Zip on A & B and I want to apply Max or Min. Here would be the results.
Zip(A,B, Max) = { 2, 4}
Zip(A,B, Min) = { 1, 3}

If I had another function called MultiplyFirstBySecond I would get:
Zip(A,B, MultiplyFirstBySecond ) = {2, 12}

ZIP doesn't actually merge as you can see. It behaves more like Aggregate but across two collections instead of one.
What you want is to merge or copy fields from one object to another in your case from Song Details to Uploaded Song.
I have included a small snippet that might help you. You gave little implementation details. I assume you don't want to divulge too much detials about you project and that is fine :)
Anyhow, here is my attempt to help you.
using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    class UploadedSong {
        public string Author{get;set;}
        public string Name{get;set;}
        public float Length{get;set;}
        public string Path{get;set;}
        public byte[] SizeInBytes{get;set;}
    }

    public void UpdateSongDetails(IEnumerable<UploadedSong> uploadedSongs, IEnumerable<UploadedSong> songDetails) {
        // Note that this might blow up if you have duplicate song names
        // You gave very little to work with so my preconditions are weak

        var lookupDetails = songDetails.ToDictionary(song => song.Name, song => song);

        foreach(var uploadedSong in uploadedSongs) {
            var key = uploadedSong.Name;
            if(lookupDetails.ContainsKey(key)) {
                var details = lookupDetails[key];
                uploadedSong.Author = details.Author;
                // ... more details here
            }
        }
    }

    static void Main()
    {
        // I am assuming that song details is something you populate from some reliable source
        // but for simpilicity I will just declare it.
        var songDetails = new List<UploadedSong>();
        var uploadedSongs = (IEnumerable<UploadedSong>)(Session["UserSongs"]);
        UpdateSongDetails(uploadedSongs, songDetails);
    }
}

Cheers and good luck!


text:
Q: Selection Sort and Bubble Sort Errors Currently having difficulty with Selection Sort and Bubble Sort codes.
The selection sort is used to sort out student ID in ascending order and the bubble sort is used to sort out last names in ascending order. The program compiles but crashes upon choosing choice 10 or 11.
My array is declared as follows:
student[] list = new student[100]; //my array

This is the code that I have for selection sort and bubble sort. I am using an array with methods:
   if (choice == 10) { // Dissplay the sorted array by student id

            SortArrayBySelection(list);

            System.out.println("Sorted studentid are:");
            for (int i =0; i< studentNumber; i++)
            {
                System.out.println(list[i]);
            }

        }

        if (choice == 11){ // Display the sorted array by family name

            BubbleSort(list);

            System.out.println("The sorted names are:");
            for(int i = 0; i < studentNumber; i++)
            {
                System.out.println(list[i].Getfamilyname());
            }
        }

    } while (choice != 1);

}

public static void SortArrayBySelection(student[] arrayToSort){ // Function to sort out the array on sutdentid
 for(int i = 0; i < arrayToSort.length-1; ++i)
 {
     int minIndex = i;
     int studentid3 = arrayToSort[i].Getstudentid();
     int studentid2 = arrayToSort[minIndex].Getstudentid();
     for(int j = i + 1; j <arrayToSort.length; ++j)
     {
         int studentid1 = arrayToSort[j].Getstudentid();
         if(studentid1 < studentid2)
         {
             minIndex = j;
         }
     }
     int temp = studentid3;
     studentid3 = studentid2;
     studentid2 = temp;

 }
}

public static void BubbleSort(student[] arraySort){
    String t;
    for(int i = 0; i<arraySort.length; i++){
        for(int j=0; j<arraySort.length-1;j++){
            String str1 = arraySort[j].Getfamilyname();
            String str2 = arraySort[j+1].Getfamilyname();
            if(str1.compareTo(str2)<0){
                t = str1;
                str1 = str2;
                str2 = t;
            }
        }
    }

}

Any suggestions would be appreciated! thank you
Errors:
Exception in thread "main" java.lang.NullPointerException
    at client.Client.SortArrayBySelection(Client.java:270)
    at client.Client.main(Client.java:232)

Exception in thread "main" java.lang.NullPointerException
    at client.Client.BubbleSort(Client.java:288)
    at client.Client.main(Client.java:246)

A: As you have not mentioned line numbers in your code, also the Student class and the code where you are preparing the student[] list = new student[100]. So, as far as i can see the code from following lines you can get the java.lang.NullPointerException

*

*Your list length will be always 100 as you are creating it with that value. So if it something dynamic values which you are preparing at runtime then it will be better if you use ArrayList<student> list=new ArrayList<student>(); and add the values using list.add(yourObject);.

*Exception in thread "main" java.lang.NullPointerException
at client.Client.SortArrayBySelection(Client.java:270)
at client.Client.main(Client.java:232)

*

*For this error you are calling SortArrayBySelection method and the lines which may end up in the above errors are
int studentid3 = arrayToSort[i].Getstudentid();
int studentid2 = arrayToSort[minIndex].Getstudentid();
int studentid1 = arrayToSort[j].Getstudentid();
Reason for the error :
You don't have the values present at the given index and as you are creating an array of length 100 where you put only let say 10-15 values then it will always have no values in other location. But your for-loop will go to 100 index position in which after 10-15 index you will always get null by calling the getters.
Same reason is for your other method as well.


text:
Q: Trying to Move Logic to DB - Reservation System So I'm planning a basic resource reservation system. Basically I'm going to have a room (resource) that has X number of open spots per 30 minute increment. When someone reserves a resource I would store it as resource A is reserved from start time to end time.
Now in order to output to the end user if any open spots are available for a resource at a given time. I need to check to see if the number of reservations (Y) in that 30 minute window are less than the number of open spots (X).
The only way I can think of to do this is inefficient. That is query the reservations for the day, loop through the times of the day, and for each 30 minute block, count the number of reservations in that block (via server side code instead of in the DB). I'm less proficient at SQL.
Is there a way I can accomplish this all on the DB end in a query so the query returns something like a row for each resource and a column for each 30 min increment with the values being the number of open/taken seats?
I'm open to a different DB schema, but the way I see it I have a table or resources which state the max start-end time for reservations, number of possible openings per time period; a table of reservations stating which resource it was and the start-end time of the reservation.

A: I would create a table to represent the room, perhaps:
Room
------------
RoomId (PK)
RoomNumber

Then a table to represent a reservation:
Reservation
------------------
ReservationId (PK)
RoomId (FK)
StartTime
EndTime

For any given period, you just need to search for all reservations that are valid for that period, e.g to find how many reservations between 10am and 11am, you would do:
SELECT COUNT(*) FROM Reservations
WHERE
    RoomId = Room AND
    (StartTime >= 1000 AND StartTime <= 1100) OR
    (EndTime >= 1000 AND EndTime <= 1100)

This SQL query should execute extremely quickly, so looping over each 30 minute period would not take that long.


text:
Q: Why are stably free modules called stably free? Being of the kind who easily get troubled by questions of semantics, I've been troubled for a while now about why "stably free" modules are called just "stably free".
It seems to me that, logically, that by applying the adverb stably to the adjective free, you would wish to specify something stronger. That a module isn't just free, but stably so. And yet, stably free is a weaker statement that free. All free modules are stably free, not all stably free modules are free.
So what's the etymology here. In what sense is the freedom of the module something stable?
As always, I look forward to your responses.

A: Okay, so I think I finally can give some background to this myself. The precise terminology (as explained by Eric Wofsey in the comments to the original post) is rather to mean "the module is free once stabilized." This in turn would seem to derive from the terminology of stably isomorphic modules, which is that two $R$-modules $P$ and $Q$ are stably isomorphic if there exists a number $n \in \mathbb{N}_0$ such that $P \oplus R^n \cong Q \oplus R^n$.
This in turn would seem to derive from the notion of stably equivalent manifolds, which was first introduced by Barry Mazur in an article in 1961. Mazur was interested in finding out when two manifolds were diffeomorphic (for a variety of purposes, one of the reasons he mentions in the paper is the Poincaré Conjecture), and so produced what he in that paper calls a "simpleminded stabilization": two real manifolds $M_1$ and $M_2$ are $k$-equivalent when there exists a natural number $k \in \mathbb{N}_0$ such that $M_1 \times \mathbb{R}^n \cong M_2 \times \mathbb{R}^n$. This notion of $k$-equivalence would in papers that followed soon be dubbed stably equivalent.
When I emailed Prof. Mazur about this, he explained to me that in his conception, the term stable here was to be read "in the same spirit" as the stable in stable homotopy theory (which predated his article), and that the process was to be thought of as analogous to taking the suspension of a space sufficiently many times. There, the term stable comes from the stable homotopy groups of spheres, which has to do with the Freudenthal suspension theorem and all that jazz.
So there we have it. The terms stable and stably have arisen to become the favoured nomenclature due to organic processes, which is why it comes across as a bit confusing. I cannot help but feel that ironically, perhaps a better term would be unstably free since in many cases, you actually need to stabilize the module by adding a few summands for it to be free.
But well, language is never perfect. I hope this little summary might be of some use to any future student who has the same confusion with the terminology as I did.


text:
Q: How to remove error ' System.AggregateException: 'Some services are not able to be constructed'' '? i am getting this error when i run the application:

System.AggregateException  HResult=0x80131500
Message=Some services are not able to be constructed (Error while validating the
service descriptor 'ServiceType:
KimiaBaseProject.Framework.Commands.CommandHandler1[KimiaBaseProject.Core.Domain.Courses.Commands.AddCourseCommand] Lifetime: Scoped ImplementationType: KimiaBaseProject.Core.ApplicationServices.Courses.Commands.AddCourseCommandHandler': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbSet1[KimiaBaseProject.Core.Domain.Courses.Entities.Course]'
while attempting to activate
'KimiaBaseProject.Infrastructures.Data.SqlServer.Courses.Repositories.CourseCommandRepository'.)
(Error while validating the service descriptor 'ServiceType:
KimiaBaseProject.Core.Domain.Courses.Repositories.ICourseCommandRepository
Lifetime: Transient ImplementationType:
KimiaBaseProject.Infrastructures.Data.SqlServer.Courses.Repositories.CourseCommandRepository':
Unable to resolve service for type
'Microsoft.EntityFrameworkCore.DbSet1[KimiaBaseProject.Core.Domain.Courses.Entities.Course]' while attempting to activate 'KimiaBaseProject.Infrastructures.Data.SqlServer.Courses.Repositories.CourseCommandRepository'.) Source=Microsoft.Extensions.DependencyInjection   StackTrace:    at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable1
serviceDescriptors, ServiceProviderOptions options)  at
Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection
services, ServiceProviderOptions options) at
Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory.CreateServiceProvider(IServiceCollection
containerBuilder) at
Microsoft.Extensions.Hosting.Internal.ServiceFactoryAdapter1.CreateServiceProvider(Object containerBuilder)    at  Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()    at Microsoft.Extensions.Hosting.HostBuilder.Build()    at KimiaBaseProject.Endpoints.WebUI.Program.Main(String[] args) in C:\Users\n.eskandari\Desktop\NedaUnitSelection_3\BaseProject_Core3.1\03. EndPoints\KimiaBaseProject.Endpoints.WebUI\Program.cs:line 17   This exception was originally thrown at this call stack: [External Code] Inner Exception 1: InvalidOperationException: Error while validating the service descriptor 'ServiceType: KimiaBaseProject.Framework.Commands.CommandHandler1[KimiaBaseProject.Core.Domain.Courses.Commands.AddCourseCommand]
Lifetime: Scoped ImplementationType:
KimiaBaseProject.Core.ApplicationServices.Courses.Commands.AddCourseCommandHandler':
Unable to resolve service for type
'Microsoft.EntityFrameworkCore.DbSet1[KimiaBaseProject.Core.Domain.Courses.Entities.Course]' while attempting to activate 'KimiaBaseProject.Infrastructures.Data.SqlServer.Courses.Repositories.CourseCommandRepository'. Inner Exception 2: InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbSet1[KimiaBaseProject.Core.Domain.Courses.Entities.Course]'
while attempting to activate
'KimiaBaseProject.Infrastructures.Data.SqlServer.Courses.Repositories.CourseCommandRepository'.

The Startup.cs is:
    namespace KimiaBaseProject.Endpoints.WebUI
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }

            public IConfiguration Configuration { get; }

            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {

                services.AddLocalization(options => options.ResourcesPath = "Resources");

                 .AddEntityFrameworkStores<CommandDbContext>()
                 .AddErrorDescriber<CustomIdentityErrorDescriber>();

                services.AddScoped<IdentityErrorDescriber, CustomIdentityErrorDescriber>();

                #endregion

                services.AddControllersWithViews()
                     .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
                    .AddDataAnnotationsLocalization(options =>
                    {
                        options.DataAnnotationLocalizerProvider = (type, factory) =>
                            factory.Create(typeof(SharedResource));
                    })
                       .AddNewtonsoftJson(options =>
                       {
                           options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

                           options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                       });

                services.AddKendo();
                services.AddSignalR();
                services.AddHttpClient();
               services.AddMemoryCache();

                services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
                services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
                services.AddDbContext<CommandDbContext>(ServiceLifetime.Transient);
                services.AddScoped<QueryDbContext>();
                services.AddScoped<IUnitOfWork, CommandDbContext>();
                services.AddTransient<IResourceManager, ResourceManager<SharedResource>>();

                services.AddAutoMapperConfigService();
                services.AddCommandHandlersRegistery(typeof(CommandHandler<>));
                services.AddCustomServicesRegistery();

            }
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager<User> userManager)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                    app.UseHttpsRedirection();

                }
                app.UseStaticFiles();
                app.UseRouting();

                app.UseAuthorization();

                app.UseEndpoints(endpoints =>
                {

                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller}/{action}/{id?}");

                    endpoints.MapControllerRoute(
                       name: "area",
                       pattern: "{area:exists}/{controller}/{action}/{id?}");
                });
                ApplicationDbInitializer.SeedDefaultUser(userManager);
                if (env.IsDevelopment())
                {
                    app.UseSpa(spa =>
                    {
                        spa.Options.SourcePath = "AppUi";
                        spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
                    });
                }
                else
                {
                    app.UseSpa(spa =>
                    {
                        spa.Options.SourcePath = "AppUi";
                        app.Use(async (context, next) =>
                        {
                            context.Request.Path = "/dist/index.html";
                            await next();
                        });
                    });
                }

                app.UseCors(bulider => bulider.AllowAnyMethod()
                .AllowAnyHeader()
                .AllowAnyOrigin());

            }
        }
    }

The CustomServiceRegistraion is:
namespace KimiaBaseProject.Core.IocConfig
{
    public static class CustomServiceRegistration

    {

        public static void AddCustomServicesRegistery(this IServiceCollection services)
        {
            services.AddTransient<ICourseCommandRepository, CourseCommandRepository>();
            services.AddTransient<ICourseQueryRepository, CourseQueryRepository>();
        }
    }

i have checked the application many times,but i don't understand what is the reason of it.


text: Q: Finding the code that attached an event listener I'm trying to find the line of JavaScript that attached an event to a node. Chrome's inspector shows me several entries under 'click' in Event Listeners, but each of these just points to the same line in _createResponder in prototype.js. I'd like to know where these events were attached, and what code runs when they fire. Is there any way to find this out?


text:
Q: Is there a way to identify the current index within a map/forEach Most languages provide something like this apples.map((apple, index) => {}). What would be Dart's equivalent of identifying the index within a map or forEach?
Someone has offered apples.asMap().map((apple, index) => {}) however that returns an unmodifiable version of the map, which is not suitable when I'm trying to map a list to produce widgets .toList() inside children: of a Column.

A: One way to use the index and value of a list item is to use the new collection for construct. The code would look something like this:
Widget build(BuildContext context) {
  final list = ['Mango', 'Orange', 'Apple'];

  return Scaffold(
    appBar: AppBar(
      title: Text(widget.title),
    ),
    body: Column(
      children: <Widget>[
        for (int i = 0; i < list.length; i++)
          ListTile(title: Text('${list[i]} has index $i')),
      ],
    ),
  );
}

For this to work you'll need to update your minimum Dart SDK version in your pubspec.yaml like so:
environment:
  sdk: ">=2.3.0 <3.0.0"

A: I'm not sure I entirely understand what you're trying to do, but map and forEach are defined on Iterable, and the elements of an Interable aren't necessarily ordered, so providing an index for each element doesn't necessarily make sense. For example, if the Iterable is a Set then the elements have no order.
I don't quite get why you need the index in your particular example.  If you expand your example, maybe I'll understand.


text:
Q: How to fetch Sidekiq job from deadset using argument Hi I want to fetch job from sidekiq deadset
I tried using jobs = Sidekiq::DeadSet.new
but this will give all the dead jobs, can we do something to fetch particular job which have certain argument.
suppose my sidekiq job was XYZWorker [1,2,3] with these three argument, so I want to fetch this job from deadset and retry it.

A: Once you create a deadset, you can iterate through it and perform operations on the jobs that match your requirements:
ds = Sidekiq::DeadSet.new
    ds.select do |job|
        if job.args[0] == 1 && job.args[1] == 2 && job.args[2] == 3
        # Do something
    end
end


text:
Q: How to fix "Uncaught TypeError: Cannot read property 'click' of null" I'm developing a Chrome Extension and getting the error "Uncaught TypeError: Cannot read property 'click' of null".  It works in the console and I made sure to close the console.  I'm trying to run this on the site below.
https://realtime.demo.sonicwall.com/main.html
popup.js
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', int);
});
function int() {
    var source = document.getElementById('j1_64_anchor').click;
}
var coll = document.getElementsByClassName("collapsible");
var i;

popup.html

<button class="collapsible">Interfaces</button>

<button onclick="int()" class="collapsible">Interfaces</button>

A: In your html there is no element with id j1_64_anchor. So your code document.getElementById('j1_64_anchor').click(); will fail.

document.addEventListener('DOMContentLoaded', function () {

    document.querySelector('button').addEventListener('click', int)
});

function int() {
    console.log('calling');
    var source = document.getElementById('j1_64_anchor').click();
}

var coll = document.getElementsByClassName("collapsible");
var i;
<button class="collapsible">Interfaces</button>

<button onclick="int()" class="collapsible">Interfaces</button>

A: Seems this line of code
function int() {
    var source = document.getElementById('j1_64_anchor').click;
}

is getting executed before the dom is ready. Try by putting it inside DOMContentLoaded event
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', int);
function int() {
    var source = document.getElementById('j1_64_anchor').click;
}
var coll = document.getElementsByClassName("collapsible");
var i;
});


text:
Q: Copy a std::u8string into a c-style string of utf8 characters Copying a string with no encodage into a c-string is quite easy:
auto to_c_str(std::string const& str) -> char* {
    auto dest = new char[str.size() + 1];
    return strcpy(dest, str.c_str());
}

But how can I do that with a std::u8string? Is there a STL algorithm that can help with that?
I tried this:
auto to_c_str(std::u8string const& str) -> char8_t* {
    auto dest = new char8_t[str.size() + 1];
    return std::strcpy(dest, str.c_str());
}

But of course, std::strcpy is not overloaded for utf8 strings.

A: In addtion to using std::memcpy, you may use std::u8string::copy and std::copy.
auto to_c_str(std::u8string const& str) -> char8_t* {
    auto dest = new char8_t[str.size() + 1];
    str.copy(dest, str.size(), 0);
    dest[str.size()] = u8'\0';
    return dest;
}

auto to_c_str(std::u8string const& str) -> char8_t* {
    auto dest = new char8_t[str.size() + 1];
    std::copy(str.begin(), str.end(), dest);
    dest[str.size()] = u8'\0';
    return dest;
}

A: strcpy isn't needed since you already know the length of what you'd like to copy, so use memcpy:
char8_t* to_c_str(std::u8string const& str) {
    auto dest = new char8_t[str.size() + 1];
    return static_cast<char8_t*>(std::memcpy(dest, str.data(), str.size()+1));
}

or std::copy:
char8_t* to_c_str(std::u8string const& str) {
    auto dest = new char8_t[str.size() + 1];
    std::copy(str.data(), str.data() + str.size() + 1, dest);
    return dest;
}

Since the u8string's own copy() method can't be used to include the null-terminator directly, I'd not use it when copying to a raw char8_t*.

A: It seems to me like it would be easier to simply leverage the built-in copying and provide .data() to the C code:
std::u8string orig = u8"abc";
auto copy = orig;
c_api(copy.data(), copy.size());

By doing this, you let the copied string manage its own lifetime and have the size on equal footing with the data. This works uniformly for any char type of std::basic_string. As an added bonus, it also works for std::vector.


text:
Q: Vuex 4 не удается изменить состояние соседнего модуля В vuex есть 2 модуля симкарт и устройств(вместе с марками,моделями,типами).
Пример элемента массива симкарт:
{
id: 4,
number: 18311770045,
iccid: 601128328639574012,
operator: Билайн,
status: Первоначальная блокировка,
device: {
  imei: 469141227904895,
  model: Abcd S-2410,
  mark: Avm
 }
}

У устройств есть отдельная таблица моделей устройств.
Сама проблема: при редактировании названия модели устройства, я изменяю названия моделей устройства и в модуле "симкарт" в каждом элементе массива менял device.model на ту что ответил сервер.
Во Vue 2 работала запись:
export const update = async ({ commit, rootState, state }, form) => {
    try {
            const res = await Api.edit(form);
            let oldModel = state.models.find(x => x.id === res.data.data.id);
            commit("setUpdatedModel", res.data.data);

            rootState.sim.items.map(sim => {
                if (sim.device?.model && sim.device.model === oldModel.title)
                  (sim.device.model = res.data.data.title)
            });
        }
    ...

и меня устраивало, но решил перейти на vue 3 и vuex 4 и столкнулся с проблемой, заметил что теперь rootState.sim.items это proxy объект и rootState.sim.items.map() изменяет только первый элемент массива, а дальше просто выбрасывает в catch и вот, не знаю что делать, где искать, куда смотреть :(

A: Сделал через root commit.
Vue 2 давало напрямую таким образом менять данные, но в Vue 3 получается закрыли эту лазейку.


text:
Q: Content with clip path with gradient border I have a bit of a complex layout. Looking for a solution for the text module. Need a dashed border with a trapezoid like shape. The shape has an opaque background and sits on top of the imagery. I have not been able to do a clip path for the trapezoid and keep the gradient dashed border as it clips it off.
clip-path: polygon(0 0, 100% 0, 95% 100%, 5% 100%);
border-width: 1px;
border-style: dashed;
border-image: linear-gradient(90deg, #ff7075 0%, #fed42e 17%, #4ec253 33%, #08b2ba 50%, #45559e 65%, #2b3570 83%, #25366c 100%) 1


text:
Q: How to use tabula to retrieve a clean table from PDF? I am trying to parse my bank statements in PDF format. I tried to use tabula.convert_into() to first extract the table from the PDF as csv file for my further processing. There are multiple pages in the PDF file and I intend to combine them into 1 single table.
import tabula
    tabula.convert_into(sourceFile, endFile.csv,output_format="csv",pages="all",java_options="-Dfile.encoding=UTF-8")

However, the CSV file retrieved is very dirty:

From where one can see the different "Balance" number (underlined in red) is not in same column, and different "Deposit" number (highlighted in yellow) is not in same column.
They are retrieved from different pages from the PDF file, while looks clean to me, as both "Balance" and "Deposit" numbers are aligned across different pages, with no misalignment:

Is there anyway where I could retrieve a clean table from the PDF using tabula?
I am very new to python so appreciate your help!


text:
Q: "site-packages\PIL\image.py",line 2131, in save...PermissionError:[error 13] permission denied: scr.png I have made a python code that takes a screenshot and saves it. Am facing the following Error in saving a piece of code:

"site-packages\PIL\image.py",line 2131, in save...PermissionError:[error 13] permission denied: scr.png

Note
Folder permission is set to read/write.
Piece of code:
snapshot = ImageGrab.grab()

    # Using png because it cannot write mode RGBA as JPEG
    file = "scr.png"
    snapshot.save(file)

A: Move your code to desktop, then your code will automatically work.
Move your code out of Site-Packages to Desktop or somewhere

A: Try in another directory and put the full path of the image file:
file = "path/to/img/scr.png"

or try with sudo or admin prompt


text:
Q: Client sending data to web server, how can the server verify the client is genuine? I am writing a c# program that sends json data to a django web server. It is very important that the data the client sends is accurate. My concern is that if someone knew the url and the data format (they could see this if they were monitoring their network traffic), they could construct their own application that sends false data to the web server. Also isn't it possible that my own client executable could be unpacked and modified?
How can the server check the data to verify that the client sending the data is genuine and unmodified?

A: You should use the Public-key cryptography.

In practice it works somehow like that:

*

*Client generates a random symmetric encryption key

*Client encrypts the message using the created key from step 1

*Client encrypts the symmetric key using the public key from the server

*Client sends the encrypted message and the encrypted key to the server

*The server can now decrypt the symmetric key with its private key and then the server uses the decrypted key to decrypt the message

I hope that you understand how it works. If not search for it on the internet. You will find a lot of information about it

A: I would say that if you are using https for your endpoint, you are fairly safe about data being tampered with between the client and the endpoint (since it is encrypted).
For the other part, it is possible for you client to get unpacked. I would suggest having a authentication process, and building your endpoint so that they would get access only to their own data.


text:
Q: Changing Dimension -> Measure Group Mapping Without Affecting Existing Views I've a cube with around 30 dimensions and 10 measure groups.
I need to add a mapping for a handful of dimensions to a particular measure group (which is already mapped for the majority of the other dimensions) - but would like to do this in such a way that existing views continue to return the same data as previous - even if the newly mapped dimensions appear in those views with non-root (i.e. not "All") members selected.
I figure there are a couple of ways of achieving this:

*

*Add a new measure group with similarly named measures that are affected by the new dimensions, leave the old measure group alone.

*Change the mappings on the existing measure group, rename the existing measures and create calculated members with the same name as the measures used to have and ensure these calculations "ignore" the newly mapped dimensions, e.g. ([Measures].[MyMeasure], Root([MyNewlyMappedDimension]), ...).

The prior option seems far and away the safer of the two - neither feels 'great' though - I'm concerned that I'm approaching this from the wrong direction!
Any thoughts / suggestions?
Thanks,
Will.

A: If you mean "Views" as in MDX code, then adding a new dimension won't change anything unless you use it in your queries (ok, unless it's default member is not the All member).
If you will be changing the queries (e.g. adding new stuff to the WHERE clause), then you are absolutely right - you can either create new measure groups so you avoid the problem with the existing ones, or use Root([Dimension]), so that you measures stay unaffected.
As for approaching it from the wrong direction - what are these "views" and can't you restrict somehow what dimensions can be used in them?


text:
Q: 3 monitors with docking station not working I have 2 ASUS 24" monitors and 1 Phillips 24" hdtv along with a usb c 3.0 docking station and a windows 10 laptop. The docking station has 1 vga and 2 display ports. I have the  2 ASUS monitors hooked up via vga and DP and they work fine. Immediately when I plug the HDTV in to the DP, it shows up BUT the ASUS monitor I have hooked up using DP immediately goes blurry. I've messed with every setting in the intel graphics settings and cannot get a crisp clear screen. The HDTV is also not crisp and clear regardless of the resolution I use.
The minute I unplug the second DP cable both ASUS monitors go back to being clear and crisp.
I've tested the cable and it works fine when I only use the two monitors. Same thing with the port on the docking station.
The HDTV works fine when plugged in to my other laptop - clear and crisp.
Laptop is a Lenovo thinkpad T470, docking station is thinkpad usb C type 40A9 and resolution I'm using is 1920x1080 60p

A: According to the ThinkPad USB-C Dock User Guide:

Maximum resolutions and refresh rates
To achieve better display experience, it is recommended that you
  connect one or two external monitors to the dock at a time.

*

*DP output only: 3840 x 2160 pixels (30 Hz)

*VGA output only: 1920 x 1200 pixels (60 Hz)

*DP and VGA simultaneous output: 1920 x 1080 pixels (60 Hz)

*DP and DP simultaneous output: 1920 x 1080 pixels (60 Hz)

A: After being told by everyone this is not possible, I was able to accomplish 1920x1080 on all 3 screens by connecting 2 via the docking station and one via the video output (hdmi) on the laptop itself.  Change power settings to do nothing when closing laptop lid, close the lid.. detect the displays and voila.
Give this a try.


text:
Q: How To Capture information about Virtual Machine resources that will be destroyed? Background
I was kind of dropped into an IaC project that uses Packer => Terraform  => Ansible to create RHEL Virtual Machines on an on-prem VMware Vsphere cluster.
Our vmware module registers output variables that we use once the VMs are created, those variables feed a  local_file resource template to build an Ansible inventory with the vm names and some other variables.
Ansible is then run using local_exec with the above created inventory to do configuration actions and run scripts both on the newly deployed VM's and against some external management applications, for example to join the VM to a domain (FreeIPA, sadly no TF good provider is available).
Issue Description
The issue that I have been wrestling with is when we run a terraform destroy (or apply with some VM count changes that destroy a VM resource), we would like to be able to repeat the process in reverse.
Capture the names of the VMs to be destroyed(Output vars from resource creation) so they can be removed from the IPA domain and have some general cleanup.
We've tried different approaches with Destroy Time Provisioners and it just seems like it would require a fundamental change in the approach outlined above to make that work.
Question
I'm wondering if there is a way to get an output variable on destroy that could be used to populate a list the VMs that would be removed.
So far my search has turned up nothing. Thanks for your time.

A: In general, it is good to plan first, even when destroying:
terraform plan -destroy -out tfplan

Then, you you can proceed with the destroy:
terraform apply tfplan

But at this moment (or before actual destroy), you have a plan what was destroyed, and you can do any analysis or automation on it. Example:
terraform show -json tfplan | jq > tfplan.json

Source:
https://learn.hashicorp.com/tutorials/terraform/plan


text:
Q: invalid characters not visible in BASH I have been working on some device that allowed login via telnet and I extracted some data from devices and made some reports, without any problems. recently, I had to switch to SSH while rest of the script is all the same, only login procedure has been changed from telnet to SSH. after switching to SSH, I am facing some problem with the data extracted that there are some invalid characters in some of the lines, below is an example: as can be seen, there is an invalid character after PON7 in the line:
OLT:LT6.PON7.ONT1,ALARM,Date time,

problem is that this invalid character is not even visible in the bash/csv file, but it was discovered when I copied the line in notepad++ or while posting it here.
now I have two problems:
1st: if someone knows what is causing these invalid characters while switching between telnet/ssh.
2nd: how to deal with this invalid character in BASH as it is not even visible in BASH, but this report is being used somewhere and these invalid characters are causing problems.
Edit:
Pasting the text into a text-to-hex converter produces this:
4f 4c 54 3a 4c 54 36 2e 50 4f 4e 37 11 2e 4f 4e 54 31 2c 41 4c 41 52 4d 2c 44 61 74 65 20 74 69 6d 65 2c

It looks like there's a DC1 character (hex 11) between the "7" and the ".".
Unfortunately, this edit also has the side effect of removing the character from the sample text.

A: Passing your text through a text to hexadecimal converter shows that the invisible character is an ASCII DC1 character (hex 11, octal 021). This character is also known as Ctrl-Q or XON. It's sometimes used in flow control.
In a bash script, you could filter it out using the tr program:
echo $badtext | tr -d '\021'

SSH doesn't inherently insert DC1 characters into text streams. If you're getting a DC1 character in the output from a device, presumably the device sent that character.


text:
Q: Encog Time Series Prediction just stick at the top and not improveing I use encog for java to do a time series prediction, but it does not seem to work at all. I am pretty new to this and i dont know whats wrong.

The red line is the training data (~3600 data entrys) and the blue line is what the Neural Net predicts...
I use the last 250 data points to predict the next one.
Network Structure:
BasicNetwork net = new BasicNetwork();
            net.addLayer(new BasicLayer(null, true, 250));
            net.addLayer(new BasicLayer(new ActivationSigmoid(), true, 6));
            net.addLayer(new BasicLayer(new ActivationSigmoid(), true, 1));
            net.setLogic(new FeedforwardLogic());
            net.getStructure().finalizeStructure();
            net.reset();
            final ManhattanPropagation train = new ManhattanPropagation(net, ndata, 0.5);

Also, it does not realy matter how many iterations i do, after the first like 10 iterations it is sticking to one error value constantly.

A: First of all, your ratio of inputs/hidden nodes/output is very unlikely to work. In his books Heaton gives advice to use following rule:
suppose that x stands for input nodes. Then hidden neurons number should be x * 2 / 3. For output neurons layer I ( Heaton doesn't give any advice except to try ) as usually use x / 15.
Second part is training algorithm. Manhattan propagation is not as good as rmsprop + backpropogation ( also according to Jeff Heaton books) .

A: I dont think your approach will work (my humble view only) in terms of time series prediction with a simple feed forward network, reason being time series prediction needs to understand a pattern of the data over time that occurs frequently and then predict the next data point. My guess is the network is not converging because of (probably) moving data. Use LSTM or Hierarchical Temporal Memory kind of networks for this probably you will get a better result hopefully.


text:
Q: Cut at the end of a Prolog statement I have encountered this cut which should return true if there exists an edge A-B or B-A for some node B of graph Graph.
node(A,Graph) :- adjacent(A,_,Graph),!.

The problem is I do not understand why removing this cut would have any effects on the returned solutions.
As I understand it the only use for a cut at the end of a Prolog statement is when there is another statement with the same name [another node(...)] which we don't want to be called if the first one succeedes. An example would be a function that takes X and Y and returns the larger one as the third parameter.
max1(X, Y, X) :- X > Y, !.
max1(_X, Y, Y).

However, there is no other statement called node(...) so I can't see how the cut could affect the solutions.
This is my code. It should find a spanning tree. It is explained in detail here. The compiler is SWI-Prolog 7.6.4 on linux.
:- op(900, fy, not).

stree1( Graph, Tree)  :-
    subset( Graph, Tree),  tree( Tree),  covers( Tree, Graph).

tree( Tree)  :-
    connected( Tree),  not hasacycle( Tree).

connected( Graph)  :-
    not ( node( A, Graph), node( B, Graph), not path( A, B, Graph, _) ).

hasacycle( Graph)  :-
     adjacent( Node1, Node2, Graph),
     path( Node1, Node2, Graph, [Node1, X, Y | _] ).

covers( Tree, Graph)  :-
    not ( node( Node, Graph), not node( Node, Tree) ).

subset( [], [] ).
subset( [X | Set], Subset)  :-  subset( Set, Subset).
subset( [X | Set], [X | Subset])  :-  subset( Set, Subset).

adjacent( Node1, Node2, Graph)  :-
      member( Node1-Node2, Graph)
      ;
      member( Node2-Node1, Graph).

node( Node, Graph)  :-  adjacent( Node, _, Graph).

path( A, Z, Graph, Path)  :-
      path1( A, [Z], Graph, Path).

path1( A, [A | Path1], _, [A | Path1] ).

path1( A, [Y | Path1], Graph, Path)  :-
      adjacent( X, Y, Graph),
      not member( X, Path1),
      path1( A, [X, Y | Path1], Graph, Path).

Solutions returned without cut (correct)
?- stree1([a-b, b-c, b-d, c-d], Tree).
Tree = [a-b, b-d, c-d] ;
Tree = [a-b, b-c, c-d] ;
Tree = [a-b, b-c, b-d] ;
false.

Solutions returned with cut (incorrect)
?- stree1([a-b, b-c, b-d, c-d], Tree).
Tree = [a-b] ;
Tree = [a-b, c-d] ;
Tree = [a-b, b-d] ;
Tree = [a-b, b-d, c-d] ;
Tree = [a-b, b-c] ;
Tree = [a-b, b-c, c-d] ;
Tree = [a-b, b-c, b-d] ;
false.

A: "As I understand it the only use for a cut at the end of a Prolog statement is when there is another statement with the same name [another node(...)] which we don't want to be called if the first one succeedes."
Well, this is not true for your condition since you are using member/2 predicate which will work with backtracking. In that situation, using cuts will prune the solution tree that Prolog uses in backtracking and can cause a change in the results you get. To explain with an example see the slightly modified code of your original post here:
node( Node, Graph , Target)  :-  adjacent( Node, Target, Graph),!.

adjacent( Node1, Node2, Graph)  :-
  member( Node1-Node2, Graph)
  ;
  member( Node2-Node1, Graph).

When you run this query in the console, you will see the output :
?- node(l,[l-x,l-y],Target).
Target = x

Why? Because in the beginning, there are two leaves of your search tree. Either the pair (l-x) or (l-y) satisfies the condition in adjacent/3. Then, according to the depth-first search, the pair (l-x) gets selected, and since you have a ! statement in your code, the rest of the search tree is now pruned. Hence, you get the result as Target = x
However, if you remove the ! statement from the code, what you will see is:
?- node(l,[l-x,l-y],Target).
Target = x ;
Target = y ;
false.

Here, you see that both leaves of the search tree are executed sequentially, according to the depth-first order, and you see two results. This is what causes you to see different results when the ! is existent or not.


text:
Q: How to query an array of objects in ActiveRecord? I am using ActiveRecord, where I am trying to query a model of Courses. Every Course has the following schema:
Courses:
[{
    name: "Intro to Math",
    id: 1,
    segments: [{id: 1, subject_id: "123-456"}, {id: 1, subject_id: "789-145"}]
},
{
    name: "Intro to Probability",
    id: 2,
    segments: [{id: 1, subject_id: "123-456"}, {id: 1, subject_id: "000-000"}]
},
{
    name: "Intro to Stats",
    id: 3,
    segments: [{id: 1, subject_id: "111-111"}, {id: 1, subject_id: "000-000"}]
}]

How would I write an ActiveRecord query that would get me every Course which has a segment which has the id "123-456" (which in this case, would be the Course with the id 1 & 2)?

A: Course.joins(:segments).where(segments: { subject_id: "123-456" })

For more information and examples, please refer to the documentation.

A: From this statement: Course which has a segment which has the id "123-456" (which in this case, would be the Course with the id 1 & 2), seems you meant Course which has a segment which has the segment_id "123-456"
If that is the case:
Courses.joins(:segments).where("segments.subject_id='123-456'")


text:
Q: Do bitwise values have to be exponential? In all bitwise examples, I see values being incremented exponentially (1, 2, 4, 8, etc).  However, in the following Enum, I use 1, 2, 3, 4 (and pardon the VB, if you will):
<Flags()>
Enum BitWiseTest
    One = 1
    Two = 2
    Three = 3
    Four = 4
End Enum

To my surprise, the following code works:
Dim TestBits As BitWiseTest

TestBits = TestBits Or BitWiseTest.One
TestBits = TestBits Or BitWiseTest.Two
TestBits = TestBits Or BitWiseTest.Three
TestBits = TestBits Or BitWiseTest.Four

Dim BitToRemove As BitWiseTest

BitToRemove = BitWiseTest.Two

TestBits = Not BitToRemove

Console.WriteLine(TestBits And BitToRemove)

Commenting out the line TestBits = Not BitToRemove will show you that not removing the bit will show you that it's still on.  Channging BitToRemove = BitWiseTest.Two to use another enum value will show you that it works for other bits, as well.
It appears to be working flawlessly, so what's up with the exponential incrementation of values that I am seeing everywhere regarding bitwise?

A:
It appears to be working flawlessly

It depends on what you mean by "flawlessly".
Do you really want BitWiseTest.One Or BitwiseTest.Two to equal BitwiseTest.Three? That's what you'll get at the moment, which isn't normally ideal... Typically you want the flags to be independent, which means that they need to be represented by independent bits in the binary representation - and that's precisely what you get by using values of 1, 2, 4, 8, 16 etc.

A: There are generally two kinds of enums. For an enum:

*

*One of the values is used.

*A combination of values is used.

One of the values is used
In this case you can just number the enum members any way you like. You can even have two members with the same value if they mean the same. For example:
Enum Comparison
    None = 0
    CaseSensitive = 1
    IgnoreCase = 2

    Default = 1
End Enum

A combination of values is used
A value is now boolean: it is either on (used, specified) or off (not used or specified). This converts nicely to bits, which are 1 (on) or 0 (off). To be able to distinguish the values from one another, you should use powers of two. Then there is for any particular bit only one value that can set that bit on or off.
<Flags()>
Enum NumberStyles
    None = 0                    ' Binary:          0
    AllowLeadingWhite = 1       ' Binary:          1
    AllowTrailingWhite = 2      ' Binary:         10
    AllowLeadingSign = 4        ' Binary:        100
    AllowTrailingSign = 8       ' Binary:       1000
    AllowParentheses = 16       ' Binary:      10000
    AllowDecimalPoint = 32      ' Binary:     100000
    AllowThousands = 64         ' Binary:    1000000
    AllowExponent = 128         ' Binary:   10000000
    AllowCurrencySymbol = 256   ' Binary:  100000000
    AllowHexSpecifier = 512     ' Binary: 1000000000
End Enum

Now you can combine two values to get a new one, and you can distinguish the values:
Dim testBits As NumberStyles
testBits = NumberStyles.AllowHexSpecifier _
        Or NumberStyles.AllowTrailingWhite _
        Or NumberStyles.AllowLeadingWhite       ' Binary: 1000000011

' If (1000000011 And 1000000000) <> 0 Then
If testBits.HasFlag(NumberStyles.AllowHexSpecifier) Then
    ' Do something
End If

And you can add those combinations to the enum too, if it makes sense:
<Flags()>
Enum NumberStyles
    ' ...
    Integer = 7                 ' Binary:        111
    Number = 111                ' Binary:    1101111
    Float = 167                 ' Binary:   10100111
    Currency = 383              ' Binary:  101111111
    HexNumber = 515             ' Binary: 1000000011
End Enum

About your example
Look at the binary values of your example. Values One, Two and Four are powers of two, but Three is not. If I extend your example, maybe you can see the problem:
<Flags()>
Enum BitWiseTest
    One = 1     ' Binary:    1
    Two = 2     ' Binary:   10
    Three = 3   ' Binary:   11
    Four = 4    ' Binary:  100
    Five = 5    ' Binary:  101
    Six = 6     ' Binary:  110
    Seven = 7   ' Binary:  111
End Enum

Now, doing Six Or Three = Seven, which is usually not what you want. Also value And Two is True when value is Three, Six or Seven, which is also probably now what you want. The reason is that the one bit that is set in Two is also present in Three, Six and Seven due to how you chose the values.

A: They don't have to be exponential, there's no language limitation for that.
For most cases it makes sense to define them exponential so they are independent from one-another. In a very few cases you may benefit from combining the exponential flag values with predefined state values:
public enum KitchenState{
    NothingHappening = 0,

    PanOnStove = 1,
    StoveOn = 2,
    Preheating = 3,

    EggsInPan = 4,
    EggsCooking = 7,
}

In this case Preheating and EggsCooking are states and PanOnStove, StoveOn and EggsInPan are flags. This is mostly a gimmick but it can come handy on occasion


text:
Q: Scripting input to XSL Transformation in XML Tools plugin for Notepad++ I'm using the Python Script plugin (http://npppythonscript.sourceforge.net) for Notepad++ to do some automated tasks with XML files. I've been able to use the XSL Transformation function in the XML Tools plugin from the script I wrote, but only to get the popup to appear, not to input a path to the .xsl file and set off the transform.
Here's my code to open an XML file then get the XSL Transformation window to pop up (in Python, running from Python Script in Notepad++):
notepad.open(xmlFilePath)
notepad.runMenuCommand("XML Tools", "XSL Transformations")
#I have a time.sleep(30) here so I can manually input the XSL file
notepad.saveAs(htmlFilePath)
notepad.close()

How would I go about being able to fill in the .xsl path automatically and simulate the button press to set off the transform?


text:
Q: Implementing XOR linked list. Size 1 or 2 Suppose this is my XOR linked list struct...

struct xList {
    int data;
    xList* xor;
}

What should xor contain if the size of the xor linked list is 1 or 2?

A:
What should xor contain if the size of the xor linked list is 1 or 2?

It should contain prev ^ next where prev is a pointer to the previous element, next is a pointer to the next element, and ^ is the XOR operator. The first element in the list obviously has nil for the previous item, and the last item has nil for the last item, so you'd get nil ^ next and prev ^ nil for those elements, respectively. In a list of size 1, there's no previous or next element, so you can probably figure out what you'd store in the xor field.
The idea with an xor linked list is that you have to know the address of either the previous or next element in the list already in order to determine the next or previous element. That's no problem if you're iterating through the list, though, and since that's what you do with linked lists, it can be a useful optimization. If you're iterating from head to tail, for example, you start with a pointer to the first element in the list. The previous element is nil, so to get the next element you compute: next = prev ^ xor. You also have to remember the pointer to the current element before moving to the next element, so that you can use it to get to the following element.

A: You store (previous ^ next) in the xorlink pointer.
Consider
struct xList
{
    int data;
    xList* xorlink;
}

A -> B -> C -> D
You start from the head. You know head doesn't have a previous - so xorlink will point to the B node. You save the current pointer(A) and move to next (B).
You do (A ^ B->xorlink) to get the pointer to C. (B ^ C->xorlink) will give you the pointer to D. And so on
Reverse traversal is also similar.
Anyway, the answer to your question

*

*If the size is 1, then the first node's xorlink should contain NULL.

*If the size is 2, then the first node's xorlink should contain a pointer to 2nd node. The 2nd node's xorlink should contain a pointer to the 1st node.


text:
Q: asp.net mvc example with db I know the basics of MVC. But I am looking for an asp.net mvc example with db.
The following example explains the same - but the db is within the app_data folder. But in real practice, as u know, we will use an external SQL server for this
http://www.asp.net/mvc/tutorials/older-versions/movie-database/create-a-movie-database-application-in-15-minutes-with-asp-net-mvc-cs
Can u pl site an example - which explains asp.net mvc with db (just save & retrieve)

A: It might not completely meet your question but it is quit usual to use Entity Framework or NHibernate to manage your database
See ASP.Net site or the Entity Framework tutorial
Maybe you can find some other answers at that site.

A: There is no difference on the mvc side. You just have a different connection string to point to a sql server instead of a file inside app_data folder.
Create the same database on you local sql server express and change the connection string to point there. You'll see that will work the same.
In order to make your life easier, you can download SQL ServerManagement Studio Express (this is 2008 version)


text:
Q: PHP Force Download For RTMP I'm trying to download rtmp stream with php but every time it returns empty file. Is there any method to this aim?
$file_url = 'rtmp://16.somestream/live';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) ."\"");
readfile($file_url);


text:
Q: Estimating phi for a time series in R with irregular time intervals I've got timeseries data where multiple locations have been visited multiple times, and I need to check whether there's temporal autocorrelation in the data. I can use the corAR1 function in the lme4 library to construct and initialize the corstruct object, but no matter what starting value of phi I supply, it just spits the same value back at me. This seems to indicate that whatever method corAR1 is using to estimate phi isn't happy with my data.
Is there some other (easy) way to get an estimate of phi somehow?

A: corAR1() is very unlikely to work with the lme4 package. It's from the nlme package. Have a look at corCAR1() or corExp() when working with irregular time series. And make sure that you specify the time variable correctly. E.g. corExp(form = ~ Time)


text:
Q: How to run a hello.js file in Node.js on windows? I am trying to run a hello world program written in javascript in a separate file named hello.js
Currently running windows version of node.js.
The code runs perfectly in console window but how do I reference the path in windows environment.
C:\abc\zyx\hello.js

in Unix I guess it is showing $ node hello.js
I'm absolutely new to Node.js Please correct me if I am doing something wrong.
I tried
> node  C:\abc\zyx\hello.js ----didn't work
> C:\abc\zyx\hello.js --didn't work
UPDATE1:
Added node.exe to the folder where hello.js file is sitting.
Added path point to the folder c:\abc\zyx\  and I get an error that says
ReferenceError: hello is not defined
see contents of hello.js
setTimeout(function() {
console.log('World!');
}, 2000);
console.log('Hello');

UPDATE 2:
So far I have tried all these version and none of them seems to work.  May be I am doing something completely wrong.
>node hello.js
>$ node hello.js
>node.exe hello.js
>node /hello.js
>node \hello.js
> \node \hello.js
> /node /hello.js
> C:\abc\xyz\node.exe C:\abc\xyz\hello.js
> C:\abc\xyz\node.exe C:/abc/xyz/hello.js
> hello.js
> /hello.js
> \hello.js
>node hello

Refer to my file structure
.
├── hello.js
├── node.exe
└── paths.txt

RESOLVED:
Instead of running node.exe, try running in command prompt with the following option and it worked.
c:\>node c:\abc\hello.js
Hello
World! (after 2 secs)

A: another simple way

*

*download nodejs to your system

*open a notepad write js command "console.log('Hello World');"

*save the file as hello.js preferably same location as nodejs

*open command prompt navigate to the location where the nodejs is located
c:\program files\nodejs

*and run the command from the location like c:\program files\nodejs>node hello.js

*in case the js file in another location give the path of file
  c:\program files\nodejs>node path\hello.js

A: I installed node for windows.
There is a node.js command prompt when I search for node.js in windows 7 start menu
If you run this special command prompt, you can node anything in any location without setting up the path or copy node.exe everywhere.

A: Install the MSI file:
Go to the installed directory C:\Program Files\nodejs from command prompt n
C:\>cd C:\Program Files\nodejs enter..
node helloworld.js
output:
Hello World

A: Here are the exact steps I just took to run the "Hello World" example found at http://nodejs.org/. This is a quick and dirty example. For a permanent installation you'd want to store the executable in a more reasonable place than the root directory and update your PATH to include its location.

*

*Download the Windows executable here: http://nodejs.org/#download

*Copy the file to C:\

*Create C:\hello.js

*Paste in the following content:

    var http = require('http');
    http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('Hello World\n');
    }).listen(1337, "127.0.0.1");
    console.log('Server running at http://127.0.0.1:1337/');

*

*Save the file

*Start -> Run... -> cmd

*c:

*C:>node hello.js
Server running at http://127.0.0.1:1337/

That's it. This was done on Windows XP.

A: You need to make sure that node is in your PATH. To set up your path, this out.
Make sure that the directory that has node.exe is in your PATH. Then you should be able to
run node path_to_js_file.js.
For a good "Hello World" example, check out: http://howtonode.org/hello-node

A: WinXp:
I have created a .bat file
node c:\path\to\file\my_program.js

That just run  my_program.bat from Explorer or in cmd window

A: Go to cmd and type: node "C:\Path\To\File\Sample.js"

A: Windows/CMD does not know where the node file is located. You can manually type out:
path=%path%;"c:\Program Files\nodejs"

each time you open a new cmd.exe prompte
OR (in Windows 10),

*

*right click on This PC -> properties.

*Click on Advanced system settings -> Environment Variables (bottom right).

*Select Path and click Edit.

*Click new and enter C:\Program Files\nodejs.

*Reboot and you should be able to run node from any directory.

A: Just change file association of .js file to node.exe and you can run directly from explorer.

*

*Right click on the file -> Select "Open with" -> Select "Choose another program"

*Check box "Always use this app to open .js file"

*Click "More apps" -> "Look for another app in PC"

*Navigate to node.js installation directory.(Default C:\Program Files\nodejs\node.exe"

*Click "Open" and you can just see cmd flashing

Now you will be able to run any .js files directly just by double clicking.
Note: Adding below code to the end of js file will be useful as it will keep the console open for a keystroke.
console.log('Press any key to exit');

process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.on('data', process.exit.bind(process, 0));

A: The problem was that you opened the Node.js repl while everyone automatically assumed you were in the command prompt. For what it's worth you can run a javascript file from the repl with the .load command. For example:
.load c:/users/username/documents/script.js

The same command can also be used in the command prompt if you first start node inside the command prompt by entering node with no arguments (assuming node is in PATH).
I find it fascinating that 1)everyone assumed you were in the command prompt rather than repl, 2)no one seems to know about .load, and 3)this has 273 upvotes, proving that a lot of other node.js beginners are similarly confused.

A: Step For Windows

*

*press the ctrl + r.then type cmd and hit enter.

*now command prompt will be open.

*after the type cd filepath of file. ex(cd C:\Users\user\Desktop\ )
then hit the enter.

*please check if npm installed or not using this command node -v.
then if you installed will get node version.

*type the command on command prompt like this node filename.js  . example(node app.js)

C:\Users\user\Desktop>node app.js

A: type node js command prompt in start screen. and use it.
OR
set PATH of node in environment variable.

A: Install node properly, that's it.
Now open terminal to path where your .js file is.
for example- if Javascript file(fileName.js) is at folder C:\Documents\Project1.
Just go to that folder, type node to check node is enable
then type node fileName.js
Simple! Your work is done!!

A: c:\> node.exe %CD%\hello.js

%CD% captures the current directory under DOS

A: For all stuck on how to start!
https://github.com/sethvincent/javascripting
Copy here incase link dies:

*

*Open node.js command prompt

*Make directory called javascripting by typing "mkdir javascripting"

*Change directory into the javascripting folder by typing "cd javascripting"

*Create a file named introduction.js by typing "touch introduction.js" OR FOR WINDOWS: "NUL > introduction.js"

*Open the file and type some javascript e.g. "Console.log('hello');"

*Save the file and check it runs by typing "javascripting verify introduction.js"

A: All you have to do is right click the .js file on Windows and press "Open with Command Prompt"
OR
Open cmd, copy the path to the folder containing your script, and run the command "cd [paste text here]". Then do "node example.js"

A: I had such problem for windows. And I decided it so:
startApp.cmd:
@set JAVA_HOME=C:\jdk160_24
@set PATH=%JAVA_HOME%/bin;%PATH%
@cd /D C:\app\

@start /b C:\WINDOWS\system32\cscript.exe
C:\app\start.js

and saved it cmd file in dir C:\scripts
next file is runApp.bat:
C:\scripts\startApp.cmd


text:
Q: Create Python Dictionary from feature classes, fields, and domains I want to create a Python dictionary with a Feature class as the key and the fields of the feature class and domains of the feature class as separate values. I'm starting off by simply attempting to add a Feature class (as a key) and its respective feature types(as values) but I'm not sure how to build that out. here's what I am trying to do by using list comprehension but my dictionary is empty:
    Dict = {fc.name: fc.featureType.values()for fc in arcpy.ListFeatureClasses(r"gdb")}

    print Dict

Any clues on how I can start this off?

A: As an alternative to list comprehension, and to try and learn more about using dictionaries with ArcPy I think you should start with an empty dictionary and then use Describe to determine and add the values as you iterate ListFeatureClasses.

A: The  *  argument passes all fields into arcpy.da.SearchCursor. The fields function returns a list of all the fields in your feature class.
fcs = arcpy.ListFeatureClasses()
features = {}
for fc in fcs:
    cursor = arcpy.da.SearchCursor(fc, '*')
    features[fc] = list(cursor.fields)


text:
Q: Return a dataset based on conditional with Highmaps Take this demo as an example
series : [{
    name: 'UTC',
    data: $.map(['IE', 'IS', 'GB', 'PT'], function (code) {
        return { code: code };
    })
}, {
    name: 'UTC + 1',
    data: $.map(['NO', 'SE', 'DK', 'DE', 'NL', 'BE', 'LU', 'ES', 'FR', 'PL', 'CZ', 'AT', 'CH', 'LI', 'SK', 'HU',
            'SI', 'IT', 'SM', 'HR', 'BA', 'YF', 'ME', 'AL', 'MK'], function (code) {
        return { code: code };
    })
}, {
    name: 'UTC + 2',
    data: $.map(['FI', 'EE', 'LV', 'LT', 'BY', 'UA', 'MD', 'RO', 'BG', 'GR', 'TR', 'CY'], function (code) {
        return { code: code };
    })
}, {
    name: 'UTC + 3',
    data: $.map(['RU'], function (code) {
        return { code: code };
    })
}]

Let's say, as an arbitrary example, I wanted to create an entry with name: 'starts with A' and I wanted the data object to contain all objects in $.map where code.indexOf('A') == 0 (basically checking if the first character in code is an 'A'.
With pseudocode, this is how I would approach it, I'm just not sure how to execute it.
{
name: 'starts with A',
data: $.map(/* Select all entries somehow */, function (code) {
        if(code.indexOf('A') == 0)
            return { code: code };
    })
}


text:
Q: clearInterval not clearing the set interval onMouseUp Trying to make a button event onMouseDown, a function should run at the end of the set amount of time. The function runs onMouseDown and clears the interval onMouseUp, but the interval still runs after releasing the button.
This is the code currently. I have the interval global and set it in the planting function. It should unset in the notPlanting function, but it does not.
import React from "react";

function PlantDefuser() {
    var interval

    function planting() {
        interval = setInterval(() => {
            console.log("Defuser Planted")
        }, 1000)
    }

    function notPlanting() {
        console.log(interval)
        clearInterval(interval)
    }

    return (
        <button onMouseDown={planting} onMouseUp={notPlanting}>Press and Hold</button>
    )
}

export default PlantDefuser

A: This could help you:
useRef allows us to store and update data in the component without triggering a re-render. Now the only re-render happens when the props are updated.
We can store interval in a ref like so
import { useRef } from "react";

const PlantDefuser = () => {
  const interval = useRef();

  function planting() {
    interval.current = setInterval(() => {
      console.log("Defuser Planted");
    }, 1000);
  }

  function notPlanting() {
    clearInterval(interval.current);
  }

  return (
    <button onMouseDown={planting} onMouseUp={notPlanting}>
      Press and Hold
    </button>
  );
}

export default PlantDefuser

A: When you declare variables like so in the function component, it is being created on each render. You should be saving the interval id in a state like so:
import React, { useState } from "react";

const PlantDefuser = () => {
    const [plantingInterval, setPlantingInterval] = useState(null);

    const planting = () => {
        const plantingIntervalId = setInterval(() => {
            console.log("Defuser Planted");
        }, 1000);
        setPlantingInterval(plantingIntervalId);
    };

    const notPlanting = () => {
        clearInterval(plantingInterval);
        setPlantingInterval(null);
    };

    return (
        <button onMouseDown={planting} onMouseUp={notPlanting}>
            Press and Hold
        </button>
    );
};

export default PlantDefuser;

You might also want to make sure the interval is being cleared when the component unmounts.

A: You can use useEffect hook with cleanup function   to manage the clearInterval method .
like this :
function PlantDefuser() {
  const [run, setRun] = useState(false);

  useEffect(() => {
    if (run) {
      const countTimer = setInterval(() => {
        console.log("Defuser Planted");
      }, 1000);

      return () => {
        console.log(countTimer);
        clearInterval(countTimer);
      };
    }
  }, [run]);

  return (
    <button onMouseDown={() => setRun(!run)} onMouseUp={() => setRun(!run)}>
      Press and Hold
    </button>
  );
}

export default PlantDefuser;


text:
Q: Unable to label axis of correlation matrix or cap the figure legend values in R studio? I am able to plot a correlation matrix of the dataframe 'Object2'.
ggcorrplot(object2)

However, when I try to extend this function, to cap the figure legend and to label the axis, it does not work:
ggcorrplot(object2, aes(x=Coef3,y=Coef4), limits=FALSE)

It gives me this:
Error in ggcorrplot(object2, aes(x = Coef3, y = Coef4), limits = FALSE) :
  unused argument (limits = FALSE)


text:
Q: How to extract number values from an array and then combine it with another string? I have an array $qwe2 from which I need to make 2 separate arrays. One which will contain not numeric values in this example mom, sister and an array with numeric values 11dad 13brother.
$qwe = " mom   11dad  sister  13brother ";
$qwe0 = ucwords(strtolower($qwe));
$qwe1 = preg_replace('/\s+/', ' ',$qwe);
$qwe7 = trim($qwe1);
$qwe2 = explode(' ',$qwe7);

var_dump($qwe2);

This is what it looks like :
array (size=4)
  0 => string 'mom' (length=3)
  1 => string '11dad' (length=5)
  2 => string 'sister' (length=6)
  3 => string '13brother' (length=9)

All these things above are also needed but I managed to do them easily. I don't understand the part below.
Desired result : $asd = array("mom, sister"); and $zxc = array("11dad, 13brother");
Also I have a string $doyou = "Do you like ?" which I need to combine with the new array $asd which will result in : Do you like mom?, Do you like sister?
Thanks in advance!

A: Use PHP's array_filter() with some custom functions that check for numbers in the string:
$asd = array_filter($qwe2, 'hasNumbers');
$zxc = array_filter($qwe2, 'hasNoNumbers');

function hasNumbers($string)
{
    return strcspn($string, '0123456789') != strlen($string);
}
function hasNoNumbers($string)
{
    return strcspn($string, '0123456789') == strlen($string);
}

Then array_map() can help you do the string replace:
echo implode(', ', array_map('myStringReplace', $asd));

function myStringReplace($string)
{
    return str_replace('?', $string, 'Do you like ?');
}


text:
Q: Is it possible to HIDE enum value or name descriptions from swashbuckle documents? We use swashbuckle to generate our API's document and swagger page.
One API takes an enum as parameter, and the swagger document will generate a list of all possible enum values.
 PerformanceEndType (string, optional): The descriptions we put in.  ['DayEnd', 'MonthEnd', 'QuarterEnd', 'YearEnd'],

In the description, we have a link which shows details about the enum, so I wants to hide the enum list swashbuckle gives us.
However, seems swashbuckle doesn't have an option to turn this on and off. I checked DescribeAllEnumsAsStrings but that doesn't really do what I want.


text:
Q: Cakephp error custom page Hello I am new in cakephp and I want to show an error page if someone enter wrong url in my cakephp application.
I am using this code as per given example on internet
CakePHP 2.0 - How to make custom error pages?
I am unable to see any custom error page in my application.I have used all the given steps added in that url

A: Try the second answer:

To customize the content of a 404-error page and don't need custom
  logic, simply edit the contents of app/View/Errors/error400.ctp.

Note that you need to also set your debug level to zero to see your custom error page.

A: The best way is handle all errors in AppController.php
public function beforeRender() {
        parent::beforeRender();
        if ($this->name == 'CakeError') {
            $this->redirect(array(
               'controller' => 'ExampleController', 'error_action'));
        }
}
And make view View/ExampleController/error_action.ctp with your needs.


text:
Q: Paths with different orientations I am given two equivalent $C^1$ paths $\alpha : [a,b] \to \mathbb R^n $ and $\beta : [c,d] \to \mathbb R^n$ such that they have different orienation. That means that there exists $\varphi : [a,b] \to [c,d]$ which is $C^1$ diffeomorphism, such that $\alpha = \beta \circ \varphi$ and $\varphi'(t)<0, t \in [a,b]$
How do i show that $\alpha(a) = \beta(d)$ and $\alpha(b) = \beta(c)$. Thought about using Bolzano-Weierstrass but i am not sure how.
I sort of get that $\alpha(a) \in \{\beta(c), \beta(d)\}$ since $\varphi$ is homeomorphism, and so it maps boundary to boundary, but i cant show that it is equal to $\beta(d)$

A: Since $ \varphi'(t) < 0 $ for all $t \in [a, b]$ this means that $\varphi(t)$ is monotonically decreasing.
Since $\varphi: [a, b] \to [c, d]$ this can only mean $\varphi(a) = d$ and $\varphi(b) = c$ because $c < d$.
Therefore $$\alpha(a) = (\beta \circ \varphi)(a) = \beta(\varphi(a)) = \beta(d)$$ and $$\alpha(b) = (\beta \circ \varphi)(b) = \beta(\varphi(b)) = \beta(c).$$