text:
Q: Create Multimedia component with Metadata fields.using core service I am creating Multimedia components using core service and everything is working fine. But when Metadata schema fields are defined on the Multimedia schema using which I am creating my Multimedia components then I am getting following error:-
Unable to find http://www.tridion.com/ContentManager/5.0/DefaultMultimediaSchema:Metadata.
This message is displayed when I have given Default Multimedia schema's TCM ID for Multimedia component. As metadata fields are saved in Tridion Database so I first have to retrieve these fields from broker or what is the best solution for this, please suggest. Below is the sample code. Please modify it if someone have any idea for providing default value for metadatafields and how to retrieve them (with/without querying broker DB):-
 public static string UploadMultiMediaComponent(string folderUri, string title, string schemaID)
    {
        core_service.ServiceReference1.SessionAwareCoreService2010Client client = new SessionAwareCoreService2010Client();
        client.ClientCredentials.Windows.ClientCredential.UserName = "myUserName";
        client.ClientCredentials.Windows.ClientCredential.Password = "myPassword"; client.Open();

        ComponentData multimediaComponent = (ComponentData)client.GetDefaultData(
                                             ItemType.Component, folderUri);
        multimediaComponent.Title = title;

        multimediaComponent.ComponentType = ComponentType.Multimedia;
        multimediaComponent.Schema.IdRef =schemaID;

        //multimediaComponent.Metadata = "";

        StreamUpload2010Client streamClient = new StreamUpload2010Client();

        FileStream objfilestream = new FileStream(@"\My Documents\images.jpg",
                                                  FileMode.Open, FileAccess.Read);
        string tempLocation = streamClient.UploadBinaryContent("images.jpg",
                                                               objfilestream);

        BinaryContentData binaryContent = new BinaryContentData();
        binaryContent.UploadFromFile = tempLocation;
        binaryContent.Filename = "images.jpg";
        binaryContent.MultimediaType = new LinkToMultimediaTypeData()
        {
            // for jpg file
            IdRef = "tcm:0-2-65544"
        };
        multimediaComponent.BinaryContent = binaryContent;

        IdentifiableObjectData savedComponent = client.Save(multimediaComponent,
                                                            new ReadOptions());

        client.CheckIn(savedComponent.Id, null);
        streamClient.Close();
        client.Close();
        Console.WriteLine(savedComponent.Id);
        //}
    }

