text:
Q: How to check the status of docker-compose up -d command When we run docker-compose up-d command to run dockers using docker-compose.yml file, it starts building images or pulling images from the registry. We can see each and every step of this command on the terminal.
I am trying to run this command from a python script. The command starts successfully but after the command, I do not have any idea of how much the process has been completed. Is there any way I can monitor the status of docker-compose up -d command so that script can let the user (who is using the script) know how much the process has completed or if the docker-compose command has failed due to some reasons.?
Thanks
CODE:
from pexpect import pxssh

session = pxssh.pxssh()
if not session.login(ip_address,<USERNAME>, <PASSWORD>):
    print("SSH session failed on login")
    print(str(session))
else:
    print("SSH session login successfull")
    session.sendline("sudo docker-compose up -d")
    session.prompt()
    resp = session.before
    print(resp)

A: You can view docker compose logs with following ways

*

*Use docker compose up -d to start all services in detached mode (-d)
(you won't see any logs in detached mode)

*Use docker compose logs -f -t to attach yourself to the logs of all
running services, whereas -f means you follow the log output and the
-t option gives you nice timestamps (Docs)

credit
EDIT: Docker Compose is now available as part of the core Docker CLI. docker-compose is still supported for now but most documentation I have seen now refers to docker compose as standard. See https://docs.docker.com/compose/#compose-v2-and-the-new-docker-compose-command for more.

A: I think should use the command docker-compose top, could check the result, It shoul not be empty when the container is running.
If the containers is stop or exit or Create, it should return empty

A: What I do to debug small issues is to run:
docker-compose up {service_name}

This way I get to see the output for an individual service. If the service has a dependency you can always start multiple services like so:
docker-compose up {service_name1} {service_name2}

Additionally I use:
docker-compose logs -f -t {service_name1}

To see the logs of an already running service or alternatively:
docker logs -t -f {container_name}

Notice that the command above needs the container name and not the service name
This way you can make sure service by service that everything works as expected and then you can launch them all in detached mode as suggested in the other answers

A: If you need a programmatic way with bash, this is the fastest implementation:

*

*sleep 2 seconds

*check the container was up several seconds ago => Means you've just successfully deployed it

docker ps will look like:
a6f088b1567e   lc_fe_isr-app   "docker-entrypoint.s…"   2 seconds ago   Up 2 seconds   0.0.0.0:10001->3000/tcp   lc_fe_isr-app-1

#!/bin/bash

#
# Check if the a single container was started successfully
#
CONTAINER_NAME="lc_fe_isr-app-1"
sleep 2
docker ps | grep $CONTAINER_NAME
UP_SECONDS_AGO=`docker ps | grep $CONTAINER_NAME | grep ' seconds'`
echo $UP_SECONDS_AGO

if [ -n "$UP_SECONDS_AGO" ]
then
    echo "Deploy successfully"
else
    echo "Deploy FAILED"
    exit 1
fi


text:
Q: pip package loses package data after reboot I have installed my python project with the help of setuptools and defined some static txt,conf and html files. But my problem is that, after rebooting my debian System, the script doesn't finds the static files anymore. I defined them in the MANIFEST.in as follows:
include data/*.conf
include data/*.html
include data/*.txt

this is my setup.py
#!/usr/bin/python3
from setuptools import setup, find_packages
setup(
    name="dnwtools",
    version = "0.0.4",
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    install_requires=[
          'jinja2',
          'pymysql'
    ],
    entry_points = {
        "console_scripts": [
            "dnwtools = dnwtools.main:main",
        ]
    },
    python_requires='>=3.6',
)

Thank you for your help in advance !

A: i solved the problem on my on: id just had to ad the __file__ variable to

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't understand a step in this equation Could someone explain how $2(x+h)^2$ becomes $2(x^2+2xh+h^2)$
What properties are used?

A: It all comes down to the distributive law:
$$
2(x+h)^2 =
2[\color{red}{(x+h)}
\color{blue}{(x+h)}]
= 2[
\color{red}x\color{blue}{(x+h)}
+ \color{red}h\color{blue}{(x+h)}]\\
= 2[\color{red}x\color{blue}x +
\color{red}x\color{blue}h +
\color{red} h\color{blue}x +
\color{red} h\color{blue}h]
= 2[x^2 + 2xh + h^2]
$$
You could reach the same conclusion using the FOIL method.


text:
Q: Creating a new user account during the installation process I need to install a windows service running under a given user. It is working with an existing user (ServiceProcessInstaller = User) but when the user does not exist then it should be created before the service install happens. The user must be a mamber of administrators.
How should I do it?
(VS2008, C#)
Thank You.
-- Hudgi

A: Adding a Local User
Adding to Active Directory


text:
Q: Discrepancy between explicit ODE solution and phase line analysis Suppose we have the separable ODE,
$$ \frac{dy}{dt} = e^t\frac{y^2-9}{2y}, \;\; y(0) = -5 $$
The explicit solution to this problem is,
$$ y = -\sqrt{9 + 16e^{e^t-1}} $$
I'm confused about the behavior of the solution when $t \rightarrow -\infty$. According to the explicit solution, $y \rightarrow -\sqrt{9 + 16e^{-1}}$. However, if we do a phase line analysis, we can show that $y = -3$ is an unstable stationary point. So as we go back in time, shouldn't,
$y \rightarrow -3$? Why do the answers not match?
Does phase line analysis not work for non-autonomous equations like above?

A: It doesn't work for nonautonomous systems. Consider the change of variables $x = e^t$. Then by the chain rule:
$$\frac{dy}{dt} = \frac{dx}{dt}\frac{dy}{dx} = e^t \frac{dy}{dx}$$
Then the equation reduces down to
$$\frac{dy}{dx} = \frac{y^2-9}{2y}$$
and notice that the final solution becomes
$$y = -\sqrt{9+16e^{x-1}}$$
which does approach the unstable fixed point just like you expected. One to think of our change of variables is that we parametrized the path of the flow lines, but in a way that doesn't retrieve the whole line.


text:
Q: What are the artifacts in the Waverider timeship? DC Comics posted a message on Instagram saying that the set decorators of Legends of Tomorrow have placed easter eggs that reference DC properties.

I am able to see a few

*

*Old Red Tornado helmet on the table

*Pied Piper's flute

*Sgt. Rock helmet

On Instagram the comments also make mention of

*

*Orion's helmet; other say it's closer to S.T.R.I.P.E. Is either true?

*Green lantern ring/lantern (I don't see this though)

What other DC properties are referenced in this photo (and where are they)?

A: You have already identified:

*

*Sgt. Rock's helmet (on the first person from the left)

*Pied Piper's flute (being played by the person in the middle with the leather trench coat)

*Ma Hunkel's Old Red Tornado helmet (on the table at the extreme left of the photo)

We also have...

*A lantern from Green Lantern Corps on the top shelf at the back of the room:

*The helmet worn by the individual at the right seems to be the DCAU-version of S.T.R.I.P.E.'s helmet (notice the two circles on top):

*The individual at the right wearing S.T.R.I.P.E.'s helmet is miming Orion's trademark stance:

*On the bottom shelf at the back, we see Pandora's skull:

*On the table in the foreground, we see the lost scrolls of Herculaneum, magical items found in the DC universe.

A: That may be the new Guardian's helmet - Jimmy Olsen is taking on the mantle of Guardian in Supergirl, and the mask in the art looks a bit like that

And technically, Rip's coat is an artifact - he got it from Jonah Hex.


text:
Q: Nuxtjs, VUEX and Firebase authentication on page reload I am using Firebase authentication in my Nuxt application, but I can't figure out a good way to persist the user logged-in state in my Store.
I am logging users in by dispatching a async action in my store. when a user refreshes the browser (reloads it), the user will be logged out in my app, but will remain logged in in Firebase (as they didn't log out). It's a problem because the user will have to sign into my app again in order to view restricted pages and perform certain actions.
I tried to grab the user in NuxtServerInit (from the index.js store as I am using modules mode) from:
firebase.auth().currentUser

But it it returns null, and I also tried to listen for:
firebase.auth().onAuthStateChanged((user)

But it also returns null
I also tried creating a middleware to check if a user is currently logged in, but it also returns null.
In a previous Vue project I was able to do it in the in the main.js file created-hook like this:
new Vue({
  router,
  store,
  render: h => h(App),
  created () {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        store.dispatch('autoSignIn', user)
      }
    })
  }
}).$mount('#app')

But I am not able to figure out how to do the same in my Nuxt application.
I appreciate any ideas on how to solve the problem keep my users logged in.


text:
Q: Tags component using UICollectionView with FlowLayout? What I am trying to do is to put every view on the next line if there is no space. The same principle that Tag libraries are using (think so). I do not want them to scroll just to be on the next line and left aligned. Here is my code:
self.collection.register(UINib(nibName: "FlowCell", bundle: nil), forCellWithReuseIdentifier: "tag")
    self.collection.showsHorizontalScrollIndicator = false
    self.collection.showsVerticalScrollIndicator = false
    self.collection.dataSource = self
    self.collection.delegate = self
    let layout = collection.collectionViewLayout as! UICollectionViewFlowLayout
    layout.estimatedItemSize = CGSize(width: 10, height: 18)

This is the result

*

*With Horizontal scroll direction. Here I have only one row:

*With Vertical scroll direction. Here the content is centered which:

And that's what I am trying to accomplish:

Of course the content of the items on the last image is different but I would like items to be left aligned if the tags can't be more than one on the same line.

A: You should try this:
https://github.com/mokagio/UICollectionViewLeftAlignedLayout
Looks like exactly what you're going for.


text:
Q: ransac with homography vs 8/5 point algorithms Im beginning to learn computer vision and I'm confused on the difference between the two.
I know that the 8 point algorithm is used to compute the fundamental matrix and the 5 point algorithm is used to compute the essential matrix.  Both of which can be used to determine the relative camera pose.
I also found that the relative camera pose can be determined using ransac with homography https://inspirit.github.io/jsfeat/#multiview in the ransac method
Is there a difference between using ransac with homography as opposed to using the algorithms?

A: First of all, note that you still need RANSAC with the 8-point or 5-point algorithms, since in practice outliers are to be expected in the matching process.
I think the main downside of pose from homography is that the point matches you use need to be coplanar. Additionaly, if I'm not mistaken, in  a scene with more than one plane, you might get different homographies depending on which planes you select in the scene. That is why applying a homography to correct perspective adds distortion to some other parts of the image (see the example in this video). So in complex scenes (e.g. urban environements) where matching is more difficult, I'd use one of the 8-point or the 5-point algorithms.
Note that you can also recover the relative pose directly (up to scale, obviously), and compute the essential from that (see this paper). It's easier than computing the fundamental/essential and then extracting relative pose.


text:
Q: Share folder from Host to Guest VM using KVM I want to share a folder from the host (linux) to a Linux VM that is running on it.
After some research I used 9p (version = 9p2000.L) sharing, following instructions given on the link below:
http://www.linux-kvm.org/page/9p_virtio
PROBLEM: I am unable to read/write to the mounted folder.
mount command shows the mounted fs as : 9p (rw,trans=virtio,version=9p2000.L)
Even doing a simple "ls" command after entering the mount point says : Permission Denied.
Any help is appreciated

A: Looks like the 9p kernel module is broken in some kernels (3.5, 3.11). I ungraded by guest to 3.10.9 and things started working! :)
I just went with a hunch and have no bug reports or anything to share. Now when I googled it,I see there are few other facing the similar problem and have solved it in a similar fashion.
 https://bugs.archlinux.org/task/36992
-HTH


text:
Q: how to mention ubuntu patch version in dockerfile is it possible to mention ubuntu patch version in dockerfile
e.g. generally to get ubuntu 16.04 we would have following line in the dockerfile
FROM ubuntu:16.04

What I want to do is within 16.04 also there will be patch versions like 16.04.04 and 16.04.05 so I want to mention that patch version in the dockerfile.
Is it possible somehow ? It doesn't work if I write FROM ubuntu:16.04.04  is there any other syntax ? other way to specify to it.

A: Those FROM values correspond to literal tag values in the ubuntu dockerhub repository.  Whether it is found depends on how the ubuntu team tags their docker images and how long they keep older versions.
You can look here to see if one meets your requirements:
https://hub.docker.com/r/library/ubuntu/tags/
It doesn't look like they tag the patch version numbers but they do retain tag patch dates like xenial-20180228.  If you know the patch date for 16.04.04, you can look in the tag list in dockerhub and see if one matches or is close.


text:
Q: Laravel get route name from given URL In Laravel, we can get route name from current URL via this:
Route::currentRouteName()

But, how can we get the route name from a specific given URL?
Thank you.

A: None of the solutions above worked for me.
This is the correct way to match a route with the URI:
$url = 'url-to-match/some-parameter';

$route = collect(\Route::getRoutes())->first(function($route) use($url){
   return $route->matches(request()->create($url));
});

The other solutions perform bindings to the container and can screw up your routes...

A: I don't think this can be done with out-of-the-box Laravel.  Also remember that not all routes in Laravel are named, so you probably want to retrieve the route object, not the route name.
One possible solution would be to extend the default \Iluminate\Routing\Router class and add a public method to your custom class that uses the protected Router::findRoute(Request $request) method.
A simplified example:
class MyRouter extends \Illuminate\Routing\Router {

    public function resolveRouteFromUrl($url) {
        return $this->findRoute(\Illuminate\Http\Request::create($url));
    }
}

This should return the route that matches the URL you specified, but I haven't actually tested this.
Note that if you want this new custom router to replace the built-in one, you will likely have to also create a new ServiceProvider to register your new class into the IoC container instead of the default one.
You could adapt the ServiceProvider in the code below to your needs:
https://github.com/jasonlewis/enhanced-router
Otherwise if you just want to manually instantiate your custom router in your code as needed, you'd have to do something like:
$myRouter = new MyRouter(new \Illuminate\Events\Dispatcher());
$route = $myRouter->resolveRouteFromUrl('/your/url/here');

A: It can be done without extending the default \Iluminate\Routing\Router class.
    Route::dispatchToRoute(Request::create('/your/url/here'));
    $route = Route::currentRouteName();

If you call Route::currentRouteName() after dispatchToRoute call, it will return current route name of dispatched request.

A: A very easy way to do it Laravel 5.2
app('router')->getRoutes()->match(app('request')->create('/qqq/posts/68/u1'))->getName()

It outputs my Route name like this slug.posts.show
Update: For method like POST, PUT or DELETE you can do like this
app('router')->getRoutes()->match(app('request')->create('/qqq/posts/68/u1', 'POST'))->getName()//reference https://github.com/symfony/http-foundation/blob/master/Request.php#L309

Also when you run app('router')->getRoutes()->match(app('request')->create('/qqq/posts/68/u1', 'POST')) this will return Illuminate\Routing\Route instance where you can call multiple useful public methods like getAction, getValidators etc. Check the source https://github.com/illuminate/routing/blob/master/Route.php for more details.


text:
Q: How to add a getter from one object to another I made a similar question not too long ago, but I have another twist to it. Suppose I have this:
  var config = {
    a: {
        value: '',
        get getValue(): {
            return this.valueType
        }
    },
    b: {
        value: '',
        get getValue(): {
            return this.value
        }
    },
    c: {
        value: {
          d: '',
          e: '',
          f: ''
        },
        get getValue(): {
            return this.d + " " + this.e + " " + this.f
        }
    }
  }

Then, I am doing this:
  assignConfig(conf) {
    array.push({
      value: { ...config[conf] } //conf Could be a, b, c
    }
  }

The idea is that I can call getValue and get the data in that format, but I will be calling it from the array where I'm pushing the config. The values inside valueType will be changing, since they are being used in an ngModel. When I try this, getValue is always empty. Is this possible to do? Maybe there's another way to approach this.


text:
Q: Cleansing data on SQL - String I am trying to clean my data on SQL. My sample data is below:

Could you please let me know how can I remove the date-time parts? Thanks,
https://docs.google.com/spreadsheets/d/1BvVxU0_a53vncGpd0Mbr57WPUbG89MgfpYGah0JBdIA/edit?usp=sharing

A: You can use this regex for selecting date-times that you want to remove:
(\(?[0-9]{2}\/){2}([0-9]{4}\)?)

Then replace that part of string with blank space, which is the same as removing.
To see how to use replace method in SQL with regex check this answer.

A: SQL Server is not particularly good at string manipulations.
However, based on the examples in your question, the "cleaning" is either removing the first 11 characters or the last 13 characters, depending on where the date is.  Fortunately, this is actually something you can do in SQL Server:
select t.*,
       (case when data like '% ([0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9])'
             then left(data, len(data) - 13)
             when data like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9] %'
             then stuff(data, 1, 11, '')
             else data
        end) as cleaned_data
from t;


text:
Q: Extract specific Type from a Record in Typescript Consider a type PageProps : Record<string, Type>:
type PageProps = Record<
  string,
  | {
      type: "title";
      title: Array<{
        type: "text";
        text: {
          content: string;
          link: {
            url: string;
          } | null;
        };
        plain_text: string;
        href: string | null;
      }>;
    }
  | {
      type: "rich_text";
      rich_text: Array<
        | {
            type: "text";
            text: {
              content: string;
              link: {
                url: string;
              } | null;
            };
            plain_text: string;
            href: string | null;
          }
        | {
            type: "equation";
            equation: {
              expression: string;
            };
            plain_text: string;
            href: string | null;
          }
      >;
      id: string;
    }
  | {
      type: "number";
      number: number;
      id: string;
    }
  | {
      type: "url";
      url: string;
      id: string;
    }
>;

How can I extract below type from the above PageProps : Record<Keys, Type>:
type RichText = {
      type: "rich_text";
      rich_text: Array<
        | {
            type: "text";
            text: {
              content: string;
              link: {
                url: string;
              } | null;
            };
            plain_text: string;
            href: string | null;
          }
        | {
            type: "equation";
            equation: {
              expression: string;
            };
            plain_text: string;
            href: string | null;
          }
      >;
      id: string;
    }

I tried Pick and Extract but couldn't get it to work for Record<Keys, Type>.
Try this in TS Playgroud

Note: PageProps comes from a module so it's not possible to edit/refactor it.

A: You can get access to this part of the discrimnated union like this:
type RichText = Extract<PageProps[string], {type: "rich_text"}>;

This essentially relies on the fact that PageProps[string] is a discrimnated union and makes use of the fact that TypeScript distributes over union types used as generic type arguments.


text:
Q: Limit Text to number of lines 3 I have to show some text in UILabel and append read more if the text goes beyond 3 number of lines. It works fine if I set number of lines = 3 and trim the text to 120 characters or so. But if the text contains newline character then this fails.
How to handle this.
func formatText() -> String {
        var formatString = self.review_description
        var maxLimit = 140
        if self.review_link != nil {
            maxLimit  = 120
        }

        if formatString.count > maxLimit {
            let substring = formatString.dropLast(formatString.count - maxLimit)
            formatString = String(substring) + "... " + AppConstants.readMoreText
        }

        if self.review_link != nil {
            formatString = formatString + " \(AppConstants.reviewSourceText)"
        }

        return formatString
    }

A: try this
make your number of lines for label as 0. because new line won't increase your char count at all


text:
Q: How do you register DapperExtension ClassMapper subclasses so they are used? I've just started playing with DapperExtensions and it looks very promising.  However, I'm confused on how to handle registering the ClassMapper subclasses.
I have both a custom PluralizedAutoClassMapper and a regular ClassMapper and I'm trying to use both.
Here's my pluralized mapper...
public class CustomPluralizedMapper<T> : PluralizedAutoClassMapper<T>
where T : class
{
    private readonly Type[] SinglularTablePocoTypes = new []{
        typeof(LibraryInfo)
    };

    public override void Table(string tableName)
    {
        base.Table(tableName);

        if(SinglularTablePocoTypes.Any(type => string.Equals(type.Name, tableName, StringComparison.CurrentCultureIgnoreCase)))
            TableName = tableName;
    }
}

...and here's the mapper specifically for the LibraryInfo class
public class LibraryInfoMapper : ClassMapper<LibraryInfo>
{
    public LibraryInfoMapper()
    {
        Map(libraryInfo => libraryInfo.Name).Column("LibraryName");
        Map(libraryInfo => libraryInfo.Description).Column("LibraryDescription");
        AutoMap();
    }
}

The PluralizedAutoClassMapper I get to work by calling the following...
DapperExtensions.DapperExtensions.DefaultMapper = typeof(CustomPluralizedMapper<>);

But I'm not sure how to use the other one at the same time.  What am I missing?

A: Ok, I figured it out.  The issue was because I'm using IoC and my POCOs are in a different assembly from the mappings.
In short, my model has no idea, nor cares about where or how it's being stored. It only defines an interface describing how it needs to interact with that storage.  My DAL defines a class which implements that interface and uses SQLite as it's backing storage.  Since the mappings only make sense in regards to SQLite, that's where I defined the mappings.
The problem is DapperExtensions reflects into the assembly that defines the POCOs looking for their ClassMappers, but since mine were in a different assembly, they weren't being found.
However, you can tell DapperExtensions to search external assemblies via the following line of code...
DapperExtensions.DapperExtensions.SetMappingAssemblies(new[]{
    assemblyA, assemblyB, ...assemblyN
});

So since my mappings are defined in the same place as my static Mapper class (which has the static 'Initialize' call) all I now have to do is tell DapperExtensions to search there like so...
public static class Mappings
{
    public static void Initialize()
    {
        DapperExtensions.DapperExtensions.DefaultMapper = typeof(CustomPluralizedMapper<>);

        DapperExtensions.DapperExtensions.SetMappingAssemblies(new[]
        {
            typeof(Mappings).Assembly
        });
    }

    public class CustomPluralizedMapper<T> : PluralizedAutoClassMapper<T>
    where T : class
    {
        ...
    }

    public class LibraryInfoMapper : ClassMapper<LibraryInfo>
    {
        ...
    }
}

And now everything works!
Better yet, since I can specify the table name in the LibraryInfoMapper, there's actually no need for my CustomPluralizedMapper and therefore I can just use the standard PluralizedAutoClassMapper like so...
public static class Mappings
{
    public static void Initialize()
    {
        DapperExtensions.DapperExtensions.DefaultMapper = typeof(PluralizedAutoClassMapper<>);

        DapperExtensions.DapperExtensions.SetMappingAssemblies(new[]
        {
            typeof(Mappings).Assembly
        });
    }

    public class LibraryInfoMapper : ClassMapper<LibraryInfo>
    {
        public LibraryInfoMapper()
        {
            Table("LibraryInfo");
            AutoMap();
        }
    }
}

Done and done!  There was ZERO documentation on finding this out so I hope this helps others!


text:
Q: Why two slice have same address, but not have same value in Golang? In go source code we can see this type declare:
type slice struct {
    array unsafe.Pointer
    len   int
    cap   int
}

So I thought s := make([]string, 0) is equal to s := &slice{}.
But when I tried to run these codes, I am confused:
s := make([]int, 0, 2)
s2 := s
s = append(s, 10)
fmt.Printf("%v, %p\n", s, s)
fmt.Printf("%v, %p\n", s2, s2)

I found s s2 have same address, but not have same value.
These two slice are obviously like:
array := [2]int{10}
s := &slice{
  array: unsafe.Pointer(&array),
  len: 1,
  cap: 2,
}
s2 := &slice{
  array: unsafe.Pointer(&array),
  len: 0,
  cap: 2,
}

They have same array pointer, but they are two different slice.
In normal way, when I run fmt.Printf("%p\n", s) it should print s` address.
But Golang seems like print s.array, which is array`s address.

A: You actually are manipulating the same underlying array. It's just that the value of s2.len is still 0, and that's used by the fmt package when printing its value.
Here's your code snippet expanded a bit to more clearly illustrate what's happening:
package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

func printSlices(slices ...[]int) {
    for _, s := range slices {
        hdr := (*reflect.SliceHeader)(unsafe.Pointer(&s))
        fmt.Printf("%v, %p, %v\n", s, s, hdr)
    }
}

func main() {
    s := make([]int, 0, 2)
    s2 := s

    fmt.Println("Add two values to s...")
    s = append(s, []int{10, 20}...)

    printSlices(s, s2)

    fmt.Println("Add a value to s2...")
    s2 = append(s2, 30)

    printSlices(s, s2)

    fmt.Println("Add another value to s, exceeding it's capacity, causing a new backing array to be allocated")
    s = append(s, 40)

    printSlices(s, s2)
}

Output
Add two values to s...
[10 20], 0xc00001c030, &{824633835568 2 2}
[], 0xc00001c030, &{824633835568 0 2}
Add a value to s2...
[30 20], 0xc00001c030, &{824633835568 2 2}
[30], 0xc00001c030, &{824633835568 1 2}
Add another value to s, exceeding it's capacity, causing a new backing array to be allocated
[30 20 40], 0xc000102000, &{824634777600 3 4}
[30], 0xc00001c030, &{824633835568 1 2}

Go Playground


text:
Q: Getting error using credentials to get accountid:getcalleridentity in aws -terraform I created an aws account and an IAM user for terraform -administrator access and got my credentials.
I am now trying to create an EC2 instance in AWS using terraform.I am running the below terraform script from git bash.
provider "aws"{
access_key = "Axxxxxxxxx"
secret_key = "Lxxxxxxxxxxxxxx"
region="us-east-1"
}
resource "aws_instance" "example"{
ami="ami-0323c3dd2da7fb37d"
instance_type="t2.micro"
}

When i give terraform plan,I am getting the following error:
Error: error using credentials to get account ID: error calling sts:GetCallerIdentity: SignatureDoesNotMatch: Signature not yet current: 20200518T060344Z is still later than 20200518T041739Z (20200518T040239Z + 15 min.)
        status code: 403, request id: 7d93e368-bf05-4110-9876-1bf6064dd255

  on instance.tf line 1, in provider "aws":
   1: provider "aws"{

I am new to AWS as well as terraform.Can you please let me know why this error appears?I tried updating the git bash.If I am missing out something,please let me know.

A: Your system clock may be miss-configured.
From this AWS forum thread:

API services verify timestamps to be within 5 minutes of actual time. If the system clock is off by more than 5 minutes, then the API requests will fail.


text:
Q: Angularjs 1.2rc2: isolated scope differences across browsers (especially older chrome)? I stumbled across a weird issue when testing an application on an old chrome version (5.0.3).
So basically I'm using a controller on a directive like:
<div ng-controller="MyController" class="my-directive-with-isolated-scope">
<!-- ... -->
</div>

This seems to be perfectly valid in most recent browsers, however it throws an exception in older versions of Chrome:
Multiple directives [myDirectiveWithIsolatedScope, ngController] asking for isolated scope   on:…

Any idea why there's a difference?
[Edit]: Just noticed that this also applies to Firefox.

A: I would probably say that having a controller directive and another directive sharing an element may be problematic. In this case, you are saying I want each directive to have an isolated scope on the same element. What is your directives purpose? If you moved your directive to a sub element then the problem would go away. Of course this may not answering your question.


text:
Q: Detect battery percentage with applescript How would I detect what my computer's battery percentage is at and set it to a variable using applescript? All answers to similar questions say to install additional software, but I would like to do this with purely applescript. Is this possible? I've also tried searching through the applescript library with no success.

A: on run
    set theBattString to (do shell script "pmset -g batt")
    -- the above will return something like...
    -- Now drawing from 'Battery Power' -InternalBattery-0  82%; discharging; 4:06 remaining
end run

Now you can parse theBattString to get the information you'd like from it.
Another option...
on run
    do shell script "ioreg -l | grep -i capacity | tr '\\n' ' | ' | awk '{printf(\"%.2f%%\\n\", $10/$5 * 100)}'"
    -- will output...
    -- 79.63%
end run

A: The applescript unsigned variable can be used like a signed FileMaker variable... the ** can be removed I tried it Bold it
set batteryPercent to do shell script "pmset -g batt "
tell application "FileMaker Pro.app"
tell table "Power Test Results"
tell record 1
set cell "Test percentage via AppleScript Global" to batteryPercent
end tell
end tell
end tell

A: Thank ThrowBackDewd for his answer.
I made something a bit strange but it works for me.
Here is the AppleScript
[EDIT]
Here a more efficient code thanks to user @user3439894.
    set batteryPercent to word 6 of paragraph 2 of (do shell script "pmset -g batt")

if batteryPercent < 40 then

    beep

    repeat 3 times

        say "Attention " & batteryPercent & "%" & " before shut down."

        display notification "Attention " & batteryPercent & "%" & " of charge before shut down." sound name "Glass"

    end repeat

end if

idle application
    on idle

    set batteryPercent to word 6 of paragraph 2 of (do shell script "pmset -g batt")

    if batteryPercent < 40 then

        repeat 3 times

            beep

            say "Attention " & batteryPercent & "%" & " of charge before shut down."

            display notification "Attention " & batteryPercent & "%" & " of charge before shut down." sound name "Glass"

        end repeat

    end if

    return 60

end idle

[First post]
  set theBattString to (do shell script "pmset -g batt")
-- the above will return something like...
-- Now drawing from 'Battery Power' -InternalBattery-0  82%; discharging; 4:06 remaining

set batteryLevel to splitText(theBattString, space)

--set totalItembatLvl to length of batteryLevel

set remainingTime to item 9 of batteryLevel

if remainingTime < "2:40" then
    display alert "low battery " & remainingTime & " before shut down."
    --batteryLevel & " " & remainingTime
end if

on splitText(theText, theDelimiter)
    set AppleScript's text item delimiters to theDelimiter
    set theTextItems to every text item of theText
    set AppleScript's text item delimiters to ""
    return theTextItems
end splitText
on getPositionOfItemInList(theItem, theList)
    repeat with a from 1 to count of theList
        if item a of theList is theItem then return a
    end repeat
    return 0
end getPositionOfItemInList

You can add it in an idle statement and check every minute for your battery level.
Any suggestions or corrections will be appreciated.
Regards.


text:
Q: How to check if a specific file exists in directory or any of its subdirectories In C#, how do I check if a specific file exists in a directory or any of its subdirectories?
System.IO.File.Exists only seems to accept a single parameter with no  overloads to search subdirectories.
I can do it with LINQ and System.IO.Directory.GetFiles using the SearchOption.AllDirectories overload, but that seems a bit heavy handed.
var MyList = from f in Directory.GetFiles(tempScanStorage, "foo.txt", SearchOption.AllDirectories)
             where System.IO.Path.GetFileName(f).ToUpper().Contains(foo)
             select f;

foreach (var x in MyList)
{
    returnVal = x.ToString();
}

A: The alternative is to write the search function yourself, one of these should work:
private bool FileExists(string rootpath, string filename)
{
    if(File.Exists(Path.Combine(rootpath, filename)))
        return true;

    foreach(string subDir in Directory.GetDirectories(rootpath, "*", SearchOption.AllDirectories))
    {
        if(File.Exists(Path.Combine(subDir, filename)))
            return true;
    }

    return false;
}

private bool FileExistsRecursive(string rootPath, string filename)
{
    if(File.Exists(Path.Combine(rootPath, filename)))
        return true;

    foreach (string subDir in Directory.GetDirectories(rootPath))
    {
        if(FileExistsRecursive(subDir, filename))
            return true;
    }

    return false;
}

The first method still extracts all of the directory names and would be slower when there are many subdirs but the file is close to the top.
The second is recursive which would be slower in 'worst case' scenarios but faster when there are many nested subdirs but the file is in a top level dir.

A: If you're looking for a single specific filename, using *.* is indeed heavy handed. Try this:
var file = Directory.GetFiles(tempScanStorage, foo, SearchOption.AllDirectories)
                    .FirstOrDefault();
if (file == null)
{
    // Handle the file not being found
}
else
{
    // The file variable has the *first* occurrence of that filename
}

Note that this isn't quite what your current query does - because your current query would find "xbary.txt" if you foo was just bar. I don't know whether that's intentional or not.
If you want to know about multiple matches, you shouldn't use FirstOrDefault() of course. It's not clear exactly what you're trying to do, which makes it hard to give more concrete advice.
Note that in .NET 4 there's also Directory.EnumerateFiles which may or may not perform better for you. I highly doubt that it'll make a difference when you're searching for a specific file (instead of all files in the directory and subdirectories) but it's worth at least knowing about. EDIT: As noted in comments, it can make a difference if you don't have permission to see all the files in a directory.

A: To Check for file existing in any specific directory do the following
Note: "UploadedFiles" is name of the folder.
File.Exists(Server.MapPath("UploadedFiles/"))
Enjoy Coding

A: It is a recursive search on the filesystem. You have some functional examples in CodeProject:

*

*Simple File Search Class (by jabit)

*Scan directories using recursion using events (by Jan Schreuder)

A: This is a recursive search function that will break out as soon as finds the file you've specified. Please note the parameters should be specified as fileName (eg. testdb.bak) and directory (eg. c:\test).
Be aware that this can be quite slow if you do this in a directory with a large quantity of subdirecories and files.
private static bool CheckIfFileExists(string fileName, string directory) {
        var exists = false;
        var fileNameToCheck = Path.Combine(directory, fileName);
        if (Directory.Exists(directory)) {
            //check directory for file
            exists = Directory.GetFiles(directory).Any(x => x.Equals(fileNameToCheck, StringComparison.OrdinalIgnoreCase));

            //check subdirectories for file
            if (!exists) {
                foreach (var dir in Directory.GetDirectories(directory)) {
                    exists = CheckIfFileExists(fileName, dir);

                    if (exists) break;
                }
            }
        }
        return exists;
    }


text:
Q: Iteratively Reference Controls by Name Pattern (VB.NET) Is there a way to iteratively reference an ASP.NET control based on it's name pattern? Perhaps by a "pointer" or something?
What I have are a large set of comboboxes (each with an associated DropDownList and TextBox control). The DropDownList always has an item selected by default, but the use may wish to submit a NULL value. I come up with the following code to handle three cases: NULL, Existing Item, New Item.
'TextBoxControl & DropDownListControl should iteratively reference their
'  respective TextBox & DropDownList controls by the actual control name
If StrComp(TextBoxControl.Text, DropDownListControl.SelectedItem.ToString) = 0 Then
    'When an Existing Item is selected, Do Something
ElseIf Not TextBoxControl.Text = "" Then
    'When a New Item is entered, Validate & Do Something
Else
    'When NULL, Do Something
End If

The problem is, with so many comboboxes, I could easily end up with hundreds of lines of code. I wish to handle this in a more dynamic way, but I do not know if it is possible to reference controls in this way. Say I wanted to reference all the TextBox Controls and DropDownList Controls, respectively.
I can do string formatting with a given naming pattern to generate a name ID for any of the controls because they are all named with the same pattern. For example by attaching a specific suffix, say "_tb" for TextBox Controls and "_ddl" for DropDownList Controls:
Left(item.SelectedItem.ToString, item.SelectedItem.ToString.Length - 3) + "_tb"

Can this sort of thing be done in VB? Ultimately, my goal is to take the value entered/selected by the user, if any, and send it to a stored procedure on SQL Server for insertion into the database.

A: Yes. Write your code inside of a function having parameters for the textbox and the dropdown, and then write the function in terms of those two parameters. Then you simply call that function for every set instead of copy/pasting code everywhere.
Don't attempt choosing things by name. That's fragile and imposes machine requirements on a field that'd designed for human consumption.

A: I am not sure if the samething that applies VBA will apply to your situation, but I had the same issue and was able to use:
Me.MultiPage1.Pages(1).Controls("ref" & i + 1).Value
where controls encompasses all controls on the userform ("Me").  So if the controls in your program conform to a consecutive naming structure it is easy handle if the above applies vb.net


text:
Q: Submitting a pull request with a Visual Studio ? I'm studying art, but decided to take a course in programming. We were recently given a github URL, cloning it produced an empty folder(except .git). We were instructed to submit a solution to homework as pull requests on that project.
I don't want to mess up such a simple task, so I'd appreciate an advice on how to do the pull request. One of the things that bothers me are what parts of my folders and files do I need to include. I have folders like _ReSharper.Classes and packages (from NuGet), how do I handle those?

A: This is a good starting point for understanding Pull Requests:
http://help.github.com/send-pull-requests/
Basically on Github, hit the fork button:

This will create your own clone of the repository. Commit your code in the new repo (if you're completely clueless with git, check out a getting started guide like this).
When you're done, hit the Pull Request button:

Enter an explaination of your changes and submit.

A: As per Alex's answer, first you fork the github repo to create your own copy, though it is still on github.
Second you should clone that copy onto your own PC/laptop so that you can work on it.
Once you have the clone locally you should create yourself a branch to work in - this keeps the master branch available for reference.
Also use branches when trying new things so that you can keep the 'mistakes' separate from the good stuff before merging (often simply 'fast forwarding').
At suitable intervals push your repo back to github as a backup - check up on whether it is public (relative to any course restrictions)


text:
Q: How div can be removed according size screen? I know I can hide element using this css:
@media only screen and (max-height: 350px) {
    .sizeResponsive{
        display: none;
    }
}

but I need to remove element.
Any idea who can I remove div according to screen size using CSS?

A: You can't do this using CSS as it does not have the ability to affect the DOM. Only the way it is displayed can be affected.
Using jQuery, you could do $(window).height() or $(document).height() (or screen.height if you prefer to stick to plain javascript) to get the height.
Get the div by using either var el = $('div.sizeResponsive'); or var el = document.querySelector('div.sizeResponsive'); and remove it from the DOM like so: el.parentElement.removeChild(el);
In order to achieve the effect you are looking for with CSS, you would have to add an eventlistener like so:
// Usually it's a good idea to store your eventhandler in a variable so that you can dispose of it at a later time
var resizeHandler = function() {
    if (screen.height < 350) {
        var responsiveDivs = document.querySelectorAll('div.sizeResponsive');
        for (i = 0; i < responsiveDivs.length; i++) {
            responsiveDivs[i].parentElement.removeChild(responsiveDivs[i]);
        }
    }
}

document.onload(function() {
    window.addEventListener('resize', resizeHandler);
});

// When you no longer need it
window.removeEventListener('resize', resizeHandler);

The question remains though, why do you want to remove the element per se? Now you are losing these elements and you would have to add them again if the screen size goes back into your threshold which allows them to be displayed.
You could store the elements in variables and re-add them if the height gets within bounds again, but this seems unnecessarily complicated for a problem that the CSS property display: none; solves just fine.
EDIT:
Sometimes it's just fun to solve these little things anyway. Here's a codepen that does this without any jQuery, in case anyone's interesed: http://codepen.io/anon/pen/YWvxwQ

A: use javascript or jquery for this task
Calculate width of window using screen.width in javascript or $(window).width() in jquery and remove your desired elements according to screen width you got.

A: display:none will make it hidden and not affect the flow of the layout, however it will still be in the html source code, so it will load with the page and the browser will decide what to do with it. This means that an outdated browser may no understand display:none and show it anyway.
If you don't want it to load to a mobile version then it shouldn't be sent from the server. Or use js to add it after the page loads to a non-mobile browser. This could also eliminate outdated browsers from showing it.
Keep in mind that CSS is for style only, it does not have the ability to affect the DOM

A: I'm pretty sure that css can not manipulate DOM. So, there is no way to truly remove element.
display: none makes element hidden, so there is no space allocated for the element.
You can also consider using position: absolute, which removes element from the document flow, and setting height to 0.
There is an SO question with more details: How to remove an element from the flow of HTML/CSS?

A: You cannot remove an element using css alone, removing an element is very costly (more expensive than hiding it.) since the HTML needs to rebuild the DOM tree and the RENDER tree on each child removal.
I would suggest hiding it and disabling its javascript functionality through javascript.
window.addEventListener('resize', function() {
   if(window.innerHeight > 350) {
      ... // .style.display = 'none';
      ... // disable functionality.
   }
});


text:
Q: Append-only comments field from SP List not displaying in Infopath form I am trying to get a data connection set up in InfoPath to display the comments history in a multi-line text field with "Append Changes to Existing Text" option enabled. The field comes from a SharePoint Form Library which is what the form submits to (no problems there).
I was able to get a normal multi-line text field to display properly in the form with the same data connection, but when I turn on "Append Changes to Existing Text" nothing shows in the text area on the form.
I have read that this should be possible from sources such as this and this but have not been able to get it working myself. Can anyone provide a little more detail on setting this up? I am trying to avoid workarounds that involve recreating the functionality with custom columns but I will do that if there is no other option.
My environment is SharePoint Enterprise 2010 with InfoPath 2010. Considering I'm using a Form Library, could the problem be that this only works with normal lists?


text:
Q: Error from Entity Framework: Unable to update database to match the current model I'm new to Entity Framework in general, and just starting to work toward implementing migrations.
When I first set up my model classes and corresponding DbContext class, the class got an override of OnModelCreating, into which I put FluentAPI commands to set things like IsMaxLength and HasPrecision.
I have since created an InitialCreate migration that was given the name "201708081210041_InitialCreate".
Database (re)creation was not an issue before, but it is now.  If I leave all of that in place, and allow EF to create the database, I get this error message:

Unable to update database to match the current model because there are
  pending changes and automatic migration is disabled. Either write the
  pending model changes to a code-based migration or enable automatic
  migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to
  true to enable automatic migration.

While I have found references to this message in other Q&A, I don't understand it all well enough to make sense of the underlying problem that I have caused.
Some additional bits of information:

*

*If I comment out the code in OnModelCreating the error stops.

*No changes have been made to the model classes since InitialCreate
    was made.

*The database initializer is being set to MigrateDatabaseToLatestVersion.

*AutomaticMigrationsEnabled = false
Are these things incompatible?  Am I supposed to "save" those changes myself, somehow?  Should I avoid OnModelCreating now that I have turned on migrations?
UPDATE:
I was able to resolve this particular issue by eliminating the OnModelCreating code altogether.  To do so, I added all of its actions to the InitialCreate code.  I also learned that the previous model is stored in the resx of the migration (which you can only see by examining the XML directly, btw), which was also injecting some changes.  Apparently, there was a slight difference between that previous iteration, the OnModelCreating code, and the actual migration.  The whole thing seems very fragile to me.


text:
Q: woocommerce variation displaying all option even if it's not related to that variantion Hello,
I have 2 variation in woocommerce first is series and second is name like this:
Series :  and Name :

in Series two type of Series A and B
in Name lots of names
Series :     Name:
A            ANNN1,ANNN2,ANNN3
B            BMMM1,BMMM2,BMMM3

Like you can See A-Name is related to A series and B-Name to B series
But when see product page Name: variation shows all option
Even I choose Series A or B
ANNN1
ANNN2
ANNN3
BMMM1
BMMM2
BMMM3

So what I should I do to show specific Name to related that Series Like this
If I choose Series A
Series: A
Name: ANNN1
      ANNN2
      ANNN3

If I choose Series B
Series : B
Name :BMMM1
      BMMM2
      BMMM3

A: Check out this plugin and scroll down where it says "Set dependency between the options"
https://yithemes.com/themes/plugins/yith-woocommerce-product-add-ons/
You can even test out the features before buying by going on to this website http://plugins.yithemes.com/yith-woocommerce-product-add-ons/product/custom-post/ and using the top botton for launching admin demo


text:
Q: Highcharts how to customize enableMouseTracking? I am currently using highcharts to display data on a line chart. I have enabled the enableMouseTracking option in order to be able to see the value of the point the hovers over. I am attempting to add a % at the end of the value. For example, my current hover over is 4.4 I would like it to show 4.4%.
I've tried adding a percent sign to the end of values that I was using to populate the chart but that did not work so I believe I do now need to customize highchart itself. I do not see any of directly customizing the plotOptions section in the Highcharts documentation.
Currently displaying:

Would like to display: 1.8%
Highcharts.chart('container', {

    chart: {
        type: 'line',
        backgroundColor: '#fafafa',
    },
    title: {
        text: stateArr.graphTitle
    },
    xAxis: {
        categories: '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017','2018'],
        title: {
            text: 'Year'
        },
    },
    credits: {
        text: stateArr.creditTitle,
        position: {
            align: 'right',
            verticalAlign: 'bottom',
            x: -20,
            y: -20
        }
    },
    exporting: {
        enabled: false
    },
    yAxis: {
        //categories: ['2', '4', '6', '8', '10'],
        title: {
            text: 'Percentage Change (%)'

        }
    },
    plotOptions: {
        line: {
            dataLabels: {
                enabled: false
            },
            enableMouseTracking: true
        }
    },

series: [{
    name: stateArr.stateTitle,
    data: [...stRounded],
    color: '#002F65',
    custom: {
        state: stateArr.stateTitle
    },
}, {
    name: 'US',
    color: '#0B7070',
        data: [...usRounded],

    dashStyle: "DashDot",

        }],
});

A: You can build your own tooltip with the use of tooltip.formatter.
 tooltip: {
      borderColor: '#2c3e50',
      shared: true,
      formatter: function (tooltip) {
        //u can make your custom tooltip here
        return `<span >${this.y} <br> ${this.x}%</span><br/>`
      }
    },

this is one example demo about custome tooltip


text:
Q: How do I stop excel from automatically adding an "@" to the beginning of my formula? I have a project in which I need to use VBA to create a formula that links cells together. The line of code I am using to do this is:
wb1.Sheets("Sheet2").Range("A1").Formula = "=[File Name]Sheet1!D100:D120

When I use that line of code, I get a value error and the formula bar of cell A1 looks like this:
"=@[File Name]Sheet1!D2900:2902"

Removing the "@" gets rid of the error and the formula works fine.
I would love some help in making it so that excel doesn't automatically insert the @ sign when I run the code. Thanks!


text:
Q: List styling next to floating element Take a look at my example, second list style is totally off because it's next to floating element (unless you add inline-block style).
The problem is that I have no way of knowing when the it's next to floating element and it has to work without it like normal (i.e has to be block).
How to fix the second list styling?

It's rich text editor content, I can't wrap image and second list into div and use flexbox or something else, it has to flow naturally.
Edit: even browser is confused - if you press "Run" enough times, bulletins sometimes appear next to text and sometimes above the image on left.

.wrapper {
  padding: 20px;
  border: 2px dashed #ec6161;
}

.wrapper::after {
  content: "";
  clear: both;
  display: table;
}

ul {
  /* display: inline-block; */
}

