text:
Q: Excel Sumifs Index Match returning only value Trying to use a combination of SUMIFS, INDEX and MATCH but the formula only returns a value from the first column and ignores subsequent columns which share the same field.  What formula can I use to overcome this issue please?
         A          B   C   D   E   F
1   Name           Week1    Week1   Week2   Week2   Year
2   CustomerA   10  20  30  40  2019
3   CustomerB   50  60  70  80  2019
4   CustomerA   90  100 110 120 2018
5   CustomerB   130 140 150 160 2018

I have to get the Week 1 Total for Customer A in 2019.
I tried using this formula:
=SUMIFS(INDEX(B:E,0,MATCH("Week1",B1:E1,0)), A:A,"CustomerA", F:F, "2019")

The formula however, only returns $10 for Customer A in Week 1 in 2019 instead of $30 ($10 from Cell B2 + $20 from cell C2).  This means it matches the Week 1 field in column B and ignores the Week 1 field in column C.
What amendment do I need to make to the formula to overcome this problem please?
Thanks.

A: That method will only work if the values are unique, as it will only return the first column where a match is found.
You will need SUMPRODUCT:
=SUMPRODUCT(($B$1:$E$1="Week1")*($A$2:$A$5 = "CustomerA")*($F$2:$F$5 = 2019)*($B$2:$E$5))


text:
Q: join 2 files and print each line even if they don't match I'm sure this is super simple but I can't think of a way to do it.
I have File1 and File2 (below) and I need to join based off the letter in the alphabet, but also print out the lines that have no match.
File1:
a james
b mike
c joe
d john
e nick
f chris

File 2
a 10 20 30 40
b 11 12 13 14
d 20 30 40 50
f 15 16 17 18

I want the output file to say
a james 10 20 30 40
b mike 11 12 13 14
c joe
d john 20 30 40 50
e nick
f chris 15 16 17 18

I'm supposed to use one line only. I tried:
join file1 file2 > file3

but that didn't print the lines that don't have a match.

A: If you do join -a1 file1 file2 > file3 that will work because it makes it a left outer join. join on its own is an inner join.

redpajama_set_name: RedPajamaStackExchange


text:
Q: django logout redirects me to administration page I have provided a simple login functionality. For logout, I tried to use the built-in one. This is my urls.py:
(r'', include('django.contrib.auth.urls')),

And this is my template file:
{% if user.is_authenticated %}
logged in as {{ user }}
(logout)
{% else %}

I have also enabled the default django admin site. When I click logout, it shows me the administration logout view. How can I pass the logout next page attribute to tell django which view to render?

A: If you are seeing the log out page of the Django administration site instead of your own log out page (your_application/templates/registration/logged_out.html), check the INSTALLED_APPS setting of your project and make sure that django.contrib.admin comes after 'your_application'. Both templates are located in the same relative path and the Django template loader will use the first one it finds.

A: You can put LOGOUT_REDIRECT_URL in your settings.py file with a url name to redirect to, e.g. LOGOUT_REDIRECT_URL = 'index'

A: This is all fairly well explained in the manual, is there anything specific you don't understand?
https://docs.djangoproject.com/en/dev/topics/auth/default/#how-to-log-a-user-out
from django.contrib.auth import logout

def logout_view(request):
    logout(request)
    # Redirect to a success page.

Alternatively if you don't want to create your own view
https://docs.djangoproject.com/en/dev/topics/auth/default/#django.contrib.auth.views.logout
{% url 'logout' next='/some/url/' %}

A: i was experiencing the same isssue following Django by example... found this url worked for me
url(r'^logout/$', 'django.contrib.auth.views.logout', { 'template_name': 'account/logout.html',}, name='logout' ),

A: Go to settings.py and add this code. "/" will redirect you to home
# Where to redirect during authentication
LOGIN_REDIRECT_URL = "/" #To go to home after login instead of getting redirected to accounts/profile on login which is default
LOGOUT_REDIRECT_URL = "/" #To logout back to the home page instead of the default admin logout page

A: Summary of the most common solutions:
Make sure that your_app comes before django.contrib.admin in your INSTALLED_APPS list in your settings.py file.
Also make sure that your log out page is called 'logged_out.html' as pointed out in the answers above. Mine was called logout.html and didn't work.

A: Tested on Django 1.6:
What I do is adding this into my urls.py:
(r'^management/logout/$', 'django.contrib.auth.views.logout'),

And then used it:
Log out

For the next argument, there you point to the right URL.
Tested on Django 2.1
Append to urlpatterns in urls.py:
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]

And then use it in the template:
logout

More info can be found here.

A: I'm surprised no one has mentioned this, you can put this in your settings.py to redirect when logging in and logging out:
LOGIN_REDIRECT_URL = '/go-here-after-login/'
LOGOUT_REDIRECT_URL = '/go-here-after-logout/'

A: According to docs, you can supply the next_page parameter to the logout view.
https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.views.logout
(r'^logout/$', 'django.contrib.auth.views.logout',
    {'next_page': '/logged_out/'})

A: The easiest solution is:

*

*Make sure your app comes before django.contrib.admin under installed apps in settings.py.

*Make sure your template is called logged_out.html.

A: You can give the template to be rendered also in the href tag
{% if user.is_authenticated %}

  logged in as {{ user }}
  (logout)

{% else %}
  ...
{% endif %}

if you use the default values in settings.py. Works for Django 3.1.

A: Make sure you added the following to your settings.py file:
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
It tells Django to redirect you to whatever page you want to go to after logging in or out.

A: Just replace loaders here, and auth templates will be found in "your_progect_apps/templates/registration":
TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'templates')],
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
        'loaders': [
            'django.template.loaders.filesystem.Loader',
            'django.template.loaders.app_directories.Loader',
        ],
    },
},

]
Django v2.1


text:
Q: RewriteRule : How can i handle my url I need Rewrite code for my .httaccess file where i can froward my url to specific folder default page.
LIKE if the following url not found:

www.domain.com/abc/23/121/     >>>  www.domain.com/abc/default.php

OR

www.domain.com/xyz/23/121/     >>>  www.domain.com/xyz/default.php

What ever first folder, it will redirect to its folder default file.
How can I forward URL by .httaccess to any error handler file?

www.domain.com/xyz/23/121/

when this url not found.. It will take compeler url as query string to 404.php
Like :

404.php?url=www.domain.com/xyz/23/121/

A: Try this in Root/.htaccess :
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)/?$ /404.php?url=$1 [R,QSA,L]


text:
Q: Creating a generic / abstract "DBContext" Class for shared functionality among different DBs I am working on a C# project that is pulling data from SQL Server, ODBC data-sources and Oracle Databases at different times.
At this point, I have created 3 different classes - Once for each type of DB access. However, I am seeing that 95% of the code is identical between each of the libraries - The main difference being in creating the Connection and Command objects.
As a VERY simple example of what's in the classes, here could be an example:
public class Oracle
{
    static DataTable exec_DT(string query, string conn_str)
    {
        DataTable retVal = new DataTable();

        using (OracleConnection conn = new OracleConnection(conn_str))
            using (OracleCommand cmd = new OracleCommand(query, conn))
            {
                conn.Open();
                using (OracleDataReader rdr = cmd.ExecuteReader())
                {
                    retVal.Load(rdr);
                    rdr.Close();
                }
            }

        return retVal;
    }
}

and
public class SQLServer
{
    static DataTable exec_DT(string query, string conn_str)
    {
        DataTable retVal = new DataTable();

        using (SqlConnection conn = new SqlConnection(conn_str))
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
            conn.Open();
            using (SqlDataReader rdr = cmd.ExecuteReader())
            {
                retVal.Load(rdr);
                rdr.Close();
            }
        }

        return retVal;
    }
}

Basically, I need to get the same kind of return data frmo each of my databases and the methods to do so are near-identical, the difference being the Connection and Command-type objects.
Now, when I look at both connection objects, I see that they both inherit from DbConnection:
public sealed class SqlConnection : DbConnection, ICloneable

public sealed class OracleConnection : DbConnection, ICloneable

But I still can't think of a good way to create a generic / abstract parent class that can stop the need for this kind of code duplication as the DBConnection / DBCommand classes are abstract and, when I try something along the following lines:
using (DbConnection conn = new DbConnection(conn_str))
using (DbCommand cmd = new DbCommand(query, conn))

I get errors such as Cannot create an instance of the abstract class or interface 'System.Data.Common.DbCommand'
I'm very much a newbie and any help / sample code / links to ways this has been done well in the past would really be greatly appreciated!
THANKS!!!

A: The key here is to step back and think about the problem from another angle. You are duplicating lots of code because you are creating instances of the database and command classes within the method. So inject them instead:
public class SomeDBClass
{
    static DataTable exec_DT(DBConnection conn, DBCommand cmd)
    {
        DataTable retVal = new DataTable();
        conn.Open();
        using (SqlDataReader rdr = cmd.ExecuteReader())
        {
            retVal.Load(rdr);
            rdr.Close();
        }
        return retVal;
    }
}

This approach has the added value that you can then test exec_DT without the need for either SQLServer or Oracle, by creating mock DBConnection and DBCommand that you then inject into your test cases.

A: I like David's answer. In the alternative, if you do still want to be creating connections and commands from within your shared code, what you could do is pass a DbProviderFactory instance to the constructor of your "DB Context" class.
You can then call e.g. CreateCommand, CreateConnection or whatever else you need to create, within each method.

A: The DbProviderFactory class does exactly what you're looking for.
static DataTable exec_DT(string query, string conn_str)
{
    DataTable retVal = new DataTable();

    using (DbConnection conn = MyDbProvider.CreateConnection())
    {
        conn.ConnectionString = conn_str;

        using (DbCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = query;
            conn.Open();

            using (DbDataReader rdr = cmd.ExecuteReader())
            {
                retVal.Load(rdr);
                rdr.Close();
            }
        }
    }

    return retVal;
}

You can even use the DbProviderFactories class to create a factory instance from the connection string in the config file.
DbProviderFactories.GetFactory(WebConfigurationManager
    .ConnectionStrings[name].ProviderName);


text:
Q: Iphone - > Copying images from bundle to documents folder takes TOO long whem my app starts for the first time I need to copy some ( arround 300-400 images ) to the documents folder. What I see is that it takes tool long (even thought now Im testing only with just 30-40 images). At the begining my app crashed when running on the phone (not on simulator) because it took too long to run. Now I'm running the method that copies all files on a thread. The app stays up, but I think that ios kill that thread after a few seconds. Should I have each image copy on a new thread???
My code is like this: (this is the part that runs in the thread)
-(void) moveInitialImagesFromBundleToDocuments {
//move all images.

    NSMutableArray *images = [MyParser getAllImagesList];
    for (int i = 0 ; i< [images count] ; i++) {
        [self copyFileFromBundleToDocuments:[images objectAtIndex:i]];
    }
}