A: I don't know why your code not working but following code is working for me
public static ComponentData GenerateMultiMediaComponent(TridionGeneration tridionGeneration, XmlData newsArticle, string componentName)
        {
            try
            {
                Dictionary<string, object> dicTridion = Common.GetTridionObject(tridionGeneration.client, ItemType.Component, tridionGeneration.Settings.ComponentFolderUri, componentName);
                int objectCount = (int)dicTridion["count"];

                SchemaFieldsData schemaFields = tridionGeneration.client.ReadSchemaFields(tridionGeneration.Settings.SchemaUri, true, new ReadOptions());

                ComponentData componentData = (ComponentData)tridionGeneration.client.GetDefaultData(ItemType.Component, tridionGeneration.Settings.ComponentFolderUri);

                if (schemaFields.Fields != null)
                {
                    var fields = Fields.ForContentOf(schemaFields);
                    Helper.FillSchemaFields(tridionGeneration, fields);
                    componentData.Content = fields.ToString();
                }

                if (schemaFields.MetadataFields != null)
                {
                   var  metafields = Fields.ForMetadataOf(schemaFields, componentData);
                    Helper.FillSchemaFields(tridionGeneration, metafields);
                    componentData.Metadata = metafields.ToString();
                }

                componentData.Title = (objectCount == 0) ? componentName : componentName + " " + (objectCount + 1).ToString();
                componentData.ComponentType = ComponentType.Multimedia;

                StreamUpload2010Client streamClient = new StreamUpload2010Client();

                FileStream objfilestream = new FileStream(@"[IMAGE_PATH]", FileMode.Open, FileAccess.Read);
                string tempLocation = streamClient.UploadBinaryContent("images.jpg", objfilestream);
                BinaryContentData binaryContent = new BinaryContentData();
                binaryContent.UploadFromFile = tempLocation;
                binaryContent.Filename = "[IMAGE_NAME]";
                componentData.BinaryContent = binaryContent;
                binaryContent.MultimediaType = new LinkToMultimediaTypeData()
                {
                    IdRef = "tcm:0-2-65544"
                };

                componentData = (ComponentData)tridionGeneration.client.Create(componentData, new ReadOptions());

                return componentData;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

Here is the Helper class:
public static class Helper
    {
        public static void FillSchemaFields(TridionGeneration tridionGeneration, Fields fields)
        {
            List<XmlData> data = XmlHelper.xmlData;

            var ofield = fields.GetEnumerator();
            while (ofield.MoveNext())
            {
                Field f = ofield.Current;
                FillFieldValue(tridionGeneration, fields, f, data[0]);
            }
        }

        private static void FillFieldValue(TridionGeneration tridionGeneration, Fields fields, Field f, XmlData data)
        {
            if (f.Type == typeof(MultimediaLinkFieldDefinitionData))
            {
                fields[f.Name].Value = tridionGeneration.Settings.DefaultImageUri;
            }
            else if (f.Type != typeof(EmbeddedSchemaFieldDefinitionData))
            {
                foreach (XmlData fieldvalue in data.Attributes)
                {
                    if (f.Type == typeof(DateFieldDefinitionData))
                    {
                        if (fieldvalue.text.ToLower() == f.Name.ToLower())
                        {
                            fields[f.Name].Value = Convert.ToDateTime(fieldvalue.value).ToString("yyyy-MM-ddTHH:mm:ss");
                        }
                        else
                        {
                            string val = FindSchemaValue(tridionGeneration, fieldvalue.Attributes, f.Name);
                            if (!string.IsNullOrEmpty(val))
                            {
                                fields[f.Name].Value = Convert.ToDateTime(val).ToString("yyyy-MM-ddTHH:mm:ss");
                            }
                        }
                    }
                    else
                    {
                        if (fieldvalue.text.ToLower() == f.Name.ToLower())
                        {
                            fields[f.Name].Value = System.Net.WebUtility.HtmlEncode(fieldvalue.value);
                        }
                        else
                        {
                            string val = FindSchemaValue(tridionGeneration, fieldvalue.Attributes, f.Name);
                            if (!string.IsNullOrEmpty(val))
                            {
                                fields[f.Name].Value = System.Net.WebUtility.HtmlEncode(val);
                            }
                        }
                    }
                }
            }
            else
            {
                Fields fs = f.GetSubFields();
                var ofield = fs.GetEnumerator();
                while (ofield.MoveNext())
                {
                    Field ff = ofield.Current;
                    FillFieldValue(tridionGeneration, fs, ff, data);
                }
            }
        }

        private static string FindSchemaValue(TridionGeneration tridionGeneration, List<XmlData> data, string fieldname)
        {
            foreach (XmlData fieldvalue in data)
            {
                if (fieldvalue.text.ToLower() == fieldname.ToLower())
                {
                    return fieldvalue.value;
                }
                else
                {
                    FindSchemaValue(tridionGeneration, fieldvalue.Attributes, fieldname);
                }
            }
            return "";
        }
    }

and the Fields class:
public class Fields
    {
        private ItemFieldDefinitionData[] definitions;
        private XmlNamespaceManager namespaceManager;

        private XmlElement root; // the root element under which these fields live

        // at any point EITHER data OR parent has a value
        private SchemaFieldsData data; // the schema fields data as retrieved from the core service
        private Fields parent; // the parent fields (so we're an embedded schema), where we can find the data

        public Fields(SchemaFieldsData _data, ItemFieldDefinitionData[] _definitions, string _content = null, string _rootElementName = null)
        {
            data = _data;
            definitions = _definitions;
            var content = new XmlDocument();
            if (!string.IsNullOrEmpty(_content))
            {
                content.LoadXml(_content);
            }
            else
            {
                content.AppendChild(content.CreateElement(string.IsNullOrEmpty(_rootElementName) ? _data.RootElementName : _rootElementName, _data.NamespaceUri));
            }
            root = content.DocumentElement;
            namespaceManager = new XmlNamespaceManager(content.NameTable);
            namespaceManager.AddNamespace("custom", _data.NamespaceUri);
        }
        public Fields(Fields _parent, ItemFieldDefinitionData[] _definitions, XmlElement _root)
        {
            definitions = _definitions;
            parent = _parent;
            root = _root;
        }

        public static Fields ForContentOf(SchemaFieldsData _data)
        {
            return new Fields(_data, _data.Fields);
        }
        public static Fields ForContentOf(SchemaFieldsData _data, ComponentData _component)
        {
            return new Fields(_data, _data.Fields, _component.Content);
        }
        public static Fields ForMetadataOf(SchemaFieldsData _data, RepositoryLocalObjectData _item)
        {
            return new Fields(_data, _data.MetadataFields, _item.Metadata, "Metadata");
        }

        public string NamespaceUri
        {
            get { return data != null ? data.NamespaceUri : parent.NamespaceUri; }
        }
        public XmlNamespaceManager NamespaceManager
        {
            get { return parent != null ? parent.namespaceManager : namespaceManager; }
        }

        internal IEnumerable<XmlElement> GetFieldElements(ItemFieldDefinitionData definition)
        {
            return root.SelectNodes("custom:" + definition.Name, NamespaceManager).OfType<XmlElement>();
        }
        internal XmlElement AddFieldElement(ItemFieldDefinitionData definition)
        {
            var newElement = root.OwnerDocument.CreateElement(definition.Name, NamespaceUri);

            XmlNodeList nodes = root.SelectNodes("custom:" + definition.Name, NamespaceManager);
            XmlElement referenceElement = null;
            if (nodes.Count > 0)
            {
                referenceElement = (XmlElement)nodes[nodes.Count - 1];
            }
            else
            {
                // this is the first value for this field, find its position in the XML based on the field order in the schema
                bool foundUs = false;
                for (int i = definitions.Length - 1; i >= 0; i--)
                {
                    if (!foundUs)
                    {
                        if (definitions[i].Name == definition.Name)
                        {
                            foundUs = true;
                        }
                    }
                    else
                    {
                        var values = GetFieldElements(definitions[i]);
                        if (values.Count() > 0)
                        {
                            referenceElement = values.Last();
                            break; // from for loop
                        }
                    }
                } // for every definition in reverse order
            } // no existing values found
            root.InsertAfter(newElement, referenceElement); // if referenceElement is null, will insert as first child
            return newElement;
        }

        public IEnumerator<Field> GetEnumerator()
        {
            return (IEnumerator<Field>)new FieldEnumerator(this, definitions);
        }
        public Field this[string _name]
        {
            get
            {
                var definition = definitions.First<ItemFieldDefinitionData>(ifdd => ifdd.Name == _name);
                if (definition == null) throw new ArgumentOutOfRangeException("Unknown field '" + _name + "'");
                return new Field(this, definition);
            }
        }

        public override string ToString()
        {
            return root.OuterXml;
        }

    }

    public class FieldEnumerator : IEnumerator<Field>
    {
        private Fields fields;
        private ItemFieldDefinitionData[] definitions;

        // Enumerators are positioned before the first element until the first MoveNext() call
        int position = -1;

        public FieldEnumerator(Fields _fields, ItemFieldDefinitionData[] _definitions)
        {
            fields = _fields;
            definitions = _definitions;
        }

        public bool MoveNext()
        {
            position++;
            return (position < definitions.Length);
        }

        public void Reset()
        {
            position = -1;
        }

        object IEnumerator.Current
        {
            get
            {
                return Current;
            }
        }

        public Field Current
        {
            get
            {
                try
                {
                    return new Field(fields, definitions[position]);
                }
                catch (IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }

        public void Dispose()
        {
        }
    }

    public class Field
    {
        private Fields fields;
        private ItemFieldDefinitionData definition;

        public Field(Fields _fields, ItemFieldDefinitionData _definition)
        {
            fields = _fields;
            definition = _definition;
        }

        public string Name
        {
            get { return definition.Name; }
        }
        public Type Type
        {
            get { return definition.GetType(); }
        }
        public string Value
        {
            get
            {
                return Values.Count > 0 ? Values[0] : null;
            }
            set
            {
                if (Values.Count == 0) fields.AddFieldElement(definition);
                Values[0] = value;
            }
        }
        public ValueCollection Values
        {
            get
            {
                return new ValueCollection(fields, definition);
            }
        }

        public void AddValue(string value = null)
        {
            XmlElement newElement = fields.AddFieldElement(definition);
            if (value != null) newElement.InnerText = value;
        }

        public void RemoveValue(string value)
        {
            var elements = fields.GetFieldElements(definition);
            foreach (var element in elements)
            {
                if (element.InnerText == value)
                {
                    element.ParentNode.RemoveChild(element);
                }
            }
        }

        public void RemoveValue(int i)
        {
            var elements = fields.GetFieldElements(definition).ToArray();
            elements[i].ParentNode.RemoveChild(elements[i]);
        }

        public IEnumerable<Fields> SubFields
        {
            get
            {
                var embeddedFieldDefinition = definition as EmbeddedSchemaFieldDefinitionData;
                if (embeddedFieldDefinition != null)
                {
                    var elements = fields.GetFieldElements(definition);
                    foreach (var element in elements)
                    {
                        yield return new Fields(fields, embeddedFieldDefinition.EmbeddedFields, (XmlElement)element);
                    }
                }
            }
        }

        public Fields GetSubFields(int i = 0)
        {
            var embeddedFieldDefinition = definition as EmbeddedSchemaFieldDefinitionData;
            if (embeddedFieldDefinition != null)
            {
                var elements = fields.GetFieldElements(definition);
                if (i == 0 && !elements.Any())
                {
                    // you can always set the first value of any field without calling AddValue, so same applies to embedded fields
                    AddValue();
                    elements = fields.GetFieldElements(definition);
                }
                return new Fields(fields, embeddedFieldDefinition.EmbeddedFields, elements.ToArray()[i]);
            }
            else
            {
                throw new InvalidOperationException("You can only GetSubField on an EmbeddedSchemaField");
            }
        }
        // The subfield with the given name of this field
        public Field this[string name]
        {
            get { return GetSubFields()[name]; }
        }
        // The subfields of the given value of this field
        public Fields this[int i]
        {
            get { return GetSubFields(i); }
        }

    }

A: Can you try this?
multimediaComponent.Metadata = "<Metadata/>";


text:
Q: OCI8 installation issue in Centos 7 I installed PHP 5.6 and Apache 2.4, and oci8 module on my fresh Centos 7 system.
The oci8 module is working on terminal, but it's not working in Apache and not showing in phpinfo.

*

*I tried to disable SELinux

*I tried to setup environment variable LD_LIBRARY_PATH

*I tried to reinstall all of them again

All of them don't work.
I tried to look at the apache log:
PHP Startup: Unable to load dynamic library '/usr/lib64/php-zts/modules/pdo_oci.so' - libclntsh.so.12.1: cannot open shared object file: No such file or directory in Unknown on line 0

Please help and thank you in advance!

A: I found that has to add environment variable in
 /usr/lib/systemd/system/httpd.service
by adding
Environment=LD_LIBRARY_PATH=/usr/lib/oracle/12.2/client64/lib/:$LD_LIBRARY_PATH

redpajama_set_name: RedPajamaStackExchange


text:
Q: Silverlight - Possible to not rotate parent window overlay when ChildWindow rotates? I've got a ChildWindow that rotates 180 degrees when I click a button.
I'm also using a ChildWindow.OverlayBrush to dim out the parent window.
This of course rotates as well when the ChildWindow rotates.
Is there anyway to dim out the parent window without it rotating with the ChildWindow?

A: 2 options spring to mind:

*

*You either need the OverlayBrush to
not be under the same element you
rotate (can you rotate a child
within the window instead?)

*Or, you need to rotate the overlay
brush in the opposite direct in the
same animation so that it cancels
out the motion.


text:
Q: use npm module of dependency The context:

*

*my app  depends on a module 'my-module'

*'my-module' depends on 'express'

*I want to require('express') form my app
without need of installing 'express' dependecy in my app directly but instead I want it to be taken from 'my-module'.

Is it possible to configure npm/package.json work this why? Maybe npm link should be used, I just not sure if it is a standard scenario.

A: I can see several possible solutions for your problem.
Explicit export
If you're the one who maintains my-module and this is one of its common use cases, then you should explicitly export any important dependency to be used in parent application.
This solution is preferable for handy utility modules, but it doesn't look like a good solution for modules like express.
Relying on npm
If you just want to eliminate duplicate dependencies, then you could add express to your parent application. If any of your application dependencies will also depend on express, npm will use already installed one (provided that there is no version mismatch).
This solution is preferable if my-module is a third-party module.
Using peer dependencies
Again, if you're the one who maintains my-module you could specify express an a peerDependency. By doing so you'll tell npm to always use express module from the parent application.
This solution is preferable for framework modules like express and mongoose.
Using the most direct approach
If none of those solution fits you for some reason, you could require any dependency of another dependency using the following code:
require('my-module/node_modules/express')

Just try to avoid this approach if you can.


text:
Q: reduce image size and keep it in 100% width I have some images in my web which linked from image hosting sites. All the images require 100% in width.
However, some images have extremely large pixel and therefore load slow.
How I can set the style to reduce the pixel of images while keep the images in 100% width in order to load faster?
For example, fix the horizontal pixel to 1440px and adjust the vertical pixel and keep it in 100% width?

A: you need to have 2 versions of each image, one with the original size and you can use this when user request to download the photo, and the other for the display and the UI, this will make your page load faster and less data bandwidth.

A: You have very little control over an image that is hosted elsewhere. Some alternate ideas:

*

*Cache them on another server and load from there

*Preload for faster results (which might not work if the image is "above the fold") How exactly does link rel="preload" work?

*Use the <picture> tag to specify a different image based on screen size: load images using the picture tag

*Load a placeholder image first: How to load a small placeholder image before loading the actual content


text:
Q: Loop import XML files I'm using MariaDB to import some files in XML.
Here is a snippet of the code I'm using:
CREATE TABLE invoices (
    InvoiceNumber VARCHAR(20),
    InvoiceStatus CHAR (1),
    InvoiceDate CHAR (10),
    Period CHAR (2)
)
;

DROP TABLE if EXISTS temptbl;

create table temp02 (
    InvoiceNumber VARCHAR(20) xpath='InvoiceNo',
    InvoiceStatus CHAR(1) xpath='DocumentStatus/InvoiceStatus',
    InvoiceDate CHAR (10) xpath='InvoiceDate',
    Period CHAR (2) xpath='Period'
)
engine=CONNECT table_type=XML file_name='..\\importmaridb\\month01.xml'
tabname='AuditFile' option_list='rownode=SourceDocuments/SalesInvoices/Invoice';

INSERT INTO invoices
SELECT * FROM temptbl;

I then repeat 12x the code of importing to table "temptbl" changing only the file name to reflect the other months.
I would like to have a loop to iterate the files each time.
I believe part of the solution would be to create a table with the file names and an auto increment column, where I would loop through the numbers.
I've attempted to define a variable and substituting in the code, like file_name=@path. But MariaDB gives me an error a syntax error.
| VARIABLE_NAME | VARIABLE_VALUE | VARIABLE_TYPE | CHARACTER_SET_NAME |
+---------------+----------------+---------------+--------------------+
| path          | ..\importmaridb| VARCHAR       | utf8mb4            |
|               | \month01.xml   |               |                    |

Can someone give me some pointers, and even if this is possible?


text: Q: View to double Conversion I need to pass a editTextNumberDecimal to a double in Android Studio, then be able to divide it by another double. How would I go about this? When I try to parse it, it just says that it is still a String.


text:
Q: confused about quotient set For $a,b\in \mathbb Z$, let $a \sim b \iff (ab>0) \lor (a=b)$. Is $\sim$ an equivalence relation on $\mathbb Z$? If so, find the quotient set.
I've already found that $\sim$ is an equivalence relation, and I kind of get that the quotient set is a partition of the set (?) but finding the quotient set isn't really clicking with me. Could someone explain how to work through a problem like this?

A: This is just a more convoluted way of writing a relation you should know very well by a different description.  I encourage you to show that these are in fact describing the same relation.  The phrasing you should be more familiar with is:
$a\sim b$ iff $a$ and $b$ are the same sign.
Remember that positive times positive is positive and negative times negative is positive.
Reading the relation in this way it should be clear what the equivalence classes are.


text:
Q: Indexing custom entity in Magento with Solr I'm trying to index a custom entity in Solr with Magento.
I've followed this guide: http://www.summasolutions.net/blogposts/magento-apache-solr-integration-part-iii-indexing-custom-data, but I still can't make it work.
In my case I have an EAV entity that represents a news and I want the default Magento search showing results including this entity.
Similar to the guide I've created the "getSolrDocument" function:
protected function getNewsSolrDocument($id, $name, $storeId, $visibility, $category, $title, $subtitle, $description) {

    $document = new Apache_Solr_Document();
    $document->addField("id", $id);
    $document->addField("unique", $id);
    $document->addField("news_name_en", $name);

    $document->addField("news_category_en", $category);
    $document->addField("news_title_en", $title);
    $document->addField("news_subtitle_en", $subtitle);
    $document->addField("news_description_en", $description);

    return $document;
}

And a "addSolrDocument":
protected function addSolrDocument(&$solrClient, $document) {
    $solrClient->addDocument($document);
    $solrClient->commit();
}

But $solrClient->addDocument($document) throws an exception:
"400" Status: [doc=15] missing required field: visibility
I've noticed that in the Solr schema provided by Magento there is this part:
<!-- System required fields. -->
    <field name="id"            type="string"   indexed="true" required="true" stored="true"/>
    <field name="unique"        type="string"   indexed="true" required="true"/>
    <field name="store_id"      type="int"      indexed="true" required="true"/>
    <field name="in_stock"      type="boolean"  indexed="true" required="true"/>
    <field name="visibility"    type="int"      indexed="true" required="true"/>

The part defines which fields are mandatory but for my news entity "in_stock" and "visibility" are useless.
I'm using Magento EE 1.14.0.1 and Solr 3.6.2.
What's the proper way to achive my goal?
Thanks

A: Without knowing much about your scenario, you could simply add the following line to your function body:
$document->addField("visibility", $visibility);

Apparently, the $visibility variable is passed, so it doesn't hurt adding it. It may increase the index size, but an integer shouldn't hurt to much (besides, the name indicates that it's just some sort of a flag).


text:
Q: Number of Vertices Within a Distance from Start Vertex I was working on a question on a judge that asked about finding the number of vertices that are within a certain distance from it. This has to be done for all vertices on the graph. The full question specifications can be seen  here. I have some Python code to solve the program, but it is too slow.
import sys, collections
raw_input = sys.stdin.readline
n, m, k = map(int, raw_input().split())
dict1 = collections.defaultdict(set)
ans = {i:[set([i])for j in xrange(k)]for i in xrange(1, n+1)}

for i in xrange(m):
    x, y = map(int, raw_input().split())
    dict1[x].add(y)
    dict1[y].add(x)

for point in dict1:
    ans[point][0].update(dict1[point])

for i in xrange(1, k):
    for point in dict1:
        for neighbour in dict1[point]:
            ans[point][i].update(ans[neighbour][i-1])

for i in xrange(1, n+1):
    print len(ans[i][-1])

What my code does is it initially creates a set of points that are direct neighbours of each vertex (distance of 0 to 1). After that, it creates a new set  of neighbours for each vertex from all the previously found neighbours of neighbours (distance of 2). Then it keeps doing this, creating a new set of neighbours and incrementing the distance until the final distance is reached. Is there a better way to solve this problem?

A: There is a plenty of good and fast solutions.
One of them (Not the fastest, but fast enough) is to use BFS algorithm up to distance K. Just run bfs, which not adds neighbours to queue when distance exceeds K, for all vertexes. K is parameter from exercise specification.

A: I would use the adjacency matrix multiplication. Adjacency matrix is a boolean square matrix n * n where n is a number of vertices. The value of adjacency_matrix[i][j] equals 1 if the edge from i to j exists and 0 otherwise. If we multiply the adjacency matrix by itself we get the paths of length 2. If we do that again we get the paths of length 3 and so on and so on. In Your case the K <= 5 so there won't be too much of that multiplication. You can use numpy for that and it will be very fast. So in pseudocode, the solution to Your problem would look like this:
adjacency_matrix = build_adjacency_matrix_from_input()
initial_adjacency_matrix = adjacency_matrix
result_matrix = adjacency_matrix
for i = 2 to K:
    adjacency_matrix = adjacency_matrix * initial_adjacency_matrix
    result_matrix = result_matrix + adjacency_matrix
for each row of result_matrix print how many values higher then 0 are in it

A: You want paths of length <=K. In this case, BFS can be used to find paths of certain length easily. Or if your graphs uses adjacency matrix representation, then matrix multiplication can also be used for these purposes.
If using BFS:
 This is equivalent to performing level-by-level traversal starting from a given source vertex. Here is the pseudo code that can compute all the vertices that are at distance K from a given source vertex:
Start: Let s be your source vertex and K represent max path length required

Create two Queues Q1 and Q2 and insert source vertex s into Q1
Let queueTobeEmptied = Q1 // represents the queue that is to be emptied
Let queueTobeFilled = Q2  // represents the queue that is used for inserting new elements discovered
Let Result be a vector of vertices: initialize it to be empty
Note: source vertex s is at level 0, push it to Result vector if that is also required

for(current_level=1; current_level<=K; current_level++) {
    while(queueTobeEmptied is not empty) {
        remove the vertex from queueTobeEmptied and call it as u
        for_each adjacent vertex 'v' of u {
            if v is not already visited {
                mark v as visited
                insert v into the queueTobeFilled
                push v to Result
            }
        }
    }
    swap the queues now for next iteration of for loop: swap(queueTobeEmptied, queueTobeFilled)
}

Empty Q1 and Q2

End: Result is the vector that contains all the vertices of length <= K


text:
Q: Defining a function, used astropy, error 'np.ndarray is not callable' what am I doing wrong here?
what I am trying to do is define for_fits function for later use.
from astropy.io import fits
from astropy.utils.data import download_file
import matplotlib.pyplot as plt
import numpy as np

image_file = download_file('http://data.astropy.org/galactic_center/gc_2mass_h.fits', cache=True)

def for_fits():
  image_data = fits.getdata(image_file)
  print("min", image_data.min(),
        "max", image_data.max())
  return image_data

coloured_image = plt.imshow(image_data(), cmap='hot')
plt.show()

the error
TypeError                                 Traceback (most recent call last)
<ipython-input-37-6d4157b52f0d> in <module>
     13   return image_data
     14
---> 15 coloured_image = plt.imshow(image_data(), cmap='hot')
     16 plt.show()

TypeError: 'numpy.ndarray' object is not callable


text:
Q: Golang Reusing Memory Address Copying from slice? I was hitting an issue in a project I'm working on.  I found a way around it, but I wasn't sure why my solution worked.  I'm hoping that someone more experience with how Go pointers work could help me.
I have a Model interface and a Region struct that implements the interface.  The Model interface is implemented on the pointer of the Region struct.  I also have a Regions collection which is a slice of Region objects.  I have a method that can turn a Regions object into a []Model:
// Regions is the collection of the Region model
type Regions []Region

// Returns the model collection as a list of models
func (coll *Regions) ToModelList() []Model {
    output := make([]Model, len(*coll))
    for idx, item := range *coll {
        output[idx] = &item
    }
    return output
}

When I run this code, I end up with the first pointer to the Region outputted multiple times.  So, if the Regions collection has two distinct items, I will get the same address duplicated twice.  When I print the variables before I set them in the slice, they have the proper data.
I messed with it a little bit, thinking Go might be reusing the memory address between loops.  This solution is currently working for me in my tests:
// Returns the model collection as a list of models
func (coll *Regions) ToModelList() []Model {
    output := make([]Model, len(*coll))
    for idx, _ := range *coll {
        i := (*coll)[idx]
        output[idx] = &i
    }
    return output
}

This gives the expected output of two distinct addresses in the output slice.
This honestly seems like a bug with the range function reusing the same memory address between runs, but I always assume I'm missing something in cases like this.
I hope I explained this well enough for you.  I'm surprised that the original solution did not work.
Thanks!

A: There is just one item variable for the entire loop, which is assigned the corresponding value during each iteration of the loop. You do not get a new item variable in each iteration. So you are just repeatedly taking the address of the same variable, which will of course be the same.
On the other hand, if you declared a local variable inside the loop, it will be a new variable in each iteration, and the addresses will be different:
for idx, item := range *coll {
    temp := item
    output[idx] = &temp
}

A: In your first (non working) example item is the loop variable. Its address is not changing, only its value. That's why you get the same address in output idx times.
Run this code to see the mechanics in action;
func main() {

    coll := []int{5, 10, 15}

    for i, v := range coll {
       fmt.Printf("This one is always the same; %v\n", &v)
       fmt.Println("This one is 4 bytes larger each iteration; %v\n", &coll[i])
    }
}


text:
Q: how to keep jpa session in the thread Now I use JPA in my web application. And I have a class like this:
class A {
    ...

    @OneToMany
    private List<B> list;
    ...
}

When it is in a HTTP request, I can use a.getList() successful. But in a schedule thread, it throws the exception:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: A.list, could not initialize proxy - no Session

Can I keep the session in the schedule thread just like the http request thread?

A: Actually, when spring handle the http request, it start the transaction by the interceptor org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor or the filter org.springframework.orm.hibernate3.support.OpenSessionInViewFilter. So if we want to keep the session, we can start and commit the transaction by our self.
Here is the code:
public class BackendThread {

    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Override
    public void onMessage(Message message, byte[] pattern) {
    new TransactionTemplate(platformTransactionManager).execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus transactionStatus) {
            ...
            your code here
            ...
            return null;
        }
    });
    }

}

A: TransactionTemplate is helpful if you use JPA. I didn't use it and created a session/transactions on my own in background thread, so that each task had its own environment:
Inject entity manager or get it from Spring context or pass it as reference:
@PersistenceContext
private EntityManager entityManager;

Then create a new entity manager, to avoid using a shared one:
EntityManager em = entityManager.getEntityManagerFactory().createEntityManager();

Now you can start transaction and use Spring DAO, Repository, JPA, etc
private void save(EntityManager em) {

    try
    {
        em.getTransaction().begin();

        <your database changes>

        em.getTransaction().commit();
    }
    catch(Throwable th) {
        em.getTransaction().rollback();
        throw th;
    }
}


text:
Q: Does Crypto++ support TOFB-I? I'm developing a C++ application to decrypt the data encrypted by someone else with TOFB-I (TDEA Output Feedback - Interleaved).
To do this I'm using the Crypto++ library.
Unfortunately, the result of the decryption doesn't seem to work: the first byte is decrypted correctly, the rest is just meaningless data.
I've double checked with the Linux command line tool OpenSSL and get exactly the same result.
So I'm inclined to believe that I'm applying a decryption algorithm with wrong feedback, so that the first IV works fine but something goes wrong with the feedbacks.
My question is: how do I apply the interleaved variant of the DES_OFB mode?
Couldn't find anything about this either in the Crypto++ or in the OpenSSL documentation.

A: Apparently Crypto++ (and also OpenSSL) doesn't support TOFB-I operation mode:
http://csrc.nist.gov/groups/STM/cavp/documents/des/tripledesval.html
Actually, according to the above link no implementation has been validated yet as conforming to TOFB-I!
So I guess I'll need to implement my own TOFB-I algo.


text:
Q: Accessing HDFS from Eclipse outside Hadoop cluster I am trying to read some files available on HDFS from a Java program. I have created a mavenized project with Eclipse, added as dependecies hadoop-core 1.2.1, hadoop-common 2.3.0 and hadoop-client 2.3.0. However, whenever I try to get a FileSystem object (also on the first line of the program):
FileSystem fs = FileSystem.get(new Configuration())

It crashes with execption:

Exception in thread "main" java.lang.UnsupportedOperationException:
  Not implemented by the DistributedFileSystem FileSystem implementation
    at org.apache.hadoop.fs.FileSystem.getScheme(FileSystem.java:215)   at
  org.apache.hadoop.fs.FileSystem.loadFileSystems(FileSystem.java:2284)
    at
  org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2294)
    at
  org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2311)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:90)   at
  org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2350)
    at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2332)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:369)     at
  org.apache.hadoop.fs.FileSystem.get(FileSystem.java:168)