img {
  margin-right: 20px;
  max-width: 50%;
  float: left;
}

Item 1

Subitem 1

Subitem 2

Item 2

Item 1

Subitem 1

Subitem 2

Item 2

A: You need to clear the floats. use clear:both to UL.
Here is the updated fiddle:

.wrapper {
  padding: 20px;
  border: 2px dashed #ec6161;
}

.wrapper::after {
  content: "";
  clear: both;
  display: table;
}

ul {
  /* display: inline-block; */
  clear:both;
}

img {
  margin-right: 20px;
  max-width: 50%;
  float: left;
}

Item 1

Subitem 1

Subitem 2

Item 2

Item 1

Subitem 1

Subitem 2

Item 2


text:
Q: My rtf documents suddenly reverted to 'Read only' documents. My rtf documents suddenly reverted to 'Read only' documents. When I saved them as Word documents, they were still 'Read only'.  How can I solve the problem?

A: *

*Right click on the file.

*Click properties on the menu that appears.

*Click the General tab, clear the Read-only check box, and then click OK.


text:
Q: Rkhunter reports openssl warning I have installed and configured rkhunter on Centos and I have no warning except
Checking version of OpenSSL                              [ Warning ]
when I check log file I see that I need to update openssl
root@server [~]#  openssl version -a
OpenSSL 1.0.1e-fips 11 Feb 2013
built on: Mon Jun 15 18:29:40 UTC 2015
platform: linux-x86_64
options:  bn(64,64) md2(int) rc4(16x,int) des(idx,cisc,16,int) idea(int) blowfish(idx)
compiler: gcc -fPIC -DOPENSSL_PIC -DZLIB -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -DKRB5_MIT -m64 -DL_ENDIAN -DTERMIO -Wall -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -Wa,--noexecstack -DPURIFY -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM
OPENSSLDIR: "/etc/pki/tls"
engines:  dynamic

