text:
Q: Image max height and max width while preserving aspect ratio Is it possible to give max-height and max-width to an image while preserving aspect ratio without using js?
For example,
I want an image to be with a height of 38px and the width auto.
If the width is higher than 200px, I want the width to be 200px and the height auto.
If it's not possible without js, does anyone have an idea how to do it with js and without resizing the image after it's already loaded?

A: There is a built in CSS style called max-width and max-height and I really do not think min-width exists, incase you are wondering. You can refer to the example below to understand better. Also I am using text instead of an image, but you should get the idea.
I have nested the actual div instead another div so you could play around with the resizing.

#con {
  resize: both;
  overflow: auto;

}

#box {
  /*Here you could say auto instead*/
  height: 200px;
  max-width: 200px;
}
<!DOCTYPE html />

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus dapibus auctor ipsum, in convallis mi lobortis in. Phasellus molestie suscipit rutrum. Duis et convallis lectus. Etiam id urna massa. Nulla sagittis erat nec arcu rutrum elementum. Vestibulum blandit erat vestibulum, ullamcorper augue vitae, accumsan mi. Sed consectetur, quam vel efficitur interdum, ante ligula interdum justo, a dictum ligula tortor sed nunc. Cras eget magna ac urna imperdiet laoreet eget sed ante. Vivamus condimentum tortor sit amet diam elementum malesuada sed sed neque. Vestibulum et magna mollis, consequat nibh ut, facilisis orci. Phasellus fermentum sodales libero, et vehicula enim ornare ut. Donec non bibendum metus. Cras hendrerit, quam a pellentesque varius, tortor nunc maximus lectus, at gravida diam ipsum ut metus. Etiam orci felis, dapibus id cursus eu, dapibus ut augue. Proin a leo viverra, tempus ipsum nec, lacinia lacus. Maecenas id dolor nec neque lobortis interdum quis quis nisi.

A: Using both width auto and height auto will give to following code. To center horizontal I used the align-items center of the flexbox.

.container,
.container * {
  box-sizing: border-box;
}
.container {
  display: flex;
  width: 800px;
  margin: 10px auto;
}
.img {
  display: flex;
  align-items: center;
  width: 25%;
  height: 150px;
  border: 2px solid silver;
}
.img img {
  display: block;
  border: 0;
  width: auto;
  max-width: 100%;
  height: auto;
  max-height: 100%;
  margin: auto;
}

A: You have to use max-width and height and object-fit CSS properties for image.. see example

.img img {
  max-width: 200px;
  height: 38px;
  object-fit: contain;
  object-position: left;
}

Hope it works... if any question comment pls

A: Here are 2 examples of the solution I think would work, the first image has less than width: 200px; and the second one has more than width: 200px;
Again, I'm not sure if it would work for you, but I think it would, and if it doesn't I would love to know why.

A: You can nest the image in a 200x38 container, then set the max-width and max-height of the image to 100%. Here is a working snippet (I have included JS to make it interactive, but it is not necessary. Try resizing the container using the sliders):

var width = document.getElementById("width");
var height = document.getElementById("height");

var widthInput = document.getElementById("widthInput");
var heightInput = document.getElementById("heightInput");

var imageContainer = document.querySelector("div");

widthInput.addEventListener("input", function() {
  width.innerHTML = this.value + "px";
  imageContainer.style.width = this.value + "px";
});

heightInput.addEventListener("input", function() {
  height.innerHTML = this.value + "px";
  imageContainer.style.height = this.value + "px";
});
div {
  width:  200px;
  height: 200px;
  border: 1px dashed #000;
}

.image {
  display:    block;
  max-width:  100%;
  max-height: 100%;
  background: #333;
}

Width: 200px

<input id="widthInput" type="range" min="0" max="400"/>

Height: 200px

<input id="heightInput" type="range" min="0" max="400"/>

You can notice that however you change the dimensions of the container, the image is still contained within it. By setting the container to 200px wide by 38px tall, you can force the image to stay within the limits 0px ≤ width ≤ 200px and 0px ≤ height ≤ 38px.

A: Specifying height or width will keep the aspect ratio. Specifying both the max-height and max-width will keep the aspect ratio. Specifying height and max-height makes no sense. Specifying height and max-width cannot guarantee your aspect ratio.


text:
Q: Android -File google-services.json is missing. The Google Services Plugin cannot function without it I'm trying to connect my app to Firebase, but it keeps saying google-services.json is missing, even though I've added it to the right place. Actually, the last time I tried this (on a different app), it worked, but this time it doesn't. I read a lot of articles but my problem still persists. Any help?
Thanks!

A: You have to download the config file for your Android app from Firebase Project settings.
Please refer to this link for steps of Getting a config file for your Android app
Note that the file should be used as follows:

Copy the file into the app/ folder of your Android Studio project, or
  into the app/src/{build_type} folder if you are using multiple build
  types.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lie Bracket of Lie Algebra Associated with Given Lie Group Let $G$ be a Lie group. Its Lie algebra, when considered as a vector space, is given by $T_e G$, the tangent space of $G$ at the identity element $e$.
However, in order to fully describe the Lie algebra associated with $G$ we must also describe the commutator $\left[\cdot,\,\cdot\right]:T_eG^2\to T_eG$ and show that it obeys the three axions: bilinearity, alternativity and the Jacobi identity.
Following Wikipedia, one defines first for any $g\in G$ left multiplication on $G$ by $g$ as $$ l_g:G\to G$$ given by $$ x\mapsto gx$$and a left-multiplication invariant vector field $X\in TG$ is one which obeys for every $\left(g,\,h\right)\in G^2$ $$ \left(d l_g\right)_h X_h = X_{gh} $$ where $\left(d l_g\right)_h:T_hG\to T_{gh}G$ is the differential of $l_g$ at $h$. We define $Lie\left(G\right)$ as the vector space of left-multiplication invariant vector fields.
Apparently $G\times Lie\left(G\right)$ is isomorphic to $TG$ via $$\left(g,X\right)\mapsto\left(g,X_g\right)$$ so that we get a $\natural$ isomorphism $Lie\left(G\right)$ with $T_eG$ given by $$Lie\left(G\right)\ni X \mapsto X_e\in T_eG$$This last isomorphism we call $\phi$.
Now apparently there is a Lie bracket structure on $TG$ which induces a Lie bracket structure on $Lie\left(G\right)$: for any $X$ and $Y$ in $TG$ we have $$ \left[X,\,Y\right]_{TG}= X\left(Y\left(\cdot\right)\right)-Y\left(X\left(\cdot\right)\right)$$ This in turn can be pushed forward to a define our desired Lie bracket on $T_e G \equiv \frak{g} $ via: If $X$ and $Y$ are any tangent vectors in $T_eG$ then $$\left[X,\, Y\right]_{T_eG}=\phi\left[\phi^{-1}\left(X\right),\,\phi^{-1}\left(Y\right)\right]_{TG}$$

My question is: is there now any easier way to describe $\left[\cdot,\,\cdot\right]:T_eG^2\to T_eG$? I tried for example to write it in coordinates and it was a mess. How do you "easily" see how $\left[X,\, Y\right]_{T_eG}$ acts on any scalar function $f$ given some $X$ and $Y$ in $T_eG$?

A: Indeed there is at least locally at the identity. The heart of the questio is given by the Baker Hausdorff Campbell formula, i.e.
$$\exp\left(X\right)\exp\left(Y\right)=\exp\left(X+Y+\frac{1}{2}\left[X,Y\right]+\frac{1}{12}\left(\left[X,\left[X,Y\right]\right]+\left[Y,\left[Y,X\right]\right]\right)...\right).$$
Usually you  read it in the opposite way deducing locally the multiplication law starting from Lie's parenthesis (you might want to remember that $\exp\left(X\right)$ can be thought as an element of the Lie Group and so $\exp\left(X\right)\exp\left(Y\right)$ it just the multiplication of two elements $g$ and $h$ of the Lie Group).
The converse, i.e. recovering the Lie parenthesis from the multiplication law, is also true but involves the logarithm function and therefore it's really just local, but anyway can be done.


text:
Q: Using multiple templates with the same class in C++ I have the following code in C++ -
template <class T>

class TempClass {

    T value;

public:
    TempClass(T item)
    {
        value = item;
    }

    T getValue()
    {
        return value;
    }
};

int main()
{
    TempClass<string>* String =
      new TempClass<string>("Rin>Sakura");

    cout << "Output Values: " << String->getValue()
         << "\n";

    class TempClass<int>* integer = new TempClass<int>(9);
    cout << "Output Values: " << integer->getValue();
}

What I would like to do is use multiple templates with the above class TempClass. I know one way of doing this is by using
template <class T1, class T2>

, but if I do that then all instances of the class must have 2 template arguments. What I want to do is something more like :
if (flag)
    //initialize an instance of TempClass with one template

    TempClass<string> s("haha");

else
    //initialize an instance of TempClass with 2 templates.

    TempClass<string, int> s("haha", 5);

Is there a way to do this without using another new class?

A: You can use a variadic template and an std::tuple to hold values of distinct types. Minimal example:
template<class... Ts>
class TempClass {
    using Tuple = std::tuple<Ts...>;
    Tuple values;

public:
    TempClass(Ts... items) : values{items...} {}

    template<std::size_t index>
    std::tuple_element_t<index, Tuple> getValue() const {
        return std::get<index>(values);
    }
};

int main() {
    TempClass<int, std::string, double> tc1{0, "string", 20.19};
    std::cout << tc1.getValue<2>(); // Output: 20.19
}

std::tuple_element_t is available only since C++14. In C+11 you should be more verbose: typename std::tuple_element<index, Tuple>::type.


text:
Q: How to load website superfast as this one? I am not sure if it is the right place to ask the question but I couldn't find any channel on StackExchange relating to the question so thought to ask here.
My client asks me to build a website that loads faster as this.
I know we can use Vue.js, Angular, React.js etc. to make the website faster and works as SPA. However, that also takes a few seconds to loads the data. I am unable to figure out the technology the referred website is using.
Can anyone help me or suggest me some technology that loads website fast as the reference one?

A: The problem is more complex. If you want a very fast website you should think at a bigger scale and not resume at technology used to build the website.

*

*First of all you must have a distributed architecture of website servers to reduce latency for your visitors. It is not making sense for a visitor from  Germany to load the site from a Tokyo server just because there we have the host provider. We must serve the German visitor from a server in proximity like France for example. Even more, here is very important also the way you are going to manage the website resources. For example the static resources should stay in a cloud front web server because they will be cached and served very fast. In general a browser has a limited number of threads used to bring data from the same domain. Having the static files on another machine will increase this number.

*All of your pictured should be optimized with the new format webp or use SVGs.

*All the pictures should be already resized in the proper dimension  (or be served in proper size) and not let the browser to resize them for you to fit in containers.

*All the JS files should be packed in one big file to reduce the number of requests

*Minify the CSS files and they should also be bundled in only one big file (if is possible)

*Enable web server compression. Gzip is the most popular and effective compression method currently available and generally reduces the response size by about 70%. Approximately 90% of today's Internet traffic travels through browsers that claim to support gzip.