- (void) copyFileFromBundleToDocuments: (NSString *) fileName {

    NSString *documentsDirectory = [applicationContext getDocumentsDirectory];
    NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
    NSString *destinationPath = [documentsDirectory stringByAppendingPathComponent:fileName];
    NSLog(@"Source Path: %@\n Documents Path: %@ \n Destination Path: %@", sourcePath, documentsDirectory, destinationPath);

    NSError *error = nil;

    [self removeFileFromPath:destinationPath];

    [[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destinationPath error:&error];

    NSLog(@"File %@ copied", fileName);
    NSLog(@"Error description-%@ \n", [error localizedDescription]);
    NSLog(@"Error reason-%@", [error localizedFailureReason]);
}

Any suggestions? First to make copying faster and second, should I make a new thread for each file I copy?

Comment 1:
This looks nice. But I would like to dim the application so the user will not be able to use the appication untill all images are loaded.
I run this methods under . It does stop the user from being able to run the application, but I think that on the phone , the thread is beeing killed because when I tried it , it took too long loading. Never stopped actualluy.
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = @"preparing...";
hud.dimBackground = YES;
hud.square = YES;
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
    // Do something...

    FileUtil *fileut = [[FileUtil alloc] init];
    [fileut moveInitialImagesFromBundleToDocuments];

    //Done something

    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    });
});

A: When calling the method, I suggest you to use GCD to move this to a background thread, so you could call the whole for cycle like this. (I also changed a little bit your for cycle to make it simple.
-(void) moveInitialImagesFromBundleToDocuments
{
//move all images and use GCD to do it

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    NSMutableArray *images = [MyParser getAllImagesList];
        for (id image in images) {
            [self copyFileFromBundleToDocuments:image];
        }
    });
}

Regarding to make the copying faster, I don't know of any solution.


text:
Q: Explain how the FFREE instruction works http://en.wikipedia.org/wiki/X86_instruction_listings
how does the ffree instruction excatly works ?
    FFREE   Free register
when i have in FPU STack:
  st2 5 , st1 2, st0 7

then after these instruction(ffree) i have..
   st 1 5, st0 2

is that right?

A: No, it clears the register without modifying the stack pointer. Whatever register you gave as an argument will be set as empty, but the others will be unchanged.
http://www.website.masmforum.com/tutorials/fptute/fpuchap3.htm#ffree


text:
Q: Ubuntu 20.04 doesn't detect all RAM free -m
total used free shared buff/cache available
Mem:           7953        3334        1265          61        3353        4262
Swap:          6047           0        6047

sudo lshw -c memory
*-firmware
       description: BIOS
       vendor: American Megatrends Inc.
       physical id: 0
       version: 4022
       date: 08/08/2018
       size: 64KiB
       capacity: 16MiB
       capabilities: pci apm upgrade shadowing cdboot bootselect socketedrom edd int13floppy1200 int13floppy720 int13floppy2880 int5printscreen int9keyboard int14serial int17printer acpi usb biosbootspecification uefi
  *-memory
       description: System Memory
       physical id: 23
       slot: System board or motherboard
       size: 16GiB
     *-bank:0
          description: DIMM DDR4 Synchronous Unbuffered (Unregistered) 2400 MHz (0.4 ns)
          product: KHX2400C15/8G
          vendor: Kingston
          physical id: 0
          serial: ED3FC90A
          slot: DIMM_A1
          size: 8GiB
          width: 64 bits
          clock: 2400MHz (0.4ns)
     *-bank:1
          description: DIMM DDR4 Synchronous Unbuffered (Unregistered) 2400 MHz (0.4 ns)
          product: KHX2400C15/8G
          vendor: Kingston
          physical id: 1
          serial: ECBA5B02
          slot: DIMM_B1
          size: 8GiB
          width: 64 bits
          clock: 2400MHz (0.4ns)

sudo dmidecode -s bios-version
4022

I started with 8GB RAM on my computer. Then I installed an extra 8GB module but Ubuntu didn't recognize total RAM as 16GB, but still 8GB. The strange thing is that when I enter the BIOS it recognizes both 8gb modules(DIM_A1 and DIM_A2 slots) but in total RAM it still 8gb.
Also from first command it shows 8gb RAM, but second one it is showing both modules (16gb)...
Motherboard : Asus Prime A320m-K
CPU : AMD Ryzen 5 2600

A: BIOS
Asus Prime A320m-K
You have BIOS 4022 from 9/7/2018.
There's a newer BIOS available, version 5602, dated 7/27/2020, and it can be downloaded from here.
Note: Confirm that I have the correct web page for your motherboard.
Note: Have good backups before updating the BIOS.
Memory
AMD Ryzen 5 2600
Ryzen processors are notorious for memory compatibility issues.
We need to test your RAM, but we do it after the BIOS update.
Go to https://www.memtest86.com/ and download/run their free memtest to test your memory. Get at least one complete pass of all the 4/4 tests to confirm good memory. This may take many hours to complete.
CPU Support: https://www.asus.com/us/Motherboards/PRIME-A320M-K/HelpDesk_CPU/
Memory Support: https://www.asus.com/us/Motherboards/PRIME-A320M-K/HelpDesk_QVL/


text:
Q: Why is my React component rendering my JSX as text rather than HTML? Please forgive me as I am a complete noob to JavaScript and React. I am trying to output a list of friends. props.friends is an array consisting of the friends' names. However, my code just outputs the
 tags as text on the page