Any idea on how to solve it?
Thanks in advance.


text:
Q: Linux bash -c in command shell script I am using ssh in a shell script in order to go on multiple linux server and get disk information on a particular disk.  I am running following but I am not able to figure out the quote sequencing...In this example I am just capturing the header for my report....
ssh dbadmin@myserver bash -c '"df -kh | grep File | awk '{ print \$1 "  |  " \$2 "  |  " \$3 "  |  " \$4 "  |  " \$5 }' | tail -n -1"'

and following error...
bash: -c: line 0: syntax error near unexpected token |'
bash: -c: line 0:df -kh | grep File | awk { print    |      |      |      |    } | tail -n -1'
Any help or suggestions would be great...
Thanks

A: Better to use quoted here-doc and avoid escaping:
ssh -t -t dbadmin@myserver<<'EOF'
df -kh | awk -v OFS="  |  " '/file/{ print $1, $2, $3, $4, $5 }' | tail -n -1
EOF


text:
Q: XmlNode.Value пустой, хотя в innerText данные есть Здравствуйте, есть xml:
<?xml version="1.0" encoding="utf-8"?>
<yml_catalog date="2015-11-12 11:57:22">
  <shop>
    <name>Интернет-магазин</name>
    <company>НазваниеОрганизации</company>
    <url>http://example.com</url>
  </shop>