*Reduce cookie size

*Have a reduced number of DOM elements

*Add Expires headers

*Combine images using CSS sprites (where is possible)

*Avoid inline JavaScript

*Use asynchronous resources

There are more other small optimizations that can improve the performance, but here you have the most important ones from my point of view.
After you thought of all these, now you should start building the website in such a way to accommodate them all and choosing the technology that will help you to cover these problems. In the end to answer your question the presented site https://aiad.com.au/ was build with NuxtJS based on Vue.js.

A: I can suggest some of the steps:

*

*Create a light weight site.

*Remove unwanted variables and codes.

*create good code for the site.

*Declare any one variable that can be use in multiple pages and codes insted of declearing multiple variables.

*Queries need to be optimized which you are using in a project.

*Depends on the server and bandwith where you will deploy your project.


text:
Q: Default value in a FOSUserBundle form : data option do not work I have modified directly a FOSUserForm (with no overriding) to try and assign a default value while building the form, I have added the
array('data'=>'default value')

such as:
namespace FOS\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class RegistrationFormType extends AbstractType
{
private $class;

/**
 * @param string $class The User class name
 */
public function __construct($class)
{
    $this->class = $class;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('username', null, array('data' => 'Default value','label' => 'form.username', 'translation_domain' => 'FOSUserBundle'))
        ->add('email', 'email', array('data' => 'Default value','label' => 'form.email', 'translation_domain' => 'FOSUserBundle'))
        ->add('plainPassword', 'repeated', array(
            'type' => 'password',
            'options' => array('translation_domain' => 'FOSUserBundle'),
            'first_options' => array('label' => 'form.password'),
            'second_options' => array('label' => 'form.password_confirmation'),
            'invalid_message' => 'fos_user.password.mismatch',
        ))
    ;
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => $this->class,
        'intention'  => 'registration',
    ));
}

public function getName()
{
    return 'fos_user_registration';
}

It doesn't work and I keep having a form validation message "Please enter a username"
what's wrong?

A: Have you tried setting the username as a hidden field instead of "null"? Or remove the username from the form completely and set it manually before the entity is persisted in the database.  I don't recommend the second option unless you have performed a check to make sure the username is unique before persisting it to the database.
Edit:
Out of curiousity, why are you modifying a vendor class directly?
Edit 2:
The default validation for the username field should probably not be removed (and if you do, make sure it is still a unique field in the database (http://symfony.com/doc/2.0/reference/constraints/UniqueEntity.html).
If you want to set a default username value, instead of setting the data option in the form, create a custom RegistrationFormHandler that overrides the default createUser method:
<?php

namespace Acme\UserBundle\Form\Handler;

use FOS\UserBundle\Form\Handler\RegistrationFormHandler as BaseHandler;

class RegistrationFormHandler extends BaseHandler
{
    /**
     * @return UserInterface
     */
    protected function createUser()
    {
        $user = $this->userManager->createUser();
        $user->setUsername('customusername');

        return $user;
    }
}

Instructions on overriding this handler can be found here (towards the bottom):
https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/overriding_forms.md
It's pretty simple, should only take a minute to implement. Additionally, creating the custom formhandler will also prevent any changes you've made in the vendor classes from being lost when you update your vendors via composer.
Edit 3:
DependencyInjection\EtienneUserExtension.php:
<?php

namespace Etienne\UserBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;

//if using xml
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;

//if using yaml
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\Config\FileLocator;

class EtienneUserExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        //if using XML
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');

        //or if using yaml services
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
    }

    public function getAlias()
    {
        return 'etienne_user';
    }
}

services.xml
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

<services>
    <service id="acme_user.form.handler.registration" class="Acme\UserBundle\Form\RegHandler" scope="request" public="false">
        <argument type="service" id="fos_user.registration.form" />
        <argument type="service" id="request" />
        <argument type="service" id="fos_user.user_manager" />
        <argument type="service" id="fos_user.mailer" />
        <argument type="service" id="fos_user.util.token_generator" />
    </service>
</services>

</container>


text:
Q: Specified cast is not valid exception when counting records with linq I'm sure this is a pretty simple one, but I can't seem to find an answer anywhere...
i am trying to count rows from a datatable using linq but exception is throwing ("Specified cast is not valid.") as a result of the condition int > 0
    countofbacklog = dt.AsEnumerable().Where(Function(x) x.Field(Of String)("status") = "open" _
        AndAlso x.Field(Of String)("generalStatus") = "PMO" _
        AndAlso x.Field(Of Integer?)("income") > 0).Count
    dt.Dispose()


text:
Q: Simpler version of my PHP I'm currently making a very rudimentary CMS, not using an OOP just simple PHP and MySQL queries. In the CMS part of the site I have form for updating the site's content and I have certain fields displayed depending on the item that is selected in the navigation - via passing the items ID in the URL and using the _GET variable to query it. I am trying to have an 'Author' input display only on two items and I am using the code below to only display it when it's value isn't equal to these three numbers...
 <?php if(($current_page["subject_id"] != 16) && ($current_page["id"] != 7) && ($current_page["id"] != 10)) {?>

Is there an easier way to do this? I know the whole point of being a good coder is to simplify the code... I think I'm failing with this one.

A: That code is as basic as it gets. If you want things a tad more simple, then you could assign $current_page["id"] to another variable to get rid of the array access overhead, but really, that isn't worth mentioning (Unless your array is huge, and still, even then it's not doing a lot). Using a function like in_array that has been suggested is also not much better in speed or simplicity. I'd say just keep it like you have.
On another note, if you're accessing those arrays more than just in that if statement, then it would be a good idea to assign them to variables. Otherwise, what you have is good.