My code:
const Friends = (props) => {
    return(

Hello, {props.name}.

Below is a list of your friends:

                {props.friends.map(x => '
' + x + '
')}

    )
}

If anyone can please help me to figure why this is not rendering an actual list, and is just showing
friend1

friend2

friend3
 as text, it would be greatly appreciated. Thank you!

A: Your
.map(x => '
' + x + '
')

creates an array of strings, not React elements. If you want to render elements, you need to use JSX syntax.
.map(x =>
{x}
)


text:
Q: 406 Not Acceptable with POST Today one of the script of web-application stop working giving 406 "Not Acceptable. An appropriate representation of the requested resource could not be found on this server.". There is POST-request sending via AJAX by jQuery to another PHP-script. Nothing was changed in code by our side. What the most interesting, I copy the whole web-app in subfolder test and it works: in site.com it doesn't work, but in site.com/test it works pretty well.
App based on shared hosting. Where I should look to solve?


text:
Q: Why shouldn't I use default java security manager Part of my project need to allow participant upload simple and very basic java code and I will run their code and return the result for them. I reduce the security risk by limiting the permission of web user account, using thread to control time out case, and use security manager to sandbox entrusted program.
Since I do not know much about what kind of request may cause unexpected danger, I decided to use default policy. But most of people are talking about using a custom policy.
I have searched a lot but I still did not find any website/literature/tutorial which talk about why shouldn't I use default security manager. Is there any bugs that can be avoid by using a custom policy while exist in default one?
I mean, is it because the default policy is too strict or useless, such that people tend to use custom policy.
I have read the java.security, but I still want to make sure of this.

A: Minimum rights must be authorized, and not the "reasonable defaults".
This depends the details of your project. These details define permissions you give to the customer code. The list of possible permissions is huge, and knowing what are you doing you can probably tune it more tightly. At least, you should look into the default policy file and think that could be additionally disabled.


text:
Q: Is there a safe way to cache and resize remote images with PHP? I am working on an RSS reader using SimplePie.
I want to pull in RSS feeds and display articles with thumbnails. I am using RSS Enclosures and will later parse RSS <items> for <img>'s.
Is there a safe way to download these remote images to my server so I can cache them and resize them?
I have some ideas about how it can be done with cURL for instance, but I'm interested in security. I know I can restrict by file extension and I could probably look at the MIME type, but I just want to know if this is at all feasible/safe. If so, what steps should be taken to ensure there are no vulnerabilities.

A: Resize Images With gd or imagemagick
or you can do it in this way Check out the following Link

A: Posible security issues:

*

*Execution of remote script. Somehow you download a php script instead of an image and server executes it on later call to this image.

Solution: in any web server you can configure upload directory so, that no script can be executed there. And don't forget to add proper extetion to images (better to select from list, do not trust mime-types).

*

*XSS on client reading RSS. You download an image. But it ocures to be a javascript.

Solution: make sure you insert link to this imgae in <img src"..."> tag. Script would not be executed from img tag. Moreover, resizing image through GD or Imagic will certanly spoil any js inside, if there was one.


text:
Q: Pandas "type of " I am writing a program using data from the Olympics.
The question being asked is:

Which country has won the most gold medals in summer games?

The answer is:

the USA

These are some of the variables and data points for reference:
# Summer  Gold  Silver  Bronze  Total medals
United Arab Emirates 8  1   0   0   1
United States   26  976 757 666 2399
Uruguay 20  2   2   6   10

The function below should return a single string value but instead it is returning a pandas Data Frame
def answer_one():
    return df.loc[df['Gold'] == df['Gold'].max()]

How can I correct this function?

A: Do this instead:
def answer_one():
    return list(df.loc[df['Gold'] == df['Gold'].max()].index)

That should give you a list of countries with max golds if there are ties. If there are no ties, it will just give a list containing one entry: in your case, the result will be ['US'].

A: If Country name is your index column this should do the trick:
df.loc[df['Gold'].idxmax()]

A: you can try this. It worked to me
df.Gold.idxmax()
Cheers

A: def answer_one():
    return df[df['Gold'] == df['Gold'].max()].index[0]


text:
Q: DOM element computed style font size too small I'm getting the font-size of a span within the DOM using the following two approaches in JavaScript code:
const element = document.querySelector('h2 span');
const fontSizeObj = element.computedStyleMap().get('font-size');
const fontSizeStr = window.getComputedStyle(element, null).getPropertyValue('font-size');

This code is getting the same value using two approaches. The first call (fontSizeObj) effectively returns the following:
{value: 25.600000381469727, unit: "px"}

While the second call (fontSizeStr) returns the following:
"25.6px"

These values are consistent; which is good.
There is no direct CSS styling on the span, but there is direct styling on the parent h2 through a stylesheet, as follows: font-size: 5rem;
Looking in the (Chrome) console at the computed font-size of the span I see that it is:
80px

This console value is considerably different from the values returned above. This console value also corresponds with the viewed/rendered size of the text in the browser.
If I set the value of the element font-size to either of the returned values then the displayed text size shrinks dramatically, obviously.
So, how do I get the actual computed font-size of the text in the span?
Thanks, in advance.

A: Okay, here's the thing… In trawling around the Internet I recall reading somewhere that the changes to the styling can happen asynchronously with respect to the thread from which you're observing the state.
So, I placed this piece of code into the mix:
setTimeout(() => {
  console.log(element.computedStyleMap().get('font-size'));
}, 0);

And now I'm getting the expected value for the font-sze as 80px.
I can work with that…
Problem solved.

A: You can use window.getComputedStyle in order to calculate the font size of the span.
 let spanEl = document.getElementsByTagName("span");

 console.log(window.getComputedStyle(spanEl[0]).fontSize)

hope it helps ...


text:
Q: Mercurial from Subversion: moves, renames and tags I have a subversion repo with the following layout:
svnrepo/projectA/trunk
svnrepo/projectA/tags
svnrepo/projectA/branches
svnrepo/projectB/trunk
svnrepo/projectB/tags
svnrepo/projectB/branches

which I would like to move to a mercurial repo with a revised layout:
hgrepo/projectA
hgrepo/projectB
What is the best way of doing this?  Some of my thoughts are:
Option1
Rearrange the paths in subversion (using svn move) to an intermediate format:
svnrepo/trunk/projectA
svnrepo/trunk/projectB
svnrepo/tags/projectA
svnrepo/tags/projectB
svnrepo/branches/projectA
svnrepo/branches/projectB

then hg convert on the svnrepo/trunk. Will this confuse hg importing?
Option 2
hg convert each of the projects/trunk into separate hg repos. Then merge them into a single hg repo (using hg init, hg pull -f projectA, etc).  I think this will lose the branch names and tags on the first imported project.

A: In Mercurial, storing unrelated codebases in the same repository is a bad idea because it will

*

*Significantly complicate merging. Merges will depend on changes made to all projects, rather than just the project you're trying to merge.

*Cause storage and checkout overhead -- Mercurial, as far as I know, does not support checking out only subdirectories of a repository. You'd have to branch all projects at once.

The solution is to convert your single Subversion repository into multiple Mercurial repositories. Most conversion tools support this.

A: Each project should be in its own Hg repository (to be able to get or tag only a specific project).
Remember than the directory you see in Subversion (trunk, tags, branches) will not exist in any modern (D)VCS, where branches and tags are first class citizen (i.e. meta-data directly managed by the tool), as opposed as simple directory resulting from a cheap copy (in SVN).
That means when you convert a SVN repository, you should not store directly any "trunk", "tags" or "branches" directory in the history of the Hg repo.
You should rather use a tool like hgsubversion to import your SVN repo (like just "repo/projectA") into a Hg repo dedicated to the projectA. it will keep tags and branches of the orignal SVN project and convert them into Hg objects.
From its documentation:

All updates using hgpullsvn are made in the branch named from the last component of the SVN URL (e.g., if the SVN URL is svn://server/myproj/branches/feature-ZZZ, hgpullsvn will create and use the named branch 'feature-ZZZ')

If you do not want "convert" but "syncing", tonfa recommend hgsubversion, although it "is currently in a state of flux due to heavy refactoring":

Right now it is not ready for production use. You should only be using this if you're ready to hack on it, and go diving into the internals of Mercurial and/or Subversion.

Since hgsvn also allow some syncing through hgpushsvn and hgpullsvn... I would stick with hgsvn for now.


text:
Q: Gltf file exported via GLTFExporter is grey color I exported a glft file on this demo page.
And then, I imported the file to Blender but 3d model looks grey color and seems missing color.
How to solve this problem?
Or doesn't glft have color data?
I'm new to glft and Blender, I'd appreciate if you share any solutions or references what I should read to solve it.

A: When debugging something like this, the first step is to narrow down the source of the issue. If the model appears correctly on viewers like http://gltf-viewer.donmccurdy.com/ or https://sandbox.babylonjs.com/, then the exporter is probably doing its part correctly. If not, file a bug on the threejs repo about the exporter.
If the Blender importer you're using can't load the file, I'd suggest filing a bug on that repository instead. I'd also suggest trying https://github.com/KhronosGroup/glTF-Blender-IO, if you haven't already.
Finally, note that by default when Blender opens, textures are disabled in the viewport. You have to enable Texture, Material, or Rendered in the Viewport Shading menu:


text:
Q: Error in PushNotification from iPhone Device I am trying to do a sample project on the Apple the push notification. I created an AppID, done some terminal commands, and finally got a Provisional Certificate for do the same.
I got the certificate installed on my device and SDK. Till now every thing goes fine. But when i try to run the app on the device.... it doesnt. It throws an error stating "Error from debugger:Error launching remote program:security policy error."
Can any one help me to overcome this.
Please Help needed.
thanks in advance
Shibin

A: Faced this problem before. Here is what solved the problem for me.
You should give it a try :
http://isagoksu.com/2009/development/iphone/how-to-get-rid-of-security-policy-error/


text:
Q: How to reliably install and setup Quick test framework on Xcode 8? Background:
While working on this answer I noticed that it's not so trivial to properly set up Quick test framework on Xcode properly. In my case, it took 3-4 failed attempts to finally have a working version. And still, I'm not sure where my previous attempts were wrong. Or more importantly why the questioner in that thread could have duplicate run each time. Then it also took him several attempts to finally have a working one.
Question:
I am asking if any of you have a reliable way to set up Quick Framework on Xcode using Cocoa pods (or Carthage or Git Submodule), up to running a properly working Quick test case, that you're willing to share.
How I did it before:
Here is how I created my working Quick framework on Xcode:
1. I follow the step in XCTest article in RayWenderlich site to set up XCTest environment.
2. Then I add the Cocoa Pods as per  installing Quick
3. Then follow instruction in Setting up your Xcode
4. Then I hacked and improvise all the rest of the way, googling for each issue I encounter after that, try this and that until it works.   (Among those steps include add Quick framework to link binary in build phase of my target)
I'm not proud to share my steps above, but I don't have a better way for now.  I hope to find a better way by asking this question. It might be too much to ask.
My Podfile :
target 'PlayQuick' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!

# Pods for PlayQuick

target 'PlayQuickTests' do
    inherit! :search_paths
    # Pods for testing
    pod 'Quick'
    pod 'Nimble'
end

end

A: Integrating Quick & Nimble via cocoapods works for me out of the box with no problems (macOS Sierra, Xcode8.3.2, iOS 10.3 SDK, Swift 3.1, cocoapods 1.2.1).
Be sure to have the latest stable cocoapods version installed (gem update cocoapods) and to call pod install and not just pod update. You can also try to reintegrate your pods from scratch by calling pod deintegrate && pod install.
Maybe there is an odd build setting or something similar in your project. You could validate this with a virgin test project.
If nothing seems to work, you should upload your project (e.g. to GitHub) so the community will be able to pinpoint the problem.

A: Git submodule way is the most lean and simple way to achieve that.
Follow the these steps to start from zero:
1.a. Create Xcode project with Include Unit Tests checked.
1.b. Alternatively, you could create unit test target on existing project.

*

*Open test Navigator.

*Click the + button in the lower-left corner, then select New Unit Test Target… from the menu:

2. Close the Xcode project in (1)

3. Create new Xcode workspace. File -> New -> Workspace.

4. Open Terminal / Bash Shell / Cmd.exe

5. Create a new sub directory for GitHubProjectClones.

*

*for example: $HOME/Developer/GitHubProjectClones

6. cd to sub directory in (5):

*

*mkdir Vendor

*git init

7. Follow step one in Git Submodule section

*

*git submodule add git@github.com:Quick/Quick.git Vendor/Quick

*git submodule add git@github.com:Quick/Nimble.git Vendor/Nimble

*git submodule update --init --recursive

8. Follow step two in Git Submodule section.

*

*Back to Xcode with Workspace open:

*

*Make sure Project Navigator is selected

*

*File -> Add files to:

*

*select the Quick folder created in step 7.

*File -> Add files to:

*

*select the Nimble folder created in step 7.

*File -> Add files to:

*

*select your Xcode project in step 1.

9. Follow step three in Git Submodule section to link Quick.framework and Nimble.framework during your test target's Link Binary with Library build phase.

10. You should be able to follow along the examples in Quick Documentation

A: Follow the steps to reliable setup of Quick and Nimble:
Prerequisites:
cocoapods installed in your machine (installation Guide)
1) create a new Xcode project
Xcode—> File —> New —> Project
2)  Select Single View App (Normally most of the application use this) —>Next

*

*Enter Product Name (App NAme) - (here we are using WeatherForecast)

*enable check mark for Include Unit Tests
3 )Installation
Open terminal
Move to your working directory cd (path of your project folder)
Ex: enter in terminal
 cd /Users/Documents/ WeatherForecast
4) Initialise pods with
Pod init

5) Open the newly created Podfile within your favourite text editor.
edit podfile with below contents
platform :ios, '9.0'

target WeatherForecast' do

  use_frameworks!

  # Pods for WeatherForecast

  target 'WeatherForecastTests' do

    inherit! :search_paths

    # Pods for testing

    pod 'Quick'

    pod 'Nimble'

  end

5) Save the podfile.Return to terminal and
enter pod install in terminal
6) This will install your new frameworks and create a pods project. It will also generate a workspace. You should now use the new workspace when working on your project. So if you've opened your project already close it and in open the WeatherForecasr.xcworkspace instead.
7) Setting up your test class
Within your tests target create a new group and file by:
 Highlighting WeatherForecast Tests.
File —>New—> Group
Rename the new Group ModelTests
Highlight your new group
File —>New —> File
Select Swift file, Press Next

*

*Name the new file CurrentSpecs . Press create

7) Within your new file replace the contents with the following
import Foundation

import Quick

import Nimble

@testable import WeatherForecast

class CurrentWeatherSpecs: QuickSpec {

}

*After this you might face an error
"No such Module Quick"
"No such Module Nimble"
Below steps worked to Fix the error
Try the Following:

*

*open Xcode schemes list

*tick Nimble and Quick with "show" and close.

*Select Nimble as a scheme and build (cmd + B)

*Select Quick as a scheme and build(cmd+B)

*Change scheme back to your app scheme and see if the error is gone and autocompletion works
This is what I have to do from time to time