I have tried to update openssl with yum openssl update but, it says it is up to date
root@server [~]# rpm -q --changelog openssl | grep CVE-2014-0224
- fix CVE-2014-0224 fix that broke EAP-FAST session resumption support
- fix CVE-2014-0224 - SSL/TLS MITM vulnerability

Please tell me what to do to fix this warning

A: RedHat/CentOS doesn't take complete new versions of packages like OpenSSL into older releases, they "backport" only security fixes; see https://access.redhat.com/security/updates/backporting .
Note the "build" date in version -a is much newer than the OpenSSL release date for 1.0.1e. And if you look at the version in the rpm name with rpm -q you should see openssl-1.0.1e-30.el6 -- the "-30" indicates the backports added to what started as upstream 1.0.1e.
If you just need a secure version, you've got it. If you want the current possibly incompatible version, you can build from upstream source; see https://stackoverflow.com/questions/22952287/how-to-upgrade-openssl-in-centos-6-5-linux-unix-from-source . Basically it's like most opensource projects: tar zx && ./config [opts] && make && make test && make install; see the INSTALL file and/or the Configure script (at top dir of the extract) for details.

A: I had this in the past too on RedHat with version 1.0.0. Had the latest version according to RedHat. You can either ignore this message or add APP_WHITELIST="openssl:1.0.0" so that rkhunter accepts this version and does not print the warning.


