text:
Q: Fastest way to remove non-numeric characters from a VARCHAR in SQL Server I'm writing an import utility that is using phone numbers as a unique key within the import.
I need to check that the phone number does not already exist in my DB. The problem is that   phone numbers in the DB could have things like dashes and parenthesis and possibly other things. I wrote a function to remove these things, the problem is that it is slow and with thousands of records in my DB and thousands of records to import at once, this process can be unacceptably slow. I've already made the phone number column an index.
I tried using the script from this post:
T-SQL trim &nbsp (and other non-alphanumeric characters)
But that didn't speed it up any.
Is there a faster way to remove non-numeric characters? Something that can perform well when 10,000 to 100,000 records have to be compared.
Whatever is done needs to perform fast.
Update
Given what people responded with, I think I'm going to have to clean the fields before I run the import utility.
To answer the question of what I'm writing the import utility in, it is a C# app. I'm comparing BIGINT to BIGINT now, with no need to alter DB data and I'm still taking a performance hit with a very small set of data (about 2000 records).
Could comparing BIGINT to BIGINT be slowing things down?
I've optimized the code side of my app as much as I can (removed regexes, removed unneccessary DB calls). Although I can't isolate SQL as the source of the problem anymore, I still feel like it is.

A: Simple function:
CREATE FUNCTION [dbo].[RemoveAlphaCharacters](@InputString VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN
  WHILE PATINDEX('%[^0-9]%',@InputString)>0
        SET @InputString = STUFF(@InputString,PATINDEX('%[^0-9]%',@InputString),1,'')
  RETURN @InputString
END

GO

A: create function dbo.RemoveNonNumericChar(@str varchar(500))
returns varchar(500)
begin
declare @startingIndex int
set @startingIndex=0
while 1=1
begin
    set @startingIndex= patindex('%[^0-9]%',@str)
    if @startingIndex <> 0
    begin
        set @str = replace(@str,substring(@str,@startingIndex,1),'')
    end
    else    break;
end
return @str
end

go

select dbo.RemoveNonNumericChar('aisdfhoiqwei352345234@#$%^$@345345%^@#$^')

A: replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(string,'a',''),'b',''),'c',''),'d',''),'e',''),'f',''),'g',''),'h',''),'i',''),'j',''),'k',''),'l',''),'m',''),'n',''),'o',''),'p',''),'q',''),'r',''),'s',''),'t',''),'u',''),'v',''),'w',''),'x',''),'y',''),'z',''),'A',''),'B',''),'C',''),'D',''),'E',''),'F',''),'G',''),'H',''),'I',''),'J',''),'K',''),'L',''),'M',''),'N',''),'O',''),'P',''),'Q',''),'R',''),'S',''),'T',''),'U',''),'V',''),'W',''),'X',''),'Y',''),'Z','')*1 AS string,
:)

A: In case you didn't want to create a function, or you needed just a single inline call in T-SQL, you could try:
set @Phone = REPLACE(REPLACE(REPLACE(REPLACE(@Phone,'(',''),' ',''),'-',''),')','')

Of course this is specific to removing phone number formatting, not a generic remove all special characters from string function.

A: From SQL Server 2017 the native TRANSLATE function is available.
If you have a known list of all characters to remove then you can simply use the following (to first convert all bad characters to a single known bad character and then to strip that specific character out with a REPLACE)
DECLARE @BadCharacters VARCHAR(256) = 'abcdefghijklmnopqrstuvwxyz';

SELECT REPLACE(
                TRANSLATE(YourColumn,
                          @BadCharacters,
                          REPLICATE(LEFT(@BadCharacters,1),LEN(@BadCharacters))),
                LEFT(@BadCharacters,1),
                '')
FROM   @YourTable

If the list of possible "bad" characters is too extensive to enumerate all in advance then you can use a double TRANSLATE
DECLARE @CharactersToKeep VARCHAR(30) = '0123456789',
        @ExampleBadCharacter CHAR(1) = CHAR(26);

SELECT REPLACE(TRANSLATE(YourColumn, bad_chars, REPLICATE(@ExampleBadCharacter, LEN(bad_chars + 'X') - 1)), @ExampleBadCharacter, '')
FROM   @YourTable
       CROSS APPLY (SELECT REPLACE(
                                TRANSLATE(YourColumn,
                                          @CharactersToKeep,
                                          REPLICATE(LEFT(@CharactersToKeep, 1), LEN(@CharactersToKeep))),
                                LEFT(@CharactersToKeep, 1),
                                '')) ca(bad_chars)

A: I may misunderstand, but you've got two sets of data to remove the strings from one for current data in the database and then a new set whenever you import.
For updating the existing records, I would just use SQL, that only has to happen once.
However, SQL isn't optimized for this sort of operation, since you said you are writing an import utility, I would do those updates in the context of the import utility itself, not in SQL.  This would be much better performance wise.  What are you writing the utility in?
Also, I may be completely misunderstanding the process, so I apologize if off-base.
Edit:
For the initial update, if you are using SQL Server 2005, you could try a CLR function.  Here's a quick one using regex.  Not sure how the performance would compare, I've never used this myself except for a quick test right now.
using System;
using System.Data;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlString StripNonNumeric(SqlString input)
    {
        Regex regEx = new Regex(@"\D");
        return regEx.Replace(input.Value, "");
    }
};

After this is deployed, to update you could just use:
UPDATE table SET phoneNumber = dbo.StripNonNumeric(phoneNumber)