text:
Q: Odata Client Code Generator-Unable to generate .cs file I have a WPF clinet and I am using Odata Client Code Generator for creating a client of an odata service using Web Api 2.
I have followed this tutorial:
http://blogs.msdn.com/b/odatateam/archive/2014/03/12/how-to-use-odata-client-code-generator-to-generate-client-side-proxy-class.aspxd
The problem is that I am getting an empty .cs file that is being created by following the steps described in the tutorial(the link of which is given above).
The MatadataDocumentUri that I am using is: http://localhost:56045/odata
Is there something I am missing?
Here is the Metadata by using http://localhost:56045/odata/$metadata:
<edmx:Edmx xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx" Version="1.0">
<edmx:DataServices xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" m:DataServiceVersion="3.0" m:MaxDataServiceVersion="3.0">
<Schema xmlns="http://schemas.microsoft.com/ado/2009/11/edm" Namespace="RestApiServer.Models">
<EntityType Name="User">
<Key>
<PropertyRef Name="UserId"/>
</Key>
<Property Name="UserId" Type="Edm.Int32" Nullable="false"/>
<Property Name="UserName" Type="Edm.String"/>
<Property Name="UserType" Type="Edm.String"/>
<NavigationProperty Name="UserAddress" Relationship="RestApiServer.Models.RestApiServer_Models_User_UserAddress_RestApiServer_Models_UserAddress_UserAddressPartner" ToRole="UserAddress" FromRole="UserAddressPartner"/>
</EntityType>
<EntityType Name="UserAddress">
<Property Name="UserId" Type="Edm.Int32" Nullable="false"/>
<Property Name="UserAddress1" Type="Edm.String"/>
<NavigationProperty Name="User" Relationship="RestApiServer.Models.RestApiServer_Models_UserAddress_User_RestApiServer_Models_User_UserPartner" ToRole="User" FromRole="UserPartner"/>
</EntityType>
<Association Name="RestApiServer_Models_User_UserAddress_RestApiServer_Models_UserAddress_UserAddressPartner">
<End Type="RestApiServer.Models.UserAddress" Role="UserAddress" Multiplicity="0..1"/>
<End Type="RestApiServer.Models.User" Role="UserAddressPartner" Multiplicity="0..1"/>
</Association>
<Association Name="RestApiServer_Models_UserAddress_User_RestApiServer_Models_User_UserPartner">
<End Type="RestApiServer.Models.User" Role="User" Multiplicity="0..1"/>
<End Type="RestApiServer.Models.UserAddress" Role="UserPartner" Multiplicity="0..1"/>
</Association>
</Schema>
<Schema xmlns="http://schemas.microsoft.com/ado/2009/11/edm" Namespace="Default">
<EntityContainer Name="Container" m:IsDefaultEntityContainer="true">
<EntitySet Name="Users" EntityType="RestApiServer.Models.User"/>
<EntitySet Name="UserAddresses" EntityType="RestApiServer.Models.UserAddress"/>
<AssociationSet Name="RestApiServer_Models_User_UserAddress_RestApiServer_Models_UserAddress_UserAddressPartnerSet" Association="RestApiServer.Models.RestApiServer_Models_User_UserAddress_RestApiServer_Models_UserAddress_UserAddressPartner">
<End Role="UserAddressPartner" EntitySet="Users"/>
<End Role="UserAddress" EntitySet="UserAddresses"/>
</AssociationSet>
<AssociationSet Name="RestApiServer_Models_UserAddress_User_RestApiServer_Models_User_UserPartnerSet" Association="RestApiServer.Models.RestApiServer_Models_UserAddress_User_RestApiServer_Models_User_UserPartner">
<End Role="UserPartner" EntitySet="UserAddresses"/>
<End Role="User" EntitySet="Users"/>
</AssociationSet>
</EntityContainer>
</Schema>
</edmx:DataServices>
</edmx:Edmx>

A: Your metadata is actually a V3 format metadata. Please check:
http://services.odata.org/V4/OData/OData.svc/$metadata, the root is:
<edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">

and for http://services.odata.org/V3/OData/OData.svc/$metadata
<edmx:Edmx xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx" Version="1.0">

So your service is actually a OData V3 service, which our client generator does not support yet.


text:
Q: call operator<< on temporary Consider the following code (godbolt):
#include <fstream>
#include <string>
#include <filesystem>

namespace fs = std::filesystem;

using namespace std::string_literals;

template<class CharT, class Traits>
void test(std::basic_ostream<CharT, Traits> &s) {
    s << "Other test\n"s;
}

struct my_struct {
    std::string s = "My Struct\n"s;
};

template<class CharT, class Traits>
std::basic_ostream<CharT, Traits> &operator<<(std::basic_ostream<CharT, Traits> &stream,
                                              const my_struct &s) {
    stream << s.s;
    return stream;
}

int main() {
    fs::path file("test.txt");
    const my_struct s;

    // A
    operator<<(std::ofstream(file, std::ios_base::app), "Other test!\n"s);   // Runs fine
    std::ofstream(file, std::ios_base::app) << "Das ist ein Test!\n"s;       // Runs fine

    // B
    operator<<(std::ofstream(file, std::ios_base::app), s);                  // Runs fine
    std::ofstream(file, std::ios_base::app) << s;                            // Runs fine

    // C
    // test(std::ofstream(file, std::ios_base::app));                        // Does not compile
}

The code parts A and B compile just fine, while C does not. It is clear that test cannot take an rvalue since the argument is a non-const reference.
But shouldn't A and B be the same? Both the operator<< of the STL and my own one take the left-hand-side as a non-const reference. So why is it possible for them to work with a temporary object?
Compiler:
clang version 10.0.0
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-pc-linux-gnu/10.1.0
Found candidate GCC installation: /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/10.1.0
Found candidate GCC installation: /usr/lib/gcc/x86_64-pc-linux-gnu/10.1.0
Found candidate GCC installation: /usr/lib64/gcc/x86_64-pc-linux-gnu/10.1.0
Selected GCC installation: /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/10.1.0
Candidate multilib: .;@m64
Candidate multilib: 32;@m32
Selected multilib: .;@m64

EDIT: First version of the question had a bug, that made the own operator<< segfault.

A:
So why is it possible for them to work with a temporary object?

Because, unlike your operator <<, some from the standard library are not free, but member functions which can readily work on temporary objects without any problem, while the non-member functions have an explicit overload taking rvalue (or more precise, forward)-references.


text:
Q: Why is a certain series in a Hilbert module well defined? Suppose $(w_{\lambda})_{\lambda\in I}$ and $(\nu_{\lambda})_{\lambda\in I}$ are orthonormal bases of a Hilbert module $E$ over the C*_algebra $\mathcal{A}$, such that $w_{\lambda}=u(\nu_{\lambda})$ where $u$ is a unitary operator on the dense submodule of $E$
. We define $U:E\to E$ $~$by $$U(x)=\sum_{\lambda} w_{\lambda}\langle \nu_{\lambda},x\rangle,$$
Why is $U$ well defined?

A: If you are taking about the convergence of the series, the coefficients are in $\ell_2$ because of Parseval's Identity. And the norms of the tails of your series are precisely the tails of Parseval's.


text:
Q: Server and Client I created a Server and Client programs using python. The both programs are working fine and were both connected to the same network.. It Tried to test it with different network, but it won't work anymore, since my ip address that I put is my private ip address.... so I change it to public ip address.. but, It still won't work.
I'm using socket module in python
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('49.145.**.**', 8888))

Can anyone please help me how to figure it out.

A: try to bind it to 0.0.0.0 (all interfaces) to see if it works.
Notice that there's a security issue by listening to all interfaces! make sure you're aware of the implications
https://www.ibm.com/support/pages/vulnerability-scan-highlights-0000-http-server-listening-ports

A: Since your application works if both - client and server - are on the same network, the problem can only be a connection problem if you put client and server on different networks.
Does the command telnet <serverip> 8888 succeed from the client's computer? That checks if not only the server is reachable from the client - like a ping command does - but also checks, if the port 8888 can actually be opened as well.
If it isn't working, you need to figure out, which firewall/router might be getting in the way and what routing or port-forwarding is missing on the way between the client's and the server's computer.
For further help, you'd have to give a lot more detail about what "test it with different networks" means in your case.


text:
Q: C read line as string char *word[128];
fgets(word, 128, stdin);
if(word == "hello")
    printf("You entered hello as your word.");

So basically I am trying to get user input as a string and then use the following comparison so see if the string the user entered is equal to "hello". however, when compiling this code, it doesn't work. What did I do wrong?
EDIT: So based on feedback so far this is what I have:
char word[128];
fgets(word, 128, stdin);
if(strcmp(word, "Hello") == 0)
     printf("match\n");

However, when I compile and run this program and enter Hello it does not print "match".

A: Use strcmp(char *s1, char *s2) to compare strings.
Also change char *wordto char word[].
fgets, as you used it, reads in characters from stdin until it has read new line, 127 characters or EOF (end of file). The new line is part of the string read in word and so the comparison is not equal.
To illustrate, you need to know that a C-style string is an array of characters ended by the special escape character \0. So you are comparing those two strings hello\n\0 and hello\0; note the newline character in the string read from stdin.
You can overwrite the \n at the 6th position with \0 so your strings compare to equal.
A better, general solution is to simply iterate over the characters of the string and replace the first found \n by \0; this could be a good exercise for you maybe.
== does not compare the strings the way you expect it. It merely compares the addresses of the two objects, which in this case are of course different.

A: You need to use strcmp to compare strings.
if(strcmp(word, "Hello") == 0)
  printf("match\n");


text:
Q: WCF and Access 95 First, don't be hatn'. I know people born when MS stopped supporting Access 95 are now in high school. I am trying to provide a path forward.
I have a WCF being developed on my Win 8.1 64 bit computer (VS 2013). When my unit test makes the call, the WCF it needs to query the DB and return a dataset. I do this using traditional dataAdapter.fill() call. This causes a 'Microsoft.jet.OLEDB.4.0' provider is not registered on local the machine.' error.  I have found several posts on this forum that state the 4.0 driver will not work in a 64 bit application. So I have set the solution platform to 'x86', in the project properties i set the platform to 'Active (x86)'.  When I set the platform Target to 'x86' and try to run I receive another error 'system BadImageFormatException....' so I had to switch it back to 'Any'. The error persists.
Next I thought VS web service host was run 64 bit. I installed IIS on my local dev machine and setup the project there and set the App Pool to enable 32 bit application = true, no change.  Then I tried moving the dlls to sysWOW64 and register them there, still no luck. I tried to set corflags with '/32bit+' parameter, only to learn the file has no headers, so it can't be set. Finally, I upgraded to the ver. 12 driver and changed to connection string only to get an almost identical error,  'Microsoft.ACE.OLEDB.12.0' provider is not registered on local the machine.'
I am open to any suggestions at this point.  I probably missed some small detail back at the beginning of all this.  Thank you in advance for your help.


text:
Q: Python, how to get the unique sets from a group of sets I have a group of sets, let's say, set1={1,2},set2={2,1},se3={1,3},set4={1,3},set5={1,4}.
I'd like to get the unique sets from this group of sets. namely, I'd like to obtain the result like: [{1,2},{1,3},{1,4}].
I tried with:
myList=[set1,set2,set3,set4,set5]

result=np.unique(np.array(myList))

This way works well with the given example, but it seems that it didn't work well when I have a large number of sets.
Is there any better solution?

A: As suggested in comments: Convert the sets to frozensets so they are immutable and thus hashable and can be put into another set (which would not be possible with sets):
>>> sets = [{1,2}, {2,1}, {1,3}, {1,3}, {1,4}]
>>> set(map(frozenset, sets))
{frozenset({1, 4}), frozenset({1, 3}), frozenset({1, 2})}

If you need them as mutable sets, you can convert back to set afterwards:
>>> list(map(set, set(map(frozenset, sets))))
[{1, 4}, {1, 3}, {1, 2}]

Or map frozenset to original set in a dict and then get the values from that:
>>> list({frozenset(x): x for x in sets}.values())
[{1, 2}, {1, 3}, {1, 4}]