A: You can just use in_array here.
For e.g.:
<?php
$id=array('7','10');
if(($current_page["subject_id"] != 16) && !in_Array($current_page["id"],$id)) {?>

If you have many number of ids you just need to pass IDs to $id.


text:
Q: How to set the referer on a rewrite rule? I have the following problem: I use a script that saves the referer URL. I want this URL to one of my own URLs. So let's say a users access the page http://example.com/page1 I want to rewrite that URL to http://example.com/page2 and safe the referer on that page.
I don't want to do that with a PHP script as otherwise I would have to extend that script each time I want to track a new referer. I already tried these rewrite rules:
RewriteRule ^page1$ /page2 [R=301,QSA,NC]
RewriteRule ^page1$ /page2 [L,R=301,QSA,NC]

The rewrite works, but the request parameter referer is missing. Do I have to use another stauts code than 301 or is there any other error in my rewrite. Is it even possible to set the referer in a rewrite rule?

A: Using the R flag causes an external redirect. If you just want an internal rewrite, omit the R flag:
RewriteRule ^page1$ /page2 [QSA,NC]


text: Q: How to add docker database to phpstorm? I am trying to add a database in phpstorm which is on docker. I chose MySql as drvier. However, when I test the connection, I get the error Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. What could be the reason?


text:
Q: In Star Trek, is there an upper size/mass limit to what the Main Deflector can deflect? My understanding is that every Federation ship has a navigational deflector which is primarily used to deflect any objects that may collide with the ship while at warp or otherwise. From what I've seen of TNG and Enterprise, the deflector can be used for other means, including as a weapon to damage larger objects. These appear to be rare exceptions to its intended use.
During conventional use, for navigation and preventing collisions while on the move, is there an upper limit, be it in terms of size, mass or speed to what the main deflectors can protect the ship from? Given that ship-to-ship collisions have been shown throughout the series (even if one ship was relatively undamaged, I would assume they don't switch off the deflector at any point), I doubt it could stop a Galaxy-class ship from accidentally crashing into a parked shuttlecraft, but are there any examples throughout the series of the main deflector sparing the ship from collision with anything bigger than dust or small debris fields?

A: There's no upper limit to the size of object the ship can move, but this is subject to the normal restriction that apply when applying force to large objects; the bigger they are, the harder it is to get them to move.
The TNG Technical Manual presents us with a wealth of information about the deflector system. In essence it consists of two main systems; a series of nested static fields that deflect interstellar dust and hydrogen and a secondary deflector/tractor-beam capable of moving larger objects out of the ship's path.

Although the density of the interstellar medium is extremely low,
significant hazards to navigation exist, especially for a starship
traveling at relativistic or warp velocities. Among these are
micrometeoroid particulates, as well as the much rarer (but more
hazardous) larger objects such as asteroids. Even the extremely
tenuous stray hydrogen atoms of the interstellar medium itself can be
a dangerous source of friction at sufficient velocities.
...
The navigational deflector, also controlled by the subspace field coils, is a powerful tractor/deflector that sweeps thousands of kilometers ahead of the ship, pushing aside larger objects that may present a collision hazard.

Although the active scanners are generally used to move the ship out of the path of very large objects, the deflectors are approximately twenty-four times as powerful as the ship's primary tractor beam, albeit subject to the same inverse square law degradation of their effect at distance.
(compare)

The heart of the navigational deflector system is three redundant high
power graviton polarity source generators located on Deck 34. Each of
these generators consists of a cluster of six 128 MW graviton polarity
sources feeding a pair of 550 millicochrane subspace field distortion
amplifiers. The flux energy output of these generators is directed and
focused by a series of powerful subspace field coils.

[vs.]

The main tractor beam emitters are built around two variable phase 16
MW graviton polarity sources, each feeding two 450 millicochrane
subspace field amplifiers. Phase accuracy is within 2.7 arc-seconds
per millisecond, necessary for precise interference pattern control.

Assuming these calculations apply equally, the ship can deflect moderate-sized objects (in the range of tens of kilogrammes) sufficiently to make it worthwhile before the ship gets there. Anything larger wouldn't have moved far enough out of the way to bother and would be avoided through course-correction but there's nothing that stops the Enterprise from trying to deflect a planet, it just wouldn't move very far. Note also that unless you can entirely envelope the object, you also risk it being torn apart


text:
Q: Java parse Object I hava a javascript object that im passing back to java via ajax:
var jsonData = {
        "testJson" : "abc",
        "userId" : "123"
};

When I println the map it looks like:
key: jsondata value:[object Object]

How can I properly parse the object?

A: You can use GSON in java:
class MyObject() {
  String testJson;
  String userId;

  public void setTestJson(String testJson) {
    this.testJson=testJson;
  }
  public String getTestJson() {
    return testJson;
  }
  ... Same for userId
}

And then create a GSON object:

class SomeClass {
  public void parseMyJson(String json) {
    Gson gson=new Gson();
    MyObject mo=gson.fromJson(json,MyObject.class);
  }
}

In which mo now contains you json object with just the use of getters and setters

A: I hope, this can help you:
int userId = object.getInt("userId");
https://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html

A: As posted the code defines a javascript object called jsonData. This can be converted into a string ( using JSON.stringify ) before passing back to the server:
var jsonData = {
    "testJson" : "abc",
    "userId" : "123"
};
var jsonString = JSON.stringify( jasonData);

or alternatively in trivial cases by defining the JSON string directly:
var jsonString = `{"testJson" : "abc",  "userId" : "123" }';


text:
Q: Char* vs String Speed in C++ I have a C++ program that will read in data from a binary file and originally I stored data in std::vector<char*> data. I have changed my code so that I am now using strings instead of char*, so that std::vector<std::string> data. Some changes I had to make was to change from strcmp to compare for example.
However I have seen my execution time dramatically increase. For a sample file, when I used char* it took 0.38s and after the conversion to string it took 1.72s on my Linux machine. I observed a similar problem on my Windows machine with execution time increasing from 0.59s to 1.05s.
I believe this function is causing the slow down. It is part of the converter class, note private variables designated with_ at the end of variable name. I clearly am having memory problems here and stuck in between C and C++ code. I want this to be C++ code, so I updated the code at the bottom.
I access ids_ and names_ many times in another function too, so access speed is very important. Through the use of creating a map instead of two separate vectors, I have been able to achieve faster speeds with more stable C++ code. Thanks to everyone!
Example NewList.Txt
2515    ABC 23.5    32  -99 1875.7  1
1676    XYZ 12.5    31  -97 530.82  2
279  FOO 45.5    31  -96  530.8  3

OLD Code:
void converter::updateNewList(){
    FILE* NewList;
    char lineBuffer[100];
    char* id = 0;
    char* name = 0;

    int l = 0;
    int n;

    NewList = fopen("NewList.txt","r");
    if (NewList == NULL){
        std::cerr << "Error in reading NewList.txt\n";
        exit(EXIT_FAILURE);
    }

    while(!feof(NewList)){
        fgets (lineBuffer , 100 , NewList); // Read line
        l = 0;
        while (!isspace(lineBuffer[l])){
            l = l + 1;
        }

        id = new char[l];
        switch (l){
            case 1:
                n = sprintf (id, "%c", lineBuffer[0]);
                break;
            case 2:
                n = sprintf (id, "%c%c", lineBuffer[0], lineBuffer[1]);
                break;
            case 3:
                n = sprintf (id, "%c%c%c", lineBuffer[0], lineBuffer[1], lineBuffer[2]);
                break;
            case 4:
                n = sprintf (id, "%c%c%c%c", lineBuffer[0], lineBuffer[1], lineBuffer[2],lineBuffer[3]);
                break;
            default:
                n = -1;
                break;
        }
        if (n < 0){
            std::cerr << "Error in processing ids from NewList.txt\n";
            exit(EXIT_FAILURE);
        }

        l = l + 1;
        int s = l;
        while (!isspace(lineBuffer[l])){
            l = l + 1;
        }
        name = new char[l-s];
        switch (l-s){
            case 2:
                n = sprintf (name, "%c%c", lineBuffer[s+0], lineBuffer[s+1]);
                break;
            case 3:
                n = sprintf (name, "%c%c%c", lineBuffer[s+0], lineBuffer[s+1], lineBuffer[s+2]);
                break;
            case 4:
                n = sprintf (name, "%c%c%c%c", lineBuffer[s+0], lineBuffer[s+1], lineBuffer[s+2],lineBuffer[s+3]);
                break;
            default:
                n = -1;
                break;
        }
        if (n < 0){
            std::cerr << "Error in processing short name from NewList.txt\n";
            exit(EXIT_FAILURE);
        }

        ids_.push_back ( std::string(id) );
        names_.push_back(std::string(name));
    }

    bool isFound = false;
    for (unsigned int i = 0; i < siteNames_.size(); i ++) {
        isFound = false;
        for (unsigned int j = 0; j < names_.size(); j ++) {
            if (siteNames_[i].compare(names_[j]) == 0){
                isFound = true;
            }
        }
    }

    fclose(NewList);
    delete [] id;
    delete [] name;
}

C++ CODE
void converter::updateNewList(){
    std::ifstream NewList ("NewList.txt");

    while(NewList.good()){
        unsigned int id (0);
        std::string name;

        // get the ID and name
        NewList >> id >> name;

        // ignore the rest of the line
        NewList.ignore( std::numeric_limits<std::streamsize>::max(), '\n');

        info_.insert(std::pair<std::string, unsigned int>(name,id));

    }

    NewList.close();
}

UPDATE: Follow up question: Bottleneck from comparing strings and thanks for the very useful help! I will not be making these mistakes in the future!

A: My guess it that it should be tied to the vector<string>'s performance
About the vector
A std::vector works with an internal contiguous array, meaning that once the array is full, it needs to create another, larger array, and copy the strings one by one, which means a copy-construction and a destruction of string which had the same contents, which is counter-productive...
To confirm this easily, then use a std::vector<std::string *> and see if there is a difference in performance.
If this is the case, they you can do one of those four things:

*

*if you know (or have a good idea) of the final size of the vector, use its method reserve() to reserve enough space in the internal array, to avoid useless reallocations.

*use a std::deque, which works almost like a vector

*use a std::list (which doesn't give you random access to its items)

*use the std::vector<char *>

About the string
Note: I'm assuming that your strings\char * are created once, and not modified (through a realloc, an append, etc.).
If the ideas above are not enough, then...
The allocation of the string object's internal buffer is similar to a malloc of a char *, so you should see little or no differences between the two.
Now, if your char * are in truth char[SOME_CONSTANT_SIZE], then you avoid the malloc (and thus, will go faster than a std::string).
Edit
After reading the updated code, I see the following problems.

*

*if ids_ and names_ are vectors, and if you have the slightest idea of the number of lines, then you should use reserve() on ids_ and and names_

*consider making ids_ and names_ deque, or lists.

*faaNames_ should be a std::map, or even a std::unordered_map (or whatever hash_map you have on your compiler). Your search currently is two for loops, which is quite costly and inneficient.

*Consider comparing the length of the strings before comparing its contents. In C++, the length of a string (i.e. std::string::length()) is a zero cost operation)

*Now, I don't know what you're doing with the isFound variable, but if you need to find only ONE true equality, then I guess you should work on the algorithm (I don't know if there is already one, see http://www.cplusplus.com/reference/algorithm/), but I believe this search could be made a lot more efficient just by thinking on it.

Other comments:

*

*Forget the use of int for sizes and lengths in STL. At very least, use size_t. In 64-bit, size_t will become 64-bit, while int will remain 32-bits, so your code is not 64-bit ready (in the other hand, I see few cases of incoming 8 Go strings... but still, better be correct...)

Edit 2
The two (so called C and C++) codes are different. The "C code" expects ids and names of length lesser than 5, or the program exists with an error. The "C++ code" has no such  limitation. Still, this limitation is ground for massive optimization, if you confirm names and ids are always less then 5 characters.

A: Resize vector to large enough size before you start populating it. Or, use pointers to strings instead of strings.
The thing is that the strings are being copied each time the vector is being auto-resized. For small objects such as pointers this cost nearly nothing, but for strings the whole string is copied in full.
And id and name should be string instead of char*, and be initialized like this (assuming that you still use string instead of string*):
id = string(lineBuffer, lineBuffer + l);
...
name = string(lineBuffer + s, lineBuffer + s + l);
...
ids_.push_back(id);
names_.push_back(name);

A: Before fixing something make sure that it is bottleneck. Otherwise you are wasting your time. Plus this sort of optimization is microoptimization. If you are doing microoptimization in C++ then consider using bare C.

A: Except for std::string, this is a C program.
Try using fstream, and use the profiler to detect the bottle neck.

A: You can try to reserve a number of vector values in order to reduce the number of allocations (which are costly), as said Dialecticus (probably from the ancient Roma?).
But there is something that may deserve some observation: how do you store the strings from the file, do you perform concatenations etc...
In C, strings (which do not exist per say - they don't have a container from a library like the STL) need more work to deal with, but at least we know what happens clearly when dealing with them. In the STL, each convenient operation (meaning requiring less work from the programmer) may actually require a lot of operations behind the scene, within the string class, depending on how you use it.
So, while the allocations / freeings are a costly process, the rest of the logic, especially the strings process, may / should probably be looked at as well.

A: I believe the main issue here is that your string version is copying things twice -- first into dynamically allocated char[] called name and id, and then into std::strings, while your vector<char *> version probably does not do that.  To make the string version faster, you need to read directly into the strings and get rid of all the redundant copies

A: streams take care of a lot of the heavy lifting for you.  Stop doing it all yourself, and let the library help you:
void converter::updateNewList(){
    std::ifstream NewList ("NewList.txt");

    while(NewList.good()){
        int id (0);
        std::string name;

        // get the ID and name
        NewList >> id >> name;

        // ignore the rest of the line
        NewList.ignore( numeric_limits<streamsize>::max(), '\n');

        ids_.push_back (id);
        names_.push_back(name);
    }

    NewList.close();
}

There's no need to do the whitespace-tokenizing manually.
Also, you may find this site a helpful reference:
http://www.cplusplus.com/reference/iostream/ifstream/

A: You can use a profiler to find out where your code consumes most time. If you are for example using gcc, you can compile your program with -pg. When you run it, it saves profiling results in a file. You can the run gprof on the binary to get human readable results. Once you know where most time is consumed you can post that piece of code for further questions.


text:
Q: ffmpeg - escaping single quotes doesn't work I've written a small python script for mass converting audio files. It uses ffmpeg. The problem is it doesn't work for files with single quotes in their filenames.
script:

import os
import subprocess
import sys
from multiprocessing.pool import ThreadPool as Pool

source_dir="/home/kris/Music/test"
output_dir="/home/kris/Music/test_opus"

def worker(file):

    try:
        dirname=os.path.dirname(file)
        file=file.replace("'","\\\\'")
        filename=file.split('.flac')[0]

        input_file=f"'{source_dir}/{file}'"
        output_file=f"'{output_dir}/{filename}.opus'"
        cmd="ffmpeg -n -i "+input_file+" -c:a libopus -b:a 320k "+output_file
        print(cmd)
        result = subprocess.call(cmd,stdout=subprocess.PIPE,shell=True)
    except:
        print('item error')

def start():
    threads=os.cpu_count()
    pool = Pool(threads)
    files=os.listdir(source_dir)
    for item in files:
        pool.apply_async(worker, (item,))

    pool.close()
    pool.join()

start()

Testing:

*

*Filename: I'm a file.flac

*When escaping single quote ' with double backslashes \\ - file=file.replace("'","\\\\'") the cmd for ffmpeg is:
ffmpeg -n -i '/home/kris/Music/test/I\\'m a file.flac' -c:a libopus -b:a 320k '/home/kris/Music/test_opus/I\\'m a file.opus'

ffmpeg returns an error: /home/kris/Music/test/I\\m: No such file or directory

*When escaping single quote ' with a single backslash \ - file=file.replace("'","\\'") the cmd for ffmpeg is:

ffmpeg -n -i '/home/kris/Music/test/I\'m a file.flac' -c:a libopus -b:a 320k '/home/kris/Music/test_opus/I\'m a file.opus'

I got an error:
/bin/sh: 1: Syntax error: Unterminated quoted string

According to ffmpeg docs: https://ffmpeg.org/ffmpeg-utils.html#toc-Examples escaping with single backslash should work.


text:
Q: create functional object with method and object I want to create a functional object which could be called later (callback) build from
an object and a member function of that object.
class A
{
public:

void AnyMethod() { cout << "Hello" << endl; }
};

int main()
{
    A a;
    function<???>f1(&A::AnyFunc, &a); // ?????

    ...
    f1();
}

I am a bit confused, because creating a thread is very simple:
thread t1 ( &A::AnyFunc, &a);
...
t1.join();

It is simple if I use it with a lamba function, but this is a bit overhead which I want to avoid.
function<void(void)> f2( [&a](){ a.AnyFunc(); } ); // works fine

Maybe there is a better way to get a callable object?

A: std::function<void()> f1 = std::bind(&A::AnyMethod, &a);


text:
Q: Basics: Importing a class in groovy I'm beating my head over this but I can't seem to figure out what I'm doing wrong.
I have a folder "myproject" and two files in it - "MyScript.groovy" and "MyClass.groovy".
MyClass.groovy
package myproject

public class MyClass {
    void printHello() {
        println("hello")
    }
}

MyScript.groovy
package myproject
import myproject.MyClass

def myObject = new MyClass()
myObject.printHello()

When I try to run MyScript.groovy, I get the following error:
[Running] groovy "c:\Users\myUser\...\myproject\MyScript.groovy"
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
C:\Users\myUser\...\myproject\MyScript.groovy: 2: unable to resolve class myproject.MyClass
 @ line 2, column 1.
   import myproject.MyClass
   ^

1 error

I don't think, this is relevant, but I'm running it via the Code Runner Extension in Visual Studio.
Any help would be appreciated. :)

A: Without further configuration Groovy assumes the current working
directory to be (part of the) classpath.  So your setup is basically
correct; assuming it is like this:
# find .
.
./myproject
./myproject/MyClass.groovy
./myproject/MyScript.groovy

So running this where package structure and directory structure match,
it works:
# groovy myproject/MyScript.groovy
hello

So your most likely problem here is, that either your IDE is not setting
the cwd correctly or you have configured .../myproject as the project
root.

A: I had this issue when using classes from a separate project directory.
This worked for me:
In the settings for code runner (file > pereferences > settings > search for "runner" )
I added/updated this in the executorMap setting:
"code-runner.executorMap": {
    "groovy": "groovy -cp \".;src;vars;C:\\GitRepositories\\my-other-library\\src\"",
}

When you then run the code you'll see the command updated with the classpath shown.
I know this question is old, but I couldn't find the answer and thought this may help others


text:
Q: Passar Controls para uma função Eu tenho uma interface em Visual C#. Nessa interface tenho uma Classe chamada T50 que contem todas as variável que preciso.
Já implementei um botão em que salvo o objeto criado pela classe T50. Consigo salvar e ler esse objeto (Usando serialize).
Só que quando releio um objeto salvo eu preciso preencher a parte da interface que o usuário já tinha preenchido.
Dentro do minha classe T50 existe uma função para fazer isso.
private void button_t50_carregar_Click(object sender, EventArgs e)
    {
        // Código de ler o dado

        // Usa uma função para preencher os dados
        T50_Data.PreencheInterface(T50_Data);
    }

Só que dentro dessa função eu preciso acessar todos os Controls da minha Form para ajustá-los(Button, Textbox, DataGridViwe....).
Sei como recebe-los individualmente, por exemplo
public void PreencheInterface (T50 T50Data, TextBox text)
{
}

Existe uma forma de eu passar todos eles ao mesmo tempo?

A: Você poderia fazer assim:
Passar seu Form para o método:
public void Metodo(NomeDoForm form)
{
    form.Controls["btnEsc"].Text = "Escape";
}

E dentro do método chamar cada componente do form usando o form.Controls["NomeComponente"].
E depois só chamar o método no Form passando o this, que seria o próprio formulário.

A: A função PreencheInterface poderia receber o objeto do formulário (https://msdn.microsoft.com/pt-br/library/system.windows.forms.form(v=vs.110).aspx) e iterar sobre a coleção de controles dentro do formulário (https://msdn.microsoft.com/pt-br/library/4z8d1tx5(v=vs.110).aspx).
private void button_t50_carregar_Click(object sender, EventArgs e)
    {
        // Obtém o formulário do botão clicado
        // (supondo que o form é o controle pai imediato do botão
        Form formulario = (Form)((sender as Button).Parent)

        // Código de ler o dado

        // Usa uma função para preencher os dados
        T50_Data.PreencheInterface(formulario);
    }

A: consegui resolver o problema reunindo as informações de todos. Obrigado ao @MeuChapeu e @rocmartins. Vou deixar a minha solução aqui para futuras dúvidas.
O problema era que a minha Form1 é composta por uma TapPage, dentro de outra TabPage, e alguns botões ainda estão dentro de um GroupBox. A partir desse botão para voltar até a Form1, tive que fazer:
Form formulario = (Form)((((((((((sender as Button).Parent) as TabPage).Parent) as TabControl).Parent) as TabPage).Parent) as TabControl).Parent);

Assim posso passar esse "formulario" para meu método. E para acessar um botão que esteja dentro de um GroupBox que esteja nessa Tabpage:
form.Controls["TabControl1"].Controls["TabPage1"].Controls["TabControl2"].Controls["groupBox1"].Controls["button"].Text = "Novo Texto Botão".

Obrigado pela ajuda!


text:
Q: Custom HTML for Breadcrumb What is the best way to create custom HTML for a breadcrumb (like SiteMapPath)?

A: You need to have a custom Control to emit the html the way you want and add it in the PageLyout

A: While Googleing I found this:
http://johanleino.wordpress.com/2009/01/11/hiding-the-rootnode-in-a-breadcrumb-control-sitemap-path/
And by using <NodeTemplate>, <RootNodeTempalte> and CssClass I was able to solve my problems.
In <RootNodeTemplate> I could even add <img /> to my HTML


text:
Q: Pandas: plot Series on a new figure by default Is there a way to force the .plot method of a pandas Series to generate a new figure, instead of trying to plot on the currently open figure?
I currently create a new figure using plt.figure() or using plt.subplots and passing the axis, but for quick plots from the interactive console it would be great to simply use the .plot method without extra lines of code.
I wonder if there are configs in pandas that can be changed to achieve this.

A: I'm not aware of a config. Defining a wrapper around .plot() should do the trick, as suggested by Stop harming Monica.
def plot(s, **kwargs):
    s.plot(**kwargs)
    plt.show();


text:
Q: Django 1.7: How to define utf8 numbers in django? I have an IntegerField in my Django model as follows:
class Item(models.Model):
    related_room = models.ForeignKey(Room)
    item_name = models.CharField(max_length=50)
    item_price = models.IntegerField()

the item_price is an integer value. When I use Django admin to create a new Item it gives me validation error for the item price because it has the value ۱۵۰۰

But when I change the value to 1500(not its unicode version) it works properly. All of my tables character-set and my DB character-set are UTF-8. Can anyone help me out?
Thanks.

A: There is a bug in the file django/forms/fields.py line 261. The line should be
        value = int(smart_text(value))


text:
Q: First Common Ancestor of a Binary Tree If I have a binary search tree like this then what will be lowest common ancestor of nodes 6 and 1?

A: According to the Wikipedia definition of the Lowest common ancestor I correct myself:

The lowest common ancestor (LCA) is a concept in graph theory and
  computer science. Let T be a rooted tree with n nodes. The lowest
  common ancestor is defined between two nodes v and w as the lowest
  node in T that has both v and w as descendants (where we allow a node
  to be a descendant of itself).

So yes going by this definition the correct answer would be 6. If this is an interview question would be good to clarify in advance with the interviewer.


text:
Q: How to do load testing on long polling? I'm trying to figure out how to do load testing on a long polling or web socket type of architecture.
I need to setup multiple clients which subscribe to channels on one side and wait for responses. The load testing should measure the time it took for messages from the publishing server to reach the clients.
Any ideas?

A: As said here,

SignalR uses a particular protocol to communicate so it's best that
  you use our tool to generate load for testing your server(s).

So, SignalR comes with Crank. Crank can only connect to PersistentConnection based apps and not Hub based app.
This another answer could help you for Hub based app.

A: You can use crank, as referred above. One of the parameters is Transport, so you can specify only LongPolling:
crank.exe /Url:http://someUri /Transport:LongPolling

A: Use JMeter (https://jmeter.apache.org/) and flood with http connections with transport-type as header.


text:
Q: Regex: Reoccuring pattern EDIT: I am using C#, I have read .NET-Regex can do this
I have a pattern like this:
name;a1;a2;a3
name;a1

It contains a name in the beginning and then a series of segments, but I they can have any number of occurrence.
I tried to solve this with
([^;]+)(?:;([stacp]\d+))+\n

but that only gets me the name and the last occurrence (but correctly matches the whole string), in the first example only "name" and "a3". What am I doing wrong?


text:
Q: Defining a property of a JavaScript object in terms of another I want to define one property of an object in terms of another, like this:
let obj = {
  prop1: some value,
  prop2: some expression in terms of prop1 (e.g. prop1 * 2)
}

So whenever I refer to prop2 in my code, that expression that I initialised it as will be evaluated. Is this possible?

A: You can do that with an accessor property with a getter function:

let obj = {
  prop1: 21,
  get prop2() {
    return this.prop1 * 2;
  }
};

console.log(obj.prop1); // 21
console.log(obj.prop2); // 42

If you like, you can also define a setter for it:

let obj = {
  prop1: 21,
  get prop2() {
    return this.prop1 * 2;
  },
  set prop2(value) {
    this.prop1 = value / 2;
  }
};

console.log(obj.prop1); // 21
console.log(obj.prop2); // 42

obj.prop2 = 8;
console.log(obj.prop1); // 4
console.log(obj.prop2); // 8

More on MDN: get, set.
Finally, you can do it in class definitions, too:
class Example {
    constructor(prop1) {
        this.prop1 = prop1;
    }
    get prop2() {
      return this.prop1 * 2;
    }
    set prop2(value) {
      this.prop1 = value / 2;
    }
}

A: You can make prop2 be a function that fetches the value of prop1, performs some logic and returns the result. This way (if you want) you can even have the output of prop2 to be up-to-date with the changes in prop1.
Example: (run it below)

let obj = {
  prop1: 45,
  prop2 : function() {
    return this.prop1 * 3;
  }
};

console.log( obj.prop2() );


text:
Q: How to convert strings to abbreviations I want to do something like this if i have a textual transcript of a speech recognition system i want to convert this text like this - Triple A converts in AAA. Can someone help ?

A: Repeating 3 times
If what you mean is that the string "Triple" is to be treated as a keyword whose following string's value is to be replaced by itself tripled, then the following can accomplish what you want:
def tripler(s):
    triples = 0
    s = [ss.strip() for ss in s.split()][::-1]

    for i in range(len(s) - 1):
        if s[i - triples + 1] == 'Triple':
            s[i - triples] *= 3

            del s[i - triples + 1]
            triples += 1

    return ' '.join(s[::-1])

Dynamic repetitions
To repeat the argument any number of times, a dictionary with different keywords and corresponding values could be used:
repeat_keywords = {'Double':2, 'Triple':3}

def repeater(s):
    repeats = 0
    s = [ss.strip() for ss in s.split()][::-1]

    for i in range(len(s) - 1):
        if s[i - repeats + 1] in repeat_keywords:
            s[i - repeats] *= repeat_keywords[s[i - repeats + 1]]

            del s[i - repeats + 1]
            repeats += 1

    return ' '.join(s[::-1])

Inputs:
1. Double x Triple y
2. Double Triple y
3. Triple x Double Double y Triple z Double
Outputs:
1. xx yyy
2. yyyyyy
3. xxx yyyy zzz Double

Note: this solution also has the effect of multiplying the value of repeated keywords. That is due to parsing the string in reverse.


text:
Q: How can I fit bounds on a geojson I load with Ajax? I'm loading a route from a geojson file with Leaflet-ajax, and I can't figure out how to set the bounds of my map to the route.
This code gives me an error of Uncaught Error: Bounds are not valid.:
L.tileLayer(' ... ', { ... }).addTo(map_of_route);
var geojsonLayer = new L.GeoJSON.AJAX("my_json.json");
geojsonLayer.addTo(map_of_route);
map_of_route.fitBounds(geojsonLayer.getBounds());

(extraneous map layer stuff removed for readability)


text:
Q: Spring-Security-UI This is the first time i have attempted to use spring security UI in my Grails application.
I am currently using Spring Security Core and it works fine but I like the ideas of the UI plugin.
I have read through the documentation and I cannot see any single commant to run to set everything up with default values. Keeping in mind I have Spring Security Core already running.
Can anyone please help me out.
Thanks

A: You just need to override your auth view using
grails s2ui-override auth


text:
Q: Need to change name of a key in a script that returns a sorted List I have some code that loops thru a flat json doc and creates a hierarchal of the items based on level and position. It all works as expected but i have the need to change the child elements name from child to items. And thats where my problem starts. There is 2 porions in code where i set the child:
   newparent = {
          ...oldparent,
          child: mItems
        };
      } else {
        newparent = {
          ...oldparent,
          child: [child]

So I tried to change that to items but that does not work, when i change it, I get the items key on the initial items but not for any additional items under that parent.
Here is also link to a working sample Replit Testbed
My Sample Output
[
  {
    enabled: true,
    guid: 'F56AAC06-D2EB-4E1C-B84D-25F72973312E',
    level: 0,
    name: 'Farms',
    parent: 'F56AAC06-D2EB-4E1C-B84D-25F72973312E',
    position: 0,
    umid: 'F56AAC06-D2EB-4E1C-B84D-25F72973312E',
    child: [
      {
        enabled: true,
        guid: '144C0989-9938-4AEC-8487-094C23A5F150',
        level: 1,
        name: 'New Farm List',
        parent: 'F56AAC06-D2EB-4E1C-B84D-25F72973312E',
        position: 0,
        umid: '144C0989-9938-4AEC-8487-094C23A5F150'
      },
      {
        enabled: true,
        guid: '8FBA7B0B-566E-47CD-885B-1C08B57F34F6',
        level: 1,
        name: 'Farm Lists',
        parent: 'F56AAC06-D2EB-4E1C-B84D-25F72973312E',
        position: 1,
        umid: '8FBA7B0B-566E-47CD-885B-1C08B57F34F6'
      },
      {
        enabled: true,
        guid: 'FCD36DBD-0639-4856-A609-549BB10BEC1A',
        level: 1,
        name: 'Farm Upload',
        parent: 'F56AAC06-D2EB-4E1C-B84D-25F72973312E',
        position: 4,
        umid: 'FCD36DBD-0639-4856-A609-549BB10BEC1A'
      },
      {
        enabled: true,
        guid: '4264DA98-1295-4A65-97C6-313485744B4D',
        level: 1,
        name: 'Campaign',
        parent: 'F56AAC06-D2EB-4E1C-B84D-25F72973312E',
        position: 4,
        umid: '4264DA98-1295-4A65-97C6-313485744B4D',
        child: [
          {
            enabled: true,
            guid: '9CBDC6BB-5B3D-4F53-B846-AFE55F34C1E9',
            level: 2,
            name: 'New Campaign',
            parent: '4264DA98-1295-4A65-97C6-313485744B4D',
            position: 5,
            umid: '9CBDC6BB-5B3D-4F53-B846-AFE55F34C1E9'
          },
          {
            enabled: true,
            guid: '281490B5-C67D-4238-9D52-DE1DFA373418',
            level: 2,
            name: 'Campaign List',
            parent: '4264DA98-1295-4A65-97C6-313485744B4D',
            position: 6,
            umid: '281490B5-C67D-4238-9D52-DE1DFA373418'
          }
        ]
      }
    ]
  }
]

Here is my Code
function menu_sorted(input) {

  let max_level = 0;
  var sorted_by_level = {};

  input.forEach(i => {
    if (sorted_by_level.hasOwnProperty("level_" + i.level.toString())) {
      sorted_by_level["level_" + i.level.toString()].push(i);
    } else {
      sorted_by_level["level_" + i.level.toString()] = [i];
      if (i.level > max_level) {
        max_level = i.level;
      }
    }
  });

  for (level = max_level; level > 0; level--) {
    sorted_by_level["level_" + level.toString()].forEach(child => {
      const oldparent = sorted_by_level[
        "level_" + (level - 1).toString()
      ].filter(p => p.guid === child.parent)[0];
      const parentIndex = sorted_by_level[
        "level_" + (level - 1).toString()
      ].findIndex(p => p.guid === child.parent);
      let newparent;

     // delete child.guid;
     // delete child.parent;
      if (oldparent.hasOwnProperty("child") && oldparent.child) {
        var mItems = [...oldparent.child, child];
        mItems.sort((a, b) => (a.position > b.position) ? 1 : -1);
        newparent = {
          ...oldparent,
          child: mItems
        };
      } else {
        newparent = {
          ...oldparent,
          child: [child]
        };
      }
      sorted_by_level["level_" + (level - 1).toString()][
        parentIndex
      ] = newparent;
    });
  }
  sorted_by_level.level_0.sort((a, b) => (a.position > b.position) ? 1 : -1);
  return sorted_by_level.level_0
}

console.log(util.inspect(menu_sorted(mydata.nofilter),false,null,true))

A: See my fork of your Replit:
https://replit.com/join/wleqdijkot-mattsenne
There are additional places you need to change "child" to "items", including lines 34, 35:
if (oldparent.hasOwnProperty("items") && oldparent.items) {
   var mItems = [...oldparent.items, child];

Also the 2 changes you noted above.  Note that we don't change the local 'child' variable, but every reference to 'items' being a property needs to accounted for as well.


text:
Q: Complex aggregation with select I have table in DB like this (ID column is not a unique UUID, just some object ID, primary key still exists, but removed for example)

ID
Option
Value
Number of searches
Search date

1
abc
a
1
2021-01-01

1
abc
b
2
2021-01-01

1
abc
a
3
2021-01-02

1
abc
b
4
2021-01-02

1
def
a
5
2021-01-01

1
def
b
6
2021-01-01

1
def
a
7
2021-01-02

1
def
b
8
2021-01-02

2
...
...
...
...

...
...
...
...
...

N
xyz
xyz
M
any date

I want to get a some kind of statistic report like

ID
Total searches
Option
Total number of option searches
Value
Total value searches

1
36
abc
10
a
4

b
6

def
26
a
12

b
14

Is it possible in some way? UNION isn't working were, clause GROUP BY also have no idea how can solve that
I can do it easily in kotlin, just request everything and aggregate to classes like that
    data class SearchAggregate (
        val id: String,
        val options: List<Option>,
        val values: List<Value>
    )

    data class Option (
        val name: String,
        val totalSearches: Long
    )

    data class Value(
        val name: String,
        val totalSearches: Long
    )

and export to file but I have to request data by SQL

A: You can use the COUNT() window function in a subquery to preprocess the data. For example:
select
  id,
  max(total_searches) as total_searches,
  option,
  max(total_options) as total_options,
  value,
  max(total_values) as total_values
from (
  select
    id,
    count(*) over(partition by id) as total_searches,
    option,
    count(*) over(partition by id, option) as total_options,
    value,
    count(*) over(partition by id, option, value) as total_values
  from t
) x
group by id, option, value

See running example at DB Fiddle #1.
Or you can use a shorter query, as in:
select
  id,
  sum(cnt) over(partition by id) as total_searches,
  option,
  sum(cnt) over(partition by id, option) as total_searches,
  value,
  cnt
from (
  select id, option, value, count(*) as cnt from t group by id, option, value
) x

See running example at DB Fiddle #2.

A: The first option is to use ROLLUP, as that is the intended SQL pattern. It doesn't give you the results in the format you asked for. That's a reflection on the format you asked for not being normalised.
SELECT
  id,
  option,
  value,
  SUM(`Number of searches`)   AS total_searches
FROM
  your_table
GROUP BY
  ROLLUP(
    id,
    option,
    value
  )

It's concise, standard practice, SQL Friendly, etc, etc.
Thinking in terms of these normalised patterns will make your use of SQL much more effective.
That said, you CAN use SQL to aggregate and restructure the results. You get the structure you want, but with more code and increased maintenance, lower flexibility, etc.
SELECT
  id,
  SUM(SUM(`Number of searches`)) OVER (PARTITION BY id)   as total_by_id,
  option,
  SUM(SUM(`Number of searches`)) OVER (PARTITION BY id, option)   as total_by_id_option,
  value,
  SUM(`Number of searches`)   AS total_by_id_option_value
FROM
  your_table
GROUP BY
  id,
  option,
  value

That doesn't leave blanks where you have them, but that's because to do so is a SQL Anti-Pattern, and should be handled in your presentation layer, not in the database.
Oh, and please don't use column names with spaces; stick to alphanumeric characters with underscores.
Demo : https://www.db-fiddle.com/f/fX3tNL82gqgVCRoa3v6snP/5


text:
Q: Auto-reload TWO pages alternatingly How to implement the following in JavaScript or so?
 - Wait 120 seconds
 - Open http://192.168.1.1/internet-disconnect (in an iframe or so, doesn't matter)
 - Wait 3 seconds
 - Open http://192.168.1.1/internet-connect
 - Repeat

Here's how I was trying:
<meta http-equiv="refresh" content="30">
<iframe id="iframe_id" src="http://heise.de"></iframe>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $('iframe#iframe_id').attr('src', 'http://192.168.1.1/internet-disconnect');
    setTimeout(function(){
        $('iframe#iframe_id').attr('src', 'http://192.168.1.1/internet-connect');
        }, 3000);
    });
</script>

But it's messy and doesn't work the way it should.
Thanks!

A: Use setInterval() instead if setTimeout()
Try this
<script>
$(document).ready(function() {

   var flag = 0;
   $(document).ready(function() {

       setInterval(function(){
           if(flag == 0){
               $('iframe#iframe_id').attr('src', 'http://192.168.1.1/internet-disconnect');
               flag=1;
           }else{
               $('iframe#iframe_id').attr('src', 'http://192.168.1.1/internet-connect');
               flag=0;
           }
       }, 3000);

});
</script>

A: window.onload = function(){
    var url1 = 'http://192.168.1.1/internet-disconnect';
    var url2 = 'http://192.168.1.1/internet-connect';
    var delay1 = 120000;
    var delay2 = 3000;
    var iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    document.body.appendChild(iframe);

    setInterval(function(){
        setTimeout(function(){iframe.src= url1;},delay1);
        setTimeout(function(){iframe.src= url2;},delay2);
    },delay1+delay2)
}


text:
Q: Piping Concurrency and Files I have a C program which takes a file as an argument, cleans up the file and writes the cleansed data to a new temp file. It then accepts some stdin, cleans it up and sends it stdout.
I have a second file which performs operations on this temp file and on the stdin again.
./file_cleanse <file1.txt> | ./file_operation <temp.txt>

I either get no or nonsensical stdout from the ./file_operation and I believe this is because it is reading from a file that's still being written/doesn't exist at this point.
Is there any way to make ./file_operation wait until ./file_cleanse has returned a value in bash?

A: What about:
./file_cleanse <file1.txt> > /tmp/temporaryFile
./file_operation <temp.txt> < /tmp/temporaryFile

A: As I understand the question, file_operation needs to read the standard output of file_cleanse after processing the temporary file, but it should not process the temporary file until file_cleanse has written some data to its standard output (the standard input of file_operation).
If that's correct, then a simple synchronization is for file_operation to read (a byte or any convenient larger amount of data) from its standard input.  When this is successful, the file_cleanse must have finished with the temporary file; file_operation can therefore process the temporary file, and then read the rest of its standard input and process that appropriately.


text:
Q: How to create a file in java that works when compiled into a jar? I have a code that creates a file that work in netbeans but not when compiled in Jar I have a java code that automatically create a file for the user after login. It works properly when I run it in netbeans/intellij. However when I compiled it into a jar file, the program works but the file is not created. Can someone please help me?
Here is my code:
private void createTxtFile(){
    String loc = new File("").getAbsolutePath();
    String dir = loc+"/src/lists/"+user+"-"+pass+".txt";
    try {
        File myObj = new File(dir);
        if (myObj.createNewFile()) {
            System.out.println("File created: " + myObj.getName());
        }
        else {
            JOptionPane.showMessageDialog(this, "User already have an existing list file.");
        }
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, "An error occured in creating file for your list.", "Error",JOptionPane.ERROR_MESSAGE);
    }
}


text:
Q: Cannot install gruntjs (always created nested folders) I had install node and npm in my ubuntu 12.04.
I am following this for installation that : https://gist.github.com/isaacs/579814 (used the top one)   worked successfully
and when I am install grunt in my terminal at home directory path :
npm install -g grunt-cli

and here the results  : http://pastebin.com/R3zP55Z2
at seen that had many created nested folder : "/home/antoni/[sudo] password for antoni:"
I didn't know where my faults.
can someone tell me.
thanks a million.

A: It looks like you don't have permissions to write to that directory. I would firstly check if you have permissions to write the directory:
ls -la /home/antoni/local

If you do have the right permission you should see something like drwxr-xr-x and your username. The key being the w character in the third column. If for some reason the directory doesn't have drwxr-xr-x then chmod it to add write permissions:
chmod -R 755 /home/antoni/local

Or if the current owner is wrong then try running:
chown -R $USER /home/antoni/local

You may need to use sudo for these. After that check you can write to it by running:
touch /home/antoni/local/test.txt

If that fails then there is still a problem with the permissions (perhaps previous commands failed). If that works and it still doesn't install then have a look at where npm is trying to write to:
npm bin -g
npm root -g

These 2 directories are where npm will install the components of grunt-cli. It's worth checking to make sure these 2 directories are writable by you to also.

A: solved.
I do like at this answer : npm global path prefix
I am wrong in my prefix npm.
before I set in home/ dir. that make npm created many nested folder. (I still dunno why ?)
and then, I fix that problem to do something like this in terminal :
sudo chown $USER:$USER /usr/local
npm config set prefix /usr/local

Horray !! :D


text:
Q: Haskell type signature for == and elem In GHCi, doing the following yield:
:t (==)

(==) :: Eq a => a -> a -> Bool

or
:t elem

elem :: (Eq a, Foldable t) => a -> t a -> Bool

I am confused with the arrow going from a to a, and then a to Bool.
Is it because == or elem is a curried function?
The type signature for elem is very similar to ==, except for the additional t.  What does t a in :t elem mean?

A: Yes, operators are curried.  Let's ignore the contexts for a second (the part of the type before =>).
(==) :: a -> a -> Bool

(->) associates to the right, so this means:
(==) :: a -> (a -> Bool)

That is, it's a function which, given an a, returns another function, which in turn takes an a and gives a Bool.  It returns the function which is only true when its argument is equal to the first a.
(We will set NoMonomorphismRestriction because otherwise it will just be extra confusing for no good reason)
ghci> :set -XNoMonomorphismRestriction
ghci> let f = (==) 1
ghci> f 1
True
ghci> f 2
False
-- or just
ghci> (==) 1 2
False

The part before the (=>) puts constraints on types. Eq a means that a must be a type that supports equality.
As for the t in elem, that might be a bit advanced for you to understand fully right now. I'll give you a little bit.  Because of the context
(Eq a, Foldable t) => ...

we know that t has to be Foldable.  Lists are foldable, and foldable doesn't mean much more than "has a toList method".  So you can read elem as:
elem :: (Eq a) => a -> [a] -> Bool

and in general, when you see a foldable type, just pretend it's a list.


text:
Q: What is the one thing I am going to forget on the math subject GRE tomorrow? As I finish up my final study session for the subject test tomorrow, I was wondering if anyone had some general advice/ often forgotten facts that might come in handy.

A: I hated myself for forgetting Sylow theorems (http://en.wikipedia.org/wiki/Sylow_theorems#Sylow_theorems). They would solve instantly one of the hard problems..

A: You forgot to register for the exam.
You will forget to bring adequate photo identification.
You will get the date and/or time wrong and miss the exam.
You will enter your name or SSN wrong on the form and will get no credit.
You will forget to sleep the night before, and to eat the morning of the exam.
You will certainly forget to bring water.


text:
Q: Wordpress woocommerce hooks and ACF in functions.php not working/printing I'm hoping someone can assist with my problem.
I have a WordPress site running WooCommerce and ACF (advanced custom fields).
I'm adding the following code to functions.php...
The add_action is the hook into WooCommerce and the rest is pulling data from ACF.
There's no errors but it's simply not printing the various images and URLs. It's just blank.
Am I missing anything obvious?
Here is the code in functions.php:
add_action('woocommerce_product_thumbnails', 'return_policy', 20);

function return_policy() {
// reverse lookup of packages

    $related_channels = get_posts(array(
        'post_type' => 'page',
        'meta_query' => array(
            array(
                'key' => 'select', // name of reverse acf custom field
                'value' => '"' . get_the_ID() . '"',
                'compare' => 'LIKE'
            )
        )
    ));

    if ($related_channels):
        foreach ($related_channels as $rchannels):
            ?>

                <a href="<?php the_permalink($rchannels->ID); ?>">
                    <img src="<?php echo get_the_post_thumbnail_url($rchannels->ID); ?>" alt="<?php echo $rchannels->post_title; ?>" title="<?php echo $rchannels->post_title; ?>" >
 <?php echo $rchannels->post_title; ?>

            <?php
        endforeach;
    endif;
}


text:
Q: Proof of $(a^2b+b^2c+c^2a)(ab^2+bc^2+ca^2)>\frac{(ab+bc+ca)^3}{3}$ For positive real numbers $a$, $b$ and $c$, how do we prove that:
$$(a^2b+b^2c+c^2a)(ab^2+bc^2+ca^2)>\frac{(ab+bc+ca)^3}{3}$$

A: By Cauchy-Schwarz:
$(a^2b+b^2c+c^2a)(ab^2+bc^2+ca^2) \ge (a^{1.5}b^{1.5}+b^{1.5}c^{1.5}+c^{1.5}a^{1.5})^2$
By the power mean inequality:
$(a^{1.5}b^{1.5}+b^{1.5}c^{1.5}+c^{1.5}a^{1.5})^2 \ge \frac{(ab+bc+ca)^3}{3}.$
(Note: The > sign in your post is false; let $a=b=c.$)

A: Just by sum of square and Schur's inequality:
$$
3(a^2b+b^2c+c^2a)(ab^2+bc^2+ca^2)-(ab+bc+ca)^3\\
=
\sum_{cyc} (a^{3}b+a^{3}c+a^{2}bc)(b-c)^2+3abc\sum_{cyc}a(a-b)(a-c) \geq 0
$$


text:
Q: Conjecture: if $a+b$ and $ab$ are rational, $a$ and $b$ are rational I can't find a rigorous proof but I have a feeling it's true.
Informal argument: Suppose $a+b$ and $ab$ are rational, $a$ and $b$ are irrational (since just one can't be irrational). Then $a$ and $b$ must have irrational "parts" that "cancel out" eg. $a = \frac4\pi$, $b = \pi$, $ab = 4$, which is rational. But then $a + b$ ends up being irrational, since the denominator has the irrational part squared and the numerator does not.
Obviously, this isn't a proper proof at all, but I can't think of any examples of numbers where this argument wouldn't hold true. Can someone provide a proof or counterexample?

A: It is not true:
$$
a = 1 - \sqrt 2, \\
b = 1 + \sqrt 2 \\
a + b = 2, \\
a b = 1 - 2 = -1
$$
$a + b$ and $a b$ are rational, but $a$ and $b$ are not rational.

A: If $s=a+b$ and $p=ab$ are rational, then $a$ and $b$ are roots of the polynomial $X^2-sX+p$ which has rational coefficients.
Then $a$ and $b$ are irrational if and only if the discriminant $D=s^2-4p$ is not a perfect square in $\mathbb{Q}$. Thus
$$
a=\frac{s}{2}+\frac{\sqrt{D}}{2},\qquad
b=\frac{s}{2}-\frac{\sqrt{D}}{2}
$$
(or conversely), so your conjecture is true, provided we interpret irrational part with a loose meaning. To wit, what's the irrational part of $\sqrt{2}$? Is it $\sqrt{2}$ or $\sqrt{2}-1$, as $\sqrt{2}=1+(\sqrt{2}-1)$?
More rigorously, when $a$ and $b$ are irrational, there is a field automorphism in $\mathbb{Q}[a,b]$ sending $a$ to $b$.


text:
Q: Can Apple's cinematic mode video camera be accessed via the AVfoundations api? i'm building a camera application and I am trying to figure out if the cinematic mode camera found on the iphone 13 and 14 can be accessed via AVfoundations api?
https://developer.apple.com/documentation/avfoundation/capture_setup/avcam_building_a_camera_app

A: Cinematic Mode is software Apple built for their cameras, but not a Camera itself.
To get a camera you want, you can use AVCaptureDevice.default(_for:position:) method.
More info here: https://developer.apple.com/documentation/avfoundation/avcapturedevice


text:
Q: Compare two data uri images php I want to compare two data URI images. is there is any solution for that?
I have used below code but it's not working:
$file1 = file_put_contents('file1.png', file_get_contents($data_before[$key]));
$file2 = file_put_contents('file2.png', file_get_contents($value));

$previousImageHash = md5_file('file1.png');
$currentImageHash  = md5_file('file2.png');

if ($previousImageHash != $currentImageHash)
{
    $description_note .= "
Signature was updated \n
";
}

it fails even i haven't made any change to the signature.
The library i am using is signature pad.

A: Use md5_file.
$file1 = file_put_contents('file1.png', file_get_contents($data_before[$key]));
$file2 = file_put_contents('file2.png', file_get_contents($value));

$previousImageHash = md5_file('file1.png');
$currentImageHash  = md5_file('file2.png');

if ($previousImageHash != $currentImageHash)
{
    $description_note .= "
Signature was updated \n
";
}


text:
Q: Title bar background color change in android studio in API Leve 11+ I have try to change style.xml to change app theme like following:
<resources>

<!-- Base application theme. -->
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    <!-- Customize your theme here. -->

</style>

<style name="AppTheme" parent="AppBaseTheme" >
    <item name="android:actionBarStyle">@style/MyActionBar</item>
</style>
<style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
    <item name="android:background">@color/primary_color</item>
</style>

give me nice solution.
Thanks in advance

A: Try something like this; I hope this is what you want and will help you:
 <style name="AppTheme" parent="Theme.AppCompat.Light">

    <item name="colorPrimary">#009000</item>
</style>


text:
Q: JQuery - can't call ajax on form submit in Firefox I have a form which, upon submission, also sends some other data to the server with ajax:
$('#continue-button').on("click", function(e){
    updateSessionVariables();
});

function updateSessionVariables(){
    $.ajax({
        type: "GET",
        url: update_bom_vars,
        data: myVars
    });
});

This works fine in Chrome but does not submit the ajax call in Firefox.
I have tried:
$('#continue-button').on("click", function(e){
    e.preventDefault();
    updateSessionVariables();
});

Now, this sends the data correctly, but the form will not submit. I even added:
     $('#continue-button').submit();

But no joy.
Any help would be much appreciated.

A: So I actually solved the problem like this:
$('#continue-button').on("click", function(e){
    e.preventDefault();
    updateSessionVariables();
});

function updateSessionVariables(){
    $.ajax({
       type: "GET",
       url: update_bom_vars,
       data: myVars
       success: ajaxComplete
    });
});

function ajaxComplete(){
    $('#parts-form').submit();
}

It seems that you must be sure the ajax call is complete before the submit can work.
Thanks for all the input!

A: Unless continue-button is the id of your form, it wont submit. I'd stick with regular JavaScript here, its a little lighter and all you need:
document.getElementById('formId').submit();

add that inside your click function and you should be good.
Edit: just reread and realized you're not having a successful AJAX call on firefox, and that was the real question. My bad.
If you are sending information to the database, try using POST instead of GET. GET is meant to do just that ... GET information, not submit it.

A: In te line...
$('#continue-button').submit();

Change for:
$('#myFormId').submit();

Greetings...

A: You have to submit the form, not the button:
$('#formwithid').submit();


text:
Q: RiotJS: How to cache values during loops? I'm looking to improve performance and readability by caching repeated values during each={} loops in RiotJS. Is there a way to do so that will not render the value and/or incur unnecessary performance overhead?
Before:
<my-tag>

    {item.text}
    {item.text}

  data = [
    {"text": "bold me", "style": "b"},
    {"text": "italicize me", "style": "i"}
  ];
</my-tag>

After:
<my-tag>

    {style=item.style}
    {text=item.text}
    {text}
    {text}

  data = [
    {"text": "bold me", "style": "b"},
    {"text": "italicize me", "style": "i"}
  ];
</my-tag>

jsfiddle

A: I think you want to do that :

  {text}
  {text}

jsfiddle

A: The following has bugs on 2.5, but works great on the next branch (3.0.0-alpha.5):
<my-tag>

    {(style=item.style) && false}
    {(text=item.text) && false}
    {text}
    {text}

  data = [
    {"text": "bold me", "style": "b"},
    {"text": "italicize me", "style": "i"}
  ];
</my-tag>

Because the expressions evaluate to false, they don't render, but the values of style and text still get set.


text:
Q: Issue in flow builder I am working on a requirement where a particular account should have only four contacts if more than four contacts then a validation error should pop up.
Since a roll-up summary is impossible as there is no master detail relation I tried an alternative way using flow builder.
I created a field named ContactTotal(number field) and a record-triggered flow for this.

Here I am getting the number of current contacts and adding it to the earlier created number field. This works fine for creating the record condition as I specified the triggering condition.
Can I do something in the flow to update the value if the record is deleted as well?
Also, the number field total contact has an initial value as blank instead of the number of contacts which gets updated when a record is created, but until then it remains blank. Is there any solution for this too?

A: I see that in Get Account you are getting multiple Accounts, can the contact be assignned to multiple accounts? if so you have to loop throug each account and for each, 1.get the number of contacts, 2. assign the value to the field you created.
To answer your question, you can create a flow (or change this one to On record created and updated) that if the Organization field (or whatever the lookup field for the account is called) is changed, then have a recount of the contacts in the parent account (by repeating the process you did in the flow). This again will only work if the relationship is one account to many contacts. Otherwise, you need to use the object linking Account and contact relationship.
Contact-Account relation is the AccountContactRelation object. You should try creating your flow from that object. Before you get to the flow, you can try a roll-up summary on that object. Here is more information about the object fields etc. developer.salesforce.com/docs/atlas.en-us.object_reference.meta/…
Updated 11/27/22


text:
Q: PreviewMouseDown occur before the SelectionChanged I try to get selected value of ListView by checking SelectedItem in PreviewMouseDown event handler.
But, PreviewMouseDown occured before SelectedItem , so i get old selected value.
How can i get the updated selected value?

A: I does, as "ArsenMkrt" and "Wallstreet Programmer" suggests to me:
In xaml, my control:
 <loc:RecipeListsControl x:Name="recipeListsControl" DataContext="{Binding Path=RecipeLists}"/>

In code behind:
 recipeListsControl.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Mouse_Down), true);
 recipeListsControl.AddHandler(UIElement.KeyDownEvent, new KeyEventHandler(Key_Down), true);

Thanks, guys


text:
Q: NextJS if statement wrapped a .map I am wondering how do I wrap my if statement to include the .map function.
Basically, if they have been featured in a video I want it to say Featured On: and then show the videos.
{
  data.directory.videos ?
Featured On:
 : <></>;
}
{
  data.directory.videos.map((video, i) => {
    return (
      <Col lg="6">
        <Vyt id={video} height="200" />
      </Col>
    );
  });
}

A: You should be able to put your map inside some JSX conditioned off of the truthiness of data.directory.videos:
{
  data.directory.videos && (
    <>

Featured On:

      {data.directory.videos.map((video, i) => {
        return (
          <Col key={video} lg="6">
            <Vyt id={video} height="200" />
          </Col>
        );
      })}
    </>
  );
}

Note: I am assuming here video can be used as the key for your Col component, but adjust accordingly.


text:
Q: A question about route definition I have defined the resources in routes.rb
resources :cars

In my view (index.html.haml), I defined a link for deleting one item:
%td
  =link_to(t("delete"), car_post_path(car))

I got the NoMethodError:
undefined method `car_post_path'
Why? (I am using Rails 3)

A: You mean you want to delete a car object, instead of a post object which belongs to a car, right?
If this is true, you should use car_path(car) instead of car_post_path(car)
There are two ways to do so:
# 1
%td= link_to t("delete"), car_path(car), :confirm => "Are you sure?", :method => :delete

# 2
%td= link_to t("delete"), car, :confirm => "Are you sure?", :method => :delete

As this is a RESTful resource, in #2 passing the car object with :method => :delete would be enough to tell rails to use car_path(car). So these two have the same effect.

A: <%= link_to 'DELETE', car, :confirm => 'Are you sure?', :method => :delete %>

Please go through this guide.

A: Change the code into the following

%td
  =link_to(t("delete"),
  car_path(car))

since u didnt associating any relation with ruote as for ur code. so check with it..

A: I see other good answer to this question. I just want to add that if you want to list the routes define in your application you should launch:
...$ rake routes

from the command line and get something like
        speakers GET    /speakers(.:format)                               {:action=>"index", :controller=>"speakers"}
                 POST   /speakers(.:format)                               {:action=>"create", :controller=>"speakers"}
     new_speaker GET    /speakers/new(.:format)                           {:action=>"new", :controller=>"speakers"}
    edit_speaker GET    /speakers/:id/edit(.:format)                      {:action=>"edit", :controller=>"speakers"}
         speaker GET    /speakers/:id(.:format)                           {:action=>"show", :controller=>"speakers"}
                 PUT    /speakers/:id(.:format)                           {:action=>"update", :controller=>"speakers"}
                 DELETE /speakers/:id(.:format)                           {:action=>"destroy", :controller=>"speakers"}

so if you do suffix with _path or _url (for instance) edit_speaker you will obtain  edit_speaker_path or edit_speaker_url that are the callable methods names of your routes.


text:
Q: Weird "Switch Case" statement I have this piece of code in one of my file:
switch ([sender tag]){
    ...

    case 100:
        UIView *v1 = [UIView alloc] initWithFrame blabllabla...
        [v1  bla bla bla...
        break;
    ...

Looks pretty standard huh? But it gives me this error:
"Use of undeclared v1"

Then i put an "NSLog()" or "if" statement, like this:
case 100:
    NSLog(@"why need a nslog here?");

or
case 100:
    if(1==1) {
        ...

Then it works.
Anyone know why is that? Is it my code or objective-c rules?

A: You cannot declare variables whose scope is limited to a case without using a C block. Change it to:
case 100:
{
    UIView *v1 = [UIView alloc] initWithFrame blabllabla...
    [v1  bla bla bla...
    break;
}

and it should work.


text:
Q: rerendering react search results via react-router redirect So, I have a Search component and a Results component. The Search component is rendered in the Header of the site so it is global. When a user enters text within that Search they will be redirected to the Results component. From the Results view, I want the user to be able to do another Search and re-render the Results component.
It's not currently working. Below is my code for the global search bar. As you can see, I use componentWillRecieveProps() and try to reset the state there. I use react-router Redirect.
   class SearchBox extends ComponentBase {

    constructor(props) {
      super(props);

      this.state = {
       fireRedirect: false,
       dropdownOpen: false,
       location: '',
       term: '',
       distance: '50 mi',
       submitted: false,
       results: {}
      };

     this.handleChange = this.handleChange.bind(this);
     this.handleSubmit = this.handleSubmit.bind(this);
     this.select = this.select.bind(this);
     this.toggle = this.toggle.bind(this);
  }

  componentWillReceiveProps(nextProps) {
   this.setState({ fireRedirect: false })
  }

  componentDidMount() {
   this.setState({
    location: this.props.city
  });

  toggle(e) {
    this.setState({
        dropdownOpen: !this.state.dropdownOpen
    });
   }

  select(event) {
    //let d = event.target.innerText.replace(" mi", "");
    this.setState({
        dropdownOpen: !this.state.dropdownOpen,
        distance: d
    });
 }

 handleChange(e) {
    const {
        name, value
    } = e.target;
    this.setState({
        [name]: value
    });
 }

handleSubmit(e) {
    e.preventDefault();
    this.setState({
        submitted: true,
        fireRedirect: true
    });
    const {
        location, term, distance
    } = this.state;
    const {
        dispatch
    } = this.props;

    if (term && location) {
      let q = "?term=" + term + "&location=" + location + "&distance=" + distance;
      this.setState({referrer: "/results" + q});
      //let q = "/" + term + "/" + location + "/" + distance;
      history.push("/results" + q);
      //history.goForward();
      //dispatch(searchActions.search(location, term, distance));
    }
}

render() {
    const {
        fireRedirect, referrer, location, term, distance
    } = this.state;

    return ( < form className = "form-inline" >
        < span className = "lead mr-sm-2" > Find < /span> < Input type = "text"
        name = "term"
        id = "query"
        size = "lg"
        className = "form-control mr-sm-2"
        onChange = {
            this.handleChange
        }
        placeholder = "e.g., stationary" / > {
            /*<span>within </span>
                    <DistanceDropdown />
                    <span> of </span> */
        } < span className = "lead mr-sm-2" > Near < /span> < Input type = "text"
        name = "location"
        id = "loc"
        size = "lg"
        className = "form-control mr-sm-2"
        onChange = {
            this.handleChange
        }
        placeholder = "Location"
        value={this.state.location}
      />

        < Button style={{backgroundColor: '#008efe', color: 'white'}}
        size = "lg"
        onClick = {
            this.handleSubmit
        } > < i className = "icon-magnifier" > < /i> Search</Button >
        {fireRedirect && (
        <Redirect to={referrer} />
        )}
         < /form>

      );
  }
 }

This is the error I get
Warning: You tried to redirect to the same route you're currently on: "/results?term=concrete&location=Palo Alto&distance=50 mi"


text:
Q: sql server replication - how to find and drop subscriptions? I had 2 subscriptions to a publication,
but they were from the same subscriber server and writing to the same subscriber database, just one was bad and one was running fine.

I could not find a way to delete the bad one, so I decided to drop both, and then recreate the subscription.

on the publisher server

use [SupplierDB]
go
exec sp_dropsubscription @publication = N'SupplierDB',
@subscriber = N'REPLON1',
@destination_db = N'SupplierDB',
@article = N'all'
GO

That dropped the good subscription.

Because I could not find a way to drop or even see the bad subscription I decided to drop the publication, but when I try it I get the following error message:
-- Dropping the transactional publication
use [SupplierDB]
exec sp_droppublication @publication = N'SupplierDB'
GO

Msg 14005, Level 16, State 1, Procedure sp_MSdrop_publication, Line 75
  Cannot drop the publication because at least one subscription exists
  for this publication. Drop all subscriptions to the publication before
  attempting to drop the publication. If the problem persists,
  replication metadata might be incorrect; consult Books Online for
  troubleshooting information.

How can I find and drop this subscription?
This is a problem that I originally had on another question:
NoSync subscriptions will need to be dropped and recreated

A: You need to look at the actual catalog/metadata table(s) and clean them up. The GUI and stored procedures often don't cleanup the underlying tables properly. So, after you have run the sp_dropsubscription SP run a select from MSsubscriptions and MSsubscriptions to see if there is any data referring to your unwanted subscriptions. See: msdn.microsoft.com/en-us/library/ms179855(v=sql.105).aspx.
Delete any row(s) representing subscriptions that shouldn't be there and it should resolve the problem. You may need to set sp_configure 'Allow Updates' = 1 to make changes to the table(s).


text:
Q: pipelight: error downloading wine-flash-installer I've been trying to use pipelight to install Flash on Firefox so I can watch HBO Now. I am able to install Widevine and Silverlight without any issues but I get the following error in console when it tries to install Flash:
[install-dependency] ERROR: Downloading of wine-flash-installer failed multiple times. Please check:
[install-dependency]
[install-dependency]        * that your internet connection is working properly
[install-dependency]
[install-dependency]        * and that the plugin database is up-to-date. To update it just run:
[install-dependency]            sudo pipelight-plugin --update
[install-dependency]
[install-dependency]        If this doesn't help then most-likely the download URLs or checksums
[install-dependency]        have changed. We recommend to open a bug-report in this case.
[install-dependency] ERROR: Download of wine-flash-installer failed.

I have found multiple threads online from a couple years back which suggest to update pipelight to v0.2.8 but I am already using v0.2.8.2. I've run --update and --create-mozilla-plugins as well. Does anyone know how I can fix this error or download the necessary installer manually?
(using Ubuntu 16.04, Firefox 50.1.0)
edit; Also, the output of 'sudo pipelight-plugin --update' if it helps:
Resolving bitbucket.org (bitbucket.org)... 2401:1d80:1010::150, 104.192.143.3, 104.192.143.2, ...
Connecting to bitbucket.org (bitbucket.org)|2401:1d80:1010::150|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 29488 (29K) [text/plain]
Saving to: '/tmp/tmp.2j7RyqWGg6'

/tmp/tmp.2j7RyqWGg6                     100%[==============================================================================>]  28.80K  --.-KB/s    in 0.03s

2016-12-26 23:56:09 (1.03 MB/s) - '/tmp/tmp.2j7RyqWGg6' saved [29488/29488]

gpg: Signature made Tue 01 Nov 2016 04:29:54 PM EDT using RSA key ID 1434FC73
gpg: Good signature from "Pipelight Dev Team (install-dependency) <webmaster@fds-team.de>"
gpg: WARNING: This key is not certified with a trusted signature!
gpg:          There is no indication that the signature belongs to the owner.
Primary key fingerprint: CF23 08D4 3507 9A77 124E  01A2 83C7 3FB2 1434 FC73

Script dependency-installer is already up-to-date.

A: Per the comments on the top post (and pipelight.net) it looks like Pipelight has been discontinued so I'm not sure there's a solution.
An alternative, for those without access to another OS, is to install Firefox and Flash with Wine. I find this to work reasonably well.


text:
Q: strange rgb2gray behavior, results in very deeply hued and contrasted images I'm using matlab to capture an image through the webcam, as an rgb image
 vid=videoinput('winvideo',1,'YUY2_160x120');
 vid.ReturnedColorSpace='rgb';
 I = getsnapshot(vid);

then when I try the following:
image(rgb2gray(I))

I get something like :

when I dont rgb2gray, the image looks completely fine and in color...
am I using the wrong function here?

A: That looks to me like you have a non-grayscale colormap.
Try adding
colormap('gray')


text:
Q: Best Linux Distro for Web Development? I want to start learning HTML and AJAX using a Linux distribution.
Can anyone recommend a distribution that has these requirements:

*

*Local Host Admin interface (like PHPmyAdmin)

*IDE for Javascript... etc

A: First question - Why do you want to do this on Linux?  You can do basic AJAX requests from any platform, simply drop in your JavaScript framework of choice (JQuery, Prototype, or even MooTools and you can be up and running on your existing development platform.
Get familiar with a decent editor, one that will provide basic syntax coloring for you.  One tool you may want to look at is the Aptana web development IDE that is based on Eclipse.  This will give you the capability to write and debug any AJAX work you do as well as provide you some documentation and access to other dynamic languages like PHP, Rails, Python as well as a basic HTML editor.
That should square you away more than enough for what you're looking to do.

A: I just setup my first linux hosting to do the same thing. I did a lot of looking around and was recommended by articles and friends to use Ubuntu. So I did and everything has been working just great.
I'm using slicehost They have lots of tutorials to get you going.
http://articles.slicehost.com/ubuntu-gutsy

A: There is no real best distro for web development.
All tools you need will run on any linux distro.
Pick something you have experience with.
If you don't have any experience I'd recommend one of the 'user friendly' distros like Ubuntu or SuSe.

A: I can't think of many distributions that won't do what you need. I'd suggest something that has a good package manager, and, works well on your hardware. There will be plenty of choice for your requirements with all the major distributions.
What are you currently using ?
Andrew

A: Ubuntu should get the job done but you might consider a slightly more server oriented distro.  In my shop, we use CentOS 5 which is more of an enterprise-oriented distro.

A: It exists specialized distributions:
The best one for me: Noys
http://www.noysweb.net/
Other one is Excelixis:
http://excelixis.wordpress.com/excelixis/
Cheers

A: HTML and AJAx don't need to be on any particular distribution, Ubuntu makes it pretty easy to install all the required features.  I like fedora personally.
Try http://www.eclipse.org/webtools and http://www.zend.com/phpide although screem http://www.screem.org/ may well do what you need if it is purely html, javascript and css


text:
Q: How to make a rectangular clockwise progress in iOS? I'm struggling to create a rectangular clockwise progress in iOS. See the attached images to understand better what I mean:

If anyone has some useful ideas, please share them. Thank you.

A: I have created a reactangular loader. You can have a look at the code here
https://github.com/NavneetSinghGill/ReactangularLoader.git
There's a method named getPointsForValue which does the main work.


text:
Q: "Expected ]" error while passing an object as parameter to js function I am trying to pass an object as parameter to the javascript function as:
    .html('' + event.title
+ '')

In the above js, the event and view are objects from the jquery calendar Full Calendar, which i am passing to call a js function.
It throws an error, Expected ']'. What may be problem or how to pass an object as above?
It shows "javascript:ShowEditEventDetails([object Object],1,'Name',[object Object])" while looking in firebug.

A: You can't pass an object in that way, because when you concatenate the HTML string of your span element, all the operands of the + operator are converted toString, including the  event object, that's why you get "[object Object]":
'' + {} == "[object Object]"; // an empty object

I would recommend you to bind the click event programmatically:
// ...
var $span = $('' + event.title + '');
$span.click(function () {
  ShowEventDetails(event, event.Id, event.Name, view);
});

$('#otherElement').append($span);
// ...

A: That's because ShowEventDetails isn't being passed event, it's being passed String(event), which is [object Object], which yields a syntax error. Assuming event and view are global variables, use this instead:
.html('' + event.title
      + '')

You shouldn't be using .html for such a thing though. This solution is better and doesn't require global variables:
.addClass("link")
.click(function () {
  ShowEventDetails(event, event.Id, event.Name, view)
})
.text(event.title);

A: What's Going Wrong
event and view are both objects.  When you concatenate an object to a string (as you're doing with '...ShowEventDetails(' + event + ','...), JavaScript casts the object to a string, resulting in the nearly useless [object Object] text you see in FireBug.  When the JavaScript interpreter later tries to parse [object Object] as code, it blows up because it is invalid syntax.
How to Fix It
The easiest thing to do is set your event handler programmatically:
var mySpan = $('');
mySpan.text(event.title);
mySpan.click(function (ev) {
  ShowEventDetails(event, event.Id, event.Name, view);
});

parentElement.append(mySpan);