text:
Q: Draggable div property is not working in IE I have created a draggable DIV by code-

Age

The DIV is working fine in Firfox, Crome, but not working in IE, Opera.
Is there any other way to create a draggable DIV that works in all browsers?
Thanks,
EDITED

Can anyone provede me the solution with jQuery?

A: As you have asked for jquery solution :-
Add these two JS files in your page :-

HTML:-

Drag me around

JS:-
  $(function() {
        $( "#draggable" ).draggable({
            drag: function(event, ui) {}
        });
    });

See the Fiddle :-
and it is working in IE7 too.


text:
Q: How to customize picker page selection I have a standard picker in a list, customized in dark colors.
When I tap on the picker, it opens the page with the choices, but the background is white, and I would like it to be black.
Didn't succeed to find the appropriate settings :(
Thanks for your help
My code :
import SwiftUI
let choices = ["red", "blue", "yellow"]

struct test4: View {

    @State private var myColor: String = choices[0]

    var body: some View {
        VStack {
            List {
                Picker(selection: $myColor, label: Text("Type")) {
                    ForEach(choices, id: \.self) { col in
                        Text(col).foregroundColor(Color.gray)
                    }
                }
                .listRowBackground(Color.row)
            }
        }
        .background(Color.black)
    }
}

Page with the picker