A: I saw this solution with T-SQL code and PATINDEX.  I like it :-)
CREATE Function [fnRemoveNonNumericCharacters](@strText VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN
    WHILE PATINDEX('%[^0-9]%', @strText) > 0
    BEGIN
        SET @strText = STUFF(@strText, PATINDEX('%[^0-9]%', @strText), 1, '')
    END
    RETURN @strText
END

A: can you remove them in a nightly process, storing them in a separate field, then do an update on changed records right before you run the process?
Or on the insert/update, store the "numeric" format, to reference later.  A trigger would be an easy way to do it.

A: Working with varchars is fundamentally slow and inefficient compared to working with numerics, for obvious reasons.  The functions you link to in the original post will indeed be quite slow, as they loop through each character in the string to determine whether or not it's a number.  Do that for thousands of records and the process is bound to be slow.  This is the perfect job for Regular Expressions, but they're not natively supported in SQL Server.  You can add support using a CLR function, but it's hard to say how slow this will be without trying it  I would definitely expect it to be significantly faster than looping through each character of each phone number, however!
Once you get the phone numbers formatted in your database so that they're only numbers, you could switch to a numeric type in SQL which would yield lightning-fast comparisons against other numeric types.  You might find that, depending on how fast your new data is coming in, doing the trimming and conversion to numeric on the database side is plenty fast enough once what you're comparing to is properly formatted, but if possible, you would be better off writing an import utility in a .NET language that would take care of these formatting issues before hitting the database.
Either way though, you're going to have a big problem regarding optional formatting.  Even if your numbers are guaranteed to be only North American in origin, some people will put the 1 in front of a fully area-code qualified phone number and others will not, which will cause the potential for multiple entries of the same phone number.  Furthermore, depending on what your data represents, some people will be using their home phone number which might have several people living there, so a unique constraint on it would only allow one database member per household.  Some would use their work number and have the same problem, and some would or wouldn't include the extension which would cause artificial uniqueness potential again.
All of that may or may not impact you, depending on your particular data and usages, but it's important to keep in mind!

A: I would try Scott's CLR function first but add a WHERE clause to reduce the number of records updated.
UPDATE table SET phoneNumber = dbo.StripNonNumeric(phoneNumber)
WHERE phonenumber like '%[^0-9]%'

If you know that the great majority of your records have non-numeric characters it might not help though.

A: I know it is late to the game, but here is a function that I created for T-SQL that quickly removes non-numeric characters. Of note, I have a schema "String" that I put utility functions for strings into...
CREATE FUNCTION String.ComparablePhone( @string nvarchar(32) ) RETURNS bigint AS
BEGIN
    DECLARE @out bigint;

-- 1. table of unique characters to be kept
    DECLARE @keepers table ( chr nchar(1) not null primary key );
    INSERT INTO @keepers ( chr ) VALUES (N'0'),(N'1'),(N'2'),(N'3'),(N'4'),(N'5'),(N'6'),(N'7'),(N'8'),(N'9');

-- 2. Identify the characters in the string to remove
    WITH found ( id, position ) AS
    (
        SELECT
            ROW_NUMBER() OVER (ORDER BY (n1+n10) DESC), -- since we are using stuff, for the position to continue to be accurate, start from the greatest position and work towards the smallest
            (n1+n10)
        FROM
            (SELECT 0 AS n1 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS d1,
            (SELECT 0 AS n10 UNION SELECT 10 UNION SELECT 20 UNION SELECT 30) AS d10
        WHERE
            (n1+n10) BETWEEN 1 AND len(@string)
            AND substring(@string, (n1+n10), 1) NOT IN (SELECT chr FROM @keepers)
    )
-- 3. Use stuff to snuff out the identified characters
    SELECT
        @string = stuff( @string, position, 1, '' )
    FROM
        found
    ORDER BY
        id ASC; -- important to process the removals in order, see ROW_NUMBER() above

-- 4. Try and convert the results to a bigint
    IF len(@string) = 0
        RETURN NULL; -- an empty string converts to 0

    RETURN convert(bigint,@string);
END

Then to use it to compare for inserting, something like this;
INSERT INTO Contacts ( phone, first_name, last_name )
SELECT i.phone, i.first_name, i.last_name
FROM Imported AS i
LEFT JOIN Contacts AS c ON String.ComparablePhone(c.phone) = String.ComparablePhone(i.phone)
WHERE c.phone IS NULL -- Exclude those that already exist

A: I'd use an Inline Function from performance perspective, see below:
Note that symbols like '+','-' etc will not be removed
CREATE FUNCTION [dbo].[UDF_RemoveNumericStringsFromString]
 (
 @str varchar(100)
 )
 RETURNS TABLE AS RETURN
 WITH Tally (n) as
  (
  -- 100 rows
   SELECT TOP (Len(@Str)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
   FROM (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n)
   CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)
  )

  SELECT OutStr =  STUFF(
       (SELECT SUBSTRING(@Str, n,1) st
        FROM Tally
        WHERE ISNUMERIC(SUBSTRING(@Str, n,1)) = 1
        FOR XML PATH(''),type).value('.', 'varchar(100)'),1,0,'')
  GO

  /*Use it*/
  SELECT OutStr
  FROM dbo.UDF_RemoveNumericStringsFromString('fjkfhk759734977fwe9794t23')
  /*Result set
   759734977979423 */

You can define it with more than 100 characters...

A: "Although I can't isolate SQL as the source of the problem anymore, I still feel like it is."
Fire up SQL Profiler and take a look.  Take the resulting queries and check their execution plans to make sure that index is being used.

A: Thousands of records against thousands of records is not normally a problem.  I've used SSIS to import millions of records with de-duping like this.
I would clean up the database to remove the non-numeric characters in the first place and keep them out.

A: Looking for a super simple solution:
SUBSTRING([Phone], CHARINDEX('(', [Phone], 1)+1, 3)
       + SUBSTRING([Phone], CHARINDEX(')', [Phone], 1)+1, 3)
       + SUBSTRING([Phone], CHARINDEX('-', [Phone], 1)+1, 4) AS Phone

A: I would recommend enforcing a strict format for phone numbers in the database. I use the following format. (Assuming US phone numbers)
Database: 5555555555x555
Display: (555) 555-5555 ext 555
Input: 10 digits or more digits embedded in any string. (Regex replacing removes all non-numeric characters)


text:
Q: gpu::morphologyEx is slower than morphologyEx in CPU? I am writing a c++ code for comparing the performance of morphologyEx method of opencv using the CPU and GPU versions. Here is my code:
#include <opencv2/opencv.hpp>
#include <opencv2/gpu/gpu.hpp>
#include <sys/time.h>
#include <ctime>
using namespace cv;
using namespace std;

double start_timer()
{
     double start_time = (double) getTickCount();
     return start_time;
}

double end_timer(double start_time,int num_tests)
{
    double time = (1000 * ((double) getTickCount() - start_time)/ getTickFrequency());
    cout << "Average time of " << num_tests  << " frames is: " << time/num_tests <<  " ms" << endl;
    return time;
}

int main()
{
    Mat cpuSrc;
    cv::gpu::GpuMat src_gpu, dst_gpu;
    Mat dst;
    Mat element;
    int element_shape = MORPH_RECT;
    element = getStructuringElement(element_shape, Size(10, 10 ), Point(-1, -1) );
    cpuSrc = imread("images.jpeg",CV_LOAD_IMAGE_ANYDEPTH);

    if (!cpuSrc.data)
    {
        cerr << "Cannot read the data" << endl;
        return -1;
    }

    cout << "Starting calculating time for CPU ....." << endl;
    double start_time = start_timer();
    int d = 0;
    while(d<100)
    {
        cv::morphologyEx(cpuSrc, dst, CV_MOP_OPEN, element,Point(-1,-1),1);
    }

    double total_time_cpu = end_timer(start_time,d);

//--------------------------------------------------------------
    cout << "Starting calculating time for GPU ....." << endl;
    d = 0;
    cv::gpu::GpuMat buf1, buf2;
    gpu::Stream stream;
    double start_time_1 = start_timer();

    while(d<100)
    {
        stream.enqueueUpload(cpuSrc, src_gpu);
        cv::gpu::morphologyEx(src_gpu,dst_gpu,CV_MOP_OPEN,element,
                   buf1,buf2,Point(-1,-1),1,stream);
        stream.enqueueDownload(dst_gpu, dst);

    }
    stream.waitForCompletion();
    double total_time_gpu = end_timer(start_time_1,d);

    cout << "Gain is: " << total_time_cpu / total_time_gpu << endl;
    return 0;
}

I am using a loop as if i am simulating a video that contains 100 frames. I am using NVIDIA Corporation GF110 [GeForce GTX 570] and Intel Corporation Xeon E5/Core i7 DMI2. Moreover, i tested the time for uploading and downloading and it is very large in the first frame but after that it can be neglected approximately for uploading it is 0.02ms per frame and downloading is 0.1ms and the main time consumption is with the morphologyEx operation.

The time results for this simulations are as follows:

for CPU morphology version, The
   average time of 100 frames is:: 0.027349 ms and for the GPU version is:: 18.0128 ms

Could you please help me to figure out what might be the reasons for such unexpected performance?!!

Thank you so much in advance.

A: In the initialization you should call:
cv::gpu::setDevice(0);

It will speed up initialization.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to talk a client out of a Flash website? I have recently been doing a bunch of web side projects through word of mouth recommendations only.  Although I am much more a of a programmer than a designer by any means, my design skills are not terrible, and do not hate dealing with UI like many programmers.  As a result, I find myself lured into a bunch of side projects where aside from a minimal back end for content administration, most of the programming is on front end interfaces (read javascript/css).
By far the biggest frustration I have had is convincing clients that they do not want Flash.  Aside the fact that I really do not enjoy Flash "development", there are many practical reasons why Flash is not desirable (lack of compatibility across devices, decreased client accessibility, plug-in requirements, increased development time, etc.).  Instead of just flat out telling the clients "I will not build you a flash website", I would much rather use tactics to convince/explain to them that this is not what they actually want, ie: meet their requirements any better than standard html/css/js and distract users from their content.
What kind of first hand experience do others have with this?  How do you explain to someone that javascript/css/AJAX is usually a better option for most websites?  Why do people want to use Flash so bad to begin with?
This question pertains to clients who do not have any technical reasons for wanting flash, but just want it because they think it makes pretty websites.

A: People like things that are flashy (no pun intended) and flash, being flashy, has a reputation that the non technical person has heard of numerous times.
EDIT:
Read here and convey these points
http://www.killersites.com/blog/2010/why-flash-only-websites-are-a-bad-idea/
The general manager of the company I work for had made a flash site for one of our new products and I had to send him an email with a list of all that was wrong with it, I feel your pain.

A: Tell 'em Flash websites are "empty" to the search engines. If the businessman wants customers to google and discover his business through the web, he has to forget Flash. Technobabble aside, the businessman will understand the cost of losing customers.
Tell 'em Flash websites are known to slow down old computers and users nowadays are getting increasingly annoyed by Flash websites, closing the page if it doesn't load in a blink of an eye.
Tell 'em Flash has become sort of an anti-businesscard these days to mark an antiquated company out of touch with the present. Tell 'em users will wrinkle and the competitors will laugh.

A true story. A while ago when I relocated to another town soon after I felt the need to visit a hair stylist. Being who I am I came with no better idea as to google for a hairdresser shop. I landed on a rating page that listed about 5-6 top places. I went for their websites and saw... what do you think? Freaking Flash! One site wouldn't load 100% at all, I even tried several times. The others had too complex navigation I was never able to comprehend and get to the needed information. In the end I landed on the last page which was just basic HTML and CSS. I got the necessary information in a few seconds, made an appointment and have been their client ever since. I guess the other shops will have to earn with their web designer since normal users just don't get through.

A: I think your view on flash is a little too shallow, which also applies to the many answers provided here. I have been working with the Flash Player as a platform for about 5 years now and I would like to take the time to explain a few things.
TLTR: goto conclusion.
The problem with Flash
One of the biggest problems of that platform is how it is monetized:
By providing development tools that lower the entry barrier to a bare minimum. As a result, you have a shitload of crappy apps out there.
What is claimed about flash is true for flash content, but is not specific for the platform. The same company, that created flash, created Dreamweaver. Last time I checked, it produced results about as crappy as average flash content.
The "Truth" about Flash

*

*Flash Player's market penetration can measure up with that of browser you'd be willing to actually be compatible with when creating a HTML solution. Estimations for IE6 still range up to over 10%.

*Flash Player is not present on mobile devices, at least not in a way one could seriously work with. OTOH, if you honestly care about mobile experience, then you should create a mobile version of the site you create.

*Flash Player is not slow. The AVM2 outperforms all JavaScript engines in general purpose situations, although the V8 is an alternative, but it is only used in Google Chrome. Flash player is also reasonably fast for both rendering vector and raster graphics and can only be signifficantly outperformed by hardware accelerated HTML renderers, which are not widely spread. If Flash Player were only used to display data the same way as HTML sites, you wouldn't notice a difference.

*Flash Player is used to create crappy multimedia sites and banners. However, Flash Player is capable to run rich internet application such as Sliderocket, Aviary Tools (notably Phoenix), games such as Tanki Online and Koyotl (I myself am working on this game and we'll hopefully launch a public beta next week, until then the screen shots at the bottom should give you an impression).

There is such a thing as actual flash development and if you're actually interested, I suggest you grab a copy of FlashDevelop which is all about actual software development on the flash platform.
Your claim that flash requires more development time is solely based on your personal skillset. It's as if a .NET developer claimed Java development requires more time.
Flash vs. HTML
Flash is - from my personal experience - a better choice than HTML, if you want to build a complex, persistent, interactive app, a fat client that deploys from the web (*).
Now to build web sites with a relatively low level of interactivity, as for example a forum, there is not much reason to use flash, except some edge cases that are not really important here. Choosing HTML makes it easier to do SEO and to ensure accessibility. But it is still a matter of taste, although I cannot imagine non-technical people having any good reason to prefer flash.
Depending on the situation and personal philosophy, one or the other is "better", but statements from "flash sucks" to "it is ok as a complement" are oversimplyfied.
What I fear is, by wanting pretty, your customers mean the kind of pretty that makes you wanna vomit. In that case flash also is the better tool to implement this nightmare. I turn down such jobs and I also don't forward them. This is a crime. And I am afraid once the HTML5 backend of Adobe CS Flash is stable enough, you will not be able to hide from this just by uninstalling flash.
If it is that what they want, I beg you to try talking them out of that. It's not hip, it's not cool, it's distasteful. You know that. Everybody here does. They should, too.
Conclusion
Demonizing flash isn't really honest and I don't think you need it.
Having experience with JavaScript/CSS/HTML is valuable. Saying you're very productive with that stack and that you feel confident you will meet your customer's requirements (supposing you are) is a good thing and an absolutely valid reasoning.
The best work you can do at minimum cost is to use the technologies you master and your customers want to get just that. Unlike a number of popular half-truths this is a solid fact.

(*) : I think standards are a lovely thing. I myself am using haXe since 2 years now, one motivation being the ability to switch, when I consider HTML a working alternative for my requirements. So far I must say, the flash player is still my prefered target for a number of reasons of which I presented a subset. So while I am looking forward to the day when HTML makes the flash player obsolete for my work, I think it's still a few years from now.

A: One valid reason is that a Flash-based website won't work on an iPhone, iPad 1, iPad 2 or iPod Touch - which is 170 million devices, last time I counted.
Yes, this is Apple's decision, but its become a serious concern when building websites. Indeed, Microsoft is abandoning development on Silverlight for the Web as HTML just works on more devices.

A: TL;DR
This more so goes inline with what a lot of contributors have already pointed out, but you really need to stick to the FACT that Flash is not fully supported. Adobe has pulled the plug on Flash Mobile support. This move made by Adobe means that other Mobile devices will soon be affected, leaving mobile devices without Flash viewing capability altogether. We have seen this happen before. Take ColdFusion for example. There are quite a few programmers and clients who were affected by the Adobe-caused death of ColdFusion.
In conclusion, a web-based platform (and any platform for that matter) is only as good as its supporters, contributors, and creators. Building a whole entire website on a wobbly platform WILL, without a doubt, cause the client to spend outside of their budget when it comes time to rebuild their website.

A: As Timk said, flashy is good in the eyes of customers. The average customer is probably not aware/thinking about things such as:

*

*SEO

*Accessibility

*Mobile access

*Doesn't work well with browser history, bookmarks etc.

You can try to talk to them about these issues and then let 'em decide.

A: Using Flash will lose them eyeballs.
One of the big reasons Google trounced Yahoo, Ask Jeeves, et. al. in the search engine wars is their landing page and results appear so incredibly fast. Even in the late 90s, when Google's search results weren't really better, they were still the go-to search engine if you didn't want to waste your time.
On the other hand, there are the Flash sites. You know, the ones where the landing page is "Loading... 10%... 20%..." I don't care at all about somebody's ego-stroking beautiful artistic visions, I just want to get the information I need and get on with my day. So most of the time, when I hit one of those sites, I either hit the "skip the animation" button if there is one, or if not, just switch to Google and find a competitor.
Add in the lack of iPhone/iPad support, and you've just subtracted even more eyeballs.
Others have covered the technical problems with Flash; like Josh K, "I block Flash (via NoScript) everywhere" because my machines run better and everything loads faster.
I'm totally cool with Flash as an optional component of the user experience in the right contexts - I'm a total CityVille addict, for instance. But being a major component of a customer-facing commercial website ain't the right context.

A: If technical reasons don't work, tell them that you can't use flash in the iPad or the iPhone

A: Explain that Flash is a tool for multimedia rather then supporting an entire website. Flash does some things extremely well, but a full Flash website is cumbersome and very frontloaded to the client. Load times are increased, bandwidth goes up, and development generally slows down.
Going with a HTML / JavaScript solution is better for 99% of the cases Flash is considered. Flash is there to augment existing markup rather then replace it. People don't write entire websites in JavaScript for that reason. It's an enhancement, not a substitute.
Flash based websites will not be picked up easily by search engines. You would have to work very hard to allow them to. Flash would also make it difficult to bookmark pages and share links, as often the URL doesn't change at all. As previously mentioned because of long load times and processing issues the user experience can often be terrible. I block Flash (via NoScript) everywhere because it has major performance issues on all my machines (Windows and Mac alike).
There is a lot of Flash-like behavior that can be replicated with JavaScript. There are even full libraries (jQuery UI) built around drop-in widgets and animations to replace Flash counterparts.

Summary
Flash shouldn't be used for the entire website. Bits and pieces can be in Flash, but the overall design should be in HTML for accessibility, portability, and speed. It costs less to maintain an HTML based website then a Flash based one, as well as increasing the number of users who can access the site effectively.

A: If their site does not require flash, tell them that their site does not require flash. IF they insist on using flash, recommend a flash developer to them.
you are under no obligation to work with clients that don't listen, or use tools you don't like.

A: Why don't you "wow" them with non-flash examples of your work? They can see the potential along with your expertise. Let them know there is nothing that can be done in Flash that you can't do your way (I hope this is true.). If they argue, then just use Flash, there have been several more technical reasons to avoid it. You need to make sure in their mind, they won't be limited by making this choice.
They may be under the impression a novice is more likely to learn how to tweak something in Flash in an emergency and not worry about being locked into a particular developer.
There's always the old "Nobody got fired for buying IBM." mentality. Flash is in the news and your clients don't distinguish good from bad publicity.

A: There may also be issues with complying with accessibility legislation e.g. for blind users. I don't know how well screen readers cope with Flash - I don't imagine very well.


text:
Q: Refit API HTTPPost 'Unexpected character encountered while parsing value' from .net Core 3.0 Console app I have an api endpoint as follows
    [HttpPost("create")]
    [MapToApiVersion("1.0")]
    public async Task<IActionResult> Post(CarDto carDto)
    {
        return Ok(await _carService.CreateCarAsync(carDto));
    }

The Dto below is a shared do in nuget package with contracts
public class CarDto
{
    [JsonProperty(PropertyName = "Id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "Colour")]
    public string Colour{ get; set; }
}

My calling code in the Console app
public interface ICarServiceApi
{
    [Post("/Cars/create")]
    Task<bool> CreateCar(CarDto carDto);
}

var carServiceApi = RestService.For<ICarServiceApi>("https://localhost:5001/api/v1");
var car = new CarDto {Id ="123", Colour = "Red"};

await carServiceApi.CreateCar(car);

The exception i get is as follows

Unexpected character encountered while parsing value: {. Path '', line
  1, position 1.

The call to the Http get works fine so something is wrong in my setup above


text:
Q: Redirect all pages to subfolder except blog in Wordpress I want to redirect my all website (that developed on wordpress) links to a sub-folder like http://mywebsite.com/ to http://mywebsite.com/new/,  but http://mywebsite.com/blog/ , this should work as previously and in address bar it should not change.
I tried to add these lines in my .htaccess

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} !^(blog)(/.*)?
RewriteRule ^(.*)$ /new/$1 [L]

It is redirecting my all page to sub-folder but with blog it is redirecting to 404 page.
Please help me out with this.

A: REQUEST_URI string starts with a leading slash. You need to put a slash before (blog)(/.*)? in your condition pattern.
Try
RewriteCond %{REQUEST_URI} !^/(blog)(/.*)?


text:
Q: how to export data to PDF from dynamic table in AngularJS I want to export data to PDF from a dynamic table, all the plugins use static tables, I mean by dynamic tables that they are created when I make request to export data and the user can't see these tables .
I need this because the way that the users see the data is different from the way that I want to print .
I'm using AngularJs in front end side and Nodejs in backend side to build my application
I tried to use this package :
https://www.npmjs.com/package/angular-save-html-to-pdf
this is an example from the documentation :
<button pdf-save-button="idOne" pdf-name="someone.pdf" class="btn">Hello
Someone</button>
<!-- below block will be saved as pdf -->

<div pdf-save-content="idOne" >
    Hello Someone
</div>

the solution I want is to create and print the data in side the div dynamically when the button is pressed.
now what is the best practice to solve this problem ?

A: You can use Angular-UI-Grid Export future... It handles dynamic data and has some export futures..


text:
Q: How to add column with query folding using snowflake connector I am trying to add a new column to a power query result that is the result of subtracting one column from another. according to the power bi documentation basic arithmetic is supported with query folding but for some reason it is showing a failure to query fold. I also tried simply adding a column populated with the number 1 and it still was not working. Is there some trick to getting query folding a new column to work on snowflake?

A: If the computation is made based only on data from source, then it could be computed during table import as SQL Statement:
SELECT col1, col2, col1 + col2 AS computed_total
FROM my_table_name

EDIT:

The problem with this solution is that native SQL statement for snowflake is only supported on PBI desktop and I want to have this stored in a dataflow (so pbi web client) for reusability and other reasons.

Option 1:
Create a view istead of table at source:
CREATE OR REPLACE VIEW my_view
AS
SELECT col1, col2, col1 + col2 AS computed_total
FROM my_table_name;

Option 2:
Add computed column to the table:
ALTER TABLE my_table_name
ADD COLUMN computed_total NUMBER(38,4) AS (col1 + col2);


text:
Q: Creating new columns using a for loop I am new to R (Economist with background in Stata) and I am having trouble getting a nested for loop to work for me. I know the issue is that I don't have a good understanding of how to use the loop counter as part of a variable name.
A bit of background. I have data frame with data on average rental rates for homes of different size (1 bedroom, 2 bedroom, etc) and data on annual earnings (mean, median, and various percentiles). I am trying to generate a series of new columns containing the ratio of these two things (rental rate / mean earnings).
Specifically my variables are:

*

*beds1, beds2, beds3, beds4

*mean, median, p10, p25, p75, p90
So you see I need to generate 24 new columns of cost/earnings data. I could write out 24 lines of code but I don't want to. More importantly, I want to learn an efficient way of doing this in R. In Stata I could do this very simply using a nested for loop, but I can't get it to work in R. Here is my code so far.
for (i in 1:4) {
    stat <- c("median", "mean", "p10", "p25", "p75","p90")
    for (x in stat) {
        df$beds[i]_[x] <- round((df$beds[i]/df$[x]),digits=3)
    }
}

When I run this code the error I get is
Error: unexpected input in:
"    for (x in stat) {
    df$beds[i]_"
>     }
Error: unexpected '}' in "    }"
> }
Error: unexpected '}' in "}"

I have tried to use the double brackets [[]] but that didn't change the results. If anyone has some insight into why the dynamic variables names aren't working please let me know. Even better, since I guess loops are evil in R, if anyone knows a way to use lapply to get this done, I would love to hear that too.

EDIT
Thanks @Spacedman for the comment. I think I am getting what you're saying. So does that mean that there simply isn't anyway to do what I want to do in R?
var1 <- c("beds1", "beds2")
var2 <- c("mean", "median")

for (i in 1:2) {
    for (j in 1:2) {
        df$var1[i]_var2[j] <- df$var1[i]/df$var2[j]
    }
}

I think this should grab the elements of the lists var1 and var2 so that  when i=1 and j=1, df$var1[i]/df$var2[j] should mean df$beds1/df$mean. Or would R get mad and think I was trying to divide strings?

FINAL EDIT WITH ANSWER FROM @SPACEEMAN
Thanks @Spacedman. I loved your spoiler and thank you for providing additional help. I didn't fully grasp the difference between the two ways of referring to columns after your last post, but I think I have a better idea now. I did a bit of tweaking and now I have something that works perfectly. Thanks again!
beds <- c("beds1", "beds2", "beds3", "beds4")
stat <- c("median", "mean", "p10", "p25", "p75","p90")

for(i in beds){
    for(x in stat){
        res = paste0(i,"_",x)
        df[[res]]=round(df[[i]]/df[[x]],digits=3)
    }
}

A: R is not a macro expansion language like other languages you might be used to.
x[i], if i=123, does not "expand" into x123. It gets the value of the 123rd element of the vector, x.
So df$beds[i] tries to get the i'th element of a vector df$beds.
You need to know two things:

*

*How to construct strings from other strings.

For this you can use paste0:
> for(i in 1:4){
+  print(paste0("beds",i))
+ }
[1] "beds1"
[1] "beds2"
[1] "beds3"
[1] "beds4"

*How to access columns by names.

For this you can use double square brackets. In a list:
> z = list()
> n = "thing"

Double squabs evaluate their index and use that. So:
> z[[n]] = 99

Will set z$thing, but dollar sign indexing is literal, so:
> z$n = 123

will set z$n:
> z
$thing
[1] 99

$n
[1] 123

hopefully that's enough hints to get you through. It should all be covered in basic R tutorials online.
Spoiler
If you want to work out how to do it yourself, look away now...
First, lets create a sample data frame - you should include something like this in your question so we have common test data to work on. I'll just have three beds and two stats:
> df = data.frame(
     beds1=c(1,2,3),
     beds2=c(5,2,3),
     beds3=c(6,6,6),
     mean=c(8,4,3),
     median=c(1,7,4))
> df
      beds1 beds2 beds3 mean median
    1     1     5     6    8      1
    2     2     2     6    4      7
    3     3     3     6    3      4

Now the work. We loop over the bed number and the character stats. The bed column name is stored in bed by pasting "beds" to the number i. We compute the name of the result column (res) for a given bed number and stat by pasting "beds" to i and "_" and the name of the stat in x.
Then set the new resulting column to the value by dividing the beds number by the stat. We use [[z]] to get the columns by name:
> for(i in 1:3){
  stats=c("mean","median")
  for(x in stats){
    bed = paste0("beds",i)
    res = paste0("beds",i,"_",x)
    df[[res]]=round(df[[bed]]/df[[x]],digits=3)
  }
 }

Resulting in....
> df
  beds1 beds2 beds3 mean median beds1_mean beds1_median beds2_mean beds2_median
1     1     5     6    8      1      0.125        1.000      0.625        5.000
2     2     2     6    4      7      0.500        0.286      0.500        0.286
3     3     3     6    3      4      1.000        0.750      1.000        0.750
  beds3_mean beds3_median
1       0.75        6.000
2       1.50        0.857
3       2.00        1.500
>


text:
Q: Dynamic link to download my app from iOS Android app stores With firebase, how can I generate a download link of my app and when click on it, redirects to the Apple store if the user has iOS and google play if he has Android??? Can I also have the data of how many users download the app through this link?
Thank you so much
I tried to search in the firebase documentation, i read the documentation of how to create dynamic link but i can't figure out how to do it.


text:
Q: Sticky Macbook Lid My MacBook Pro (Retina, 15-inch, Mid 2015) exhibits a lid-opening issue when it has been closed for a while.  It is very difficult to open, to the point where it does not stay put on the desk.  Subsequent close and opens work just fine, until the lid has been closed for a couple of hours.  It is then difficult to open again.
I suspect the rubber spacer around the display is adhering to the body.  The spacer does not feel gummy or sticky.  Has anyone experienced this issue?


text:
Q: Huge pdo_mysql.log - turning off logging doesn't stop it from growing Magento is logging SQL queries even after I turned logging off in /lib/Varien/Db/Adapter/Pdo/Mysql.php. Wondering if there's something I'm missing?
These are the spots that are set to false:
    protected $_debug               = false;

/**
 * Minimum query duration time to be logged
 *
 * @var float
 */
protected $_logQueryTime        = 2.5;

/**
 * Log all queries (ignored minimum query duration time)
 *
 * @var bool
 */
protected $_logAllQueries       = false;

/**
 * Add to log call stack data (backtrace)
 *
 * @var bool
 */
protected $_logCallStack        = false;

/**
 * Path to SQL debug data log
 *
 * @var string
 */
protected $_debugFile           = 'var/debug/pdo_mysql.log';

I need to regularly delete var/debug/pdo_mysql.log or it will grow to several gigs in size.
Debug mode is disabled in the admin area (System - Configuration - Developer - Debug set to no).
Looking for some advice.
Thanks in advance

A: This logging should be off by default in a clean install of magento so it sounds like someone has previously modified this file to turn this setting on.
That said, now that logging is disabled I see no reason why the PDO adapter should be logging queries. As suggested above if you are using APC or opcache try clearing that as because this is a change to a php file rather than a db setting it may be cached at the php level.

A: Debug mode might be on. Go to System - Configuration - Developer - Debug and if the Profiler is set to Yes, disable it.


text:
Q: Spin and parity transition levels gamma radiation Just a quick question regarding spin and parity. I am studying nuclear physics and I am just a tad confused with a concept about gamma radiation.
Say I have ${^{20}_{10}Ne}$
And the lowest electric multipole of gamma transition between some excited states, such as from 5.00Mev to 4Mev levels is E3.
What is the possible value(s) for the spin and parity of the 4 MeV level, if the 5Mev is $2^-$?
I know since it is an E3 transition then there is is a parity change, since $E_{l_\gamma}=(-1)^{l_\gamma}$
But for the spins, is there not a lot of possible number of values?
Since $l_\gamma = |J_i-J_f|,|J_i-J_f|+1,...,(J_i-J_f)-1,(J_i-J_f)$
and $J_i = 2$ and $l_\gamma = 3$
I think this solves out to be:
It could be $J_f = 1^+,2^+,3^+,4^+,5^+$ ???
This is just an example - but think I could extrapolate from it.

A: You're right that1+, 2+, 3+, 4+, and 5+ are all possible values for the final state following an E3 transition. However, if the final state were 1+,2+, or 3+, then an E1 transition would be possible. If the final state were 4+, then an M2 transition would be possible. So if the lowest multipole is E3, that leaves just one option.


text:
Q: Conditional Cell Template in ui grid angular js I need to display the text in a cell as a link based on a status or as a plain text.
If the status is 'Deleted' the name should be displayed as plain text or else as an hyperlink. Below are my grid options. I am always getting it as hyperlink. Someone please help me correct my cell template so that I am getting it correct.
$scope.gridOptions = {
    data: 'ProjectDetails',
    columnDefs: [
    { field: 'Id', displayName: 'ID', visible: false },
    { displayName: 'Name', width: 200, cellTemplate: '
 {{row.entity.ProjectStatus}} != Deleted
' ? '
{{row.entity.Name}}
' : '
 {{row.entity.Status}}
' },
    { field: 'Expense', displayName: 'Operating Expense', width: 185, cellFilter: 'noFractionCurrency' },
    { field: 'Status', displayName: 'Status', width: 150 }
    ]
};

A: ng-if helped me.
cellTemplate: "{{row.entity.Name}}
{{row.entity.Name}}
"

A: I'd do this with ngShow.
var cellTemplate = "
{{row.entity.Name}}

{{row.entity.Status}}
"

A: I just added href for Status -deleted and plain text for non-deleted option.
var cellTemplate: "{{row.entity.Name}}
{{row.entity.Name}}
"


text:
Q: How to display an element when his children is focused by keyboard navigation? Update cause I still have no clue how to do this and I would be glad to know it. Just a reminder this is about accessibility and using keyboard only (no mouse), things that people doesn't seem to understand so far, making this question fall into abyss even if IMO this is interesting.
I try to improve the accessibility of my website and I've an issue with a div displayed only when itself or the previous element are focused/hovered.
There is an input into this div and I want it to be accessible by keyboard navigation, but when the focus go on the input,
it does not consider that the div is so.
So I'm asking how can I detect when the focus go on this input and keep the parent div displayed ?
I've already tried with css but we can't select parent (except with :had but it's not implemented yet).
I've also search a solution with JavaScript and jQuery but I didn't figure out how to achieve this.

.b {
  display: none;
}

.a:hover+.b,
.a:focus+.b,
.b:hover,
.b:focus {
  display: block;
}
<button class="a">A button that displays the div</button>
<div class="b">
  <input type="checkbox">
</div>

Actually the div appear when you focus the button, but when you go on the input with tabulation, the div disappear. I want it to stay displayed while the input is focused.
It's working if you click on the button, issue only happen when you don't use your mouse.
I've found :focus-within but it's not implemented on all browser.

A: So your problem is when you click in the checkbox i.e. when checkbox is checked then it should be display: block until it is checked. When you uncheck it again it should work like before i.e. on button focus display: block else display: none Am I correct?


text:
Q: Calculation of system response time I've developed software and now I'm going to monitor the performance of system, the system is almost working well, except in some periods of working faces some slowness. Now I have prepared o log related to system response and the time which the response has been generated, the log time is like below:
Process#1   step1:   300 millisecond    step2: 700 milliseconds     step 3: 10 millisecond
Process#2   step1: 10 millisecond       step2: 50 milliseconds      step 3: 4 milliseconds
Process#3   step1:2 millisecond     step2: 40 milliseconds      step 3: 80 milliseconds
Now I want to detect that which process has suspicious response time, what is the rule for this in concepts of software engineering? I mean I have tried the values which are greater than average + 3* standard deviation, but it did not work, only a few data has been marked but I know that data more than 100 millisecond is not normal
What is the rule for this purpose in software engineering, how we detect the bottle neck of system?

A: There's no real rule of thumb for finding bottlenecks.  The rule is, you measure objectively which parts of your application are slow, and then you have a definitive answer.
Much engineering time is wasted by trying to optimise code that turns out not to be slow in the first place.  So measure, and then act.  Make sure you can reproduce the slow performance, so that you can repeat a test and test your changes reliably.

A: If you look at this Wiki page, there are many links for software that watches the performance of an application.
http://en.wikipedia.org/wiki/System_profiler


text:
Q: Forcing a TCP stream to send buffer contents I am using Csharp tcp sockets to send data between a client and server.
Now the problem as i see it or as i perceive it is that tcp is a stream protocol and will not push (send) data unless their is a sufficient amount of it.
For instance say i wanted to send some data whatever it is doesnt matter lets just say its 8 bytes long. The behaviour i am seeing is no matter how long i wait it wont send that data unless i push more behind it presumably until i reach the tcp buffer.
So my question is. If i want to send a small amount of data via tcp do i need to append garbage to the end to force the socket to send. ( I wouldnt feel good about this ) or is their an alternative way i can force the front segment of the stream to send.
thanks in advance. i am still learning tcp so excuse the ignorance.

A: Don't set NoDelay unless you are an expert at TCP/IP and understand its full ramifications. If you haven't read Stevens, don't even think about it.
Here's an example question: if you establish a socket connection and send 8 bytes on it, are the 8 bytes immediately sent or does the Nagle algorithm wait for more data to send? The answer is "the 8 bytes are sent immediately" - but don't consider messing with Nagle until you understand exactly why that is the answer.
Here's another question: in a standard command/response protocol, how much Nagle delay is applied to each packet? The answer: none. Again, you should research why Nagle causes no delays in this common scenario.
If you're not seeing the data sent by 250 milliseconds (the maximum delay caused by Nagle in the worst possible scenario), then there is something else wrong.

A: You could set the NoDelay property (I think it's what disables Nagle).


text:
Q: What is wrong with my code? I am stuck. I am trying to export some promise results I am trying to export an object to another module which includes a promise. I want results of the promises. I can get the result of promises, I just can't export. Or maybe I did everything wrong in this function.
I am building an application for people to create their own interactive stories.
I get a link, a heading, a story beginning, some story choices and story parts.
I was able to store them and sort them. I've cloned the original arrays, so I could modify the code safely.
Those clone arrays are the results of promises which are taken from the local storage. I've turned local storage functions to async functions so there is no problem about that.
The promises were ready and I've created this final function where I stuck.
export const sendToHell = {
  res: [],
  kamino: async function () {
    this.res = await Promise.all([
      stored.storedLink,
      stored.storedHeading,
      stored.storedBeginning,
      stored.storedChoices,
      stored.storedParts,
    ]);
    return this.res;
  },
  cloneLink: [...sendToHell.res[0]],
  cloneHeading: [...sendToHell.res[1]],
  cloneBeginning: [...sendToHell.res[2]],
  cloneChoices: [...sendToHell.res[3]],
  cloneParts: [...sendToHell.res[4]],
};

sendToHell.kamino();

The error I am getting here is 'Cannot access sendToHell beofre init.' What I actually need from this code is, modified clone arrays. When I used "this" key word. I get an another error. which is 'Cannot read properties of undefined reading res'
I've tried top level await but for a reason I don't know it doesn't work. "I know top level await only works in modules."
To be more clear.
"Stored" is an array which includes other arrays like stored link, stored heading...
"StoredHeading", "StoredBeginning"... Those are arrays coming from local storage. They are resolved promises.
"CloneHeading", "CloneBeginning" ... These will be the arrays which will be clones of Stored arrays and exported to another module.
Finally I know that exports and imports are synchronous. And if I write them in global scope they will be executed first while my promise is waiting. I've also tried the immediately executed function.
Thank you for your time.
Thank you for your time .

A: sendToHell is an anti-pattern of Promise.all -
const [
  cloneLink,                     // <Value 1>
  cloneHeading,                  // <Value 2>
  cloneBeginning,                // <Value 3>
  cloneChoices,                  // <Value 4>
  cloneParts,                    // <Value 5>
] = await Promise.all([
  stored.storedLink,             // <Promise 1>
  stored.storedHeading,          // <Promise 2>
  stored.storedBeginning,        // <Promise 3>
  stored.storedChoices,          // <Promise 4>
  stored.storedParts,            // <Promise 5>
])

If you insist on a wrapper function -
function kamino(stored) {
  return Promise.all([
    stored.storedLink,           // <Promise 1>
    stored.storedHeading,        // <Promise 2>
    stored.storedBeginning,      // <Promise 3>
    stored.storedChoices,        // <Promise 4>
    stored.storedParts,          // <Promise 5>
  ])
}

export { kamino }

import { kamino } from "./path/to/kamino.js"

const [
  cloneLink,                     // <Value 1>
  cloneHeading,                  // <Value 2>
  cloneBeginning,                // <Value 3>
  cloneChoices,                  // <Value 4>
  cloneParts,                    // <Value 5>
] = await kamino(stored)

A: Well, your code seems more/less correct. I am not certain what "store" variable holds, and not sure the purpose of your "sendToHell" object, however if it's possible It seems you would like to use "OOP" approach, which JavaScript is capable of since ES6 if I remember courtly. There are also closures which I am going to use in my example.
In lame terms what you want to do, is to create another async function that is awaiting your kamino function to resolve everything. If you are able to use top-level await I would suggest using this approach, I am going to create another function for that purpose.

const sendToHell = (function () {
  let res = [];

  return {
    kamino: async function () {
      res = await Promise.all([
        "stored.storedLink",
        "stored.storedHeading",
        "stored.storedBeginning",
        "stored.storedChoices",
        "stored.storedParts"
      ]);
    },
    cloneLink: function () {
      return res[0];
    },
    cloneHeading: function () {
      return res[1];
    },
    cloneBeginning: function () {
      return res[2];
    },
    cloneChoices: function () {
      return res[3];
    },
    cloneParts: function () {
      return res[4];
    }
  };
})();

const initializeApp = async function () {
  const outputEl = document.getElementById("output");
  await sendToHell.kamino();
  // Change your function name for different output
  outputEl.innerHTML = sendToHell.cloneHeading();
};

initializeApp();


text:
Q: Can't seem to create file in bash I'm trying to use this (under the root account) code in debian 7.
#!/bin/bash

cat > /root/.ssh/github.id_rsa << EOF
-----BEGIN RSA PRIVATE KEY-----
XYZ...
-----END RSA PRIVATE KEY-----
EOF
chmod 600 /root/.ssh/github.id_rsa

When I navigate to this folder afterwards it's tells me it doesn't exist. I've checked and double checked but can't work out what I'm doing wrong.
EDIT: When I run the command manually it seems to work! But I am trying to run this as part of a shell script.

A: The .ssh folder probably doesn't/didn't exist when you first ran the command. The safest thing to do is to add a command before the cat that checks/creates the folder:
#!/bin/bash

mkdir -p /root/.ssh

chmod 700 /root/.ssh
cat > /root/.ssh/github.id_rsa << EOF
<some content>
EOF
chmod 600 /root/.ssh/github.id_rsa


text:
Q: Java Input String into Time How can I make a Java program so that, in a console application, if the user were to enter a time (say 13:00) as a String with the Scanner, I can turn this String into a time object that can be used for maths.
Any ideas or am I in way over my head?
Edit:
In my app, charges apply for different times (extra for night time etc). I need to be able to get the numbers from a String (or Double, I'm flexible)

A: You need to do a couple of things first, like giving a hint to the user about how the input time can look like... So I would do:

*

*Define the input format for the time

*Give a hint to the user about it

*Parse the input to the format you defined

*And finally manipulate the date as you need it

Example:
public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    String format = "HH:mm:ss";
    System.out.println("Please give the desired time in this fomrat HH:mm:ss ...");
    String inp = s.nextLine();
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    try {
        Date date = sdf.parse(inp);
        System.out.println("this is the date:" + date);
    } catch (ParseException e) {
        System.err.println("invalid date...");
    }
}


text:
Q: Component definition is missing display name react/display-name How do I add a display name to this?
export default () =>
  <Switch>
    <Route path="/login" exact component={LoginApp}/>
    <Route path="/faq" exact component={FAQ}/>
    <Route component={NotFound} />
  </Switch>;

A: tldr: switch arrow function to a named function
Lint Error shown: Component definition is missing display name react/display-name.
To resolve, you can name your function (IOW, do not use arrow function).  In this example, I am using react-table and passing a custom component to render in a cell.
No error:
{
  Cell: function OrderItems({ row }) {
    return (

        View Items

    );
  },
}

Error:
{
  Cell: ({ row }) => (

      View Items

  )
}

A: Exporting an arrow function directly doesn't give the component a displayName, but if you export a regular function the function name will be used as displayName.
export default function MyComponent() {
  return (
    <Switch>
      <Route path="/login" exact component={LoginApp}/>
      <Route path="/faq" exact component={FAQ}/>
      <Route component={NotFound} />
    </Switch>
  );
}

You can also put the function in a variable, set the displayName on the function manually, and then export it.
const MyComponent = () => (
  <Switch>
    <Route path="/login" exact component={LoginApp}/>
    <Route path="/faq" exact component={FAQ}/>
    <Route component={NotFound} />
  </Switch>
);

MyComponent.displayName = 'MyComponent';

export default MyComponent;

A: Writing the follow line, before the "arrow function" it worked for me
> /* eslint-disable react/display-name */
Header: () => ID,

Look how work here: https://eslint.org/docs/latest/user-guide/configuring/rules

A: A way to add displayName property to anonymous component function without creating named function is to use recompose:
import { compose, setDisplayName } from 'recompose';

export default compose(setDisplayName('SomeComponent'))(props => ...);

Or just:
export default Object.assign(props => ..., { displayName: 'SomeComponent' });

A: Similarly if you have a functional component like:
export default function test(){

return (

}

And make another component inside of that like a text box which updates a state inside of a functional component from using refs which makes sure the entire page does not re-render and only just that component you need to give it a display name. Or there will be build errors.
export default function test(){
    const stateForFunctionalComponent = useRef("");

    const seperateTextBoxState = React.forwardRef((props,ref) => {
    const [textBoxDocTitle, setTextBoxDocTitle] = useState("");

    useEffect(() => {
      ref.current = textBoxDocTitle;
    },[textBoxDocTitle])

    return <input
      id="somethingUnique"
      type="text"
      required="required"
      placeholder="Enter document name..."
      onInput={(e) => setTextBoxDocTitle(e.target.value)}>
  </input>})

    //Line that matters!!!
    seperateTextBoxState.displayName = "seperateTextBoxState";
}

    return (
<seperateTextBoxState ref={stateForFunctionalComponent}/>
)
}

A: if you are using eslint this may be because of don't providing
the following code
yourclassName.displayName="name"


text: Q: Перевод декартовой системы координат в пиксельную GDI+ c# У меня есть массив точек для построения графика, подскажите пожалуйста способ перевода точек в пиксели , чтобы построить график с помощью графики GDI+


text:
Q: Getting wrong shape of logits from TFRobertaForSequenceClassification I am using the the TFRobertaForSequenceClassification class of the huggingface library to create a classifier. According to the documentation, the logits output should have a shape of (batch_size, num_labels). I however get (batch_size, seq_length, num_labels) and I dont understand why.
To reproduce this:
from transformers import TFRobertaForSequenceClassification, RobertaConfig
import numpy as np

seq_len = 512

classifier = TFRobertaForSequenceClassification(RobertaConfig())

#create random inputs for demo
input_ids = np.random.randint(0,10000, size=(seq_len,))
attention_mask = np.random.randint(0,2, size=(seq_len,))
token_type_ids = np.random.randint(0,2, size=(seq_len,))

#make a prediction with batch_size of 1
output = classifier.predict([input_ids, attention_mask, token_type_ids])

print(output.logits.shape)

This outputs logits in the shape of (512,2) but I am expecting (1,2) or (batch_size, num_labels). Can anyone shed any light on why it behaves like this?

A: Created an issue on github on this and got an answer. The predictions have to be batched (not enough to add a batch size of 1 with a list containing a prediction).  Also, 510 is the max length as well since we have to account for the beginning and end tokens - Further discussed here:
https://github.com/huggingface/transformers/issues/9102


text:
Q: Office 365 API, error: The token has invalid value 'roles' for the claim type '' I'm trying to access the office 365 API's, in particular the Exchange APIs.
I am attempting to develop a server / daemon application to poll a shared inbox therefor I am using the 'client_credentials' grant type with OAuth 2.0. I have followed steps to produce an application in Azure Active Directory, you can see from the screen grab the permissions the app has: http://gyazo.com/a2d614a690115f8a6b65de00f46b1599
Eventually I want to develop a Ruby application to pull the data but to begin with I am testing responses with cURL, here is the OAuth Token requrest:
curl -X POST https://login.windows.net/TENANT_KEY/oauth2/token \
  -F redirect_uri=http://spreadyDaemon \
  -F grant_type=client_credentials \
  -F resource=https://outlook.office365.com/ \
  -F client_id=XXXX \
  -F client_secret=XXXX=

Which returns me a JWT key that looks like this when decoded:
Header
{
  "x5t": "kriMPdmBvx68skT8-mPAB3BseeA",
  "alg": "RS256",
  "typ": "JWT"
}

Claims
{
  "ver": "1.0",
  "aud": "https://outlook.office365.com/",
  "iss": "https://sts.windows.net/TENANT_KEY/",
  "oid": "17fa33ae-a0e9-4292-96ea-24ce8f11df21",
  "idp": "https://sts.windows.net/TENANT_KEY/",
  "appidacr": "1",
  "exp": 1415986833,
  "appid": "XXXX",
  "tid": "e625eb3f-ef77-4c02-8010-c591d78b6c5f",
  "iat": 1415982933,
  "nbf": 1415982933,
  "sub": "17fa33ae-a0e9-4292-96ea-24ce8f11df21"
}

However when I then use that token to request anything from the Exchange API I get a 401 Unauthorized with the x-ms-diagnostics header set to:
x-ms-diagnostics: 2000001;reason="The token has invalid value 'roles' for the claim type ''.";error_category="invalid_token"

Here is the full header:
HTTP/1.1 401 Unauthorized
Cache-Control: private
Server: Microsoft-IIS/8.0
request-id: d08d01a8-7213-4a13-a598-08362b4dfa70
Set-Cookie: ClientId=WDALDNO0CAIOOZDZWTA; expires=Sat, 14-Nov-2015 16:40:59 GMT; path=/; HttpOnly
X-CalculatedBETarget: am3pr01mb0662.eurprd01.prod.exchangelabs.com
x-ms-diagnostics: 2000001;reason="The token has invalid value 'roles' for the claim type ''.";error_category="invalid_token"
X-DiagInfo: AM3PR01MB0662
X-BEServer: AM3PR01MB0662
X-AspNet-Version: 4.0.30319
Set-Cookie: exchangecookie=6bf68da033684824af21af3b0cdea6e3; expires=Sat, 14-Nov-2015 16:40:59 GMT; path=/; HttpOnly
Set-Cookie: X-BackEndCookie2=OrganizationAnchor@Fitzdares.onmicrosoft.com=u56Lnp2ejJqBz82am8zJx8zSzcmey9LLyZrI0p6cmp3SycjLm8eazcjIy83IgbmWi4Wbno2ajNGQkZKWnI2QjJCZi9GckJKBzc/Oy9LOzdLOy6vOycXLz8XKxoGaio2PjZvPztGPjZCb0ZqHnJeekZiak56djNGckJI=; expires=Sun, 14-Dec-2014 16:40:59 GMT; path=/EWS; secure; HttpOnly
Set-Cookie: X-BackEndCookie=OrganizationAnchor@Fitzdares.onmicrosoft.com=u56Lnp2ejJqBz82am8zJx8zSzcmey9LLyZrI0p6cmp3SycjLm8eazcjIy83IgbmWi4Wbno2ajNGQkZKWnI2QjJCZi9GckJKBzc/Oy9LOzdLOy6vOycXLz8XKxg==; expires=Sun, 14-Dec-2014 16:40:59 GMT; path=/EWS; secure; HttpOnly
X-Powered-By: ASP.NET
X-FEServer: DB4PR02CA0026
WWW-Authenticate: Bearer client_id="00000002-0000-0ff1-ce00-000000000000", trusted_issuers="00000001-0000-0000-c000-000000000000@*", authorization_uri="https://login.windows.net/common/oauth2/authorize", error="invalid_token",Basic Realm="",Basic Realm=""
Date: Fri, 14 Nov 2014 16:40:59 GMT
Content-Length: 0

I'm not sure whether I've misunderstood some documentation or missed a step somewhere. The JWT however is missing any scopes for access. I'm not sure of how to add specific permissions to the application manifest as described here: http://msdn.microsoft.com/en-us/office/office365/howto/application-manifest#AppManifest_ExchangeScopes
This is how my manifest appears:
{
  "allowActAsForAllClients": null,
  "appId": "XXXX",
  "appMetadata": {
    "version": 0,
    "data": []
  },
  "appRoles": [],
  "availableToOtherTenants": false,
  "displayName": "Fitzdares",
  "errorUrl": null,
  "groupMembershipClaims": null,
  "homepage": "http://spreadyDaemon",
  "identifierUris": [
    "http://spreadyDaemon"
  ],
  "keyCredentials": [],
  "knownClientApplications": [],
  "logoutUrl": null,
  "oauth2AllowImplicitFlow": false,
  "oauth2AllowUrlPathMatching": false,
  "oauth2Permissions": [],
  "oauth2RequirePostResponse": false,
  "passwordCredentials": [
    {
      "customKeyIdentifier": null,
      "endDate": "2016-11-14T16:30:45.0745603Z",
      "keyId": "46cce171-ed65-4828-8af7-d02af950e44a",
      "startDate": "2014-11-14T16:30:45.0745603Z",
      "value": null
    }
  ],
  "publicClient": null,
  "replyUrls": [
    "http://spreadyDaemon"
  ],
  "requiredResourceAccess": [
    {
      "resourceAppId": "00000002-0000-0ff1-ce00-000000000000",
      "resourceAccess": [
        {
          "id": "3b5f3d61-589b-4a3c-a359-5dd4b5ee5bd5",
          "type": "Scope"
        },
        {
          "id": "185758ba-798d-4b72-9e54-429a413a2510",
          "type": "Scope"
        },
        {
          "id": "75767999-c7a8-481e-a6b4-19458e0b30a5",
          "type": "Scope"
        },
        {
          "id": "5eb43c10-865a-4259-960a-83946678f8dd",
          "type": "Scope"
        }
      ]
    },
    {
      "resourceAppId": "00000002-0000-0000-c000-000000000000",
      "resourceAccess": [
        {
          "id": "5778995a-e1bf-45b8-affa-663a9f3f4d04",
          "type": "Scope"
        },
        {
          "id": "78c8a3c8-a07e-4b9e-af1b-b5ccab50a175",
          "type": "Scope"
        },
        {
          "id": "311a71cc-e848-46a1-bdf8-97ff7156d8e6",
          "type": "Scope"
        }
      ]
    }
  ],
  "samlMetadataUrl": null,
  "defaultPolicy": [],
  "extensionProperties": [],
  "objectType": "Application",
  "objectId": "8af97a9f-74c7-499d-b29a-7fca6926d84e",
  "deletionTimestamp": null,
  "createdOnBehalfOf": null,
  "createdObjects": [],
  "manager": null,
  "directReports": [],
  "members": [],
  "memberOf": [],
  "owners": [],
  "ownedObjects": []
}

Any help would be greatly appreciated!

A: Venkat,
I suspect the problem is in how you're requesting the token. You're using grant_type=client_credentials, which isn't supported by Exchange Online (at least not for now). The only grant type supported by Exchange is authorization_code. See Matthias' comment on 11/4 on this post:
http://blogs.msdn.com/b/exchangedev/archive/2014/03/25/using-oauth2-to-access-calendar-contact-and-mail-api-in-exchange-online-in-office-365.aspx
This may also be helpful:
http://blogs.msdn.com/b/exchangedev/archive/2014/10/28/oauth2-in-action-with-the-release-of-office-365-calendar-contacts-and-mail.aspx
UPDATE: Client credential flow is now supported! http://blogs.msdn.com/b/exchangedev/archive/2015/01/22/building-demon-or-service-apps-with-office-365-mail-calendar-and-contacts-apis-oauth2-client-credential-flow.aspx
Jason

A: Thanks for the detailed info!  Your issue may be the same as the one discussed in this StackOverflow question and unchecking "Have full access to a user's mailbox" may fix the issue you are seeing.
Please let me know if you have any questions or if you are getting access denied even after unchecking this permission.
[UPDATE]: Jason is right - we don't yet support client-credential flow.  However, we are very close to making this available.  So, please stay tuned for a blog in a few weeks with an announcement that it is available and instructions to use it.
[UPDATE]: Support for service accounts is now available. Please see our blog announcement for more details.


text:
Q: Elegant reduce function I am trying to reduce an array of objects (config values in my case).
My array looks like this:
const settings = [
  {room: null, key: 'radioEnabled', value: true},
  {room: 24,   key: 'radioEnabled', value: false},
  {room: 24,   key: 'name',         value: 'Jack'},
  {room: 23,   key: 'name',         value: 'Mike'},
  {room: 23,   key: 'radioEnabled', value: false},
  {room: null, key: 'tvEnabled',    value: false},
];

This array is not ordered in any way.
If a room is set to null, this means it is a global setting.
Global settings can be overwritten by local settings.
I am trying to write a function to get all settings for a room.
For room 24 it should return:
[
  {room: 24,   key: 'radioEnabled', value: false},
  {room: 24,   key: 'name',         value: 'Jack'},
  {room: null, key: 'tvEnabled',    value: false},
]

The order in which the values are returned is not important to me.
I have been able to achieve this in more than one way, but the solutions just don't seem that elegant/readable to me. Can anybody suggest a more elegant idea?
My solutions are below and on jsfiddle.

const settings = [
  {room: null, key: 'radioEnabled', value: true},
  {room: 24,   key: 'radioEnabled', value: false},
  {room: 24,   key: 'name',         value: 'Jack'},
  {room: 23,   key: 'name',         value: 'Mike'},
  {room: 23,   key: 'radioEnabled', value: false},
  {room: null, key: 'tvEnabled',    value: false},
];

const getAll_1 = function(room){
 return settings.reduce( (a, b) => {
   // remove all other rooms
   if(b.room && b.room!== room){
     return a;
   }

  // see if the setting is already added
   let found = a.find( (setting) => {
     return setting.key === b.key;
   })

  // we already have a local value in our return array, don't add/replace anything
   if( found && found.room === room) {
     return a;
   }

   // we have a value, but it's not local. Replace the current value with the new one
   if( found ) {
      const index = a.findIndex( (setting) => {
      return setting.key === b.key;
    })
     a[index] = b;
     return a;
   }

   // we don't have this setting at all. add it.
   return a.concat(b);
 }, []);
}

const getAll_2 = function(room){
 return settings
    // first filter out all other room settings, only keep current room and global values
   .filter( (setting) => {
    return setting.room === null || setting.room === room;
  })
    // than sort em so all local (high prio) values are up top
  .sort( (a, b) => {
    return (a.room > b.room) ? -1 : ( a.room < b.room ) ? 1 : 0;
  })
    // reduce the array, adding only global values if they are not already added as local value
  .reduce( (a, b) => {
    const found = a.find( (setting) => {
      return setting.key === b.key;
    })
    if (found){
     return a;
    }
    return a.concat(b);
  }, [])
}

console.log(`Stack Overflow does not support console.table. Open your console for better representation`);

console.log(`getAll_1 response:`);
console.table(getAll_1(24));
console.log(`getAll_2 response:`);
console.table(getAll_2(24));
Check your console

A: Another approach, which might or might not help with your fundamental requirements, is to convert this to a more useful format:

const roomSettings = settings => {
  const globals = settings.filter(s => s.room == null)
    .reduce((all, {key, value}) => ({...all, [key]: value}), {})

  return settings.filter(s => s.room != null)
    .reduce((all, {room, key, value}) => ({
      ...all,
      [room]: {...(all[room] || globals), [key]: value}
    }), {} )
}

const settings = [{"key": "radioEnabled", "room": null, "value": true}, {"key": "radioEnabled", "room": 24, "value": false}, {"key": "name", "room": 24, "value": "Jack"}, {"key": "name", "room": 23, "value": "Mike"}, {"key": "radioEnabled", "room": 23, "value": false}, {"key": "tvEnabled", "room": null, "value": false}, {"key": "name", "room": 25, "value": "Beth"}]

console.log(roomSettings(settings))

Note that this returns something like the following:
{
  23: {
    radioEnabled: false,
    tvEnabled: false,
    name: "Mike"
  },
  24: {
    radioEnabled: false,
    tvEnabled: false,
    name: "Jack"
  },
  25: {
    radioEnabled: true,
    tvEnabled: false,
    name: "Beth"
  }
}

(I added 'Beth' to have at least one that wasn't false/false.)
This format looks more useful, but it certainly might not be for you.

A: basically it is easier to use filter over your array, this filter function wrapped in a higher function to receive the room number as a parameter.
edit: forgot about the reduce to remove the duplicates.

const settings = [{
    room: 24,
    key: 'radioEnabled',
    value: false
  },
  {
    room: null,
    key: 'radioEnabled',
    value: true
  },
  {
    room: 24,
    key: 'name',
    value: 'Jack'
  },
  {
    room: 23,
    key: 'name',
    value: 'Mike'
  },
  {
    room: 23,
    key: 'radioEnabled',
    value: false
  },
  {
    room: null,
    key: 'tvEnabled',
    value: false
  },
];

const getConfigs = (room = null, settings = []) => {
  return settings
    // filter all the options that match our criteria.
    .filter(setting => setting.room === room || setting.room === null)
    // using reduce we will remove the duplicated key entries.
    .reduce((accum, currentVal) => {
      // if the index is -1 it means it is not on the array, so we add it.
      const index = accum.findIndex(accumSetting => accumSetting.key === currentVal.key)
      if (index === -1) {
        accum.push(currentVal);
      } else { // it means that we have the entry. replace if we have a local one.
        if(currentVal.room === room && accum[index].room === null){
          accum[index] = currentVal;
        }

      }
      return accum;
    }, [])
}

const result24 = getConfigs(24, settings);
const result23 = getConfigs(23, settings);

console.log(result24);
console.log(result23);

A: Here's a possible alternative -

const globals =
  { radioEnabled: true
  , tvEnabled: false
  }

const settings =
  [ { room: 24, name: 'Jack' }
  , { room: 24, radioEnabled: false }
  , { room: 25, name: 'Mike' }
  , { room: 25, tvEnabled: true }
  ]

const assign = (o1, o2) =>
  ({ ...o1, ...o2 })

const getConfig = (room, settings = []) =>
  settings
    .filter (s => s.room === room)
    .reduce (assign, globals)

console .log
  ( getConfig (24, settings)
    // { radioEnabled: false
    // , tvEnabled: false
    // , room: 24
    // , name: 'Jack'
    // }

  , getConfig (25, settings)
    // { radioEnabled: true
    // , tvEnabled: true
    // , room: 25
    // , name: 'Mike'
    // }
  )

A: You could first get the specific settings, and then add the general ones if there isn't already a specific one for the key:

const settings = [
  {room: null, key: 'radioEnabled', value: true},
  {room: 24,   key: 'radioEnabled', value: false},
  {room: 24,   key: 'name',         value: 'Jack'},
  {room: 23,   key: 'name',         value: 'Mike'},
  {room: 23,   key: 'radioEnabled', value: false},
  {room: null, key: 'tvEnabled',    value: false},
];

const generalSettings = settings.filter(x => x.room === null);

const getSettings = (roomID) =>
{
    let keysAdded = new Set();

    // Get specific settings and add keys on the set.

    let res = settings.filter(x => x.room == roomID && keysAdded.add(x.key));

    // Add general settings.

    return generalSettings.reduce(
        (acc, curr) => keysAdded.has(curr.key) ? acc : [...acc, curr],
        res
    );
}

console.log(getSettings(23));
console.log(getSettings(24));

A: I would suggest:

*

*Filter first for where room is null

*Then filter for where room is the desired room number

*Concatenate both results in that order

*Add that to a Map to get only one entry per key

*Output as an array

The fact that the first two filter-results are concatenated in that order will ensure that null room entries get lower priority than non-null entries.

function getAll(room){
    return [...new Map([...settings.filter(a => a.room === null),
                        ...settings.filter(a => a.room === room)]
               .map(a => [a.key, a])).values()]
}

const settings = [{room: null, key: 'radioEnabled', value: true},{room: 24,   key: 'radioEnabled', value: false},{room: 24,   key: 'name', value: 'Jack'},{room: 23,   key: 'name',         value: 'Mike'},{room: 23,   key: 'radioEnabled', value: false},{room: null, key: 'tvEnabled', value: false}];

console.log(getAll(24));

A: You can do this with one reduce loop if you store result in object based on key field and then get its values to return an array as a result.

*

*Check if room is null or target value

*Check if key property for that setting doesn't exist or if its room value is null

const settings = [{"room":null,"key":"radioEnabled","value":true},{"room":24,"key":"radioEnabled","value":false},{"room":24,"key":"name","value":"Jack"},{"room":23,"key":"name","value":"Mike"},{"room":23,"key":"radioEnabled","value":false},{"room":null,"key":"tvEnabled","value":false}]

const getAll = room => {
  return Object.values(settings.reduce((r, e) => {
    if (e.room == null || e.room == room) {
      if (!r[e.key] || r[e.key].room == null) r[e.key] = e
    }
    return r;
  }, {}))
}

console.log(getAll(24))


text:
Q: Run .bashrc only if terminal launched from within GUI Some of the similar questions don't quite seem to match with my question. What I'm trying to do is to have .bashrc (or similar) to only run certain custom commands when I launch it from within the GUI (Xfce), but not in the initial login screen.
Some details:

*

*Ubuntu 16.04 Virtual Machine (VirtualBox 5.2.10) on Windows host

*When I launch it, I use the user vagrant in the boot login screen

*I normally launch Xfce manually with sudo startxfce4

*Then once the GUI has loaded, I launch a terminal (Terminator) and it runs for user vagrant
So what currently happens:

*

*I launch the VM

*It asks for user in the boot screen

*Then it will use the .bashrc of that user and already does the commands I have there. I would want them to only run when I use the GUI terminal (This is my question - how to do that?)

*Start the GUI

*Then when I launch the terminal in the GUI, it will run those same commands again.

What I would like to happen:

*

*Launch the VM

*Login as the user - and do not run the specified commands yet

*Start the GUI

*Launch the terminal from GUI - now it should run the commands automatically

So, basically I'm looking for some kind of system flag that tells it is not running on GUI. Does such exist? I imagine you could check it from somewhere, like xfce status or similar?
The key thing is, I would like it to run automatically instead of running a script from PATH, because that is easy to forget and you might spend quite some time debugging why something doesn't work, only to notice you forgot to run the prerequisite commands.
Thanks!

A: The shell variable TERM
I think you can check the value of the shell variable TERM with 'if' or 'case' statements to control what to do in text screen and graphical desktop environment.
It is already used in the default bash configuration file ~/.bashrc files of Ubuntu Desktop.

*

*In Ubuntu 18.04 LTS graphical desktop:
$ echo "$TERM"
xterm-256color

This may vary between versions of Ubuntu. Check in your installed system.

*In Ubuntu 18.04 LTS text screen:
$ echo "$TERM"
linux

Demo example
Add an 'if' statement to the bash configuration file ~/.bashrc
It is a good idea to make a backup copy before doing it.
cp -p ~/.bashrc ~/.bashrc.backup

and then add something like the following lines (modified for your particular purpose) at the end of the file ~/.bashrc
if [ "$TERM" != "linux" ]
then
 echo "Do your commands for a graphical desktop"
 ...
 ...
fi


text:
Q: Query SQL Server from SPSS how to connect I am at a total loss on how to do what I think is a fairly simple and standard task:
I am running SPSS 20 on Mac and want to connect to a SQL Server database on a remote server.
When going to File -> Open Database -> New Query (The command names may be a bit off, my SPSS is in German and I'm just translating) it only shows myodbc as data source. I assume I have to add a driver for SQL Server however I don´t really know where to get it or how to install it as I cannot find it in the SPSS installation at hand. Anyone can help me out?
Thanks a lot in advance!

A: The Data Access Pack is available with your Statistics installation (may be a separate download), and it contains drivers for most major data sources.

A: It looks like IBM doesn't include (or make!) the drivers for Mac installations. Check it out:

*

*http://www-01.ibm.com/support/docview.wss?uid=swg21480987
You have to buy them separately. For example:

*

*http://www.actualtech.com/download.php


text:
Q: How to silence ActionController::UnknownHttpMethod errors? On my Rails production website I sometimes get a dozen or so errors along the lines of:

An ActionController::UnknownHttpMethod occurred in #:
TRACK, accepted HTTP methods are OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, UNLOCK, VERSION-CONTROL, REPORT, CHECKOUT, CHECKIN, UNCHECKOUT, MKWORKSPACE, UPDATE, LABEL, MERGE, BASELINE-CONTROL, MKACTIVITY, ORDERPATCH, ACL, SEARCH, MKCALENDAR, and PATCH

I guess this is when bots hit my site with HTTP methods that Rails can't handle (in my case it's mostly OPENVAS, TRACK, DEBUG, TRACK, and INDEX but also weird methods like WMIXLVXM).
Is there a way to silence these messages in any way? I am still unsure as to whether this is a Rails issue or an Nginx issue.
I am using a custom controller to render custom error pages to the user:
Rails.application.routes.draw do

  %w(404 500).each do |status|
    match status, :to => 'errors#show', :status => status, :via => :all
  end

  ...

end

class ErrorsController < ApplicationController

  def show
    status = params[:status] || 500
    @title = "Error"
    render(:status => status, :template => "errors/show.html.erb")
  end

end

But my custom controller is probably not causing the errors?
Thanks for any help.

A: Actually, what bothers me the most is the Exception Notifications I am getting from Rails when a bot hits my site with an unknown HTTP method. (Sometimes I get a dozen or so exception emails à la An ActionController::UnknownHttpMethod occurred in ... within a matter of seconds.)
So in my production.rb I added one extra line:
  config.middleware.use ExceptionNotification::Rack,
    :ignore_exceptions => ['ActionController::UnknownHttpMethod'] + ExceptionNotifier.ignored_exceptions, # I added this line
    :email => {
      :email_prefix => "[ERROR]",
      :sender_address => %{"Error Notification" <notification@mydomain.com>},
      :exception_recipients => %w{administrator@mydomain.com}
    }

Let's see how that works out. I will post updates in a few weeks.

A: Since these are requests that you are not going to handle anyway, better way is to limit https methods at nginx level, so that these will not hit rails at all:
server {
  # (your vhost for this app)

  if ($request_method !~ ^(GET|HEAD|PUT|POST|DELETE|OPTIONS|PATCH)$ ){
    return 405;
  }
}


text:
Q: Favicon not working in Firefox if the page is in Lightning App Builder We have requirement for adding Favicon for Lightning Home page which was built in Lightning App Builder. If the page is in Tab or Preview mode I am able to see favicon, but the samepage is in Lightning App Builder I am able to see salesforce default favicon.

A: When posting browser specific issues, make sure you include the following:

-browser name
-browser version
-device being used

Validate that you are using the latest browser version and see if you can reproduce the issue, test with other device(s) as well.
If the issue persists, contact browser support, for ex.
for google chrome:

https://support.google.com/chrome

Firefox:

https://support.mozilla.org/

Or last but not least, Salesforce support. unfortunately, there isint much we can do here for these specific issues.


text:
Q: Find the number of $n-1$ dimensional subspaces $V_2$ such that $V_1+V_2=V$ where $\dim V_1=1$
Let $V$ be an $n$ dimensional vector space over a finite field $F$ of order $p$ where $p=q^t$ and $q$ is a prime.
Let $V_1$ be a $1$ dimensional subspace of $V$.
  Show that number of $n-1$ dimensional subspaces $V_2$ of $V$ such that $V_1+V_2=V$ is $p^{n-1}$.

My try:
I took $n=3,p=2$. Then $V$ has $7$ one-dimensional and $7$ two-dimensional subspaces.
Listing the $1$ dimensional subspaces:
$\langle (1,0,0)\rangle ,\langle (0,1,0)\rangle ,\langle (0,0,1)\rangle ,\langle (1,1,0)\rangle ,\langle (0,1,1)\rangle ,\langle (1,0,1)\rangle ,\langle (1,1,1)\rangle $
Listing the  $2$ dimensional subspaces:
$\langle [1 0 0],
 [0 1 0] \rangle, \langle [1 0 0],
 [0 0 1]\rangle,\langle [1 0 0]
 ,[0 1 1]\rangle ,\langle [0 1 0],
 [0 0 1]\rangle ,\langle [1 1 0],
 [0 0 1]\rangle ,\langle [1 0 1],
 [0 1 0]\rangle ,\langle [1 0 1]
 ,[0 1 1]\rangle $
If we take  $V_1=(1,0,0)$ then we have $4$ choices for $V_2$ namely $\langle [0 1 0],
 [0 0 1]\rangle ,\langle [1 1 0],
 [0 0 1]\rangle ,\langle [1 0 1],
 [0 1 0]\rangle ,\langle [1 0 1]
 ,[0 1 1]\rangle $
So the answer is in this case $2^2=4$ and is true for any subspace $V_1$  of $V$
But how to frame the argument in general?I am unable to proceed in this case.Please help.

A: I'm going to reverse your notation to correspond to usual conventions.  So let $p$ be a prime, let $q$ be a power of $p$.
Let's also establish the following notation:  $[k] = [k]_q = \frac{q^k-1}{q-1}$,  $[k]! = [k][k-1]\cdots [2][1]$, and  $\genfrac [ ] {0pt}{} {n} {k} = \frac{[n]!}{[k]! [n-k]!}$.
Let $\def\F{\mathbb F} \F$ be a field of size $q$, and let $V$ be an $n$-dimensional vector space over $\F$.  We fix a subspace $V_1$ of dimension $1$.
In general, the number of subspaces of $V$ of dimension $k$ is $\genfrac [ ] {0pt}{} {n} {k}$.  In particular the number of subspaces of dimension $n-1$ is $\genfrac [ ] {0pt}{} {n} {n-1} = [n]$.
Note that subspaces of dimension $n-1$ which contain $V_1$ correspond one to one with subspaces of $V/V_1$ of dimension $n-2$, so using the previous paragraph, the number of these is $[n-1]$.
We want to count the number of subspaces of $V$ of dimension $n-1$ which do not contain $V_1$, thus the number is $[n] - [n-1] = q^{n-1}$.

A: I am sure that @fredgoodman 's approach is the right way to go about these questions in general. I only offer this to show that this particular question does not need the whole $q$-apparatus.
Let $V$ be $n$-dimensional over the finite field $\mathbb{F}_q$, and let $U$ be a fixed $r$-dimensional subspace. How many subspaces are there such that $V=U\oplus W$?
Let $e_1,e_2,\dots, e_r$ be a basis of $U$, and extend this to a basis $e_1,e_2,\dots, e_n$ of $V$.
The requirement $V=U+W$ implies that $W$ has a basis $e_{r+1}+u_{r+1}, \dots, e_n+u_n$ with the $u_i\in U.$
Moreover the requirement $U\cap W=0$ implies that different choices of the $u_i$ yield different spaces $W$.
So the number of $W$ is just the number of ways of choosing $(n-r)$ not necessarily different vectors in $U$; that is $(q^{r})^{n-r}$.
(The amended question asks only for the case $r=1$.)


text:
Q: What determines whether or not $|jm\rangle$ can be rotated into $|jm'\rangle$? I was surprised to learn that not every $|jm\rangle$ can be rotated into a given $|jm'\rangle$ with any finite rotation $R(\alpha, \beta, \gamma)$, and I am curious whether or not there is any physical intuition that would let us tell when this can and can't be done. I think I understand mathematically why this is the case. Rotations about a given axis are generated by the angular momenta operators, and we can get the matrix corresponding to a finite rotation by exponentiating. That is, we can say:
$$
R(\alpha, \beta, \gamma) = e^{-i\alpha L_x/\hbar}e^{-i\beta L_y/\hbar}e^{-i\gamma L_z/\hbar}
$$
For a given subspace corresponding to a fixed $j$, only the first $2j$ terms in the series expansion of each exponential will be linearly independent and we can can actually write down a compact expression for each of this operators. For simplicity, I will take $j=1$. Then:
$$
e^{-i\theta L_i/\hbar} = \mathbb{1} - \frac{i}{\hbar}\sin (\theta) L_i + \frac{(\cos(\theta) -1)}{\hbar^2} L_i^2
$$
If you turn plug in the forms for $L_x$ and $L_y$ and turn the crank, the above rotation becomes:
$$
\begin{pmatrix}
    \cos^2(\alpha/2)       & -i\sin\alpha / \sqrt{2} & -\sin^2(\alpha/2) \\
    -i\sin\alpha / \sqrt{2}       & \cos \alpha  & -i\sin\alpha / \sqrt{2} \\
    -\sin^2(\alpha/2)       & -i\sin\alpha / \sqrt{2} & \cos^2(\alpha/2)
\end{pmatrix}
\times
\begin{pmatrix}
    1-\sin^2(\beta/2)       & -\sin\beta / \sqrt{2} & \sin^2(\beta/2)  \\
    \sin\beta / \sqrt{2}       & \cos \beta & -\sin\beta / \sqrt{2}  \\
    \sin^2(\beta/2)       & \sin\beta / \sqrt{2} & 1-\sin^2(\beta/2)
\end{pmatrix}
\\ \times
\begin{pmatrix}
    e^{-im\gamma}       & 0 & 0 \\
    0       & e^{-im\gamma} & 0 \\
    0       & 0 & e^{-im\gamma}
\end{pmatrix}
$$
It's messy, but you can show using this for example that if you start at $|1, 1 \rangle$ you can't rotate into $|1, 0 \rangle$, but you can rotate into $|1,-1\rangle$. This is super odd to me, as I can't see much that would distinguish these two cases. Both $|1,0\rangle$ and $|1,-1\rangle$ are in the same subspace as $|1,1\rangle$, both are basis vectors, and classically if you had an angular momentum such that its projection along $z$ was $1$, you could rotate it both so that its projection was $0$ (rotate around $x$ by $\pi/2$) or $-1$ (rotate around $x$ by $\pi$). So what is different between these two states that makes one rotation possible and the other not?
Are there any arguments on physical grounds we could have made to arrive at the above conclusion without going through the math? Is there a general way to classify which states you can reach from a given starting state via finite rotations?

A: This isn't a full answer, but an easy way to see you can't reach every state with a rotation is that the set of rotations has three real dimensions, while the set of normalized spin $s$ states has real dimensions $2(2s+1) - 2 = 4s$ real dimensions, where the subtraction is due to tossing out a global phase and demanding normalization. This means that for spin $s=1$ and higher, almost all states can't be reached by a rotation, just on dimensional grounds. The classical intuition doesn't work, because a "classical" spin always has a two-dimensional state space.

A:
Are there any arguments on physical grounds we could have made to arrive at the above conclusion without going through the math?

Yes. This answer uses some mathematial notation, but it doesn't use any matrices. It uses only geometric intuition and the most basic general principles of quantum physics.
 Notation
Consider an irreducible representation of the spin group (the double cover of the rotation group), and use this notation:

*

*$\hat u$ is a unit vector in 3d space.

*$J(\hat u)$ is the generator of rotations about the $\hat u$-axis. For every axis $\hat u$, the generator $J(\hat u)$ is an observable represented by a self-adjoint operator on the Hilbert space.

*$j$ is the largest eigenvalue of $J(\hat u)$ in the given irreducible representation.

*$\big|\hat u\big\rangle$ is the eigenstate of $J(\hat u)$ with the largest eigenvalue $j$:
$$
 J(\hat u)\,\big|\hat u\big\rangle = j\,\big|\hat u\big\rangle.
$$
We can think of $|\hat u\rangle$ as having an angular momentum with a specific orietnation in 3d space, namely along the $\hat u$-axis, but that interpretation isn't necessary for this answer to work.
 Intuition
Rotations affect observables in the obvious way: applying a rotation $\hat u\to R\hat u$ transforms $J(\hat u)\to J(R\hat u)$. This immediately implies two things:

*

*All of the states $|\hat u\rangle$, for all directions $\hat u$, can be obtained from each other by rotations, up to a physically irrelevant overall phase factor. (A state can be represented by a vector in the Hilbert space, but the representation is not one-to-one: vectors related to each other by an overall nonzero complex constant represent the same state.)

*For any given direction $\hat u$, the only states that can be obtained by rotating $|\hat u\rangle$ are largest-eigenvalue eigenstates of the generators $J(R\hat u)$.
Rotating clockwise about $\hat u$ is the same as rotating counterclockwise about $-\hat u$, so the eigenstate of $J(\hat u)$ with eigenvalue $j$ corresponds to the eigenstate of $J(-\hat u)$ eigenvalue $-j$. This implies:

*

*The eigenstate of $J(\hat u)$ with eigenvalue $-j$ is a rotation of the eigenstate of $J(\hat u)$ with eigenvalue $j$.

The case $j=1/2$ is special, because then $J(\hat u)$ doesn't have any other eigenstates: the only two eigenstates it has are the ones with eigenvalues $\pm j$.
Now consider a representation with $j>1/2$, and consider an eigenstate $|m\rangle$ of $J(\hat u)$ with eigenvalue $m\neq \pm j$. The operator $J(\hat u)$ is the generator of rotations about the $\hat u$ axis, so $|m\rangle$ must be invariant under rotations about the $\hat u$-axis, up to a physically meaningless overall phase. On the other hand, if $|m\rangle$ could be obtained from $|\hat u\rangle$ by a rotation, then $|m\rangle$ would be an eigenstate of $J(R\hat u)$ for some other direction $R\hat u$ with the largest eigenvalue $j$. But $J(R\hat u)$ is not invariant under rotations about the $\hat u$-axis unless $R\hat u=\pm\hat u$, so that would contradict the fact that $|m\rangle$ must be invariant under rotations about the $\hat u$-axis. Altogether, this implies

*

*The eigenstate of $J(\hat u)$ with eigenvalue $-j$ is a rotation of the eigenstate of $J(\hat u)$ with eigenvalue $j$, and the other eigenstates of $J(\hat u)$ cannot be obtained by rotating the one with eigenvalue $j$.

 By the way
The answer above focused on eigenstates of $J(\hat u)$, but as knzhou's answer pointed out, we can also make a more general statement: in a representation with $j>1/2$, most states are not equal (or proportional) to $|\hat u\rangle$ for any direction $\hat u$. Every state can be expressed as a superposition of these, but in most cases the superposition needs to involve more than one direction in 3d space. Furthermore, the superposition is not unique: the same state may be expressed as different superpositions, involving different sets of directions in 3d space. This follows simply from the fact that the basis $\big\{|\hat u\rangle\big\}$ is overcomplete, which in turn follows from the fact that the parameter $\hat u$ is continuous: an irreducible representation has a basis with a finite number of vectors, so the basis parameterized continuously by $\hat u$ must be overcomplete.


text:
Q: mysql rows to columns, text type If i have a table of data like
Option_id|Component_id|Option_parent|Option_name|Option_value
1         1            0             id
2         1            1             option1     Some value
3         1            1             option2     Other
4         1            0             id          Value
5         1            4             option1     More
6         1            4             option2     More&More

Is it possible to return rows with the option_name as columns when providing the "option_name" to select and the component_id. The option_name with "id" will be the parent using it's "option_id".
So Select option1, option2 where Component_id = 1 returns

Option1    |Option2
Some Value  Other
More        More&More

I'm basically trying to see if i can have a generic table that can be used by components to store varying amounts of data. I know i can use joins but wondered if there might be a better way as one component could have 10 options.

A: Use:
  SELECT MAX(CASE WHEN t.option_name = 'option1' THEN t.option_value END) AS option1,
         MAX(CASE WHEN t.option_name = 'option2' THEN t.option_value END) AS option2
    FROM TABLE t
   WHERE t.option_name IN ('option1', 'option2')
GROUP BY t.component_id, t.option_parent


text:
Q: What is the discrete Fourier transform of the sets $(1,0,0,0)$ and $(0,1,0,0)$? What is the discrete Fourier transform of the sets $(1,0,0,0)$ and $(0,1,0,0)$?
I am unable to understand the progression from a continuous Fourier transform to a discrete Fourier transform.
Regards.

A: Up to scaling with the sequence length, the DFT in this case is the coefficient tuple of the cubic polynomial, that has the given tuple of values as the values $(p(1),p(i),p(-1),p(-i))$ on the circle points $i^k$, $k=0,1,2,3$.
Now you may note that in $p(1)\pm p(-1)$ and $p(i)\pm p(-i)$ the relation of values and coefficients becomes more concentrated. This is the basis for the FFT.


text:
Q: Peoplesoft CreateRowset with related display record According to the Peoplebook here, CreateRowset function has the parameters {FIELD.fieldname, RECORD.recname} which is used to specify the related display record.
I had tried to use it like the following (just for example):
&rs1 = CreateRowset(Record.User, Field.UserId, Record.UserName);
&rs1.Fill();

For &k = 1 To &rs1.ActiveRowCount
MessageBox(0, "", 999999, 99999, &rs1(&k).UserName.Name.Value);
End-for;

(Record.User contains only UserId(key), Password.
Record.UserName contains UserId(key), Name.)
I cannot get the Value of UserName.Name, do I misunderstand the usage of this parameter?

A: Fill is the problem. From the doco:

Note: Fill reads only the primary database record. It does not read
  any related records, nor any subordinate rowset records.

Having said that, it is the only way I know to bulk-populate a standalone rowset from the database, so I can't easily see a use for the field in the rowset.
Simplest solution is just to create a view, but that gets old very soon if you have to do it a lot. Alternative is to just loop through the rowset yourself loading the related fields. Something like:
For &k = 1 To &rs1.ActiveRowCount
  &rs1(&k).UserName.UserId.value = &rs1(&k).User.UserId.value;
  &rs1(&k).UserName.SelectByKey();
End-for;