text:
Q: Images in plugin broken after URL migration I have a portfolio plugin that was part of a theme I paid for. The plugin doesn't actually show up in the plugins list of the WP admin console.
My problem is that, since doing a migration from one domain to another, the images associated with this plugin aren't showing up correctly. I wish I could tell you what the plugin is called, but I don't see a name for it. Even in the code within the theme folder. It does have some stuff in the plugin php about motopress-wrapper ?
Anyways, http://supkingston.com/gear/ is the link to the specific page I am having issues with. All the other pages seemed to have migrated fine. This one is buggy. The images don't load at first, but if you click on them, you see them? The images that aren't loading are the "featured images"
I have gone in to the media and made sure all the URL's that the images are using still work, and they do... I have also recreated some portfolio items from scratch using brand new uploaded images and it does the same thing... something is wrong with the plugin but I don't know what. Please help. I will provide as much info as I can.
UPDATES
I just found out that it's putting each image URL as 'http://supkingston.com/gear/' for some reason, and not actually pointing to the media

*Thanks to your help I found the code I think. It's in a JS file called filterable-portfolio-loop.php
I've uploaded the code here because it didn't copy paste well in to this editor.


text:
Q: Matplotlib Remove Graph Boundary I'm working on creating a graph in Matplotlib. I'm having issues where the graph's borders are cutting into my labels as seen in this screenshot:

I'm trying to remove the boundary line on the top and right side of the graph. I know that the code looks like this in plotly, but I'm unsure of matplotlib's equivalent.
fig.update_xaxes(showline=True, linewidth=1, linecolor='#FBFBFB', mirror=False)
fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor="#FBFBFB",showline=True, linewidth=2, linecolor='#FBFBFB', mirror=False)

Here is my entire code for context:
import matplotlib.pyplot as plt
from connect_to_db import get_df2

df = get_df2()

ax = df.plot(x='A', y='B', fontsize=10, color='#6C90B6', linewidth=3.0, legend=False,
             xlabel='', ylabel='B', figsize=(10, 5)).grid(axis='y')

for i in range(len(df)):
    x = df['A'][i]
    y = df['B'][i]
    plt.plot(x, y, 'bo', color='#6C90B6')
    plt.text(x, y + 3, y, fontsize=12, horizontalalignment='center')

plt.show()


text:
Q: Import sample Active Directory into LDAP For development purposes so I can query and test a C# LDAP integration, I have set up an Active Directory Lightweight Directory Services (AD LDS) instance on my Windows 10 box.  I need to populate this with an LDAP structure taken from a sample Active Directory implementation.  Test data is fine (vs someone's live production data).
Here are my questions...

*

*Can I initialize my local AD LDS store with sample data taken from AD?

*If so, how is this done?

*Is there somewhere I can obtain a downloadable sample AD LDAP structure that can be used to import/initialize my local AD LDS store?

A: AD is more than just an LDAP database (it's like the mutant inbred offspring of LDAP and x500 along with some MS flavoring thrown in) but you should be able to dump a large portion of AD's LDAP data with the ldapsearch tool.
Try the following
ldapsearch -h ad.domain.com -p 389 -D username@ad.domain.com -w password -LLL > export.ldif

Then use ldapadd to import the LDIF file.


text:
Q: How to pass routing control from Node server to client? Let's say this is the part where all routes are handled on a Node server with Angular front end.  When the user enters the site URL, the server sends all the static files for the browser to render. However, I would like the client to handle certain routes instead of it going directly to the server.
For example, if I enter www.exemple.com/page2, a Get request is sent to the server but the route doesn't exist so the request just hangs there and ultimately resulting an error.
I want Angular to handle the routing instead of it going automatically to the server. I've only successfully got this to work on localhost where the Angular app is served from a different port than the one that the server listens to. Can anyone one tell me how to achieve this? Thanks a lot.

module.exports=function(app,dir){
    app.use(express.json());
    app.use(express.static(dir+'/dist/probeeshq'));
    app.get('/',(req,res)=>{res.sendFile(path.join(dir));});
    app.use('/auth', userAuth);
    app.use('/api/me',userData);
    app.use('/api/org',organization);
    app.use('/api/messaging',messaging);
    app.use('/api/search',search);
    app.use(error);
}

This is what I have in Angular

const routes: Routes = [
  { path:'', component: HomeComponent },
  { path:'project_gaea', component:ProjectGaeaComponent},
  { path:'dashboard', component: DashboardComponent ,canActivate:[AuthGuardService]},
  { path:'explore', component:ExploreComponent, canActivate:[AuthGuardService]},
  { path:'create', component: CreateComponent },
  { path:'user/:id', component:UserProfileComponent},
  { path:'**', component: PageNotFoundComponent}
];

A: You can achieve this by implementing the Route feature that Angular has out of the box. After you implement this, you can then just use your back-end as an API.

A: So it turns out that I was supposed to serve the application like this:
app.use('/', express.static(dir));
And Express will let Angular handle all the routing after failing to match all the routes at the server side. dir is just the path were the Angular app is.

A: I have the same issue, with wildcard routes we can fix this. And client routes handling any unrecognised urls. Good from the user experience perspective no issues on that
like so
app.get("*", (req, res) => {
  // send HTML files
});

But what about auditing wise, like a simple question like "if I send a unrecognised URL to server, it should give a 404 status code, instead of redirecting me to client and showing a 404 page or something"
Made a valid point, which doubted my knowledge on the web. But to resolve this we need to manually whitelist the client URL's in server, still figuring out myself, if any better solution please let me know.


text:
Q: How to get the complete object / array with jq? I'm running:
$ jq ".environments[] | select(.name | contains(\"docker\")) | .database.database_config.host = \"${DGRAPHIP}\"" weaviate.conf.json

on this file: https://github.com/weaviate/weaviate/blob/develop/weaviate.conf.json
The output of this is (if DGRAPHIP = 1.2.3.4):
{
  "name": "docker",
  "database": {
    "name": "dgraph",
    "database_config": {
      "host": "1.2.3.4", <== THIS IS GOOD!
      "port": 9080
    }
  },
  "schemas": {
    "Thing": "https://raw.githubusercontent.com/weaviate/weaviate-semantic-schemas/master/weaviate-Thing-ontology-s
chema_org.min.json",
    "Action": "https://raw.githubusercontent.com/weaviate/weaviate-semantic-schemas/master/weaviate-Action-ontology
-schema_org.min.json"
  },
  "mqttEnabled": false
}

This is not the desired outcome, I would like the outcome to be encapsulated like:
{
    "environments": [{
        RESULTS
    }]
}

A: Simple adjustment:
jq --arg dgraphip "1.2.3.4" '{"environments" : .environments
 | map(select(.name | contains("docker"))
 | .database.database_config.host = $dgraphip)}' weaviate.conf.json

The output:
{
  "environments": [
    {
      "name": "docker",
      "database": {
        "name": "dgraph",
        "database_config": {
          "host": "1.2.3.4",
          "port": 9080
        }
      },
      "schemas": {
        "Thing": "https://raw.githubusercontent.com/weaviate/weaviate-semantic-schemas/master/weaviate-Thing-ontology-schema_org.min.json",
        "Action": "https://raw.githubusercontent.com/weaviate/weaviate-semantic-schemas/master/weaviate-Action-ontology-schema_org.min.json"
      },
      "mqttEnabled": false
    }
  ]
}

A: Here is another approach which uses update assignment |= with map
.environments |= map(
     select(.name | contains("docker"))
   | .database.database_config.host = "1.2.3.4"
)

Sample Run (assumes data in data.json)
$ jq -M '.environments |= map(select(.name | contains("docker")) | .database.database_config.host = "1.2.3.4")' data.json
{
  "environments": [
    {
      "name": "docker",
      "database": {
        "name": "dgraph",
        "database_config": {
          "host": "1.2.3.4",
          "port": 9080
        }
      },
      "schemas": {
        "Thing": "https://raw.githubusercontent.com/weaviate/weaviate-semantic-schemas/master/weaviate-Thing-ontology-schema_org.min.json",
        "Action": "https://raw.githubusercontent.com/weaviate/weaviate-semantic-schemas/master/weaviate-Action-ontology-schema_org.min.json"
      },
      "mqttEnabled": false
    }
  ]
}

Try it online at jqplay.org


text:
Q: How do I make a layout background flashing in android? I need to make a layout background flash or blink, changing every second. I wrote this code:
int colours[]={0xff00ff00, 0xffff0000, 0xff0000ff,0xffffffff};
RelativeLayout fondo;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    fondo = (RelativeLayout) findViewById(R.id.fondo);
    this.fondo.setBackgroundColor(colours[0]);
    this.fondo.setOnTouchListener(this);
}

Here is the onTouch method:
public boolean onTouch(View v, MotionEvent event) {
    if(event.getAction() == MotionEvent.ACTION_UP) {
        int i=1;
        long delay= 1000;
        long time = System.currentTimeMillis();

        while(true) {
            long time2 = System.currentTimeMillis();
            long time3 = (time2 - time);
            if (time3 > delay) {
                this.fondo.setBackgroundColor(colours[i]);
                Log.d("DEBUG", "EEEEEEEEEEEEEEEEEEEEEEEEEEEEE");
                time = System.currentTimeMillis();
                i++;
                if (i >= colores.length)
                    i=0;
            }
        }
    }
    return true;
}

My problem is that I can't change the background color every second, but I can write the Log.d("DEBUG") every second.

A: You should use AnimationDrawable.
If you use an infinite loop in a UI Thread it causes ANR (Android Not Responding) Window
   public boolean onTouch(View v, MotionEvent event) {

        final int DELAY = 100;

        if(event.getAction() == MotionEvent.ACTION_UP) {

            RelativeLayout fondo = (RelativeLayout) findViewById(R.id.fondo);

            ColorDrawable f = new ColorDrawable(0xff00ff00);
            ColorDrawable f2 = new ColorDrawable(0xffff0000);
            ColorDrawable f3 = new ColorDrawable(0xff0000ff);
            ColorDrawable f4 = new ColorDrawable(0xff0000ff);

            AnimationDrawable a = new AnimationDrawable();
            a.addFrame(f, DELAY);
            a.addFrame(f2, DELAY);
            a.addFrame(f3, DELAY);
            a.addFrame(f4, DELAY);
            a.setOneShot(false);

            fondo.setBackgroundDrawable(a); // This method is deprecated in API 16
            // fondo.setBackground(a); // Use this method if you're using API 16
            a.start();
         }
         return true;
    }

A: You need to use timer and handler. in handler change color of background.
there is good example here that you can customize it based on your need.