Picker selection

A: Use instead preferred color scheme, like
    VStack {
       // List here ...
    }
    //.background(Color.black)
    .preferredColorScheme(.dark)    // << use this !!


text:
Q: continued fraction of $\sqrt 3$ I'm trying to prove that $\sqrt 3 = [1;2,1,2,1,\ldots]$
I have found the recursive relation $$\sqrt 3 +1= 2+\frac{2}{\sqrt 3 +1}$$
and it's quite close to a continued fraction, but the problem is that the numerators here are $2$'s and not $1$'s.

A: Just apply Gauss' iteration until you find a loop. The integer part of $\sqrt{3}$ is $1$ and
$$ \frac{1}{\sqrt{3}-1}=\frac{\sqrt{3}+1}{2}=1+\frac{\sqrt{3}-1}{2}=1+\frac{1}{\frac{2}{\sqrt{3}-1}}=1+\frac{1}{\sqrt{3}+1}=1+\frac{1}{2+(\sqrt{3}-1)}$$
hence $\sqrt{3}=[1;\overline{1,2}]$.


text:
Q: Code is not working when i am trying to edit the API URL by data entered in form and fetch data from API Hello everyone as I am beginner in nodejs and expressjs, I am trying to fetch data according to the value entered in the form. And according to the value URL will be edited and send request and get data and show it to page. I wrote the code but it is not working.
Index.ejs
    <form action="/index" method="POST">
        <label for="name">Enter json/xml: </label>
        <input type="text" name="name">
        &nbsp&nbsp&nbsp&nbsp&nbsp<button type="submit">Submit</button>
    </form>

app.js
    var express = require('express');
    var app = express();
    var request = require('request');
    var bodyParser = require('body-parser');

    app.set('view engine', 'ejs');

    var urlencoderparser = bodyParser.urlencoded({ extended : true });

    app.get('/', function(req, res){
        res.render('index');
    });

    app.post('/', urlencoderparser, function(req, res){
        res.render('form-data', {data : req.body});
        request.post({
        "headers": { "content-type": "application/json" },
        "url": "http://mysafeinfo.com/api/data?list=englishmonarchs&format="+req.body.name,
        }, (error, response, body) => {
            if(error) {
                return console.log(error);
            }
            data = JSON.parse(body);
        });
        console.log(req.body);
    });

Please help me to find the solution

A: I think you have a problem with bodyParser.
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

Add these just after app.set('view engine', 'ejs');
And your post function should be like this
     app.post('/', function(req, res){
     request('http://mysafeinfo.com/api/data?list=englishmonarchs&format='+req.body.name, function (error, response, body) {
     var data = JSON.parse(body);
     console.log(req.body);
    });
    });

And make sure that in the form in your index file you should have <input type="text" name="name">
Because you are using as req.body.name

A: app.use(express.urlencoded({
  extended: true
}));

app.post('/index', function(req, res){
        res.render('form-data', {data : req.body});
        request.post({
        "headers": { "content-type": "application/json" },
        "url": "http://mysafeinfo.com/api/data?list=englishmonarchs&format="+req.body.name,
        }, (error, response, body) => {
            if(error) {
                return console.log(error);
            }
            data = JSON.parse(body);
        });
        console.log(req.body);
    });