</yml_catalog>

Пытаюсь получить значение элемента name, но свойство Value возвращает пустую строку.
// priceList - объект класса XmlDocument в который уже загружен XML
XmlNode yml_catalog = priceList.SelectSingleNode("yml_catalog");
string priceDate = yml_catalog.Attributes["date"].Value;
XmlNode shop = yml_catalog.SelectSingleNode("shop/name");
string shopName = shop.Value; //пустой
string innerText= shop.innerText; // Интернет-магазин

Как получить значение элемента name через Value?

A: Например, так:
XmlNode shop = yml_catalog.SelectSingleNode("shop/name/text()");
string shopName = shop.Value;

A: Чисто технически, текст "Интернет-магазин" лежит не непосредственно в самой ноде <name>. Вместо этого в элемент <name> вложена еще одна нода, с типом Text. И вот у нее уже Value - "Интернет-магазин".
Его можно выбрать напрямую:
XmlNode shopNameText = yml_catalog.SelectSingleNode("shop/name/text()");
string shopName = shopNameText.Value; // Интернет-магазин

или через родительский элемент:
XmlNode shop = yml_catalog.SelectSingleNode("shop/name");
string shopName = shop.FirstChild.Value; // Интернет-магазин


text:
Q: Creating a Snapshot of a Database in MS SQL Server On my instance I have a database called SampleDB. I want to create snapshot on it called SampleSnap.
-- Create a Snapshot on a Database
CREATE DATABASE SampleSnap ON
(
    NAME = SampleDB,  -- Logical File Name
    FILENAME ='C:\Users\Eleonora\Desktop\SampleSnap.ss'
)
AS SNAPSHOT OF SampleDB;
GO

This gives me an error

Directory lookup for the file "C:\Users\Eleonora\Desktop\SampleSnap.ss" failed error 5(Access is denied.).

What can I do to fix this?
Besides I can't understand the use of logical file name. What is it and how to specify it correctly?
Thanks for your time.

A: To create a snapshot you must be member of the role sysadmin
Where source_database_name is the source database, logical_file_name is the logical name used in SQL Server when referencing the file, os_file_name is the path and file name used by the operating system when you create the file
Read more here
Edit - If it is not the sysadmin rights. Then its because the SQL Server Service Account doesnt have access to your path.
Edit2 If you want it on C drive - I created a new folder C:\Test
I gave the NETWORK SERVICE Full control - Dont know if that is nessecary

A:
What can I do to fix this?

YOu start with reading the error.

Directory lookup for the file "C:\Users\Eleonora\Desktop\SampleSnap.ss" failed error
  5(Access is denied.).

is an operating system error telling you that the database server can basically not access the folder. SImple like that.
You COULD change permissions, or you just put the data not in your C users folder. Which is way smarter - db database files have no business on your DESKTOP.


text:
Q: vim: How can you pipe the output of something that prints to the message log to a buffer? e.g. When you type :version it shows up in the message log. I'd like to pipe the Compilation line to tr ' ' '\n' to be able to read the log faster.

A: You could use redir command
:redir @"> | silent version | redir END | new | put

That will put version output to a new buffer

:redi[r] @">
Redirect messages to the unnamed register. For
                          backward compatibility, the ">" after the register
                          name can be omitted.


text:
Q: An unhandled exception occurred: NGCC failed I tried to compile my project and I'm getting an error:
An unhandled exception occurred: NGCC failed.
See "C:\Users\hp\AppData\Local\Temp\ng-sKaJxi\angular-errors.log" for further details.

I used ng add @angular/material , npm rxweb and  npm instal  and I got this error.

A: Run visual studio code as administrator i had same problem and running as administrator helped me


text:
Q: How to connect to a wireless network in Lubuntu I just don't know how to turn on my Wi-Fi or choose a Wi-Fi connection.
I'm now using the cable, but I really need to use the Wi-Fi on school. How to do that?

A: Go to your applications, bottom left of screen, if I remember correctly.
Find System Settings.  Click on Network.
Click on Wireless, then turn on wireless.
It should scan available networks and allow you to connect if you have network password.
NEW INFO
Try re-setting your network services first.
sudo service networking restart

or this
sudo /etc/init.d/networking restart

Then go back to see your Network Settings to see if wifi is working.


text:
Q: Bootstrap dropdowns in Durandal 2.0 I am trying to wire up some bootstrap dropdown navigation in a durandal 2.0 app:

            Dropdown

Option A

Option B

Clicking "dropdown" causes Durandal's router to attempt to navigate to the root route (which is "#" or ""). And never opens the menu. Is this correct? Workarounds?
Update
Tabs suffer the very same problem:

Section 1

Section 2

I'm in Section 1.

Howdy, I'm in Section 2.

A: The problem was actually quite simple. There was no conflict with the routing module. I assumed the bootstrap javascript was included by default on the starter kit, but it is not.
The fix is as simple as adding an additional line to my require dependencies:
var system = require('durandal/system'),
    app = require('durandal/app'),
    viewLocator = require('durandal/viewLocator');
require('bootstrap');

Note that my require.config is:
require.config({
    paths: {
        'text': '../lib/require/text',
        'durandal':'../lib/durandal/js',
        'plugins' : '../lib/durandal/js/plugins',
        'transitions' : '../lib/durandal/js/transitions',
        'knockout': '../lib/knockout/knockout-2.3.0',
        'bootstrap': '../lib/bootstrap/js/bootstrap',
        'jquery': '../lib/jquery/jquery-1.9.1'
    },
    shim: {
        'bootstrap': {
            deps: ['jquery'],
            exports: 'jQuery'
       }
    }
});