text:
Q: How to correct for font rendering issues in mobile Safari? I've been having an issue with font rendering in mobile Safari (Safari on my Mac renders fine). I'm using an OpenType font along with the @font-face selector and some of the characters (mainly just 's' and 'c') are appearing a lot more thin than others (very noticeably so - relative to each other one looks 'light' and the others look 'bold'. The weirdest thing about this is that it's only happening in landscape mode. Has anyone seen this before? The only thing that makes this go away is to set -webkit-transform: translate3d(0,0,0); on the body selector which seems completely wrong, but may give a bit of insight into the problem. I came across that on another site: http://openradar.appspot.com/11097956.
Thanks in advance for any help,
Brandon

A: This looks like what you need:
Fix font size issue on Mobile Safari (iPhone) where text is rendered inconsistently and some fonts are larger than others?
They used this code to fix it:
/* Mobile browsers only */
@media only screen and (max-device-width: 480px) {
        td#main_box { -webkit-text-size-adjust:100% }
}


text:
Q: PHPMailer no guarda las variables la otra vez vine aquí preguntando como podía hacer para que me lleguen los mails de phpmailer y pude resolver la cuestion. Hoy vengo para pedirles ayuda porque me llega el mail pero no la informacion del mismo, digo, solicito un nombre y apellido, un correo electronico y un mensaje pero no me llegan.
En el body puse codigo html para que quedara mejor a la vista y sí me lee el codigo html pero no las variables. para solucionarlo intenté con un require pero no funcionó.
Cabe aclarar que el formulario es vía ajax.
Formulario HTML
                    <input type="text" required id="nombre" class="nombre" name="nombre" placeholder="Name:" minlength="3" maxlength="15">
                    <input type="text" required id="apellido" class="apellido" name="apellido" placeholder="Lastname:" minlength="2" maxlength="50">
                    <input type="email" required name="mail" id="mail" class="mail" placeholder="Mail:">
                    <textarea name="texto" required id="texto" class="textarea" cols="30" rows="10" placeholder="Tell us your project..." minlength="50"></textarea>
                    <button type="submit" class="btn-send" id="submit" name="submit">Send</button>

Archivo PHPMailer
<?php
require 'views/index-view.php';
if(isset($_POST['submit'])){
    $nombre = htmlspecialchars($_POST['nombre'],ENT_QUOTES);
    $apellido = htmlspecialchars($_POST['apellido'],ENT_QUOTES);
    $correo = $_POST['mail'];
    $texto = $_POST['texto'];
}
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/Exception.php';
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';

// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
    //Server settings
    $mail->SMTPDebug = 0;                      // Enable verbose debug output
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = 'gator4021.hostgator.com';                    // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = '***';                     // SMTP username
    $mail->Password   = '***';                               // SMTP password
    $mail->SMTPSecure = 'ssl';         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
    $mail->Port       = 465;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

    //Recipients
    $mail->setFrom('***');
    $mail->addAddress('***');     // Add a recipient

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = "Correo enviado desde Programmark.com";
    $mail->Body    = "<!DOCTYPE html>

Nombre: $nombre

Apellido: $apellido

Correo: $correo

Mensaje:

$texto

    ";
    $mail->send();

Archivo Ajax
$('#formulario').submit(function(e){
        e.preventDefault();
        let formulario = $(this).serialize();
        let nombre = $('#nombre').val(),
            apellido = $('#apellido').val(),
            correo = $('#mail').val(),
            text = $('#texto').val();
            $.ajax({
                type: "post",
                url: "../enviarCorreo.php",
                data: {name: nombre, lastname: apellido, email: correo, texto: text},
                success: function(data){
                    $('#formulario').trigger('reset');
                    alert('The form has been sent successfully!');
                },
                error: function(data){
                    alert('The form could not be sent')
                },
            })
    });

Captura de como me llega el mail:

Agradeecría mucho que me ayuden para solucionar el tema de las variables

A: En tu Archivo PHPMailer estás mandando desde el Ajax tus variables con otro nombre, las mandas en inglés especificamente:
data: {name: nombre, lastname: apellido, email: correo, texto: text},

Y en el Archivo PHPMailer podrías probar esto:
// Esto solo es para asegurar que las variables sean globales.
$nombre = "";
$apellido = "";
$correo = "";
$texto = "";

if(isset($_POST['submit'])){
$nombre = htmlspecialchars($_POST['name'],ENT_QUOTES);
$apellido = htmlspecialchars($_POST['lastname'],ENT_QUOTES);
$correo = $_POST['email'];
$texto = $_POST['texto'];
}


text:
Q: A fetal error occurred processing the restoration data Today when I tried to start my computer from hibernation, it stucked on windows log, so I shouted down the computer by pressing the power button and then when I tried to start it again the recovery error page appeared contained the (A fetal error occurred processing the restoration data)
File:hiberfil.sys
I searched for solution for solving this problem on the internet and the solution seems to be accessing the cmd and then turn off the hibernation mode and restart the computer then deleting the hibernation file and turning it on again.
But now my problem is that, when I press the F8 key to enter into Startup setting to access the cmd, the error page appears again and again, and there is no way for me to access the cmd.
The op system is windows 10
I will appreciate any help.
Thank you


text:
Q: Can limit superior and limit inferior exist for an unbounded sequence? Can limit superior and limit inferior exist for an unbounded sequence? If not then why doesn't text books say limit inferior and superior of a bounded sequence instead of limit superior and inferior of a sequence?

A: Yes. Sort of the whole point to $\limsup$ and $\liminf$ is that they are defined for any sequence of reals. You need to keep in mind that $\infty$ and $-\infty$ are allowed as values.
If $\sup a_n=\infty$ then $\limsup a_n=\infty$. This  is clear from the definition: If $\sup_na_n=\infty$ then for every $n$ we have $\sup_{j>n}a_j=\infty$, hence $$\limsup a_n=\lim_{n\to\infty}\sup_{j>n}a_j=\lim_{n\to\infty}\infty=\infty.$$

A: $\limsup$ and $\liminf$ always exists for any real sequence. For $(a_j)_{j=0}^\infty$,
$$ \liminf_{j \to \infty} a_j = \lim_{m \to \infty} \inf_{j \geq m} a_j
$$
Since $\left(\inf_{j \geq m}\right)_{m=0}^\infty$ form an increasing sequence, its limit exists. (Possibly equal to $\pm \infty$) and likewise for $\limsup$.
Since $(a_j)_{j=0}^\infty$ is bounded, its $\liminf$ and $\limsup$ are guaranteed to be real numbers and not $\pm\infty$.


text:
Q: How exactly do I create a custom EntityManager in Symfony2/Doctrine? New guy at Symfony/Doctrine. So kindly guide me.
Requirement: To create a custom EntityManager which would override some of the methods like remove (instead of remove, i want to perform an update and modify a parameter like isValid in my class, so that the records are never deleted) and a find ( find a record which has a non zero isValid ) etc and use it instead of Doctrine's EntityManager.
I started reading through this thread:
Is there a way to specify Doctrine2 Entitymanager implementation class in Symfony2? and found the answer by user2563451 to be not so straightforward. I got lost when he talks about not to follow certain approaches (again no location of the files to be modified).
I have looked at the EntityManager.php and it specifically tells not to use extend the EntityManager class. Rather it asks to extend the EntityManagerDecorator. On looking at the EntityManagerDecorator, there are no methods available inside it (like create, persist, etc which I found in EntityManager) Does it mean I need to create new methods for each and every single Entity Manager functionality ?
Since there is no clear defined way to get this done, I am confused to get this thing started. Also Doctrine cookbook is of little use to me as it does not have any information to achieve this.
So any help regarding the extending of EntityManagerDecorator or EntityManager is appreciated.
Best if you can provide me step by step directions to achieve the same.
Thanks !
Edit 1: my requirement is to use my custom EntityManager instead of Doctrine's EntityManager (EM) and modify those 'remove' and 'find' methods as per my requirements. I am not sure whether I need to reuse the functionality provided by Doctrine's EM or write from scratch.

A: I think you may be confusing a Manager with a Repository.
An EntityManager is really nothing more than a Service you use to manage that specific or a collection of entities.
A repository extends \Doctrine\ORM\EntityRepository and is what tells Doctrine how to store your entity in the database.
You can use the combination of these two to achieve what you want.
For example.  Let's take our entity Foo
class Foo
{
    //...other properties

    protected $isValid;

    //...Getters and setters
}

We then have a manager for Foo.
class FooManager
{
    protected $class;
    protected $orm;
    protected $repo;

    public function __construct(ObjectManager $orm , $class)
    {
        $this->orm = $orm;
        $this->repo = $orm->getRepository($class);

        $metaData = $orm->getClassMetadata($class);
        $this->class = $metaData->getName();
    }

    public function create()
    {
        $class = $this->getClass();
        $foo = new $class;

        return $foo;
    }

    public function findBy(array $criteria)
    {
        return $this->repo->findOneBy($criteria);
    }

    public function refreshFoo(Foo $foo)
    {
        $this->orm->refresh($foo);
    }

    public function updateFoo(Foo $foo, $flush = true)
    {
        $this->orm->persist($foo);
        if($flush)
        {
            $this->orm->flush();
        }
    }

    public function getClass()
    {
        return $this->class;
    }
}

We have some basic functions for Creating and Updating our object.  And now if you wanted to "remove" it without actually deleting it, you can add the following function in the Manager.
public function remove(Foo $foo)
{
    $foo->setIsValid(false);
    return $this->update($foo);
}

This way, we update the isValid fields to false and persist it to the database.  And you'd use this like any service inside your controller.
class MyController extends Controller
{
    public function someAction()
    {
        $fooManager = $this->get('my_foo_manager');
        $newFoo = $fooManager->create();

        //...
        $fooManager->remove($newFoo);
    }
}

So now we've got the remove part.
Next, we only want to find entities that isValid set to TRUE.
Honestly, the way I'd handle this is not even modify the find and instead in your controller
if(!$foo->getIsValid())
{
    //Throw some kind of error.  Or redirect to an error page.
}

But if you want to do it the other way.  You can just make a repo.
use Doctrine\ORM\EntityRepository;
class FooRepository extends EntityRepository
{
    public function find($id, $lockMode = LockMode::NONE, $lockVersion = null)
    {
        //Some custom doctrine query.
    }
}

We override EntityRepository's native find() function with our own.
Finally we get all of this registered in the right places.  For the manager you've got to make a service.
services:
    my_foo_manager:
        class: AppBundle\Manager\FooManager
        arguments: [ "@doctrine.orm.entity_manager" , 'AppBundle\Entity\Foo']

And for the repository, you must specify the repositoryClass in the ORM definition of your entity.
AppBundle\Entity\Foo:
    type: entity
    repositoryClass: AppBundle\Entity\FooRepository
    table: foos
    id:
        id:
            type: integer
            generator: {strategy: AUTO}
            options: {unsigned: true}
    fields:
        isValid:
            type: boolean

Knowing all of this you can now do some pretty cool things with Entities.  I hope this helped.  Good luck!

A: Regarding your use cases, you should instead use Doctrine Lifecycle Callbacks for the remove case and simple overide the find method in your entity repository.


text:
Q: FMU getState/setState for model exchange with PyFMI I'm involved in a project in which I use a model exchange FMU. I'm using PyFMI to interact with it. One of the things that I need to do is get the state of the model at certain time ( get_fmu_state() is the function in PyFMI) and restore it later (set_fmu_state(state)). The flag "canGetAndSetFMUstate" is activated.
The use of these sentences seem to do nothing in my code...is it neccesary to do something more?
I didn't find any example that shows that capability. The FMI specification (https://www.fmi-standard.org) only dedicates a few lines to that feature.
Have you ever deal with this feature?
Thanks in advance.
Regards,
Ignacio.


text:
Q: How can i color half of my CircleAvatar with one color, and aother half with another in flutter I want to color half of my Circle Avatar as Dark Blue and other half to be Light Blue. I mean Exactly half. How can I achieve this?
Just Like them -

I tried this, but it didn't worked -
Container(
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                Color(0xFF040663),
                Color(0xFF434599),
              ],
            ),
          ),
          child: CircleAvatar(
            backgroundColor: Colors.transparent,
            radius: MediaQuery.of(context).size.height*0.045,
            child: Icon(
              icon,
              size: size,
              color: Colors.white,
            ),
          ),
        ),