text:
Q: Undeletable element in CKEditor I'm wondering if there's a way to make an element 'undeletable' in CKEditor 4.
I might have some HTML like so:

...

In this case .gallery shouldn't be able to be deleted from .content, either by backspacing or selecting and pressing delete.
UPDATE: It seems widgets can not be undeletable, or at least from what I can tell.
Take a look at http://ckeditor.com/demo#widgets, the widgets can be deleted. Any other ideas?
Thanks

A: What you are looking for are widgets. They will be implemented in CKEditor 4.3 and provide this kind of features. Be patient ;)
At the moment there's only placeholder plugin that does "similar" thing, but I guess this is not enough for you.

A: I use a workaround to make widgets undeletable. In the widget definition, I added this to the init property:
    init: function () {
        this.on('key', function(e) {
            let k = e.data.keyCode;
            // Backspace, delete, ctrl+x
            if ([8, 46, 1114200].includes(k)) { e.cancel() }
        })
    }

It will prevent the user from deleting the widget using the keyboard. The "cut" function needs to be disabled too.


text:
Q: Unable to see in the console in deno logger I have written a very simple Typescript class. But I am unable to see the loggers in the console. I want to know what I am doing wrong. I referred to the following link.
https://deno.land/std/log
import * as log from "https://deno.land/std/log/mod.ts";

export class Test1 {

    public show() {
        log.debug("Hello world");
        log.info("Hello world");
        log.warning("Hello world");
        log.error("Hello world");
        log.critical("500 Internal server error");
        console.log("Hello ....")
    }

}

const test = new Test1();
test.show();

Please suggest me in this case. I am learning deno.

A: There's a bug in the default logger, the setup happens asynchronously, so you have to wait until it's been set up correctly.
For now, a workaround is to wait until the next tick
import * as log from "https://deno.land/std/log/mod.ts";

await new Promise((resolve) => setTimeout(resolve, 0));

export class Test1 {
  /* ... */
}

Or setup your own logger:
import * as log from "https://deno.land/std/log/mod.ts";

await log.setup({
  handlers: {
    console: new log.handlers.ConsoleHandler("DEBUG"),
  },
  loggers: {
    // configure default logger available via short-hand methods above
    default: {
      level: "DEBUG",
      handlers: ["console"],
    }
  },
});

const logger = log.getLogger()

export class Test1 {

    public show() {
        logger.debug("Hello world");
        logger.info("Hello world");
        logger.warning("Hello world");
        logger.error("Hello world");
        logger.critical("500 Internal server error");
        console.log("Hello ....")
    }

}

const test = new Test1();
test.show();

Update: I've submitted a PR for this, and hopefully soon it will work as expected.
2nd Update: The PR was merged and it will be released on std/0.52.0.


text:
Q: JQuery POSTing data after getting the response I have some code, posting data from "my_form" to server with JQuery $post every 3 seconds.
Everything works fine, but sometimes maybe because of slow Internet connection the response doesn't come in 3 seconds, when cycle triggers.
This makes an error. Of course, I can increase the delay from 3 seconds to 6 and more, but it slows down the process.
How can I change the code to post data only after getting the response?
$(document).ready(function() {
    $("#my_form").submit(function() {
        document.forms["my_form"]["submit"].disabled="true";
        counter=0;
        var post_data = function() {
            $.post("formProcessor.php", $("#my_form").serialize(),
            function(data) {
                $("#formResponse").html(data);
                txt = $("#formResponse").text();
                ...
                //some code analyzing response
                ...
                if (counter == 50){
                    clearInterval(nre);
                    return false;
                };
                changeFields(counter);
            }
        );
    };
    var nre=setInterval(post_data,3000);
    return false;
});
});

A: I would do something like in code below. Pretty simple. Just additional variable requestFinished which is set to true if request is done .
    var requestFinished = true;
$(document).ready(function() {
    $("#my_form").submit(function() {
        document.forms["my_form"]["submit"].disabled="true";
        counter=0;
        var post_data = function() {
            if(requestFinished) {
                requestFinished = false;
                $.post("formProcessor.php", $("#my_form").serialize(),
                    function(data) {
                        requestFinished = true;
                        $("#formResponse").html(data);
                        txt = $("#formResponse").text();
                        ...
                        //some code analyzing response
                        ...
                        if (counter == 50){
                            clearInterval(nre);
                            return false;
                        };
                        changeFields(counter);
                    }
                );
            }
    };
    var nre=setInterval(post_data,3000);
    return false;
});
});


text:
Q: $(y-\sqrt{x})(y-\sqrt{-x})=0$ $(y-x)(y+x)=0$ is a graph that combines $y-x=0$ and $y+x=0$.
I understood that by multiplication 2 functions (or more) that in the form of $a=0$ and $b=0$, so $a\cdot b=0$ will be the 2 functions. (Please explain it to me more, and why it happens).
So my question is why: $(y-\sqrt{x})(y-\sqrt{-x})=0$ is not a graph that includes $y=\sqrt{x}$ and $y=\sqrt{-x}$
How can I  get to a $y$ and $x$ form which will give me a graph that includes $y=\sqrt{x}$ and $y=\sqrt{-x}$ ?

*Help me wil the correct tags
Thanks

A: I'm only guessing what you want: Probably, you want to graph the $f:[0, \infty) \to \mathbb{R}$ and $g:(-\infty,0] \to \mathbb{R}$ of the functions $f(x) = \sqrt{x}$ and $g(x) = \sqrt{-x}$. To define a function that kind of "graphs" both functions, you can define
$$ h : \mathbb{R} \to \mathbb{R}, \ h(x) = \begin{cases} \sqrt{x} \quad &\text{ if } x \geq 0, \\ \sqrt{-x} &\text{ if } x <0. \end{cases} $$

A: Because$\sqrt x$ and $\sqrt{-x}$ are not both real numbers except for $0$. You can use $y=\sqrt{|x|}$