A: Probably the best option in the long run would be converting those bootstrap widgets into knockout custom bindings (like e.g. https://github.com/billpull/knockout-bootstrap)  or even better into native Durandal widgets.
Check out how Durandal 1.2 messageBox is implemented. This can be used as a rough guideline to convert bootstrap tabs and dropdowns into Durandal widgets. As you can see href attributes in the view have been replaced by data-bind="click: ...". In addition you'd have to convert the Bootstrap JavaScript into a Durandal viewmodel.
e.g. http://twitter.github.io/bootstrap/javascript.html#modals

    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal header

One fine body…

    Close
    Save changes

becomes
https://github.com/dFiddle/dFiddle-1.2/blob/gh-pages/App/durandal/messageBox.html

        <button class="btn" data-bind="click: function () { $parent.selectOption($data); }, html: $data, css: { 'btn-primary': $index() == 0, autofocus: $index() == 0 }"></button>

Update: Here's a minimalistic tab widget implementation. Live version at http://dfiddle.github.io/dFiddle-2.0/#bootstrap
view:

viewmodel:
define(['durandal/composition', 'jquery'], function(composition, $) {

    var ctor = function() { };

    ctor.prototype.activate = function(settings) {
        this.settings = settings;
    };

    ctor.prototype.detached = function() {
        console.log('bootstrap/widget/viewmodel: detached', arguments, this);
    };

    ctor.prototype.toggle = function(model, event){
        this.deactivateAll();
        model.isActive(true);

    };

    ctor.prototype.deactivateAll = function(){

        $.each(this.settings.items(), function(idx, tab){
            tab.isActive(false);
        });
    };

    return ctor;
});

A: Have you tried changing the containing a element to a div or span instead of an anchor tag?


text:
Q: Could not find module 'XXXX' for target 'x86_64-apple-ios-simulator'; found: arm64, arm64-apple-ios-simulator in Swift Project? This error has been stopping me progress with my project for a while now and nothing seems to be working for me.
I have added A pod to my swift project but when I try to import it into my app, I get this error:
Could not find module 'ImagePicker' for target 'x86_64-apple-ios-simulator'; found: arm64, arm64-apple-ios-simulator

I've searched far and wide and tried almost all the solutions and still nothing seems to be working.
I'm using the latest Xcode.
is there anything I need to do fix this as this is stopping me from building the app.

A: I have the same issue on the M1 laptop.
Have you tried this solution:
post_install do |installer_representation|
    installer_representation.pods_project.targets.each do |target|
        target.build_configurations.each do |config|
            config.build_settings['ONLY_ACTIVE_ARCH'] = 'NO'
            config.build_settings['BUILD_LIBRARY_FOR_DISTRIBUTION'] = 'YES'
        end
    end
end

Alternatively, you can change default scheme to Release, instead of Debug, by going to the top menu Product -> Scheme -> Edit Scheme, select your Run scheme as Release.
However, better solution would be to simply make sure you're running Xcode using Rosetta. Simple do the Get Info on the Xcode icon, from there in popup window make sure that Open using Rosetta is checked

A: I'm using SPM for dependency management and ran into issues with my M1 laptop.
I had Excluded architectures within the top level project build settings set to arm64, which is where I ran into the problem

After I removed that it worked.
Here's a screenshot of the Architectures section in the Project build settings, after making the change (ignore dark mode look, I was switching laptops).


text:
Q: How to put XML content in reverse order? I tried a few solutions already posted here, but nothing seems to work. That might be, because I am really not that familiar with php or xml. I just need to output xml for xcoding. So hopefully someone can shed some light, on how I can reverse the order of my xml, so that the last entry is on top.
My last try what with:
$query = array_reverse($doc->xpath('query'));

but it did not like it ,e.g. it did not work.
So here is my code in order to create my xml document:
<?php

if(!$dbconnect = mysql_connect('localhost', '-', '-')) {
echo "Connection failed to the host 'localhost'.";
exit;
} // if
if (!mysql_select_db('-')) {
echo "Cannot connect to database '-'";
exit;
} // if

$table_id = 'table1';
$query = "SELECT Name,Age,Sex FROM $table_id";

$dbresult = mysql_query($query, $dbconnect);

// create a new XML document
$doc = new DomDocument('1.0');

// create root node
$root = $doc->createElement('root');
$root = $doc->appendChild($root);

// process one row at a time
while($row = mysql_fetch_assoc($dbresult)) {

// add node for each row
$occ = $doc->createElement($table_id);
$occ = $root->appendChild($occ);

// add a child node for each field
foreach ($row as $fieldname => $fieldvalue) {

$child = $doc->createElement($fieldname);
$child = $occ->appendChild($child);

$value = $doc->createTextNode($fieldvalue);
$value = $child->appendChild($value);

} // foreach
} // while

// get completed xml document
$xml_string = $doc->saveXML();
$doc->save("yolo.xml")

//echo $xml_string;
?>

A: The best thing to do is to issue an SQL query which returns results in the order you want.  The SQL query you have here has no ORDER BY clause, so results come back in no particular order.
However, you can also reverse the order of results as you add them to your XML document: instead of appending new child nodes for each row, prepend them. Replace this line:
$occ = $root->appendChild($occ);

With
$occ = $root->insertBefore($occ, $root->firstChild);

Also generally speaking it's best to finish building a tree of XML before you add it to the document.


text:
Q: JSP doesn't open images, CSS ou JS Good morning,
I try put CSS, JS and IMGs on my JSP, but doesn't work, but its strange because I use c:url da "jstl/core"
I'm use JSP, jstl and servlet, no frameworks.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html>

            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>clientes atuantes</title>
            <link rel="stylesheet" href="<c:url value="/bootstrap/css/bootstrap.min.css"/>">
            <link rel="stylesheet" href="<c:url value="/css/layout.css"/>">

<img src="<c:url value="/img/ativo.gif"/>" /> ativo

<img src="<c:url value="/img/congelado.gif"/>" /> congelado

<img src="<c:url value="/img/cancelado.gif"/>" /> cancelado


text:
Q: _GET en bucle infinito PHP Tengo un gestor de consultas en php al que llamo desde AJAX con Jquery con un GET asyncrono, este gestor se encarga de llamar a la función pertinente.
Una de estas funciones debe ejecutar un proceso que depende del número de registros que se han insertado hasta determinada fecha. Si el numero de registros es pequeño el proceso finaliza, realiza el echo, ajax obtiene el resultado y todo funciona correctamente, pero si el proceso es largo este finaliza (tengo un log que guarda el json de respuesta y este es correcto) pero parece que el echo no se realice, desde Ajax no se obtiene ninguna respuesta e inmediatamente vuelve a comenzar todo el proceso como si se realizase una nueva llamada _GET al gestor con los mismos parámetros.
header("Content-Type: application/json; charset=UTF-8", true);
switch(mb_strtoupper($_GET['funcion'])){
[...]
}

$json = json_encode($respuesta);
Log::insertaLog('Gestor Consulta > Respuesta ' . $json);
// En ambos casos siempre se está guardando el registro del json y este es correcto, pero el _GET
echo($json); flush();

La llamada ajax:
$.ajax({ type: "GET", async: true, url: "/Code/Herramientas/GestorConsultas.php", dataType: "json", data: parametros, success: function (datos) { console.log(datos); }, error: function (peticion, mensaje) { console.log("Error invocacio: /Code/Herramientas/GestorConsultas.php " + parametros + " " + peticion + " " + mensaje); GNR_GestionaError(arguments.callee.name, mensaje); } })

Agradeceré cualquier ayuda.
Editado
Si ejecuto la llamada a la función sin pasar por el gestor se ejecuta correctamente siempre.

A: Si el problema surge cuando son varios registros, probablemente estás llegando al límite de memoria o al tiempo máximo de ejecución. Estos valores los podés modificar con un archivo .htaccess o con la función ini_set() de php.
htaccess:
php_value memory_limit 256M          # la letra indica la unidad de memoria: Megabyte, Gigabyte...
php_value max_execution_time 300     # tiempo en segundos

ini_set:
ini_set('memory_limit', '256M');
ini_set('max_execution_time', 300);

Peeeeerooooo, antes de hacer esto recomendaría revisar cada uno de los procesos que estás ejecutando. Probá activando que se muestren todos los errores de PHP:
error_reporting(E_ALL);
ini_set('display_errors', true);


text:
Q: Is there any git management GUI? I want to edit git history: change commit's authors (someone they're marked incorrectly) etc.
Is there any GUI for git, focused not on "pull & push" current commit, but on history editing?
P.S. I use linux, so linux clients are preferrable, but i can start wine for it

A: You could try one of these :

*

*git-cola

*gitk

*Giggle
If you work with Eclipse IDE, there is the EGit plugin .

A: in git Bash type gitk. Suppose its what you need

A: If you can run mono on Linux, then I think GitExtensions is the best choice.
GitExtensions relies on command line git.
GitExtensions is actively developing and has many fancy functions.

A: If you develop C# in Linux with Monodevelop, there is a built-in git plugin based on NGit library.
Monodevelop does not call command line git.


text:
Q: Why does my toString() method not return my Singly Linked List in a string format? I am trying to implement a toString() method that returns the values in my singly-linked list in a string format by iterating through the list. See below for the SinglyLinkedList.java file which contains the toString() method.
import java.util.NoSuchElementException;
import java.util.*;

/**
 * Your implementation of a Singly-Linked List.
 */
public class SinglyLinkedList<T> {

    /*
     * Do not add new instance variables or modify existing ones.
     */
    private SinglyLinkedListNode<T> head;
        private SinglyLinkedListNode<T> tail;
        private int size;

    /*
     * Do not add a constructor.
     */

    /**
     * Adds the element to the front of the list.
     *
     * Method should run in O(1) time.
     *
     * @param data the data to add to the front of the list
     * @throws java.lang.IllegalArgumentException if data is null
     */
        public void addToFront(T data) {
        if (data == null){
            throw new IllegalArgumentException("Data cannot be null");
        }
            SinglyLinkedListNode<T> newNode = new SinglyLinkedListNode<T>(data);
        if (head == null){
            head = newNode;
            tail = newNode;
        }
        else{
            newNode.setNext(head);
            head = newNode;
        }
        size++;
        }

    /**
     * Adds the element to the back of the list.
     *
     * Method should run in O(1) time.
     *
     * @param data the data to add to the back of the list
     * @throws java.lang.IllegalArgumentException if data is null
     */
    public void addToBack(T data) {
        if (data == null){
            throw new IllegalArgumentException("Data cannot be null");
        }
            if (head == null){
            head = new SinglyLinkedListNode<T>(data);
        }
        else {
            SinglyLinkedListNode<T> current = head;
            while (current.getNext() != null){
                current = current.getNext();
            }
            current.setNext(new SinglyLinkedListNode<T>(data));
        }
        size++;
        }

    /**
     * Removes and returns the first data of the list.
     *
     * Method should run in O(1) time.
     *
     * @return the data formerly located at the front of the list
     * @throws java.util.NoSuchElementException if the list is empty
     */
        public T removeFromFront() {
        if (head == null){
            throw new NoSuchElementException("You cannot remove elements from the front of an empty list");
        }
        SinglyLinkedListNode<T> var = head;
            head = head.getNext();
        size--;
        return var.getData();
        }

    /**
     * Removes and returns the last data of the list.
     *
     * Method should run in O(n) time.
     *
     * @return the data formerly located at the back of the list
     * @throws java.util.NoSuchElementException if the list is empty
     */
        public T removeFromBack() {
            if (head == null){
            throw new NoSuchElementException("You cannot remove an element from the back of an empty list");
        }
        else if (head.getNext() == null){
            SinglyLinkedListNode<T> var = head;
            head = null;
        }
        SinglyLinkedListNode<T> current = head;
        while (current.getNext().getNext() != null){
            current = current.getNext();
        }
        SinglyLinkedListNode<T> var = current.getNext();
        current.setNext(null);
        size--;
        return var.getData();
    }