Can someone tell me how can i edit this code, or tell me a new way to achieve this?

A: You are almost there. You need to repeat a color in the gradient and use the stops property to get a sharp gradient.
return Container(
      padding: const EdgeInsets.all(8.0),
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Colors.purple,
            Colors.purple,
            Colors.blue,
          ],
          stops: [
            0, 0.5, 0.5
          ]
        ),
      ),
      child: Icon(
        Icons.camera,
        size: 32,
        color: Colors.white,
      ),
    );

Here is the result:

Refer to the stops property documentation for more information: https://api.flutter.dev/flutter/painting/Gradient/stops.html


text:
Q: Workaround for Perl threading on a cPanel server I am developing a perl script to generate DNSSEC keys for several thousand domains. Since key generation is a bit slow, it is taking so much time when the number of keys to generate are on 10000s. As a workaround, I was trying to use Perl threads to spawn new threads and distribute the work. ( the script needs to be run on a cPanel server ) As it turns out cPanel perl does not have support for threads. I cannot recompile the perl in the server as it is a production server and many things would break.
What are my options? Basically, I want to distribute the load to multiple cores and decrease the total time required for the script. Is forking an option?, if so, how I would go about using it?

A: Check this tutorial as a good example for forking.
You may need to estimate a bit the time needed per domain to spawn the right amount of child processes without overloading your machine.


text:
Q: Switching between two 12 volt sources I am trying to build a switch: I have to batteries both 12V, I want to minimize voltage spikes when switching from one battery to another. the switch is essentially being made as an emergency. One battery will operate, if it goes out then the other will begin to operate.

A: Simply use two diodes, this does the trick automatically.
In this example V1 and Bat are power sources, and +VE will be the output.

Note that if you have a load which has a serious current draw (e.g. over 1A) then the diodes must be sized accordingly, and you have to prepare for some power loss on the diode. (0.7W @ 1A).
This can be solved by using a so-called "ideal-diode" which in fact a FET with very low resistance, plus a proper driver chip called "ideal diode controller".
This solution scales well, the example below works up to 10A, and basically you can easily get FETs at 50A too, nowadays.

(source: linear.com)

A: The question has nothing about current draw or switch speed, but given that the current draw isn't high and the switching event is reasonably fast, you could simply place a large-value capacitor between the load and the switch.
The capacitor would supply voltage for a small amount of time, that time being proportional to the current that you were drawing.  If you know the current draw, you could even do a 5 minute SPICE simulation to find the 'ideal' capacitor value.

A: You can use an LTC4353:

The LTC ®4353 controls external N-channel MOSFETs to
implement an ideal diode function. It replaces two high
power Schottky diodes and their associated heat sinks,
saving  power  and  board  area.  The  ideal  diode  function
permits low loss power supply ORing and supply holdup
applications.
The LTC4353 regulates the forward-voltage drop across
the MOSFET to ensure smooth current transfer in diode-OR
applications.  A  fast  turn-on  reduces  the  load  voltage
droop during supply switchover. If the input supply fails
or  is  shorted,  a  fast  turn-off  minimizes  reverse-current
transients.
The controller operates with supplies from 2.9V to 18V. If
both supplies are below 2.9V, an external supply is needed
at the VCC pin. Enable inputs can be used to turn off the
MOSFET  and  put  the  controller  in  a  low  current  state.
Status outputs indicate whether the MOSFETs are on or off.

This is called a dual low voltage ideal diode controller, which is part of a category called PMIC (Power management integrated circuit).

A: First, you aren't building a switch, you will place a switch on each battery negative lead, like a knife edge switch. The spike is natural and you can place a voltage regulator between the batteries and the load which will compensate a little for the brownout.

Place the two batteries on the left side of this circuit. The capacitor 4700 micro farads (THIS IS A BIG CAP MAKE SURE YOU GET POLARITY RIGHT ) will store charge and donate it to the circuit as battery drops.
The Diode will adjust for low spikes in reverse voltage situations.
Second, what you are doing switching a circuit from one battery to another is a dangerous impulse condition on circuits. I assume you don't have shunted condition when one battery is opening and closing opposite polarity that would be dangerous as well. You could fry both batteries (batteries are current sources in parallel with resistors), burn the circuits, burn your house etc.   I don't know what the rest of the circuit is so I can't prove or disprove this. Solid state electronics can't handle spikes without a regulator.
This switching is making discontinuous conditions that might lead to current spikes that overload it. All it takes is one transistor to blow while capacitors are loaded and they do blow.  That's worse than stopping to disconnect and reconnect a new battery.
One way to avoid dangerous conditions like this and I hope I am exaggerating, is to use heavy duty variable resistors - ones that can take many times the wattage of the circuits -  that are tunable  from 0 to 10 mega ohms with a mechanical rotary switch. A suitable potentiometer can be used. With mega ohm resistors that will decrease current to pica amps before you turn the other battery up.  You can ramp one up to 10M ohm and ramp the other down to zero as the switch.
If you don't understand what I am describing here then you shouldn't be playing with batteries and switches, the raw power of even milli amp-hour DC batteries is enough to kill you if you happen to connect them to your heart through your arms. I've known mechanics melting their wedding rings to terminals through their wrenches. I implore you to wear insulated gloves and insulated work boots if these are automotive circuits. Even sweaty hands can make enough connection.
AC is a skin effect electromagentic current, it oscillates along the rim. DC is a bulk current that goes through the centre of conductor. In this case you.


text:
Q: Error al conectar con la base de datos Estoy trabajando con un servidor Debian en cual tengo una base de datos con MariaDB, no esta instalado PHPMyAdmin.
Desde la terminal al ejecutar show databases; me da el siguiente resultado:
+---------------------+
| Databases           |
+---------------------+
| information_schema  |
| pruebas             |
| mysql               |
| performance_schema  |
+---------------------+

Ingreso a pruebas; use pruebas; y me muestra la tabla usuario:
+---------------------+
| ID | nombre | pass  |
+---------------------+
| 1  | mario  | 12345 |
| 2  | ana    | 23456 |
| 3  | luis   | 34567 |
| 4  | juan   | 45678 |
+---------------------+

Hasta ahí todo funciona bien, pero cuando hago el archivo de conexión tengo este error:

Connection failed: SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

conexion.php
<?php

$servername = "localhost";
$username = "root";
$password = "prueba1234";