text:
Q: Regex number filtering from textarea I have been looking for way how I could filter data within textarea using regex function for a quite a while now without any success. Below is the regex I want to use to filter UK telephone numbers.
(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?

Fiddle: https://jsfiddle.net/qdypo04y/
I want to achieve the result when the button is clicked it will remove lines which do not meet the regex? Alternatively would remove values which are not UK telephone numbers.
Any guidance would be appreciated.

A: Apart the use of textarea element your issue is:

*

*how attach click event listener to your button (refer to: querySelector and addEventListener)

*how get the content of textarea and split it into rows (refer to: textContent plus split and join)

*finally how use your regex: refer to test
An example is:

document.querySelector('button').addEventListener('click', function(e) {
    var txtArea = document.querySelector('textarea[rows="4"][cols="50"]');
    var re = /(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?/;
    var txtArr = txtArea.textContent.split('\n');
    txtArr.forEach(function(ele, idx) {
        txtArr[idx] = ele + '  test result is: ' + re.test(ele);
    });
    txtArea.textContent = txtArr.join('\n');
});
<textarea rows="4" cols="50">
+447222555555
0800 042 0213
2017/07/14
2017/07/17
2017/07/27
</textarea>
<button>Click me</button>

A: <script>
function myFunction() {
    var regexp = /(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?/;
    var content=$.trim($("textarea").val()).split('\n');
    var result="";
    for(var i = 0;i < content.length;i++){
        if(regexp.test(content[i])){
            result=result+content[i]+'\n';
        }
    }
    $("textarea").val(result);
}

</script>

used JQuery to take the value from textarea


text:
Q: VIM - How to select a substring I have the following line, that has no spaces -

123456789abcdefghij01234123456780900dfasdfsadfsadfsa

I want to select (highlight for yanking) 10 characters, starting at column 10.
I can navigate to column 10 by :10| but then how would I visually select ten characters starting under the cursor?

A: 10|v9l

(without the colon) moves the cursor to column 10, enters visual mode and expands the selection 9 characters to the right, ready to yank.


text:
Q: How to check if a service is installed and to start the service if installed else if install and start a service in chef for windows How to check if a service is installed and to start the service if installed else if install and start a service in chef for windows
if service "VigilEntAgent"
 supports :status => false then
 package 'VigilEntAgent' do
source 'xxx'
 action :install
end
else
 service "VigilEntAgent" do
 action :start
end

A: You can check, if the windows service installed with
::Win32::Service.exists?( '<service_name>' )

But if you use package resource to install service, most probably you just need to provide a right name for the package resource. The one you see in Control Panel\All Control Panel Items\Programs and Features. Chef will check it the package already installed and will not try to install it again.

A: Chef is made to be idempotent, what you should do is:
package 'VigilEntAgent' do
  source 'xxx'
  action :install
end

windows_service "VigilEntAgent"
  action :start
end

The service name has to match the service short name in windows service manager, the one you would use with NET START to start it from the command line IIRC.
The windows_service resource is available since chef 12.
Documentation of resources is here: https://docs.chef.io/resources.html


text:
Q: Existence of a map via universal property? Let $X$ be a topological space and $A,B$ be subspaces of $X.$ Let $C \subseteq A \cap B.$ Let $f : A \longrightarrow B$ be a map. Then does it necessarily induce a map $\widetilde {f} : A/C \longrightarrow B/C\ $? If not, then what are the criterions the map $f$ should satisfy to induce the map $\widetilde f\ $?
EDIT $:$ I think if $f$ maps $C$ homeomorphically onto $C$ then we can have such maps by universal property of quotient topology. In fact then the map will be one-one and onto.

A: We have the canonical quotient maps $\pi_A:  A\to A/C$ and $\pi_B :B\to B/C$. From $f$ we get a map $\pi_B\circ f : A\to B/C$. This induces a map $A/C\to B/C$ if, and only if, $\pi_B\circ f$ is constant on $C$. We see that this is the case if, and only if, one of the following holds :

*

*$f|_C$ is constant ;

or

*$f(C) \subset C$


text:
Q: Implementing LDAP with Public IP I'd like to implement an LDAP using FreeIPA for centralized authentication and for security sake (Kerberos).
The problem is my servers (Ubuntu) running as public cloud with no private interface provided.
So, my only choice is using public but I'm not sure is this a nice idea to implement with public IP for both server and clients.
Apart from that, I'm worrying about external services. How can external services access to the REALM?.
also wondering about users, We have two types of users

*

*external users with various public IP

*external users that using one public IP but using NAT to assign private IP

I have little experience with LDAP and that was implement only on private.
Please share you suggestion. I'm really appreciated.

A: Yes, you can allow access to Kerberos and LDAP directly over the internet. Carefully.
Kerberos was designed to run over untrusted networks.
Only run LDAP over TLS; disable unencrypted service. Limit what an anonymous user can query. Check how sensitive data in LDAP is, would there be a compliance or legal problem if some PII leaked?
Knowing a user's IP addresses by itself is not authentication. (Although the trustworthiness of IP addresses can be useful as threat intelligence.) Auth is implemented with strong cryptography in these applications.
As these services will be provided via internet, make an effort to secure it. Harden the services, do not run anything else on this host. Monitor, review failed logins and firewall hits to get an idea of how many probes take a try. Consider consulting with a red team to try a mock attack on your defenses.

NATs are no fun. Consider implementing IPv6, offering dual stack like internet services should be.
Easier to allow list large contiguous IPv6 net blocks, if you wish to do so. The space is so large it is infeasible to brute force scan, less noise due to slightly more work for attackers to find you. And it reinforces that NAT is not security, change a firewall rule and your directory is no longer accessible from the internet, despite having a "public" IP address.


text:
Q: Should You Use an Else Statement if All Other Branches Return? I am currently working with Java, though this question is relevant for other languages as well. If ALL  "if" and "else if" branches return or throw an exception, should you still use an else statement? Here's an oversimplified example of accessing the index of a linked list with a head pointer:
public Node getIndex(int index){
    //Make sure it's a non-negative index
    if(index < 0) {
        throw new IndexOutOfBoundsException();
    }
    //Index 0 is the head, no need to iterate
    else if(index == 0) {
        return head;
    }
    //Option A
    else {
        //Use a for loop to iterate to the element inside the else statement
    }
    //Option B
    //Use a for loop to iterate to the element outside of the if/else block
}

This portion of code would function exactly the same with option A or option B since index <= 0 would always throw or return before reaching it. Functionally, I don't believe it's necessary to have the else statement here. Are there any agreed upon standards for this or is it a personal preference? My intuition says to remove the "else" statement in these situations.

A: I think having the else is confusing, because it is sending mixed signals: when I see the else I think there must be some path in the if statement that doesn't return that I need to look out for. Also I think it is easier to read code that isn't deeply nested.
Here is a quote from a site that tries to list standards and good practices,   http://www.javapractices.com/topic/TopicAction.do?Id=114:

Some programmers find that, occasionally, some methods become clearer if multiple return statements are used, instead of the usual single point of exit.
This technique can be easily abused, and should be used with care. It's mainly used to replace nested if structures.
Multiple return statements seem to work well for "guard code" at the beginning of a method, in which the main body of the method is executed only if certain conditions are satisfied.

Here is some of the example code on that page:
public final class Automobile {

  @Override public boolean equals(Object aThat) {
    if (this == aThat) return true;
    if (!(aThat instanceof Automobile)) return false;
    Automobile that = (Automobile)aThat;
    for(int i = 0; i < this.getSigFields().length; ++i){
      if (!Objects.equals(this.getSigFields()[i], that.getSigFields()[i])){
        return false;
      }
    }
    return true;
  }

There isn't any particular claim to authority here though. And you will find people who really don't like methods that have more than one return statement.

A: It's a matter of taste. Write whatever looks clearer in any given case. There's no need to do the same thing in every situation.
Sometimes the if-then-else chain helps to make it visually clear that you're choosing one alternative, even if some of those alternatives are 'return' and therefore the 'else' is not technically needed.
Sometimes, if it's a matter of handling the fast cases first and getting out quickly, it looks better to not do the 'else'.
if (wrong args)
    throw new WobblyException();
else if (trivial case)
    return trivial answer;
else
    … complicated stuff …

versus
if (wrong args)
    throw new WobblyException();
if (trivial case)
    return trivial answer;
… complicated stuff …

In your example, both of these are reasonable.  Don't sweat it.
The only thing I'd suggest is all of the elses or none of the elses.  Don't mix.  So your example B is not so good, because it keeps the first possible 'else' but not the second one.
The bottom line is, good programming is a matter of taste, and not about following fixed rules, especially not when the rules are called "best practice".


text:
Q: Jmeter :- ArrayList Handling in Parameters tab Case: Select 100 records and mark them verified.
Steps:

*

*Getting 25-100 records based on IDs via JSON extractor.

*Posting verified on 25-100 records selected.

Actual Result: (Getting 500 Error)

Expected Result: (How it is working in application)

How can I handle the above case?

A: Your format is not correct, you need to send the data like:

The request body can be generated dynamically using JSR223 PreProcessor and some Groovy scripting, check out HTTPSamplerBase.addArgument() function for more details.


text:
Q: What's the best way to organize components database? Thinking of building a local components database which maps company part number to multiple manufacturers.  Assume SQL type thinking.
Option 1.  One table with company part numbers as primary key, fields with component values, names of symbols, and footprints.  Another table with company part numbers as primary key, and fields with manufacturer and manufacturer part numbers.  A join on company part number is performed to get multiple manufacturer part numbers per company part number.  Advantage is simplicity.  Disadvantage is I don't get a list of components and their values for each manufacturer which would be nice, and I need to explicitly maintain the second table which does the mapping, which could have mistakes.
Option 2.  First table same as above.  A different table for each manufacturer with all their components and values.  Join on values.  Advantage is mapping between company part number and manufacturer part number is automatic based on values and I don't have to curate the mapping. Also it would be nice to have a separate list of components from each manufacturer.  Disadvantage is sometimes you want to exclude components based on rohs or something else, so that's a new field in both tables.  Instead of curating an explicit mapping, which could be arbitrary (for better or worse), I now need to curate fields across multiple tables and make sure each manufacturer table has the same schema.
Which is best?

A: There may be a lot of web sites with info on MRP II RDBMS on SQL for EMS.  Only you can decide how to create each database for efficiency so that you don't have just 2 or 3 tables. Each edit to a field is updated live and you want to consider Rev control of each data base for sanity and effectiveness.  Each user will have different needs. Purchasing, Board design, BOM design, Manufacturing , Quality and Accounting.  Each set of fields should be indexed or keyed according to use and relation to each other for optimal size , speed and avoid redundancy or putting everything into compartmentalized or Departmentalized tables.

Knowing how much you can support and design of each database parameter, type and size from the start is critical. Start with a spec of all user needs, reports, parameters, frequency of use and then design the tables. Then rank Must Haves and Nice to Haves.

Here is an example of one page of one report of my Master Registry which did not include PCB design parameters. It was for Commodity Code 15 on connectors, showing description, Stock on Hand (SOH) and Bin Location.  This Report used only 3 tables. Some fields could be unique and others blank.

personal anecdotes
I also did the above from '94 to '96 in Foxbase, when I was Ops Mgr for an R&D firm that could make rapid prototypes.  The relationships of RDB table was done graphically with independent index and key fields with parameter attributes for each field.
The Master Registry was a book of all in-house Engineering Part numbers,  which used commodity codes, and clear concise descriptions.  It was a lot of work, but necessary.
e.g. Don't use SCR as the 1st descriptive word if you also have SCR screws use hierarchical key words.  Choose as many Tables as needed with at least one relational index, usually, but not always the part number.
The Master Registry was used in all BOM's, my stockrooms,  Purchasing for RFQ's and PO's so we could send all the unique part numbers to distributors with matching commodity codes, or Mfg by a unique list per source and put the supplier price cost, qty values into another indexed database for doing Costed BOM quotes.
The products were micro/RF modules for automated meter reading and 2-way network telemetry.
There were dozens of reports which included a paper binder of all the in-house part numbers organized by commodity code with abut 10k part numbers and typically 2 to 4 approved vendors for each part.
Standardized reports for; Costed Boms, design selection, Stock bin location, daily BOM pick lists for proto assembly with organized trays with array numbered 35mm film container for each SMD part on cut strips (hand soldered.) etc etc.
I did a lot of work the database structure, but then got a genious Comp Science grad student working for us to help me out on all Foxbase reports in evenings.
At that time Design was done on MAC's with PC's for PO's as it was faster with big spreadsheets for Quote merging.  Accounting was separate on Great Plains.  It worked although clumbsy at times but much easier and cheaper than any MRP II system I reviewed or had used in the past.
We had 25 Hardware Design Eng. 25 S/W designers and I had 5 in production, 1 in purchasing 1 in Quality and I ordered all the PCB's quick turn and occasionally designed custom Test Jigs.

A: There is no single "best".  It depends on your requirements, what software you use, what the capabilities of your existing software are, etc.
I use Eagle to design boards, and long ago created my own system around Eagle for generating BOMs.  Cadsoft later brought out some ULPs and the like for the same purpose but that work differently.  Since mine work, and quite nicely at that, I continue to use my existing software.
In Eagle, I use attributes on parts for defining things like manufacturers, their part number, suppliers, their part numbers, values, description string for the BOM, etc.  This by itself works fine except for dealing with in-house part numbers for multiple different customers.
To do that, I have a series of CSV files stored in a place known to the BOM software.  These files relate the part information in Eagle to in-house part numbers.  The entries can also be set up to use the same stocked part for different purposes, and then group the result on a single BOM line.
Here is the header line common to these CSV files:

Desc,Value,Package,Subst,Inhouse Acme,Manuf,Manuf part #,Supplier,Supp part #

Note the "Inhouse Acme" field.  This sample file is for the Acme customer, and that field gives the in-house part number for Acme.  I keep one CSV file per customer.
Each directory in a tree where I keep Eagle files can have a "housename" file.  The lowest down the tree to a particular leaf node of such files provides the house name.  This is how my system automatically handles multiple customers, each with their own part numbering scheme.
The BOM software has the data specified for each part in Eagle, and looks for matches in this file.  Matches can be by value or definitive.  For example, if two parts have the same manufacturer and manufacturer part number, then they are the same part definitively.  Otherwise, if the description, value, and package match, then the part matches by value.
Here is a snippet of such a file:

"Capacitor, unpolarized",22pF,SMD-0805,Yes,9133053,,,,
"Capacitor, unpolarized",47pF,SMD-0805,Yes,9133052,,,,
"Capacitor, unpolarized",100pF,SMD-0805,Yes,9133055,,,,
"Capacitor, unpolarized",200pF,SMD-0805,Yes,9133056,,,,
"Capacitor, unpolarized",1nF,SMD-0805,Yes,9133058,,,,
"Capacitor, unpolarized",10nF,SMD-0805,Yes,9133061,,,Mouser,81-GRM40X103K50D
"Capacitor, unpolarized",100nF,SMD-0805,Yes,9133049,,,,

These are a bunch of 0805 capacitors that only differ in capacitance.  The capacitance value is added to the base part in the schematic, and has to be entered the same as here for it to match.  If a match is found to any of the above, the in-house part number is known.  For example, such a cap given a value of "1nF" in the schematic will pick up in-house part number 9133058.
Another useful thing my software does is collapse all uses of the same in-house part.  Here is another snippet from the Acme file:

"Capacitor, unpolarized",1uF 10V,SMD-0805,Yes,9133054,,,,
"Capacitor, unpolarized",1uF 25V,SMD-0805,Yes,9133054,,,,
"Capacitor, unpolarized",1uF 35V,SMD-0805,Yes,9133054,,,,
"Capacitor, unpolarized",1uF 50V,SMD-0805,Yes,9133054,,,,
"Capacitor, ceramic",1uF 50V 10% -55+100C,SMD-0805,Yes,9133054,,,,

Note that these are all 1 µF 50 V capacitors in 0805 surface mount package.  Acme has decided to only stock 50 V parts, then use those even when lower voltage parts would do.  That's a very legitimate stocking strategy, especially for cheap parts like these.
However, I still want to show on the schematic that only a 10 V part is needed.  In that case, the 10 V part description matches the first line, and part number 9133054 is assigned.  Since the next line has the same in-house part number, it matches that line too, and the description is updated to "1uF 25V".  This continues until it gets to the bottom line shown, where the description is updated to "1uF 50V 10% -55+100C".  That's what ends up on the BOM for any of the capacitors listed.  The schematic might show a "1uF 10V" cap in one place and a "1uF 35V" cap in another, but they both get lumped on the same BOM line as "1uF 50V 10% -55+100C" for this customer only.
If Acme ever decides to stock 1 µF 35 V parts, this section of the file would be updated.  When the BOM is re-run, the 10-35 V parts would be on one BOM line and the 50 V parts on another.
When I use a new part they don't stock, it shows up on the BOM with the in-house part number blank.  Someone then assigns a part number, feeds that back to me, and I update the file.  After that, my BOM system automatically fills in the in-house number for that part for subsequent designs or BOM runs.
This may sound complicated, but it's really been very nice to use.

A: I'd do it with three tables...
1. Supplier <- lists supplier info
    Lists contact info, address etc.

2. Supplier_Parts linked to Supplier_ID, includes field Company_Part_ID

   Which parts are available from which suppliers, and supplier catalog #

3. Company_Parts listed by Company_Part_ID

   Company_Part_NO and with tech info of parts, anything company specific about that part

The rest you can do with queries.

A: None of the above. But Option 1 is less worse than Option 2.
I pick door number 3
Use a company part numbering system that contains the values of the component it identifies.
Not knowing you company inventory that's about all I an offer.
Back in 2006 I developed an inventory system with meaningful part numbers.  A single table contained both parts that were used to build the products and also the products and sub-assemblies as well.
If you had a part number just by the part number you would know it was an 0603 1K 1% resistor
A part could not be entered without all the required values for a part of that type.

A: You might want to take a look at BOMIST: https://bomist.com
It's a parts inventory and BOM manager software for electronics. It runs locally, no server nor setup or cloud needed. And it's integrated with Octopart, meaning you get pretty usefull real-time info about your parts (think getting real time availability and quotations when ordering parts).
DISCLAIMER: BOMIST's developer here.


text:
Q: MFC how to get CString from another Class to CRegSettings class I have a problem about save Edit text to registy.
I did in main class save to registy text data and i did another registry class that call
CRegSettings  so this class doing enum each time when i clicked button like
MyItem\0, MyItem\1.
my problem is i cant get that CString text into this CRegSettings  class, this class doesnt have DoDataExchange so when i did it somehow its turn to error "CMySettingsItem::DoDataExchange' : recursive on all control paths" so it's doesnt work and i cant get CString from main class to this class, does anyone know how to do it ? Thanks.
Here is my codes.
Main.cpp
// CNewConnectionDlg dialog

IMPLEMENT_DYNAMIC(CNewConnectionDlg, CDialog)

CNewConnectionDlg::CNewConnectionDlg(CWnd* pParent /*=NULL*/)
: CDialog(CNewConnectionDlg::IDD, pParent)
    , m_csIp(_T("localhost"))
    , m_csPort(_T("22"))
    , m_csUsername(_T("Username"))
    , m_csPassword(_T("Password"))

{

}

class CMySettingsItem : public CRegSettings
{
public:
    DWORD Id;

    CString m_Password;
    CString Password;

    BEGIN_REG_MAP(CMySettingsItem)
        REG_ITEM(Id, 1)
        REG_ITEM(Password, m_Password)
    END_REG_MAP()
protected:
    virtual void DoDataExchange(CDataExchange* pDX);

};

// Sample application configuration
class CMySettings : public CRegSettings
{
public:

    DWORD RootId; // DWORD option
    CString RootName; // String option
    std::string FullName;

    // list of options (CMySettingsItem)
    CSimpleArray<CMySettingsItem> Profile;  // ATL CSimpleArray
    //std::list<CMySettingsItem> ProfileList;   // STL list

    CMySettingsItem SubItem; // Subitem test

    BEGIN_REG_MAP(CMySettings)
        REG_ITEM(RootId, 1)
        REG_ITEM(RootName, "Profile")
        REG_ITEM_STL(FullName, "Profile")
        REG_ITEM_SIMPLE_ARRAY(Profile)
        //REG_ITEM_LIST(ProfileList)
    END_REG_MAP()
};

void CMySettingsItem::DoDataExchange(CDataExchange* pDX)
{
    CMySettingsItem::DoDataExchange(pDX);

    DDX_Text(pDX, IDC_PASSWORD, m_Password);

}

CNewConnectionDlg::~CNewConnectionDlg()
{
    AfxGetApp()->WriteProfileString("Settings", "UserName", m_csUsername);
    AfxGetApp()->WriteProfileString("Settings", "IP",       m_csIp);
    AfxGetApp()->WriteProfileString("Settings", "Port",     m_csPort);
    AfxGetApp()->WriteProfileString("Settings", "Password", m_csPassword);

    CMySettings configuration(HKEY_CURRENT_USER, "Software\\MyItem\\Item");

    // Load configuration
    if(configuration.Load() != ERROR_SUCCESS)
        printf("failed to load\n");

    // Use loaded configuration
    configuration.RootId++;

    CMySettingsItem item;
    item.Id = configuration.RootId;

    configuration.Profile.Add(item); // CSimpleArray
    //configuration.ProfileList.push_back(item); // list

    // Save new configuration
    if(configuration.Save() != ERROR_SUCCESS)
        printf("failed to save\n");

}

void CNewConnectionDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);

    DDX_Text(pDX, IDC_IP, m_csIp);
    DDV_MaxChars(pDX, m_csIp, 255);

    DDX_Text(pDX, IDC_PORT, m_csPort);
    DDV_MaxChars(pDX, m_csPort, 6);

    DDX_Text(pDX, IDC_USERNAME, m_csUsername);
    DDV_MaxChars(pDX, m_csUsername, 20);

    DDX_Text(pDX, IDC_PASSWORD, m_csPassword);
    DDV_MaxChars(pDX, m_csPassword, 255);

}

BEGIN_MESSAGE_MAP(CNewConnectionDlg, CDialog)
    ON_EN_CHANGE(IDC_PASSWORD, &CNewConnectionDlg::OnEnChangePassword)
    ON_EN_CHANGE(IDC_USERNAME, &CNewConnectionDlg::OnEnChangeUsername)
END_MESSAGE_MAP()

void CNewConnectionDlg::OnEnChangePassword()
{

}

void CNewConnectionDlg::OnEnChangeUsername()
{

}

And Header
Main.h
#pragma once
#include "InnerDlg.h"
#include <afxtempl.h>

class CNewConnectionDlg : public CDialog
{
    DECLARE_DYNAMIC(CNewConnectionDlg)

public:
    CNewConnectionDlg(CWnd* pParent = NULL);   // standard constructor
    virtual ~CNewConnectionDlg();

     CNewConnectionDlg(const CString sSection, const CString sArrayName);

    // Dialog Data
    enum { IDD = IDD_NEWCONNECTION };

public:
    virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

protected:
    DECLARE_MESSAGE_MAP()
public:

    // The server ip or name
    CString m_csIp;

    // The negotiating port on the server
    CString m_csPort;

    // Username for the server
    CString m_csUsername;

    // Password for the server
    CString m_csPassword;

    afx_msg void OnEnChangePassword();
    afx_msg void OnEnChangeUsername();

};

A: DoDataExchange is only intended for user interface classes, such as your CDialog-based class. It is used to connect the user interface elements on screen with the member variables of that object. So your data is sitting in the m_csIp, m_csPort, m_csUsername, and m_csPassword members. You just need to assign it to the relevant member of your CMySettingsItem instance.
For example:
item.m_Password = m_csPassword;


text:
Q: For loop creates error when recursivley permutating strings in C I am new to C and am trying to write a function that returns the all the permutations of a subset of size k of a string using recursion.  For example, for the string 'abc' and k = 1, I would get 'a', 'b' and 'c', for k = 2 I would get 'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb' and 'cc', and so on.
I want to return all the generated strings so that I can do other things with them - right now it just prints them out, but I will use them later.  I wrote this code:
#include <stdio.h>
#include <string.h>

#define CHARS "abc"

char *recur(char* prefix, int k, int n);

int main(void)
{
    int k = 2; //for example
    int n = strlen(CHARS); //set n as length of CHARS
    //print string generated by recur
    printf("string: %s\n", recur("", k, n));
}

char *recur(char *prefix, int k, int n)
{
    //if base case (have already added all letters), return string
    if (k == 0)
    {
        return prefix;
    }
    //otherwise, add character from CHARS to string
    else
    {
        for (int i = 0; i < n; i++)
        {
            // for each letter in CHARS, make a new prefix and add a letter from chars to it
            int prefLen = strlen(prefix);
            char newPrefix[prefLen + 2];
            strcpy(newPrefix, prefix);
            newPrefix[prefLen] = CHARS[i];
            newPrefix[prefLen + 1] = '\0';
            return recur(newPrefix, k-1, n);
        }
    }
}

However, I get the error 'recur1.c:40:1: error: control may reach end of non-void function
      [-Werror,-Wreturn-type]' when trying to compile.
To explore this a bit further, I removed the for loop which results in a reversed string:
char *recur(char *prefix, int k, int n)
{
    //if base case (have already added all letters), return string
    if (k == 0)
    {
        return prefix;
    }
    //otherwise, add character from CHARS to string
    else
    {
        //make a new array called newPrefix, copy current prefix into it and add new letter from CHARS
        int prefLen = strlen(prefix);
        char newPrefix[prefLen + 2];
        strcpy(newPrefix, prefix);
        newPrefix[prefLen] = CHARS[k-1];
        newPrefix[prefLen + 1] = '\0';
        return recur(newPrefix, k-1, n);
    }
}

After substitution of this second function, the code compiles without any issues.  Any ideas as to why the version with a for loop won't compile?

A: If n <= 0, then the for loop will never be entered, and so the return statement in the loop body will never be reached. Since there's no return statement after the loop, the compiler complains (rightly so).
That said : are you sure it's not a mistake to have an unconditional return  statement inside the loop body ? That makes the loop quite useless.

A: If i < n is 0 when for (int i = 0; i < n; i++) is encountered then program control does not enter the for loop body, and a return statement is not reached. Should the return statement really be in the for loop body?
If that happens, the behaviour of the whole program is undefined. Your compiler is warning you of that, and you have elevated warnings to fail program compilation.
Worse than that, newPrefix has automatic storage duration. You are returning a pointer to it, and that pointer is invalid in the function caller. That's more undefined behaviour.