    /**
     * Returns the head node of the list.
     *
     * For grading purposes only. You shouldn't need to use this method since
     * you have direct access to the variable.
     *
     * @return the node at the head of the list
     */
        public SinglyLinkedListNode<T> getHead() {
        // DO NOT MODIFY THIS METHOD!
            return head;
        }

    /**
     * Returns the tail node of the list.
     *
     * For grading purposes only. You shouldn't need to use this method since
     * you have direct access to the variable.
     *
     * @return the node at the tail of the list
     */
        public SinglyLinkedListNode<T> getTail() {
        // DO NOT MODIFY THIS METHOD!
            return tail;
        }

    /**
     * Returns the size of the list.
     *
     * For grading purposes only. You shouldn't need to use this method since
     * you have direct access to the variable.
     *
     * @return the size of the list
     */
        public int size() {
        // DO NOT MODIFY THIS METHOD!
            return size;
        }

    public String toString() {
        String answer = "";
        SinglyLinkedListNode<T> current = head;
        while (current != null){
            answer += current + " ";
            current = current.getNext();
        }
        return answer;
    }

    public static void main(String[] args){
        SinglyLinkedList<Integer> list = new SinglyLinkedList<>();
        list.addToFront(1);
        System.out.println(list.toString());
    }
}

And for my SinglyLinkedListNode.java file...
/**
 * Node class used for implementing the SinglyLinkedList.
 *
 * DO NOT MODIFY THIS FILE!!
 *
 * @author CS 1332 TAs
 * @version 1.0
 */
public class SinglyLinkedListNode<T> {

        private T data;
        private SinglyLinkedListNode<T> next;

    /**
     * Constructs a new SinglyLinkedListNode with the given data and next node
     * reference.
     *
     * @param data the data stored in the new node
     * @param next the next node in the list
     */
        SinglyLinkedListNode(T data, SinglyLinkedListNode<T> next) {
            this.data = data;
            this.next = next;
        }

    /**
     * Creates a new SinglyLinkedListNode with only the given data.
     *
     * @param data the data stored in the new node
     */
        SinglyLinkedListNode(T data) {
            this(data, null);
        }

    /**
     * Gets the data.
     *
     * @return the data
     */
        T getData() {
            return data;
        }

    /**
     * Gets the next node.
     *
     * @return the next node
     */
        SinglyLinkedListNode<T> getNext() {
            return next;
        }

    /**
     * Sets the next node.
     *
     * @param next the new next node
     */
        void setNext(SinglyLinkedListNode<T> next) {
            this.next = next;
    }

}

Whenever I call the toString() method from my SinglyLinkedList class, I get the following printed in my command prompt.
Command Prompt
Does anyone know why I do not see the value "1" which I am adding to the front of the linkedlist prior to calling the toString() method? And if so, what can I do to fix it? Instead, it keeps printing the node object.

A: The problem is you have an object 'current' of type SinglyLinkedList whose toString method is not overridden.
public String toString() {
    String answer = "";
    SinglyLinkedListNode<T> current = head;
    while (current != null){
        answer += current + " ";
        current = current.getNext();
    }
    return answer;
}

If you cannot override toString method in SinglyLinkedListNode class then you can modify the while loop to:
while(current != null){
    answer += current.getData() + " ";
    current = current.getNext();
}

Assuming your T has appropriate toString() method overridden.
To make the code more efficient you can use StringBuilder rather than concatenating strings.
public String toString() {
    //String answer = " ";
    StringBuilder answer = new StringBuilder();
    SinglyLinkedListNode<T> current = head;
    while (current != null){
        //answer += current + " ";
        answer.append(current.getData());
        answer.append(" ");
        current = current.getNext();
    }
    return answer.toString();

}


text:
Q: Determine whether a number is a power of 3 Why does $\frac{\log(n)}{\log(3)}$ being an integer determine whether $n$ is a power of three?
While doing some programming exercises I came across this problem and the above formula was a proposed solution. Can someone explain to me why this is the case?

A: Assume $\frac{\ln n}{\ln 3}=k$ with $k$ being an integer.
Then $\ln n=k\ln 3=\ln 3^k$ and so $n=3^k$

A: Because $n = 3^k$ for some $k \in \mathbb Z$ iff $k = \log_3 n = \frac{\lg n}{\lg 3} \in \mathbb Z$.

A: There is a change of base formula for logarithms : $$\log_b(x)=\frac{\log_d(x)}{\log_d(b)}$$Also note the following formula to relate logs to exponents:$$\log_b(b^x) = x$$ this since for any base $b$, $\log_3(n)=\frac{\log_b(n)}{\log_b(3)}$, and and power of $3$ will be of the form $3^x$, we have:$$\frac{\log(3^x)}{\log(3)}=\log_3(3^x)=x$$
Therefore, if $n$ is put into the formula, you will recieve a number $x$ such that $n=3^x$. If $x$ is an integer, then you know that $n$ is a power of $3$.