try {
  $conn = new PDO("mysql:host=$servername;dbname=longa", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected successfully";
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}

?>

Nota: al configurar el usuario y la contraseña de la base de datos cree el usuario pruebaroot y la contraseña prueba1234, si cambio el usuario root por pruebaroot el error es este:

Connection failed: SQLSTATE[HY000] [1045] Access denied for user 'pruebaroot'@'localhost' (using password: YES)

Agradezco la ayuda de antemano.

A: El primer error que indicas  SQLSTATE[HY000] [1698] se debe a que la BBDD no permite el acceso al  usuario de root  sin permisos de sudo.
En este enlace  hay una resolucion al error 1698
En cuanto al segundo error (SQLSTATE[HY000] [1045] Access denied)  la base de datos te esta denegando el acceso por fallo de las credenciales , revisa que el usuario y la pass sean  correctas.
Antes de utilizar el usuario de root es recomendable que trate de acceder con pruebasroot resolviendo los problemas de acceso.
Puede ejecutar mysql -u pruebaroot -p y tratar de logarse con ese usaurio desde la consola.
Una ultima cosa , estas intentando conectarte a un base que no exite en tu base de datos:
$conn = new PDO("mysql:host=$servername;dbname=longa", $username, $password);

Si esta tratando de conectarse a la base de pruebas deberia verse asi:
$conn = new PDO("mysql:host=$servername;dbname=pruebas", $username, $password);


text:
Q: Search result comes out at the top of the page I have not been able to make the search result appear below the search button on the page.
I have not found a way to show the result in the tbody of the view, without trying to call the method in the model to make a while error.
this is controller/clienteController.php
<?php
include_once 'model/cliente.php';
class clienteController{
private $model;
public function __CONSTRUCT(){
$this->model = new cliente();
}
public function Paginar(){
require_once 'view/header.php';
require_once 'view/cliente/cliente.php';
}

public function buscar(){
$cliente = new cliente();
if(isset($_POST['dni'])){
$cliente = $this->model->Buscarme($_POST['dni']);
}
require_once 'view/header.php';
require_once 'view/cliente/cliente.php';
}
}

this is model/cliente.php
  <?php
  class cliente
  {
  private $pdo;
  public $id;
  public $dni;
  public $Nombre;
  public $Apellido;
  public $Correo;
  public $Telefono;
  public $res;
  public function __CONSTRUCT()
  {
  try
  {
  $this->pdo = conectar();
  }
  catch(Exception $e)
  {
  die($e->getMessage());
  }
  }
  public function Buscarme($dni)
  {
  try {
  $stm = $this->pdo->prepare("SELECT * FROM cliente WHERE dni = :dni");
  $stm -> bindParam(':dni', $dni, PDO::PARAM_INT);
  $stm -> execute();
  $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  foreach($res as $row){
  echo  $row['id'] . '
';
  echo  $row['dni'] . '
';
  echo  $row['Nombre'] . '
';
  echo  $row['Apellido'] . '
';
  echo  $row['Correo'] . '
';
  echo  $row['Telefono'] . '
';
  }
  } catch (Exception $ex) {
  die($e->getMessage());
  }
  }
  }

the data is sent to this view view/cliente/cliente.php

CRUD con el patrón MVC en PHP POO y PDO

Agregar
Ardila
Mateus

ID
DNI
Nombre
        Apellido
        Correo
Telefono

<?php foreach($this->model->Listar() as $r): ?>

        <?php echo $r->id; ?>
        <?php echo $r->dni; ?>
        <?php echo $r->Nombre; ?>
        <?php echo $r->Apellido; ?>
        <?php echo $r->Correo; ?>
        <?php echo $r->Telefono; ?>

<?php endforeach; ?>

<form action="?c=cliente&a=buscame" method="post" >
<input type="text" name="dni" id="dni"/>
<input type="submit" name="boton" id="boton"/>
</form>


text:
Q: Taylor polynomials expansion with substitution I am working on some practice exercises on Taylor Polynomial and came across this problem:
Find the third order Taylor polynomial of $f(x,y)=x + \cos(\pi y) + x\log(y)$ based at $a=(3,1).$
In the solution provided, the author makes a substitution such that $x=3+h$ and $y=1+k$. I am not sure why he makes this substitution. Also, why not just find the Taylor polynomial for $f(x,y)$, then plug in the values for $x$ and $y$ to solve for $f(x,y)$?
If you could provide some references for reading on this I would appreciate that as well.
Thanks in advance.

A: It's generally a good policy to "always expand around zero". This means that you want to have variables that go to zero at your point of interest.
In your case, you want to have $h$ go to zero for $x$ and $k$ go to zero for $y$. For this to happen at $x=3$ and $y=1$, you want to use $x=3+h$ and $y = 1+k$.
One reason that you want to see what happens when $h \to 0$ is that $h^2$ (and higher powers) are small compared to $h$, so they can be disregarded when you are seeing what happens. If $h$ does not tend to zero, then $h^2$ and higher powers cannot be disregarded and, in fact, may dominate.


text:
Q: CMake error: The source directory does not exist I am using Mac Mountain Lion 10.8.4, git version 1.8.3.4 (Apple Git-47)
When I run the command
 cmake "$ALICE_ROOT" \

in my build directory the following error is shown:
  CMake Error: The source directory "/opt/alice/aliroot/v5-05-77-AN/src" does not exist.

A: Ran into the same problem.
For me helped to create the src directory and symlink all sources in it.


text:
Q: What is the locale of UTF-8? I am getting an XML file from the Facebook API with the data:
<?xml version="1.0" encoding="UTF-8"?>
<fql_query_response xmlns="api.facebook.com/1.0/"; xmlns:xsi="w3.org/2001/XMLSchema-instance"; list="true">
    <user>
        <uid>100000022063315</uid>
        <name>0xD7 0x99 0xD7 0x95 0xD7 0x97 0xD7 0x90 0xD7 0x99 0x20 0xD7 0x95 0xD7 0x9B 0xD7 0x98 0xD7 0xA8</name>
    </user>
</fql_query_response>

I want to translate the UTF-8 to wchar_t. I am trying to do so with mbstowcs but apparently I need to know what locale to set. Is there a standard locale for Facebook? or for UTF-8?

A: To translate data that's not associated with the user's configured locale, but rather an explicitly specified encoding, you should use iconv, not mbsrtowcs. You don't need setlocale at all for this.

A: As @pst notes, the terminology here is a bit wrong. "Locale" is used sometimes to refer to which ANSI code page is used to represent international text when unicode is not available.
Read Joel Spolsky's fantastic "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)"
Now, to answer your question, if you need to convert UTF-8 encoded text to UTF-16 (or what in Windows is commonly called "wide char") you can use a function such as MultiByteToWideChar  with the parameter CP_UTF8

A: Here is a little discussion I started a while ago on this subject.
Basically, I would personally distinguish two separate paths on encoding handling:

*

*One is an encoding-agnostic, "internally portable" path that using mbstowcs to convert the external multibyte data from char * argv[] and convert it into an internal, fixed-width wide string, all without ever talking about encodings.

*The other is a fixed-encoding, serializable path that deals with data that ships in deterministic encodings. To translate among those, the Posix iconv library does the trick.

*You can bridge between the two paths by using iconv's special WCHAR_T encoding.
Since the situation that you describe requires you to read serialized, deterministic data, I would suggest using iconv to convert FROM UTF8 (which you know you have) and convert TO WCHAR_T, which you can then treat with your standard C wide string functions (but don't make assumptions about the actual encoding). If you need to print data to the console, you can always wcstombs from your internal wide strings to a multibyte representation (the details of which are again not of your concern) that the console told you it wants.


text:
Q: Find gmail id based on project id of appspot I have so many appengine projects running on different google accounts. I have forgotten which google account I have used for one of my appengine projects. Is there a way to find out the google account id based on my project id?

A: There is not; this would likely be a security concern if it were possible.
The solution would be to iterate over all your accounts and test each account in turn -- like a key -- in the project's lock until you -- hopefully -- find one that works.
You'll want to identify a command that you consider sufficient to determine that you have access, perhaps:
gcloud projects describe ${PROECT}

Then you could iterate across all your authenticated accounts, trying this command:
for ACCOUNT in $(gcloud auth list --format="value(account)"); do
  gcloud projects describe ${PROJECT} --account=${ACCOUNT}
done

UPDATE
More cute (but in full-disclosure I find gcloud filter|formatting challenging cf to jq):
for ACCOUNT in $(gcloud auth list --format="value(account)"); do
  ROLE=$(\
    gcloud projects get-iam-policy ${PROJECT} \
    --flatten="bindings[].members" \
    --filter="bindings.members=user:${ACCOUNT}" \
    --format="value(bindings.role)")
  printf "%s\t%s\n" ${ACCOUNT} ${ROLE}
done


text:
Q: Node.js error in Vaadin Spring Boot application Trying to run Creating CRUD UI with Vaadin project in Intellij IDEA thar contains following build.gradle :
plugins {
    id 'org.springframework.boot' version '2.3.2.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
    maven { url "https://maven.vaadin.com/vaadin-addons" }
}

dependencyManagement {
    imports {
        mavenBom 'com.vaadin:vaadin-bom:14.3.9'
    }
}

dependencies {
    implementation 'com.vaadin:vaadin-spring-boot-starter'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    runtimeOnly 'com.h2database:h2'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

test {
    useJUnitPlatform()
}

Got node problem while run project:
2020-10-07 19:01:42.637  INFO 8364 --- [           main] NodeInstaller                            : Installing node version v12.18.3
2020-10-07 19:01:42.637  INFO 8364 --- [           main] NodeInstaller                            : Downloading https://nodejs.org/dist/v12.18.3/node-v12.18.3-win-x64.zip to C:\Users\g\.vaadin\node-v12.18.3-win-x64.zip
2020-10-07 19:01:42.638  INFO 8364 --- [           main] ProxyConfig                              : No proxies configured
2020-10-07 19:01:42.638  INFO 8364 --- [           main] FileDownloader                           : No proxy was configured, downloading directly
2020-10-07 19:01:52.244  INFO 8364 --- [           main] NodeInstaller                            : Unpacking C:\Users\g\.vaadin\node-v12.18.3-win-x64.zip into C:\Users\g\.vaadin\node\tmp
2020-10-07 19:01:54.523  INFO 8364 --- [           main] NodeInstaller                            : Copying node binary from C:\Users\g\.vaadin\node\tmp\node-v12.18.3-win-x64\node.exe to C:\Users\g\.vaadin\node\node.exe
2020-10-07 19:01:54.524  INFO 8364 --- [           main] NodeInstaller                            : Extracting NPM
2020-10-07 19:02:21.733  INFO 8364 --- [           main] NodeInstaller                            : Local node installation successful.
C:\Users\g\.vaadin\node\node.exe: bad option: --no-update-notifier
C:\Users\g\.vaadin\node\node.exe: bad option: --no-audit
C:\Users\g\.vaadin\node\node.exe: bad option: --scripts-prepend-node-path=true
2020-10-07 19:02:22.336 ERROR 8364 --- [           main] dev-updater                              : Command `C:\Users\g\.vaadin\node\node.exe --no-update-notifier --no-audit --scripts-prepend-node-path=true install` failed:

2020-10-07 19:02:22.336 ERROR 8364 --- [           main] dev-updater                              : >>> Dependency ERROR. Check that all required dependencies are deployed in npm repositories.
2020-10-07 19:02:22.340 ERROR 8364 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Exception sending context initialized event to listener instance of class [com.vaadin.flow.spring.VaadinServletContextInitializer$DevModeServletContextListener]

java.lang.RuntimeException: Unable to initialize Vaadin DevModeHandler

How to solve this problem?

A: The version of Node.js that comes with vaadin is the problem. Install the latest version of Node.js. Go to its installation directory copy node_modules folder and node.exe and replace those in C:\Users~.vaadin\node.

A: For me was help:

*

*install npm,

*add path to PATH

*restart console/ide.


text:
Q: Creating colored .obj file (point cloud with color) I have all-focus image and depth-map image. Using depth map image I can create .obj file(point cloud). But in meshlab I can see only points without color. How can I add color information for .obj file?
(could you show me simple example of .obj file with color info)....

A: This question is not related to meshlab, and seems you did a poor research effort before of bring it here. Anyway, here you have a .obj file with color info, just add values of R, G, B after the coordinates.
v 1220.094482 -572.500000 77.713943 1.0 0.0 0.0
v 1291.571533 -609.439636 28.628490 0.0 1.0 0.0
v 1251.571533 -609.439636 38.628490 1.0 1.0 1.0
f 1 2 3


text:
Q: Cannot find symbol getWidth and getHeight in GLAutoDrawable in JOGL I just checked out the newest JOGL from git://jogamp.org/srv/scm/jogl.git and installed it.
The installation seems ok. I did run "ant junit.run" and saw 3d graphics.
However, when I tried to compile some example code, I kept getting errors about GLAutoDrawable. It says:
  symbol:   method getHeight()
  location: variable glautodrawable of type GLAutoDrawable

I'm running RHDL 6.5:
$ lsb_release
LSB Version:    :base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch
$ uname -a
Linux oc5088881832.ibm.com 2.6.32-431.21.1.el6.x86_64 #1 SMP Tue Jun 3 19:11:40 EDT 2014 x86_64 x86_64 x86_64 GNU/Linux

This is my java version:java -version
java version "1.7.0_55"
  OpenJDK Runtime Environment (rhel-2.4.7.1.el6_5-x86_64 u55-b13)
  OpenJDK 64-Bit Server VM (build 24.51-b03, mixed mode)

And this is my classpath:
# For JOGL
export CLASSPATH=/usr/local/JOGL/gluegen/build/gluegen-rt.jar:$CLASSPATH
export CLASSPATH=/usr/local/JOGL/jogl/build/jar/jogl-all.jar:$CLASSPATH
export LD_LIBRARY_PATH=/usr/local/JOGL/jogl/build/lib:$LD_LIBRARY_PATH

For your reference, I am compiling this example:
http://jogamp.org/wiki/index.php/Using_JOGL_in_Java_Web_Start
It seems like either I missed something in my classpath or this version of JOGL didn't implement getWidth in GLAutoDrawable...
Please can someone let me know what I did wrong?

A: GLDrawable.getWidth() and GLDrawable.getHeight() have been renamed GLDrawable.getSurfaceWidth() and GLDrawable.getSurfaceHeight() when adding the support of HiDPI: GLDrawable.java
GLAutoDrawable extends GLDrawable. Please rather post your questions about JOGL on our official forum. Best regards.


text:
Q: Return an IEnumerable with variable number of columns WebApi I have a request coming with with some filtering parameters and a list of possible calculations to perform. My code is filtering my database and then grouping it by a Date field.
At this point it is supposed to run through the dataset and perform the requested calculations, then join them based on the Date field and return this to my front end which will graph the different calculations against each other.
My question is if there is a way to have Web Api return an IEnumerable where the number and name of the columns are unknown until the function is called, or if the only way to do this is to create a class to represent each data point where the calculation properties will be null unless called for?

A: Yes, you could return IEnumerable.  Or you can serialize them in the controller to a string and return a string.