text:
Q: materializecss selectbox: option not selectable The Problem
I have a selectbox from materialize in a container with position:absolute.
Right under this container there is another container with something in it (also position:absolute). The containers have the same z-index.
When I want to select something in the selectbox, the option which overlaps the secound container is not clickable. :(
What I tried
I tried to set the z-index to a higher value if the selectbox is focused like that:
$(".select-dropdown").on("focusin",function(){
    $(this).parents(".content-container").css("zIndex","100");
});

Also I tried to make the containers positioned relative, which worked, but unfortunatelly I cant do that in the final solution.
The jsFiddle
How to make all options of the selectbox clickable, if it is in an absolute positioned container?
Note: Here I am reasking this question, but a little bit simpler, since I was able to remove the gridstack part and narrowed it down to the materialize selectbox.

A: The solution is so easy, you just have to remove z-index: 80 under .content-container, .card because both div have the same class .content-container which mean the same z-index and this was making a wrong behavior.
Also without the need of Javascript.
Check the updated Fiddle , hope this helps.
Update
Just add z-index for div.one to prevent input or other elements to override the dropdown list.
Updated Fiddle with input below dropdwon list.


text:
Q: How to convert `Multiple words` into `multiple-words as "Multiple words"`? Say I have a text:
Multiple words
In yellow and in blue

How can I make it to this?
multiple-words as "Multiple words"
in-yellow-and-in-blue as "In yellow and in blue"

So far my best try is this:

*

*Find: (.*)

*Replace: -\1- as "\1"
To have it in the form of -Multiple words- as "Multiple words". The - is to mark the boundary easier. But I can't tell it to only replace the spaces in between the boundaries.

A: You can do that in several steps:

*

*Search for ^.*$ and replace with $& as "$&": it just wraps all lines with quotes.

*Search for (?:\G|^\S*)\K\h+(?=.* as ".*"$) and replace with -: it replaces all horizontal whitespaces  (\h) from the start of the line till a as "..." pattern.

*Search for (?:\G-|^)[^-]+(?=\S* as ".*"$) and replace with \L$&: it will turn to lowercase all chunks of non-hyphen chars from the start of string till as "..." pattern.

Note \L, \U and other case changing operators do not work with non-ASCII letters in Notepad++.


text:
Q: Check string includes a substring without extra characters? I am trying to get my code to sort through two arrays and create a dictionary that contains values from both, but when I search through them I end up getting extra values that I don't want. For example while searching through 'USD' symbols, I can end up with XXX-USDT when I specifically want USD, not USDT. How can I make sure there aren't extra characters before or after?
var symbols = ['ETH', 'BTC', 'USD', 'USDT'];
var marketPairs = ['AAVE-USD', 'AAVE-USDT', 'AAVE-BTC', 'AAVE-ETH'];

var marketDict = {};

for (let i = 0; i < symbols.length; i++) {
    marketDict[symbols[i]] = [];
    for (let j = 0; j < marketPairs.length; j++) {
        if (marketPairs[j].includes('-'+symbols[i]) || marketPairs[j].includes(symbols[i]+'-')) {
            marketDict[symbols[i]].push(marketPairs[j]);
        }
    }
}

A: You can use endsWith and startsWith here
marketPairs[j].endsWith("-" + symbols[i]) || marketPairs[j].startsWith(symbols[i] + "-")

var symbols = ["ETH", "BTC", "USD", "USDT"];
var marketPairs = ["AAVE-USD", "AAVE-USDT", "AAVE-BTC", "AAVE-ETH"];

var marketDict = {};

for (let i = 0; i < symbols.length; i++) {
  marketDict[symbols[i]] = [];
  for (let j = 0; j < marketPairs.length; j++) {
    if (
      marketPairs[j].endsWith("-" + symbols[i]) ||
      marketPairs[j].startsWith(symbols[i] + "-")
    ) {
      marketDict[symbols[i]].push(marketPairs[j]);
    }
  }
}

console.log(marketDict);

A: Your if condition checks if a string contains -USD, not if it exactly matches it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
If you're looking to match the end/start of the string, you can use .endsWith and startsWith:
if (marketPairs[j].endsWith('-'+symbols[i]) || marketPairs[j].startsWith(symbols[i]+'-'))

(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith for reference)
Alternatively, you can use RegEx in combination with .search (if you want to get an array of matched chars) or .match (if you just want an index of the first match):
if (marketPairs[j].match(new RegExp(symbols[i] + '|' + symbols[j])) > -1)

(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)


text:
Q: did wamp server supports ffmpeg in my windows local machine Did wamp server supports ffmpeg in my windows local machiine. If so can I straight away run my code in wamp server to encode video (or) did I have to install the ffmpeg or any related thing to run it

A: *

*Download ffmpeg dll files from here: http://sergey89.ru/files/ffmpeg-php-win32-all.zip

*Extract and put php_ffmpeg.dll to you php ext folder(D:\xampp\php\extensions)

*Put the rest of dlls to you windows/system32 folder(C:\WINDOWS\system32)

*Add code "extension=php_ffmpeg.dll"in your php.ini file located here: D:\xampp\apache\bin

*Restart apache and run phpinfo() – you should see the ffmpeg extension .

Hope this will solve your problem.

A: WAMP won't install ffmpeg for you, that's outside its purview. But nothing says you can't install it yourself and then use something like this to interface with it.


text:
Q: How to retrieve value from tag,SOAP I am using SOAP , and got this returnString.
<?xml version="1.0" encoding="UTF-8" ?>
<result>
dddddddddddd5
ccccc+
<c>hi</c>
</result>

How can I retrieve the value from tag  and assign it to a NSString??

A: You'll have to parse the XML response you get … I would recommend you to use an external library for this problem. Give this article a shot to decide which one you want to use: How To Choose The Best XML Parser for Your iPhone Project.
A really great article about using SOAP services with iOS is this one: Working with iOS and SOAP.
Hope this helps!

A: you must parse the result to get the value
i advice you this lib to parse your result GDataXML
as i know there is no official client  soap  library in objective C

A: got it running this works NSString *UIDFromXml = [returnUID stringBetween:@"" and:@""];. thanks for the response –


text:
Q: Can't apply styles to Textfield using className in materi-ui latest version V1.0.0-beta.26 I am unable to style Textfield using className in latest material UI version. I am passing style object to className but it does no effect. Please find warning message below
Warning: Failed prop type: Invalid prop className of type object supplied to TextField, expected string.
Find code Below:
import TextField from 'material-ui/TextField';

const textField = {
  width: 200,
  fontFamily: 'Open Sans,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif',
  fontStyle: 'normal',
  fontWeight: 400,
  fontSize: 16,
  color: '#504572',
}
<TextField className={textField} label="Email" placeholder="Enter your email" value={this.state.email} onChange={this.changeEmail} name="email" />

In docs https://material-ui-next.com/demos/text-fields/ it is actually an object passed to className. It is working there but dono why it is failing for me.

A: Material-ui team overhauled their approach to styling with material-ui v1. If you don't want to use inline style prop or plain css then you need to use withStyles HOC.
    import React from "react";
    import TextField from "material-ui-next/TextField";
    import { withStyles } from "material-ui-next/styles";

    const styles = {
      textField: {
        width: 200,
        fontFamily:
          "Open Sans,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif",
        fontStyle: "normal",
        fontWeight: 400,
        fontSize: 16,
        color: "#504572"
      }
    };

    const stack = function(props) {
      const { classes } = props;
      return (
        <TextField
          className={classes.textField}
          label="Email"
          placeholder="Enter your email"
          name="email"
        />
      );
    };

    export default withStyles(styles)(stack);

A: You need InputProps to apply className. For Eg:
<TextField
           label={"Name"}
           name={"name"}
           variant={"outlined"}
           inputProps={
                         {className:chatClasses.textEdit}
              }/>

A: instead of className
use style property instead
import TextField from 'material-ui/TextField';

const textField = {
  width: 200,
  fontFamily: 'Open Sans,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif',
  fontStyle: 'normal',
  fontWeight: 400,
  fontSize: 16,
  color: '#504572',
}
<TextField style={textField} label="Email" placeholder="Enter your email" value={this.state.email} onChange={this.changeEmail} name="email" />


text:
Q: Why is python writing ` instead of @ So I'm trying to write a spam bot to annoy my friends in discord (I know I'm evil)
Here's the code
import time
import pyautogui
time.sleep(10)
victim = "Saka"
f = open("spamtext", 'r')
for word in f:
    pyautogui.keyUp('shift')
    pyautogui.typewrite("@" + victim)
    pyautogui.press("enter")
    time.sleep(1)

The problem is, instead of typing "@Saka", it types "`Saka".
I've tried pyautogui.keyUp('shift'), but it still doesn't work,any ideas?
(Also this is my first time asking a question here, so sorry if I didn't provide enough info)

A: Lol! This is a funny post. Cheers to the prank.
With pyautogui, it literally presses the keyboard. Imagine a human robot doing it really fast. So you need to pass the exact keys you press in your keyboard to output the "@"
In order to do this, the función hotkey is available.
To make pressing hotkeys or keyboard shortcuts convenient, the hotkey() can be passed several key strings which will be pressed down in order, and then released in reverse order.
In my keyboard, I can output an @symbol with shift + 2 which I think it would be something like:
pyautogui.hotkey('shift', '2')

A: I think this problem is about your keyboard layout,
So you can print at sign in ASCII, and be sure it works everywhere
import time
import pyautogui
time.sleep(10)
victim = "Saka"
at_sign = chr(64) # 64 is at-sign ascii character: @
f = open("spamtext", 'r')
for word in f:
    pyautogui.typewrite(at_sign + victim)
    pyautogui.press("enter")
    time.sleep(1)

A: Thank you everyone for your help! The thing was that Japanese keyboard doesn't work well with pyautogui because it has 2 modes, English and Japanese, which it keeps switching between. All I had to do was download US keyboard and now I think my friends hate me...
Thanks to Martin Castellon for the help!


text:
Q: Vagrant up hangs at "ssh auth method: private key" I've been having some issues getting vagrant version 1.8.1 to run with virtualbox 5.0.10, box precise64. My operating system is Windows 7.
Essentially, when I run
vagrant up

...this happens
So far, I've attempted the following:
opening another command line and running a myriad of different codes, including:
vagrant ssh
vagrant ssh-config
ssh 127.0.0.1

I've also attempted the fix shown on this video (to no avail)
https://www.youtube.com/watch?v=vDQpfb0eFTc
As well as manually specifying the ssh key, and changing the ssh key.
My attempts to ssh into the box manually are met with a "connection refused" error.
When I open the VM GUI through virtualbox, it stops at the login page, rather than the boot menu others have reported.
My vagrantfile is unmodified, however I've attempted all of the above with additions:
config.ssh.username = "vagrant"
config.ssh.password = "vagrant"

.. which didn't work
I also attempted adding this (with and without the above Vagrantfile additions)
config.ssh.private_key_path = "C:/Users/Luka/.vagrant.d/insecure_private_key"

Which also gave me nothing.

A: I spent multiple hours trying to troubleshoot this issue, and tried every solution listed above and more, and I wasn't getting anywhere.
The error I was getting when running vagrant up:
[...]
default: Booting VM...
default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2222
default: SSH username: vagrant
default: SSH auth method: private key
Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.
[...]

I decided to pursue this event I was seeing in the VirtualBox log for my running VM:
00:00:01.752390 HM: HMR3Init: Attempting fall back to NEM: VT-x is not available

When I saw that, I decided to check using the "Intel Processor Identification Utility" (from Intel's website) to verify if VT-x was enabled or not. To my surprise, it showed that "Intel Virtualization Technology" was disabled:

I was pretty sure VT-x was enabled in my BIOS, but I checked again to make sure. Indeed, VT-x was enabled in my BIOS.
Pretty stumped by what I was seeing, I kept looking on the internet as to why VT-x was enabled in BIOS, but showing as disabled by the OS. A lot of articles kept pointing at "Hyper-V" being the culprit. So I uninstalled "Hyper-V" using the Windows Features utility [as well as my Docker Desktop" because it relies on Hyper-V to function], but the Intel CPU identification utility kept showing VT-x as disabled.
Next thing I tried was to remove all the items that are identified as "interfering" with Hyper-V in the Windows 10 "Windows Features" [listed as "Turn Windows features on or off" in the search bar]. The items in red are the ones I removed:

*

*Containers

*Hyper-V

*Virtual Machine Platform

*Windows Hypervisor Platform

*Windows Subsystem for Linux

I restarted my PC, again, I checked the status of VT-x with the CPU identification utility, and still, it was disabled.
At this point I was pretty much going to throw the towel at the issue until I found some article where someone ran this command manually in an elevated command prompt (cmd.exe):
dism.exe /Online /Disable-Feature:Microsoft-Hyper-V

I restarted my PC, checked the status of VT-x with the CPU identification utility, to my surprise it was showing as ENABLED!!:

When I checked the VirtualBox logs from my running VM after VT-x showed as enabled, I could see the following event instead:
00:00:01.556258 HM: HMR3Init: VT-x w/ nested paging and unrestricted guest execution hw support

In my command-line window, after vagrant up, I could now see:
default: Booting VM...
default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2222
default: SSH username: vagrant
default: SSH auth method: private key
default:
default: Vagrant insecure key detected. Vagrant will automatically replace
default: this with a newly generated keypair for better security.
default:
default: Inserting generated public key within guest...
default: Removing insecure key from the guest if it's present...
default: Key inserted! Disconnecting and reconnecting using new SSH key...
default: Machine booted and ready!

My solution in a nutshell?
Make sure the OS sees VT-x as enabled using a utility such as "Intel Processor Identification Utility" [Or whatever utility depending on your CPU architecture]. I believe there is a bug in Windows 10 that causes this issue, but I haven't been able to put my finger on it (and I don't have time to do so). It seems Hyper-V is the root cause of all the issues. For the people concerned about not being able to use Docker Desktop anymore, I believe there are alternatives out there for non-Hyper-V solutions (i.e. free Docker EE??).
Good luck.

A: Happened to me with "ubuntu/focal64". I tried different solutions, but nothing worked.
Switch box to "ubuntu/xenial64" - everything loads successfully.
My setup:
win10 home 10.0.19041 Build 19041
vagrant 2.2.9
virtualbox 6.2

A: I am on:

*

*Windows 10

*Vagrant 2.2.19

*Virtualbox 6.1.30

I have been using laravel homestead for a long time.
A co-worker recently recommended I try docker. After installing docker desktop & configuring my machine to use WSL, I experimented with Laravel Sail over the weekend.
Then I tried to vagrant up into my normal homestead machine this morning, but my system would hang at default: SSH auth method: private key
After trying several of the other solutions above and elsewhere, here's what finally worked for me:

*

*Open Oracle VM VirtualBox manager

*File > Host Network Manager

*Select "VirtualBox Host-Only Ethernet Adapter #2"

*Click "Remove"

*Switch to your normal terminal of choice and run vagrant up as ususal

The system will re-build the network adapter and the vagrant machine will boot up as normal. Back to work.
Credits: https://github.com/hashicorp/vagrant/issues/11987#issuecomment-903666254
And: https://stackoverflow.com/a/56318621

A: I also got this issue when I am trying to use laravel/homestead vagrant box. For me, I found out that the issue is caused by WindowsFeature VirtualMachinePlatform. I have enabled it since I am using WSL 2 in my machine. Simply disabling that feature helped with the issue.
To disable the VirtualMachinePlatform feature, open PowerShell as an Administrator and run:
dism.exe /online /Disable-Feature /FeatureName:VirtualMachinePlatform /NoRestart

Then Restart your machine and try vagrant up. It worked for me.
You can enable the  VirtualMachinePlatform feature again by simply running the below command on PowerShell as an Administrator:
dism.exe /online /Enable-Feature /FeatureName:VirtualMachinePlatform /all /NoRestart

Then Restart your machine again and the feature is enabled again.
I have reported an issue regarding this also. If anyone needs to keep track on that bug click here

A: I know this is an old topic, but I ran into the same issue and for me the solution was to enable the Hardware virtualization in BIOS (VT-x), which is required on Windows OS to run any kind of virtual machine.
I hope this will help someone who stumbles into this.

A: This happened to me with box ubuntu/bionic64 too. By switching to ubuntu/trusty64 it runs without a problem. (Win10 Pro v2004 build 19041.572)
As state here there is a confirmed bug that causes some of the newer Ubuntu boxes to boot slowly, which is causing the SSH timeout in this case.
You can work around this by adding the following customizations to your Vagrantfile:
config.vm.provider :virtualbox do |vb|
    vb.customize ["modifyvm", :id, "--uart1", "0x3F8", "4"]
    vb.customize ["modifyvm", :id, "--uartmode1", "file", File::NULL]
end

A: After a couple of days of trying to solve the problem with "SSH auth method: private key", it was found that windows 10 has a conflict with vagrant.
As a tool to validate the status of virtualization, the program was used: "https://www.intel.com/content/www/us/en/download/12136/28539/intel-processor-identification-utility-windows-version .html "
I show you the capture of the initial state: https://i.imgur.com/hidKDRN.png
Fix it by disabling the following windows features: https://i.imgur.com/ZzjryTA.png
Once the aforementioned features were deactivated and the computer was restarted, I share the new state of the processor where it is evident that virtualization is already working: https://i.imgur.com/IVzh4YR.png
PS: On saying that you already activate virtualization on the board (bios)
With this solution already vagrant works perfectly for me.

A: It's worth to try this too if other ways didn't help yet.
In VirtualBox go to Settings, click on Network, then on Advance, then change your Network type to : Intel PRO/1000 MT Server (82545EM) and refresh the MAC-address

Make sure your Port Forwarding is set to default like this image:

A: I have also faced the issue "Vagrant up hangs at ssh auth method: private key", after trying out a lot off stuff. But as stated above by morkitz Enabling the Hardware Virtualization solved my issue as well.
My Stack was
1. Win 8.1 Enterprise
2. Vagrant 2.1.2
3. Virtual Box 5.2.18

A: Hope this helps someone as I struggled with mine for quite some time after upgrading Virtualbox, clearly I did not investigate very well due to time constraints, then after reading quite a few posts, decided to clear my known_hosts file on my machine, the the issue is now resolved.


text:
Q: mypy: base class has no attribute x, how to type hint in base class I recently discovered mypy and I want my code to be type checked with it.
I have a Connector base class:
class Connector():
    ... some methods, but no __init__ ...

And I have several subclasses, they are all connectors, but of different types:
class Siphon(Connector)
    def __init__():
        short_name = "S"

class Tube(Connector)
    def __init__():
        short_name = "T"

When I use these objects, I normally put them in a list:
c1 = Siphon()
c2 = Tube()
list_connectors: List[Connector] = list()
list_connectors.append(c1)
list_connectors.append(c2)

Now let's say I want to write a function to return all the short names of all the connectors, as a list. I'd write something like that:
def get_names(list_connectors: List[Connector]) -> List[str]:
    tmp_list: List[str] = list()
    for c in list_connectors:
        tmp_list.append(c.short_name)
    return tmp_list

When I do that, mypy complains:
error: "Connector" has no attribute "short_name"

Which is true, the base Class Connector doesn't have this attribute, only the subclasses. But all Connector subclasses will have this attribute.
How should I correct that? I can"t use a class attribute here since all my subclasses will need their own short_name attribute.
Should I use a Union in the type hinting of my get_names function (in my real life situation, there are much more than 2 types of connectors, and the user of my API could add his own)?
I'm also not sure I could write a base __init_ function and override it in the subclasses, because the subclasses all have a different init

A: If you are using python 3.6 or later then
class Connector():
    short_name: str
    ...

should work. This doesn't actually exist in the namespace, but MYPY will find it. See https://www.python.org/dev/peps/pep-0526/.

Another option is to do
import abc
class Connector(abc.ABC):
    @property
    @abc.abstractmethod
    def short_name(self) -> str:
        ...

A: You'd add that attribute to the base type; you don't need to give it a value:
class Connector:
    short_name: str

This uses Python 3.6's Variable Annotation syntax, which is new in Python 3.6 or newer. It defines the type of an instance attribute, not a class attribute (for which there is a separate syntax).
You can use a comment otherwise, at which point you do have to give the attribute an initial value, and is a class attribute:
class Connector:
   short_name = ''  # type: str


text:
Q: Can ScrollTo work on a form page or is there another way? I have a scrollTo() on a form page that is not working.  My function takes a string that is an ElementId and should then scroll to that element in this case it is an .  The exact same code and html layout works on another page.  The only difference is that this is on a form page and is wrapped in a . Is there any reason that this should not work?
I have tried removing the div, changing the way I call scrollTo(), such as ngOnInit(), ionViewDidLoad(), from a button, moving the button.
This is my function
public scrollTo(elementId: string) {
        console.log("SCROLL TO");
        let y = document.getElementById(elementId).offsetTop;
        this.content.scrollTo(0, y);
    }

Expected results - When the function is executed the page scrolls to the specified element.
Actual results - the function executes without error, but nothing happens.


text:
Q: Why is IE using styles from media=print CSS? I have the following HTML where there is a DHTML behavior added to the CSS class. When the code is written in the following way, Internet Explorer (version 8 in compatibility mode) reads the @media print as well instead of using the top style only.
<!--[if IE]>
<style>
.roundCorners {
border: 1px solid #b4b4b4;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
background: #fff;
behavior: url(/css/border-radius.htc);
}

@media print {
.roundCorners {
 border: 5px solid #b4b4b4;
 -moz-border-radius: 5px;
 -webkit-border-radius: 5px;
 border-radius: 5px;
 background: #fff;
 behavior: url(/css/border-radius_remove.htc);
}
}
</style>
<![endif]-->

A: IE8 is using the print CSS instead of the media one, because the print CSS is inline, and not coming from an external file. This code will help.
<style type="text/css" rel="stylesheet" href="stylesheet_media.css" screen="media">
<style type="text/css" rel="stylesheet" href="stylesheet_print.css" screen="print">


text:
Q: Relational database in django rest framework serializers I'm working on a Rest API for a web blog, I have made the custom user class and related between custom user class and the post class, but when i try to make a post request and add a post to the database i'm stuck in serializering the post because of the the relation between the user and the post models, all i want to do is just make the author of the post is the current logged in user but i don't actually know how to do this
Custom user model:
class CustomUser(AbstractBaseUser, PermissionsMixin):

    email = models.EmailField(max_length=255, unique=True, blank=False, null=False)
    username = models.CharField(max_length=255, unique=True, blank=False, null=False)
    date_joined = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)
    is_superuser = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    objects = CustomUserManager()

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return self.is_superuser

Post model:
class Post(models.Model):
    title = models.CharField(max_length=255, blank=False, null=False)
    content = models.CharField(max_length=10000, blank=False, null=False)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

Post serializer:
class PostSerializer(ModelSerializer):

    class Meta:
        model = Post
        # I don't know if this way is right
        fields = ('id', 'title', 'content', 'author')
        extra_kwargs = {"author": {"read_only": True}}

    def create(self, validated_data, request):
        post = Post(
            title=validated_data['title'],
            content=validated_data['content'],
            # I don't know what's gonna be assigned to the author
            author=
        )
        post.save()
        return post

Post View:
class AddPostView(APIView):

    serializer_class = serializers.PostSerializer

    def post(self, request):
        serializer = serializers.PostSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(data=serializer.data)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

A: At first, it doesn't seem to me like you need to specify your custom create method in PostSerializer. And author field can't be read_only otherwise it will be ignored and won't be saved. So it could just look like this:
class PostSerializer(ModelSerializer):
  class Meta:
    model = Post
    fields = ('id', 'title', 'content', 'author')

Then this is how you assign an author in your view action:
def post(self, request):
  current_user = request.user
  serializer = serializers.PostSerializer(data={**request.data, author=current_user})
  ...

A: I found a way that works fine for me.
Pass the context to the serializer from the view
Post View:
class AddPostView(APIView):

serializer_class = serializers.PostSerializer

def post(self, request):
    serializer = serializers.PostSerializer(data=request.data, context={'request': request})
    if serializer.is_valid():
        serializer.save()
        return Response(data=serializer.data)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Then here is the serializer. Post Serializer
class PostSerializer(ModelSerializer):

    class Meta:
        model = Post
        fields = ('id', 'title', 'content', 'author')
        extra_kwargs = {"author": {"read_only": True}}

    def create(self, validated_data):
        user = self.context['request'].user
        post = Post(
            title=validated_data['title'],
            content=validated_data['content'],
            author=user
        )
        post.save()
        return post


text:
Q: UserForm to VLookup and display data 'Entry = MAC address entered and MAC should display the same MAC found in my worksheet
'Error 424: Object required
Private Sub MAC_Search_Click()

MAC = Application.WorksheetFunction.VLookup(Entry, MAC_Database.Range("A4:M3573"), 2, False)

End Sub

A: The code is complaining about MAC_Database which is neither Dim'ed nor Set.
You have similar problems with MAC and Entry.  Once these problems have been corrected, you will need at least a MsgBox to display the value of MAC


text:
Q: AngularJS Accessing Value In Querystring Im trying to accessing a value in a querystring.
Here's what i see in the browser:
http://localhost:1010/products/chairs.html?searchMe=testing123

And in my Controller, i have:
var mySearchMeQuery = $location.search().searchMe;

console.log("searchMe = " + mySearchMeQuery );

In my console.log, i am seeing: searchMe  = undefined
I have checked i have $location injected in my controller.
** Solution must work in IE8+ **

A: $location works only if you use path with hash (#). See this.

A: Use $location.search()
It returns an object key-value pairs; The key is your query string and the value is the query string value.
Example:
function MainCtrl($scope, $location) {
    $scope.queryString = $location.search();
    // returns {searchMe: "testing123"}
}

And if you want to print the same message as in your question
 console.log("searchMe = " + $location.search().searchMe);

A: You can inject dependecy $routeParams and get the parameter value using something like this:
$routeParams.searchMe

Docs on routeParams
UPDATED Answer:
I have updated an existing fiddle which had $routeParams as an example. If you click on Moby link and check console over there you can see that SearchMe as a querystring is available.
Fiddle