text:
Q: No more spool space in Teradata while trying Update I'm trying to update a table with to many rows 388.000.
This is the query:
update DL_RG_ANALYTICS.SH_historico
from
(
SELECT
    CAST((MAX_DIA - DIA_PAGO) AS INTEGER) AS DIAS_AL_CIERRE_1
FROM

(SELECT * FROM DL_RG_ANALYTICS.SH_historico A
        LEFT JOIN
            (SELECT ANO||MES AS ANO_MES, MAX(DIA) AS MAX_DIA FROM DL_RG_ANALYTICS.SH_CALENDARIO
            GROUP BY 1) B
        ON A.ANOMES = B.ANO_MES
) M) N

SET DIAS_AL_CIERRE = DIAS_AL_CIERRE_1;

Any help is apreciate.

A: This first thing I'd do is replace the SELECT * with only the columns you need.  You can also remove the M derived table to make it easier to read:
UPDATE DL_RG_ANALYTICS.SH_historico
FROM (
  SELECT CAST((MAX_DIA - DIA_PAGO) AS INTEGER) AS DIAS_AL_CIERRE_1
  FROM DL_RG_ANALYTICS.SH_historico A
  LEFT JOIN (
    SELECT ANO || MES AS ANO_MES, MAX(DIA) AS MAX_DIA
    FROM DL_RG_ANALYTICS.SH_CALENDARIO
    GROUP BY 1
  ) B ON A.ANOMES = B.ANO_MES
) N
SET DIAS_AL_CIERRE = DIAS_AL_CIERRE_1;

What indexes are defined on the SH_CALENDARIO table?  If there is a composite index of (ANO, MES) then you should re-write your LEFT JOIN sub-query to GROUP BY these two columns since you concatenate them together anyways.  In general, you want to perform joins, GROUP BY and OLAP functions on indexes, so there will be less row re-distribution and they will run more efficiently.
Also, this query is updating all rows in the table with the same value.  Is this intended, or do you want to include extra columns in your WHERE clause?


text:
Q: How to add integer (seconds) to hh:mm:ss format in Python? I have the following data frame in python where am trying to compute column 'New time' by adding 'Duration' (which is in seconds) to the 'start_time'
Serial  start_date     start_time     Duration(seconds)  New time
    A   5/22/2017       10:37:24        216
    A   5/22/2017       10:37:26        213
    A   5/22/2017       10:37:29         3
    A   5/22/2017       10:39:55         60
    A   5/22/2017       10:51:50        380
    A   5/22/2017       10:51:57        339

I want to add duration into start_time. The duration is in seconds.
'New time' is expected in hh:mm:ss format.
I tried looking for similar queries in the forum but could not get around this.
Below is the info
data.info()

start_date         13661 non-null object
start_time         13661 non-null object
Duration           13661 non-null int64

I tried taking a cue from a similar problem in the forum, using datetime
data.newtime = data.start_time + datetime.timedelta(data.Duration)

when i execute this am getting the following error :     TypeError: unsupported type for timedelta days component: Series
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-95-fdfac1490ba5> in <module>()
----> 1 data.newtime = data.start_time + datetime.timedelta(data.Duration)

TypeError: unsupported type for timedelta days component: Series

Not sure how to go about it. New to python.
Help appreciated
TIA

A: You can use to_timedelta and output is timedelta too:
df['New time'] = pd.to_timedelta(df['start_time']) +
                 pd.to_timedelta(df['Duration(seconds)'], unit='s')
print (df)
  Serial start_date start_time  Duration(seconds) New time
0      A  5/22/2017   10:37:24                216 10:41:00
1      A  5/22/2017   10:37:26                213 10:40:59
2      A  5/22/2017   10:37:29                  3 10:37:32
3      A  5/22/2017   10:39:55                 60 10:40:55
4      A  5/22/2017   10:51:50                380 10:58:10
5      A  5/22/2017   10:51:57                339 10:57:36

But if seconds is more, output is changed, because there are also days:
print (df)
  Serial start_date start_time  Duration(seconds)
0      A  5/22/2017   10:37:24                216
1      A  5/22/2017   10:37:26             213000
2      A  5/22/2017   10:37:29                  3
3      A  5/22/2017   10:39:55                 60
4      A  5/22/2017   10:51:50                380
5      A  5/22/2017   10:51:57                339

df['New time'] = pd.to_timedelta(df['start_time']) +
                 pd.to_timedelta(df['Duration(seconds)'], unit='s')
print (df)
  Serial start_date start_time  Duration(seconds)        New time
0      A  5/22/2017   10:37:24                216 0 days 10:41:00
1      A  5/22/2017   10:37:26             213000 2 days 21:47:26
2      A  5/22/2017   10:37:29                  3 0 days 10:37:32
3      A  5/22/2017   10:39:55                 60 0 days 10:40:55
4      A  5/22/2017   10:51:50                380 0 days 10:58:10
5      A  5/22/2017   10:51:57                339 0 days 10:57:36

Also is posible add datetime:
df['New date'] = pd.to_datetime(df['start_date']) + \
                 pd.to_timedelta(df['start_time']) +  \
                 pd.to_timedelta(df['Duration(seconds)'], unit='s')
print (df)
  Serial start_date start_time  Duration(seconds)            New date
0      A  5/22/2017   10:37:24                216 2017-05-22 10:41:00
1      A  5/22/2017   10:37:26                213 2017-05-22 10:40:59
2      A  5/22/2017   10:37:29                  3 2017-05-22 10:37:32
3      A  5/22/2017   10:39:55                 60 2017-05-22 10:40:55
4      A  5/22/2017   10:51:50                380 2017-05-22 10:58:10
5      A  5/22/2017   10:51:57                339 2017-05-22 10:57:36

df['New date'] = pd.to_datetime(df['start_date']) + \
                 pd.to_timedelta(df['start_time']) +  \
                 pd.to_timedelta(df['Duration(seconds)'], unit='s')
print (df)
  Serial start_date start_time  Duration(seconds)            New date
0      A  5/22/2017   10:37:24                216 2017-05-22 10:41:00
1      A  5/22/2017   10:37:26             213000 2017-05-24 21:47:26
2      A  5/22/2017   10:37:29                  3 2017-05-22 10:37:32
3      A  5/22/2017   10:39:55                 60 2017-05-22 10:40:55
4      A  5/22/2017   10:51:50                380 2017-05-22 10:58:10
5      A  5/22/2017   10:51:57                339 2017-05-22 10:57:36

---
And if need convert timedelta to string in format HH:MM:SS and lost days (if exist):
df['New time'] = pd.to_timedelta(df['start_time']) +
                 pd.to_timedelta(df['Duration(seconds)'], unit='s')
df['New time'] = pd.to_datetime(df['New time']).dt.strftime('%H:%M:%S')
print (df)
  Serial start_date start_time  Duration(seconds)  New time
0      A  5/22/2017   10:37:24                216  10:41:00
1      A  5/22/2017   10:37:26             213000  21:47:26
2      A  5/22/2017   10:37:29                  3  10:37:32
3      A  5/22/2017   10:39:55                 60  10:40:55
4      A  5/22/2017   10:51:50                380  10:58:10
5      A  5/22/2017   10:51:57                339  10:57:36

A: Here is a snippet that may help you solve the problem yourself:
from datetime import datetime, timedelta

my_date = datetime.strptime('5/22/2017 10:37:24', '%m/%d/%Y %H:%M:%S')
my_time_diff = timedelta(seconds=216)
my_new_date = my_date + my_time_diff
print(my_new_date.strftime('%m/%d/%Y %H:%M:%S'))

Useful resource:

*

*https://docs.python.org/2/library/datetime.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to change TopLink logging level in GlassFish In a GlassFish 2.1 environment, I am trying to increase the logging level for TopLink... to see the raw SQL being generated.  In the GlassFish Admin Console, I go to:
Configurations -> my-config -> Logger Settings -> "Log Levels" tab

The logging level for TopLink is determined by the "Persistence" pulldown menu.  To dump generated SQL to the logs, you increase the level from "SEVERE" to "FINE" (or greater).
I've done this before on multiple other GlassFish boxes.  However, on THIS box the value always reverts back to "SEVERE" after I click the Save button.  No error message in the Admin Console, and nothing logged that I can find... the new value simply doesn't stick.
The really confusing thing is that I CAN successfully update the logging level for every other category in the system (e.g. "JMS", "JTA", etc).  The problem is specific to the "Persistence" category.
Anyone ever encountered this problem before?  Any thoughts would be appreciated.

A: Odd.
You can always set the log level directly in your JPA persistence.xml,
"toplink.logging.level"="fine"

A: I eventually confirmed with Oracle that this was a bug in this particular version of GlassFish.  Shouldn't be an issue for people who are up to the 3.x generation of GlassFish, and there will eventually be an update for 2.1x.
I have found a workaround for the meantime, though.  On that "Log Levels" page, add a new property in the "Additional Properties" section at the bottom.  Set the property Name to "oracle.toplink.essentials" (the same package name indicated beside the "Persistence" pulldown), and set the property Value to whatever logging level you want.
Clicking Save will remove this entry from the "Additional Properties" section, but the "Persistence" pulldown will be set to the logging level you had entered.


text:
Q: Angular 13 MSAL 2.0 & .NET core API: Bearer error="invalid_token", error_description="The signature is invalid" To isolate the problem, I have created the famous Visual Studio default "weather forecast" .NET core project with angular and tried to make the Angular ClientApp authenticate using a bearer token.
I have created a similar project two years ago with MSAL 1.0 which works just fine. I am using the same app registration, authority etc. as in this project. I get a token, send it to the API and this is what I get in the response header:

Bearer error="invalid_token", error_description="The signature is invalid"

When I check the token at jwt.io, I indeed see that there is a validation error in the signature as well, I also compared the tokens from MSAL v1 and MSAL v2, they pretty much look the same apart from v1 containing groups": ["cc...d1"] and "roles": ["MyAdminRole"] (which I also need to find out how to get these in a token from v2). The token from v1 validates without any problems.
In Postman if I try to send the bearer token I got from my productive v1 app to my test API, it also works without any problems which convinces me that something goes wrong in the process of obtaining the token.
The code I mainly took from the angular13-rxjs7-sample-app on GitHub. I am running it locally in VS2022 with @azure/msal-angular@2.2.0. This is how it looks like:
app.module.ts:
    export function loggerCallback(logLevel: LogLevel, message: string) {
      console.log(message);
    }

    export function tokenGetter() {
      return localStorage.getItem("jwt");
    }

    export function MSALInstanceFactory(): IPublicClientApplication {
      return new PublicClientApplication({
        auth: {
          clientId: environment.clientID, // PPE testing environment
          authority: environment.authority, // PPE testing environment.
          redirectUri: environment.redirectUri,
          postLogoutRedirectUri: '/'
        },
        cache: {
          cacheLocation: BrowserCacheLocation.LocalStorage,
        },
        system: {
          loggerOptions: {
            loggerCallback,
            logLevel: LogLevel.Info,
            piiLoggingEnabled: false
          }
        }
      },);
    }

    export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
      const protectedResourceMap = new Map<string, Array<string>>();
      protectedResourceMap.set('https://localhost:44491/weatherforecast', ['user.read']);

      return {
        interactionType: InteractionType.Redirect,
        protectedResourceMap
      };
    }

    export function MSALGuardConfigFactory(): MsalGuardConfiguration {
      return {
        interactionType: InteractionType.Redirect,
        authRequest: {
          scopes: ['user.read']
        },
        loginFailedRoute: '/login-failed'
      };
    }

    @NgModule({
      declarations: [
        AppComponent,
        NavMenuComponent,
        HomeComponent,
        CounterComponent,
        FetchDataComponent
      ],
      imports: [
        BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
        HttpClientModule,
        FormsModule,
        BrowserModule,
        HttpClientModule,
        JwtModule.forRoot({
          config: {
            tokenGetter: tokenGetter
          }
        }),
        MsalModule,
        RouterModule.forRoot([
          { path: '', component: HomeComponent, pathMatch: 'full' },
          { path: 'counter', component: CounterComponent },
          { path: 'fetch-data', component: FetchDataComponent },
        ])
      ],
      providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: MsalInterceptor,
          multi: true
        },
        {
          provide: MSAL_INSTANCE,
          useFactory: MSALInstanceFactory
        },
        {
          provide: MSAL_GUARD_CONFIG,
          useFactory: MSALGuardConfigFactory
        },
        {
          provide: MSAL_INTERCEPTOR_CONFIG,
          useFactory: MSALInterceptorConfigFactory
        },
        MsalService,
        MsalGuard,
        MsalBroadcastService
      ],
      bootstrap: [AppComponent, MsalRedirectComponent]
    })

app.component.ts

    export class AppComponent implements OnInit, OnDestroy {
      title = 'MSAL Sample';
      isIframe = false;
      loginDisplay = false;
      loggedIn = false;

      private readonly _destroying$ = new Subject<void>();

      constructor(
        @Inject(MSAL_GUARD_CONFIG) private msalGuardConfig: MsalGuardConfiguration,
        private authService: MsalService,
        private msalBroadcastService: MsalBroadcastService
      ) { }

      ngOnInit(): void {
        this.setLoginDisplay();

        this.authService.instance.enableAccountStorageEvents(); // Optional - This will enable ACCOUNT_ADDED and ACCOUNT_REMOVED events emitted when a user logs in or out of another tab or window
        this.msalBroadcastService.msalSubject$
          .pipe(
            filter((msg: EventMessage) => msg.eventType === EventType.ACCOUNT_ADDED || msg.eventType === EventType.ACCOUNT_REMOVED),
          )
          .subscribe((result: EventMessage) => {
            if (this.authService.instance.getAllAccounts().length === 0) {
              window.location.pathname = "/";
            } else {
              this.setLoginDisplay();
            }
          });

        this.msalBroadcastService.inProgress$
          .pipe(
            filter((status: InteractionStatus) => status === InteractionStatus.None),
            takeUntil(this._destroying$)
          )
          .subscribe(() => {
            this.setLoginDisplay();
            this.checkAndSetActiveAccount();
          })

        if (!this.loginDisplay) {
          this.loginRedirect();
        }
      }

      setLoginDisplay() {
        this.loginDisplay = this.authService.instance.getAllAccounts().length > 0;
      }

       checkAndSetActiveAccount() {
        /**
         * If no active account set but there are accounts signed in, sets first account to active account
         * To use active account set here, subscribe to inProgress$ first in your component
         * Note: Basic usage demonstrated. Your app may require more complicated account selection logic
         */
        let activeAccount = this.authService.instance.getActiveAccount();

        if (!activeAccount && this.authService.instance.getAllAccounts().length > 0) {
          let accounts = this.authService.instance.getAllAccounts();
          this.authService.instance.setActiveAccount(accounts[0]);
        }
      }

      loginRedirect() {
        if (this.msalGuardConfig.authRequest) {
          this.authService.loginRedirect({ ...this.msalGuardConfig.authRequest } as RedirectRequest);
        } else {
          this.authService.loginRedirect();
        }
      }

      loginPopup() {
        if (this.msalGuardConfig.authRequest) {
          this.authService.loginPopup({ ...this.msalGuardConfig.authRequest } as PopupRequest)
            .subscribe((response: AuthenticationResult) => {
              this.authService.instance.setActiveAccount(response.account);
            });
        } else {
          this.authService.loginPopup()
            .subscribe((response: AuthenticationResult) => {
              this.authService.instance.setActiveAccount(response.account);
            });
        }
      }

      logout(popup?: boolean) {
        if (popup) {
          this.authService.logoutPopup({
            mainWindowRedirectUri: "/"
          });
        } else {
          this.authService.logoutRedirect();
        }
      }

      ngOnDestroy(): void {
        this._destroying$.next(undefined);
        this._destroying$.complete();
      }
    }

Program.cs
    builder.Services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }
        ).AddJwtBearer(options =>
    {
        options.Audience = builder.Configuration.GetValue<string>("AzureAd:Audience");
        options.Authority = builder.Configuration.GetValue<string>("AzureAd:Authority");
        options.RequireHttpsMetadata = builder.Configuration.GetValue<bool>("AzureAd:RequireHttpsMetadata");
    });

Variables used (just to show the format I provided:
    environment.clientID = "45xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxaf"
    environment.audience = "45xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxaf"
    environment.authority = "https://login.microsoftonline.com/4fxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxad/"
    environment.redirectUrl = "https://localhost:44491/"

When comparing the v1 and v2 bearer tokens I realized that the first line is different:
v1: "aud": "api://45xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxaf"
v2: "aud": "00000003-0000-0000-c000-000000000000" (this is actual data)

Update: This is caused by requesting the user.read scopes etc, these are only supported by the MS Graph API. Obviously MSAL recognizes this and sends you a graph token without even requesting one. Removing all scopes but the custom api://... one from the code solves that issue. Still, the verification fails.
Other things I tried:
In the API controller I added a simple [Authorize] decorator. I also tried to alter it with parameters like [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] as suggested here but that did not change anything. (Why would it as I can authenticate successfully with the token from V1.)
This answer somehow suggests that it is a problem with the Microsoft.AspNetCore.Authentication.JwtBearer v6.0.4 library that I am using. Tried installing the latest version of System.IdentityModel.Tokens.Jwt as suggested, without any success.
Some sources suggested to provide the correct scope. There is a scope defined in the app registration so I replaced the authRequest scopes in app.module.ts (protectedResourceMap.set and authRequest) with the following code, but this did not change anything. Also tried to only use "access_as_user", but that ended in an authentication loop.
    authRequest: {
      scopes: ['api://45xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxaf/access_as_user']
    },

There are some funny answers around like disabling some of the token validations which I tried for debugging purposes only, but not even that solved the problem.
Important before flagging as duplicate
I am aware that similar questions have been asked. I literally went through all of those I could find or that were suggested before posting. Many are outdated (MSAL v1.0) or about the B2C auth flow which does not apply. There are other unanswered questions about similar scenarios, but here I tried to collect as much information as I possibly could find, and I will update the question with any new findings. And an answer, if I find one.

A: I did not find out what the root cause was. However, I ended up re-creating the whole project from scratch using the same code and the same library versions and then it worked without any issues. I compared both projects but could not find any obvious differences. I assume that maybe packet management got confused at some stage.
What I found out though is that the scopes are handled differently in v2 than they were in v1. In v1 it does not matter if I have "user.read" in the scopes as long as I have my user-defined api://.../... scope in the array. In v2 it only works if that one is the only scope I provide, otherwise it will default to MS Graph (See update above)


text:
Q: A macro that passes each word of its argument to another macro as an argument? I'd like a command that works like this:
\dothings{Takes several words as argument}

and have this expand to:
\@dothings{Takes} \@dothings{several} \@dothings{words}...

I know how to define a simple macro that takes everything up to the next space, but I don't know how to use that to apply it to each word in a sentence. Is there a simple way to do this?
I'm also curious about taking the next letter as an argument, but I guess that's maybe a separate question...

A: Herbert has shown how to seperate words by spaces. Here is a very similar solution which prevent deep \ifx ... \fi nesting (Deep nesting may produce errors when many words is used):
\documentclass{minimal}
\begin{document}

\def\wordsloop#1{\wordsloopiter#1 \nil}
\def\wordsloopiter#1 #2\nil{%
  \do{#1} %
  \ifx&#2&% #2 is empty, then & equeals &
    \let\next\relax
  \else
    \def\next{\wordsloopiter#2\nil}% iterate
  \fi
  \next}

\def\do#1{(#1)}
\wordsloop{This is a sentence.}
% we have: (This) (is) (a) (sentence.)

\end{document}

However, it is still very slow if you use many words in the argument.

Loop on tokens can be obtained by similar approch, if you remove the spaces after #1 in the definitions above. But it can be easier:
\documentclass{minimal}
\begin{document}

\def\tokensloop#1{\tokensloopiter#1\nil}
\def\tokensloopiter#1{%
  \ifx\nil#1\else\do{#1}\expandafter\tokensloopiter\fi}

\def\do#1{(#1)}
\tokensloop{aa  bb}
% we have (a)(a)(b)(b)

\end{document}

You can also use \toksloop command from etextools package directly.
Note that spaces are ignored.

For spaces, catcode or other tricks may be used to read the characters verbatimly. That is more complex.
For example, we can use \obeyspaces to change the catcode of spaces:
\documentclass{minimal}
\begin{document}

\def\charsloop{\begingroup\obeyspaces\charsloophelper}
\def\charsloophelper#1{\charsloopiter#1\nil\endgroup}
\def\charsloopiter#1{%
  \ifx\nil#1\else\do{#1}\expandafter\charsloopiter\fi}

\def\do#1{(#1)}
\charsloop{aa  bb}
% we have (a)(a)( )( )(b)(b)

\end{document}

(Newlines are still ignored with \obeyspaces only.)

A: ConTeXt provides a macro \processisolatedwords that does exactly that. For example, to draw a frame around each word, you can use
\processisolatedwords {\input ward \relax} \inframed

In MkIV, this macro is implemented in lua using the following funcction:
local function applytowords(list,what,nested)
    local doaction = context[what or "ruledhbox"]
    local noaction = context
    local current  = checkedlist(list)
    local start
    while current do
        local id = current.id
        if id == glue_code then
            if start then
                doaction(copynodelist(start,current))
                start = nil
            end
            noaction(copynode(current))
        elseif nested and (id == hlist_code or id == vlist_code) then
            context.hbox()
            context.bgroup()
            applytowords(current.list,what,nested)
            context.egroup()
        elseif not start then
            start = current
        end
        current = current.next
    end
    if start then
        doaction(copynodelist(start))
    end
end

See also:

*

*\applytowords

*\processwords and \applytosplitstringword

A: \documentclass{article}
\usepackage{xcolor}
\makeatletter
\def\dothings#1{\color{blue}\expandafter\dothings@i#1 \@nil}
\def\dothings@i#1 #2\@nil{%
  \color{.!80}#1
  \ifx\relax#2\relax\else\dothings@i#2\@nil\fi}
\makeatother

\begin{document}
\dothings{Takes several words as argument}

\end{document}

A: LaTeX3 now provides
\seq_set_split:Nnn<seq var>{<delimiter>} {<argument>}
which splits the <argument> at each occurrence of <delimiter> (and strips spaces from both ends of each argument), and puts the result in the <seq var> (the list data structure in LaTeX3). Once you have that sequence, you can map a given function on all its items.
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\seq_new:N \l_foo_seq
\NewDocumentCommand{\dothings}{m}
  {
    \seq_set_split:Nnn \l_foo_seq {~} {#1}
    \seq_map_inline:Nn \l_foo_seq { \fbox{##1} }
  }
\ExplSyntaxOff
\begin{document}
\dothings{Takes several words as argument}
\end{document}

EDIT: Actually you can do it faster with xparse's argument processors (here \SplitList).
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand {\dothings}
  { > { \SplitList { ~ } } m }
  { \tl_map_inline:nn {#1} { \fbox{##1} } }
\ExplSyntaxOff
\begin{document}
\dothings{Takes several words as argument}
\end{document}


text:
Q: Description in 'Share on facebook' is missed up I just added a new buttons for sharing contents of my posts on blogger using this code that I installed afer <data:post.body/> :

The problem is that when I want to share it on facebook, Description show other element like a sort of an 'html' code on it ! I tried to fix with the previous questions posted here but it didn't work !
Here you can see it when you share : http://scheissemag.blogspot.com/2011/06/this-summers-faux-pas.html

A: In the  tag, add this:
 <meta property="og:description" content="Your description"/>

Alternatively, you can set this:
<meta name="description" content="Your description" />

You should be setting the second one anyways for SEO purposes.  If you implement this and you don't see the change apply, use Facebook's linter tool to refresh their cache.


text:
Q: How to create Lost found/target in sequence diagram in VS2010 When we generate sequence diagram using the code in VS2010, the generated diagram normally has a found target defined.
I would like to add a lost target in the diagram.
How can it be achieved?

A: Found a solution...
In my case, it worked when I created asynchronous message.


text:
Q: Why does casting a string pointer to a void pointer and back cause the string data to dissappear? (Opencv) I'm trying to create a function that initializes all my mouse handlers for every OpenCV window in one place.  The code works in the main loop, but not inside my function (Yes, I am passing by reference).
The problem seems to stem from passing a pointer to the string - when it comes out the other side it won't successfully dereference (*).  What gives?
Here's a minimalist example of what I'm talking about (It sets the mouse handlers for two identical windows - one window works, the other window doesnt):
// mouse problem.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <string.h>
#include <iostream>  //for cout, cin

using namespace std;
using namespace cv;

void onMouse(int event, int x, int y, int flags, void* param){

    string windowname = *((string*)param);  //just recasting the void* we passed into the mousehandler to string
    if(windowname.empty()){
        cout << "ERROR.";
    }else{
        cout << "SUCCESS for window:" << windowname;
    }
    cout <<  "  param: "<< param << " windowname: "<< windowname << "\n";
}

void initializer(const string& name){
        namedWindow( name, CV_WINDOW_AUTOSIZE );
        cout << " initializing mouse handler for " << name << " with string at address :" << &name << "\n";
        setMouseCallback(name, onMouse, (void*)&name);  //this line is exactly the same as the other setmousecallback line
}

int _tmain(int argc, _TCHAR* argv[]){
    string name; Mat src; VideoCapture cap(0);  cap >> src; // get a single frame from camera

    //this works just fine
    name = "frameA";
    namedWindow( name, CV_WINDOW_AUTOSIZE );
    cout << " initializing mouse handler for " << name << " with string at address :" << &name << "\n";
    setMouseCallback(name, onMouse, (void*)&name);

    //this fails even though it contains the same code and we pass by reference
    initializer("frameB");

    imshow("frameA",src);   imshow("frameB",src);  //display frame - mouseing over them triggers the OnMouse() event
    while(true){  //loop forever
        waitKey(30);
    }
    return 0;
}

And here is the result after I mouseover each window once.
What really KILLS me is that, as you can see in the picture, the address of the string is successfully recognized!  And no errors on casting it to a string!  But when I de-reference it, it says its empty!
Yes, I did try to avoid using Void*.  Sadly, I cannot avoid the void.  OpenCV requires a void to be the last argument of any mousehandler function   :(

A: The problem has nothing to do with the casts. You are keeping a pointer to a temporary string object, and are trying to dereference that pointer after the object has gone out of scope.
The following:
initializer("frameB");

is equivalent to:
initializer(std::string("frameB"));

In other words, a temporary is created, and the function takes and keeps the address of that temporary. Since the temporary disappears at the end of the statement, you are left with a dangling pointer.


text:
Q: How do I move an array element in a hash? I am trying to put an array into hash:
@friends = {}
@friend = ['network' => 'facebook', 'picture' => picture, 'name' => name, 'id' => id]

How can I move @friend into @friends to get a result such as:
friends: {
  [
    'network': 'facebook',
    'picture': 'http://fb.com/myimage.jpg',
    'name':    'MyName',
    'id':      '46846546'
  ]
}

An array in array I can do. An hash in array I also can do. But an array in a hash - I can't find how to do it.
It might be impossible. I was searching the documentation for hashes and arrays and there was nothing about this.
for @dave newton related to last comment:

for @Borodin related to his answer:

A: You cannot "put an array into a hash" to obtain something like {[]}. Hashes are built from key-value pairs. An array can either take the key or value role within a hash.
For example, here an array is the value and a symbol :friends is the key:
{:friends => ['Pete', 'Robert', 'Katrin']}

The @friend variable (as you have defined it) results in an array having one element, which is a hash.
@friend = ['network' => 'facebook', 'picture' => picture, 'name' => 'name', 'id' => 42]
#=> [{"network"=>"facebook", "picture"=>"picture", "name"=>"name", "id"=>42}]

I guess you want @friend to be a hash, and @friends to be an array which contains many friend-hashes.

A: That specification is nonsense. It has arrays with keys and a hash with no keys. The {} and [] pairs should be swapped, and there should be commas between the key/value pairs.
I think it is intended to look like this
{
  "connections" : [
    {
      "network" : "facebook",
      "picture" : "http://facebook.com/picture.jpg",
      "name" : "User Name",
      "id" : "12345679"
    },
    {
      "network" : "linkedin",
      "picture" : "http://linkedin.com/picture.jpg",
      "name" : "Another User",
      "id" : "959d919sd92"
    }
  ]
}

but I cannot be sure, and you need to go back and ask the question.


text:
Q: News Feed Response parsing in iphone using Facebook Graph Api I am using Facebook Graph API...for fetching the data of news feed of the facebook profile..
and here is the response that i am getting in the console
    {
    application =         {
        id = 2309869772;
        name = Links;
    };
    "created_time" = "2011-02-10T09:44:27+0000";
    from =         {
        id = 1845195019;
        name = "Paritosh Raval";
    };
    icon = "http://static.ak.fbcdn.net/rsrc.php/v1/yD/r/aS8ecmYRys0.gif";
    id = "1845195019_192144087475935";
    likes =         {
        count = 1;
        data =             (
                            {
                id = 1845195019;
                name = "Paritosh Raval";
            }
        );
    };
    link = "http://www.facebook.com/AMDAVAD";
    name = "once you live in AHMEDABAD u cannot live anywhere else in the world..";
    picture = "http://profile.ak.fbcdn.net/hprofile-ak-snc4/203562_115963658443669_4129246_n.jpg";
    properties =         (
                    {
            name = Page;
            text = "21,803 people like this.";
        }
    );
    type = link;
    "updated_time" = "2011-02-10T09:44:27+0000";
},
    {
    application =         {
        id = 2392950137;
        name = Video;
    };
    "created_time" = "2011-02-02T04:18:22+0000";
    description = "must watch and explore :))";
    from =         {
        id = 1845195019;
        name = "Paritosh Raval";
    };
    icon = "http://static.ak.fbcdn.net/rsrc.php/v1/yD/r/aS8ecmYRys0.gif";
    id = "1845195019_194836027209359";
    likes =         {
        count = 1;
        data =             (
                            {
                id = 100000701228096;
                name = "Bhargav Jani";
            }
        );
    };
    link = "http://www.facebook.com/video/video.php?v=152586058110610&comments";
    name = "It Happens Only in....";
    "object_id" = 152586058110610;
    picture = "http://vthumb.ak.fbcdn.net/hvthumb-ak-snc4/50893_152586468110569_152586058110610_18299_1832_t.jpg";
    properties =         (
                    {
            name = Length;
            text = "0:54";
        }
    );
    source = "http://video.ak.fbcdn.net/cfs-ak-ash2/70137/56/152586058110610_53804.mp4?oh=481e53b824f6db8e3195fc9c0d07571d&oe=4DAFC300&__gda__=1303364352_7670272db65e93ec75dcaaed16b6d805";
    type = video;
    "updated_time" = "2011-02-02T04:18:22+0000";
}

And I want to show every data in the organized structure in the console. Can anyone help me with this?

A: it's unclear what you exactly asking but I try to answer.
First of all you need to parse this response in the method
- (void)request:(FBRequest *)request didLoad:(id)result of Facebook iOS SDK
result can be a string, a NSArray if you have multiple results and NSDictionary
In you console output we can see NSDictionary with included arrays and dictionaries in it.
I have little tutorial about it but it's on russian only and site is down today :( so i just copy one example from my article.
Let say we want to know what facebook user Likes
- (IBAction)getUserInfo:(id)sender {
  [_facebook requestWithGraphPath:@"me/likes" andDelegate:self];
}

if we try this Graph API response in browser or output to console we can see what this request returns. It returns dictionary with one and only key - "data" and corresponded array to this key. This array contents dictionary objects again with keys -
 «name»,"category","id","created_time". Dont forget request «user_likes» permission before.
So we have parsing method like that:
- (void)request:(FBRequest *)request didLoad:(id)result {
    if ([result isKindOfClass:[NSArray class]]) {
        result = [result objectAtIndex:0];
    }
    if ([result objectForKey:@"owner"]) {
        [self.label setText:@"Photo upload Success"];
    } else if ([result objectForKey:@"data"]){
        NSArray *likes = [result objectForKey:@"data"];
        NSString *text=@"You don't like Steve";
        for (NSDictionary* mylike in likes) {
            NSString *mylikeName = [mylike objectForKey:@"name"];
            if ([mylikeName isEqualToString:@"Steve Jobs"]) {
                text=@"You like Steve";
                break;
            }
        }
        [self.label setText:text];
    }
};

You can parse you result same way and fill your object's variables and then use it to display information in TableView for example. good luck!


text:
Q: Как записать из консоли в файл в C Я пытаюсь написать програму (наподобии tee), которая будет из консоли записывать сразу в файл  в цикле, пока не кончится память буфера. Пробовал через fwrite, fputc, fflush. Проблема заключается в том, что я не понимаю почему даные, которые я ввел, не появляются ни в файле, ни на экране.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char * argv[])
{
    //char buffer[BUFSIZ];
    char * buffer =(char*) malloc(sizeof(BUFSIZ));
    char ch;
    FILE * fp;
    int i;

if((fp = fopen(argv[1],"a")) == NULL )
{
    printf("Can't open \n");
    exit(1);
}

//while((ch = getchar()) != '\n')
for(i = 0; i< BUFSIZ; i++)
{
    ch = getchar();
    buffer[i] = ch;
    fwrite(buffer,sizeof(char), sizeof(buffer),fp);
    printf("%s", buffer);
}

fclose(fp);

}

A: У вас несколько ошибок.
В вашем варианте с циклом for вам нужно забивать весь буфер - но разве вы хотите именно этого? Действительно лучше уж по достижению конца строки, а еще надежнее - посимвольно, с завершением при закрытии потока (^D, кажется, в Linux).
Далее, вы не ограничиваете введенную строку нулевым символом - так что выбрасывается при выводе на экран все подряд, пока где-то не найдется нулевой символ.
buffer у вас - просто указатель, так что sizeof(buffer) вам даст просто размер указателя - 4 или 8 байт. в зависимости от разрядности приложения...
Я бы делал так (только нужно еще добавить проверку, что передано имя файла!):
int main(int argc, char * argv[])
{
    char ch;
    FILE * fp;

    if((fp = fopen(argv[1],"a")) == NULL )
    {
        printf("Can't open \n");
        exit(1);
    }

    for(;;)
    {
        if (EOF == (ch = getchar())) break;
        fputc(ch,fp);
        fputc(ch,stdout);
    }

    fclose(fp);

}

A: Чтобы построчно прочитать стандартный ввод (stdin) и скопировать его в стандартный вывод (stdout) и в файлы, переданные в командной строке (аналог tee):
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
  // open output files
  FILE* file[argc];
  file[0] = stdout;
  for (int i = 1; i < argc; ++i)
    if (!(file[i] = fopen(argv[i], "w"))) {
      fprintf(stderr, "failed to open '%s': %s", argv[i], strerror(errno));
      exit(EXIT_FAILURE);
    }

  // copy input lines to output files
  char line[BUFSIZ];
  while(fgets(line, sizeof line, stdin))
    for (int i = 0; i < argc; ++i)
      if (fputs(line, file[i]) == EOF) {
        fprintf(stderr, "failed to write to '%s': %s", (i ? argv[i] : "stdout"),
                strerror(errno));
        exit(EXIT_FAILURE);
      }

  return !feof(stdin); // success on eof
}

fgets() читает строчку, fputs() выводит строчку. Пример:
$ cc tee.c -o tee
$ echo abc | ./tee файл1 файл2
abc

Обратите внимание, файлы открываются в режиме "w" (как это tee делает), то есть содержимое существующих файлов затирается (truncate), прежде чем новые строки в них копируются. Можно добавить поддержку tee -a опции, чтобы в конец файла писать, не трогая начало файла.
Код рассчитывает на то, что при нормальном выходе из программы, автоматически закрываются файлы и очищаются соответствующие буферы ввода/вывода. Это значит, что во время работы программы, пока буфер для выходного файла не заполнится, ничего в файл не запишется. Если вы хотите, чтобы сразу появлялся ввод в выводе, то можно сделать вывод небуферизированным, как это GNU сoreutils' tee делает или сразу использовать небуферизированное API как это tee на FreeBSD делает.
tee на FreeBSD использует здесь POSIX read/write вызовы. GNU coretutils' tee использует read/fwrite комбинацию.

A: Спасибо всем. Проблема была в том, что процес я заканчивал с помощью ctrl + C. С помощью ctrl + D все записывается


text:
Q: Need help locating CPP files that were excluded from project in solution explorer I have been using Visual Studios 2019 as my IDE to learn C++ in school for a little over a month now. I often create new CPP files for practice or class lab work which means I have multiple CPP files in a single solution.
I have learned you can 'exclude' CPP files from the solution to allow you to run other CPP files when testing or debugging a program. However I know this isn't a perfect way to do this because it seems that the IDE will often completely remove the files from the solution explorer leaving me with no way to include them back into the solution.
I have set the solution explorer to list all files and have seen the files stay in the solution explorer with the file name still listed with a little 'do not enter' symbol over the file icon to indicate it is not a part of the solution anymore. This is fine as it allows me to right click and interact with the file at will which in turn allows me to include or exclude the file without issue.
I have had so many different and weird issues when doing this but the question I want answered right now is how can I prevent a CPP file (or any file for that matter) from utterly disappearing out of the solution explorer?

A: I'd like to suggest a different workflow: create multiple projects within your solution.
Use menu File -> Add -> New Project...
Follow the wizard (likely - Console App), name it as something you can recognize (Lab1, for example).
Now you can select any of your projects in the Solution Explorer and use Set as a Startup Project in the context menu.
This allows you to browse your entire code easily, copy/paste (I don't endorse that :) ), and run/debug the active project.


text:
Q: Android Horizontal Scroll VIew like gallery I want to make horizontal scroll view in android like gallery view, in which centered image zooms in while scroll. Often seen in web but I haven't found one in andriod. Here is an example from one iOS app.

I have tried with HorizontalScrollView, ListView, ViewPager but not able to reproduce zoomed Effect in center while scroll, and next images comes from behind.

A: You can use CoverFlow .Its a view for Android with several fancy effects.

*

*https://github.com/davidschreiber/FancyCoverFlow

*https://github.com/moondroid/CoverFlow

A: You can Directly Use View  Pager with DepthPage Transformation to Acheive as you like according to Android Documentation.
You can Acheive like :Demo of ViewPager
To achieve this kind of View
View Pager with Transformation Speed in Android

A: May be you can use a ViewPager inside a TabHost to get something close to what you are looking for.
<TabHost
        android:id="@+id/calendar_add_edit_th"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:id="@+id/ll_tabs_com"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:baselineAligned="false"
                android:orientation="horizontal"
                android:weightSum="1">

                <TabWidget
                    android:id="@android:id/tabs"
                    android:layout_width="match_parent"
                    android:layout_height="37dp"
                    android:layout_gravity="bottom"
                    android:orientation="horizontal" />
            </LinearLayout>

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_below="@+id/ll_tabs_com"
                android:background="#fff" />

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/ll_tabs_com">

                <android.support.v4.view.ViewPager
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:background="#fff" />

            </RelativeLayout>
        </RelativeLayout>
    </TabHost>


text:
Q: Software for calculating products and sums of Kronecker deltas I am looking at a Kahler metric $g$ on a certain manifold $M$, which has the good taste to be invariant under a transitive group of isometries, and I want to say something about its holomorphic sectional curvature.
Now, I can calculate the curvature tensor $R$ of $g$ explicitly at the center of a holomorphic coordinate system. If $(X_1, \ldots, X_n)$ is an orthonormal frame of tangent vectors at a given point, then the entries of the tensor are of the form
$$ R_{j \overline k l \overline m} := R(X_j, \overline X_k, X_l, \overline X_m) = \text{term 1} \cdot \text{term 2} - \text{term 3} $$
where the terms are sums of Kronecker deltas in $j$, $k$, $l$ and $m$. So if $X = \sum_j a_j X_j$ is a holomorphic tangent vector, which we may assume is of unit norm, the holomorphic sectional curvature in the direction of $X$ is
$$ H(X) = \sum_{j,k,l,m} a_j \overline a_k a_l \overline a_m R_{j \overline k l \overline m}. $$
This is where the pain begins. So far I haven't been able to make any sense of the herd of Kronecker deltas which comes out (except in exceptional cases, like for $R_{j \overline j k \overline k}$), and I'd be quite happy if I could just let a computer work the damn thing out for me.
Question: Is there software that calculates this sort of thing? Or is there a language particularily well adapted to hacking out a script that will calculate this?

A: Yes, there are a number of packages, check out for example:
http://www.math.washington.edu/~lee/Ricci/
and more generally
http://en.wikipedia.org/wiki/Tensor_software
(I know people use the mathematica packages heavily, and have for the last 25 years, not sure about the other ones).


text:
Q: F# - Overload Functions Is there a way to do somehow overload a function?
Let's take those 3 functions:
// Returns StringPropertyInfo
let stringProperty (expr:Expr<'a -> string>) (cfg:EntityInfo<'a>) =
    cfg.Property expr

// Returns DatePropertyInfo
let dateProperty (expr:Expr<'a -> System.DateTime>) (cfg:EntityInfo<'a>) =
    cfg.Property expr

// Returns BytePropertyInfo
let byteProperty (expr:Expr<'a -> System.Byte>) (cfg:EntityInfo<'a>) =
     cfg.Property expr

is there a way to merge them all into just:
let property expr cfg = ....

if not, whats the most neat way to accomplish something similar?

A: i think a discriminated union is your friend in this instance, you would have something like
type PropertyInfo =
| StringPropertyInfo of string
| DatePropertyInfo of System.DateTime
| BytePropertyInfo of byte

and then would match on it and do appropriate action returning the union in one function...

A: One semi-ugly way to get what you're looking for would be to generalize it a bit and use:
let inline property expr cfg =
    (^t : (member Property : Expr<'a -> 'b> -> 'c)(cfg, expr))

However, this can be applied to values of types other than EntityInfo<'a>, as long as they have a Property member with the right signature.

A: If you want to use an approach based on discriminated unions, then I think the declaration is more suitable (as you don't need to manipulate with quotations). Slight modification of the type suggested by Alex is:
type PropertyInfo<'a> =
  | String of Expr<'a -> string>
  | Date of Expr<'a -> System.DateTime>
  | ...

Then you'd write something like:
let property (pi:PropertyInfo<'a>) (cfg:EntityInfo<'a>) =
  match pi with
  | String e -> cfg.Property e
  | ...

cfg |> property (String <@ fun e -> e.Foo @>)

Another option would be to implement property as a static member of a type, in which case you can use usual overloading (similar to C#). Something like:
type EF =
  static member property (expr:Expr<'a -> string>) (cfg:EntityInfo<'a>) =
    cfg.Property expr
  static member property (expr:Expr<'a -> System.DateTime>) (cfg:EntityInfo<'a>) =
    cfg.Property expr
  static member property (expr:Expr<'a -> System.Byte>) (cfg:EntityInfo<'a>) =
     cfg.Property expr

Then you'd write:
cfg |> EF.property <@ e -> e.Foo @>

Finally, you could also make it a bit simpler (but less safer) by making the function fully generic and doing dynamic type test (to decide what return type is used). Something like:
let property<'a, 'r> (e:Expr<'a -> 'r>) (cfg:EntityInfo<'a>) =
  if typeof<'r> = typeof<string> then
    // ...

A: Short answer, no. There's another question dealing with this here.
You can however overload methods in classes etc. otherwise the .NET integration wouldn't work too well. This is one possible solution albeit not in my eyes, a pretty one.
You could put them in different sub-modules.
Perhaps you could make a generic function and decide the return type through one of the parameters. I'm too much of a newbie when it comes to the type inference to say for certain though.


text:
Q: How order words from a text file in Python I've written a Python script which I use to print out all words from a text file:
file = open(raw_input("Enter a file name: "))

for line in file:
    for words in line.split():
        print words

But how to print them out in order?

A: If you want to sort the words in each line you can use sorted:
with open(raw_input("Enter a file name: ")) as f :

   for line in f:
      for words in sorted(line.split()):
        print words

But if you want to print all the words in a sorted order you need to apply the sort on all words :
with open(raw_input("Enter a file name: ")) as f :
     for t in sorted(i for line in f for i in line.split()):
           print t


text:
Q: Can you set the mergedCells property in Kendo UI for jQuery ooxml.Workbook.sheets without range name? I am having an issue merging cells that are in an existing sheet in a workbook. My attempt to use mergedCells after the sheet is created has presented a roadblock, I can't seem to get the range name in string format as documented for the mergedCells option in Workbook.sheet:
mergedCells: ["A6:A8"]

All I have are indexes of the cells.
I have the logic to determine which cells' indexes I want to merge, but only the indexes. I can't figure out a way to get the range in an Excel cell name/string like "A1". In the following example, ignoring how I got the index values, I can't merge the cells based on index where indexA is the column and indexB1 and indexB2 are rows.
let indexA = 0;

let indexB1 = 5;

let indexB2 = 7;

sheet.mergedCells = [[{indexA, indexB1},{indexA,indexB2}]]

I have attached a picture of the types of cells I want to merge that are in my workbook, my loop first hits A6 through A8 and determines the indexes are to be merged because all the cells' values equal "Boat". Any help is appreciated, and I will try to provide more detail if needed, but it is difficult to provide much more because of the nature of the system I am on.
Thanks in advance.format of workbook

A: So you have the R1C1 notation of the cells you need to merge? If so, following the suggestion in this thread you can generate the range in A1 notation - example:
function columnName(index) {
    var cname = String.fromCharCode(65 + ((index - 1) % 26));
    if (index > 26)
      cname = String.fromCharCode(64 + (index - 1) / 26) + cname;
    return cname;
  }

  var r1 = 2;
  var c1 = 3;
  var r2 = 4;
  var c2 = 5;

  var rangeAsString = `${columnName(c1)}${r1}:${columnName(c2)}${r2}`;

  var workbook = new kendo.ooxml.Workbook({
    sheets: [{
      mergedCells: [rangeAsString],
      rows: [
        { cells: [ { value: "Document Title" }  ] },
        { cells: [ { value: 22 }, { value: 33 }, { value: 44 }, {value: 55}  ] }
      ]
    }]
  });

  kendo.saveAs({
    dataURI: workbook.toDataURL(),
    fileName: "Test.xlsx"
  });


text:
Q: 'C' why I declare the variable as 'pointer'? #include <stdio.h>
void main()
{
int a[] = {10,20,30,40,50,60,70,80,90,100};
int k,m,i,*ptr;
k=m=0;
ptr=a;
for(i=0; i<10; i+=2)
{
    k+=ptr[i];
    m+=ptr[i+1];
}
printf("***** result ***** \n\n");
printf("(10+30+50+70+90)=%d\n",k); //250
printf("(20+40+60+80+100)=%d\n",m); //300
}

Why I use the *ptr as 'pointer'? I mean it cannot run using just 'ptr'?
How the variable '*ptr' load the array 'a[]'.

A: Here the pointer ptr points to the first element of the array. If you declared it as a regular variable, you could only assign one value to it. But now you can assign the address of an array element & access all other elements through it by incrementing or decrementing the value of the pointer, which you won't be able to do, if it was declared as a variable.
The pointer ptr points to the first element of the array. So if you write ptr[1], it points to the second element of the array (since arrays are '0'-indexed). You can access other elements too.


text:
Q: ROR API Trying to create a zip code search So far I have separate zip+5 and zip+9 searches running. I want to create a search that returns results as specific as the input, and more specific when possible (user inputs a +5, they get results containing +5 and +9, user inputs a +9 gets back only matching +9's)
Here's what I have so far
scope :by_postal9, ->(postal_code) { where('postal_code = ?', (postal_code)) } #9 digit
scope :by_postal5, ->(postal_code) { where('postal_code = ?', (postal_code[0..4])) } #5 digit
scope :by_postal, ->(postal_code) { where('postal_code = ?', (postal_code[0..4])) or where('postal_code = ?', (postal_code)) } #all lengths

Working with a dataset of
ID \ postal_code
1  \ 92110-4441
2  \ 92110
3  \ 92110-4441

My 9 digit search seems to be the best one, it has no problems returning matching results for either +5 or +9 searches, but ONLY returns exact matches (searching postal9 with 92110 yields 1 result, searching with 92110-4441 yields 2 results, non-overlapping)
The 5 digit search operates as you might expect, and upon input of a 9 digit zip, returns matches for 5 digit results, but ONLY 5 digit results (search postal5 with 92110-4441 returns 1 result, ID 2)
The last example is probably just trash, but was my final effort in getting combined results.

A: Why don't you use LIKE?
scope :by_postal, ->(postal) { where('postal_code LIKE ?', "#{postal}%") }

If your postal is 5-digit it returns 5-digit and 9-digit variants. If 9-digit -- 9-digit only.

A: I would use separate scopes
by_postal, ->(postal_code) { where('postal_code LIKE ?', "%#{}%") }
by_length, ->(length) { where('LEN(postal_code) = ?', length) }

*

*for +5 by_postal('211').by_length(5)

*for +9 by_postal('211').by_length(9)

*for both by_postal('211')


text:
Q: How to read headers in body/response promise I'm calling API endpoint using fetch API.
How can I read response body and headers in resolved body promise?
My code snippet below:
  fetch(url, {
      credentials: 'include',
      method: 'post',
      headers: {
        "Content-Type": "application/json; charset=utf-8",
      },
      body: JSON.stringify({
        email: email,
        password: password,
      }),
    })
    .then(response => response.json())
    .then(function(response) {
      // How to access response headers here?
    });

A: As described in the Fetch API documentation, you can get response headers with this snippet:
fetch(myRequest)
  .then((response) => {
     const contentType = response.headers.get('content-type');
     if (!contentType || !contentType.includes('application/json')) {
       throw new TypeError("Oops, we haven't got JSON!");
     }
     return response.json();
  })
  .then((data) => {
      /* process your data further */
  })
  .catch((error) => console.error(error));

For the body you will find here some examples.


text:
Q: Как применить значение функции скрипта в html? Используется Spring MVC + Angular.
Есть табличка пользователей в html:
...

                        ID
                        NAME
                        AGE
                        ADMIN
                        CREATED_DATE

                        {{u.id}}
                        {{u.name}}
                        {{u.age}}
                        {{u.admin}}

                            getDate({{u.createdDate}})

                            <button type="button" ng-click="ctrl.editUser(u.id)" class="btn btn-success custom-width">
                                Edit
                            </button>
                        	...

метод ctrl.getAllUsers обращается к Controller'у возвращающих юзеров и соответственно в цикле отображает информацию о каждом юзере. Но значение u.createdDate - unix timestamp. Я бы хотел отображать в более читаемой форме. Для этого в html странице объявил скрипт:

и попытался его вызвать:

    getDate({{u.createdDate}})

Но он отображает значение непосредственно строки.
Подскажите, каким образом можно вызвать функцию и отобразить возвращаемый ей параметр?
P.S. В технологиях фронта разбираюсь плохо, возможно есть более корректные способы для отображения времени в корректном формате, когда от сервера приходит значение timestamp

A: Для angularjs есть фильтр date :
вместо
getDate({{u.createdDate}})

пишем, например
{{u.createdDate | date: 'dd.MM.yyyy'}}


text:
Q: How to measure predictor contribution in Generalized Linear Mixed Model? In GLM, there is explained deviance (D square) (Guisan and Zimmerman 2000). Contribution of each predictor in the best model can be compared using the explained deviance in the model excluding each predictors to that of the full model, and expressed as ΔD2.
GLMM has conditional R square (Nakagawa and Schielzeth 2013), but I do not know how to compare contribution of each predictor. When I try the same method as the GLM, I get negative contribution in delta marginal R square.


text:
Q: Google drive API and auth I want to create a web app letting any user upload a file to my Google drive and then be able to view it through the browser.
So far looking at Google's examples it seems I have to auth to my Google Drive on the server side (makes sense....) but also end-users have to auth before uploading anything to my drive using Oauth. Is there a way to prevent having to ask users to authenticate prior to uploading documents given that I am authorized through my server to my Google Drive account?
Allowing anyone to view a document is more straightforward through the use of a public folder...


text:
Q: Wordpress admin suddenly not an admin I have installed a template that I bought, and this template came with a SQL script to run. After I ran it everything works fine, except that the admin user now doesn't have permission to delete articles, media, and other stuff.
I have complete access to the server along with knowledge of PHP and SQL. How can I fix this?

A: Check the wp_user_level value in the wp_usermeta table of your database.  It should probably be 10.

A: Found the solution.
The original WordPress installation used a prefix for all table names. Apparently, fields in wp_users, wp_options and wp_usermeta whose names begin with "wp_" are supposed to begin with the full prefix.
I changed the table names in the script, but not the actual field names.
Setting the names to the full prefix solved this.
example:
if the prefix is wp_f3refs then wp_user-settings should be wp_f3refs_user-settings.
Thanks everyone for your help.


text:
Q: My javascript won't load in python-flask I'm attempting to load a piece of javascript funconality into my index.html
however when I load in flask it doesn't seem to be working.I am not an JS expert however I'm assuming it's JS Faulty because I've made sure everythings on right directory and being loaded correctly. Please take a look at what I'm doing wrong.
base.html
<!doctype html>

  <title>Flask-Mobility example</title>

  {% block content %}
  {% endblock %}

app\static\index.js

index.html
{% extends 'base.html' %}

{% block content %}

    <link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/index.css') }}">

    <form id="msform">

Account Setup

Social Profiles

Personal Details

      <fieldset>

Create your account

This is step 1

        <input type="text" name="email" placeholder="Email" />
        <input type="password" name="pass" placeholder="Password" />
        <input type="password" name="cpass" placeholder="Confirm Password" />
        <input type="button" name="next" class="next action-button" value="Next" />
      </fieldset>
      <fieldset>

Social Profiles

Your presence on the social network

        <input type="text" name="twitter" placeholder="Twitter" />
        <input type="text" name="facebook" placeholder="Facebook" />
        <input type="text" name="gplus" placeholder="Google Plus" />
        <input type="button" name="previous" class="previous action-button" value="Previous" />
        <input type="button" name="next" class="next action-button" value="Next" />
      </fieldset>
      <fieldset>

Personal Details

We will never sell it

        <input type="text" name="fname" placeholder="First Name" />
        <input type="text" name="lname" placeholder="Last Name" />
        <input type="text" name="phone" placeholder="Phone" />
        <textarea name="address" placeholder="Address"></textarea>
        <input type="button" name="previous" class="previous action-button" value="Previous" />
        <input type="submit" name="submit" class="submit action-button" value="Submit" />
      </fieldset>
    </form>

{% endblock %}

index.js
//jQuery time
var current_fs, next_fs, previous_fs; //fieldsets
var left, opacity, scale; //fieldset properties which we will animate
var animating; //flag to prevent quick multi-click glitches

$(".next").click(function(){
    if(animating) return false;
    animating = true;

    current_fs = $(this).parent();
    next_fs = $(this).parent().next();

    //activate next step on progressbar using the index of next_fs
    $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");

    //show the next fieldset
    next_fs.show();
    //hide the current fieldset with style
    current_fs.animate({opacity: 0}, {
        step: function(now, mx) {
            //as the opacity of current_fs reduces to 0 - stored in "now"
            //1. scale current_fs down to 80%
            scale = 1 - (1 - now) * 0.2;
            //2. bring next_fs from the right(50%)
            left = (now * 50)+"%";
            //3. increase opacity of next_fs to 1 as it moves in
            opacity = 1 - now;
            current_fs.css({
        'transform': 'scale('+scale+')',
        'position': 'absolute'
      });
            next_fs.css({'left': left, 'opacity': opacity});
        },
        duration: 800,
        complete: function(){
            current_fs.hide();
            animating = false;
        },
        //this comes from the custom easing plugin
        easing: 'easeInOutBack'
    });
});

$(".previous").click(function(){
    if(animating) return false;
    animating = true;

    current_fs = $(this).parent();
    previous_fs = $(this).parent().prev();

    //de-activate current step on progressbar
    $("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

    //show the previous fieldset
    previous_fs.show();
    //hide the current fieldset with style
    current_fs.animate({opacity: 0}, {
        step: function(now, mx) {
            //as the opacity of current_fs reduces to 0 - stored in "now"
            //1. scale previous_fs from 80% to 100%
            scale = 0.8 + (1 - now) * 0.2;
            //2. take current_fs to the right(50%) - from 0%
            left = ((1-now) * 50)+"%";
            //3. increase opacity of previous_fs to 1 as it moves in
            opacity = 1 - now;
            current_fs.css({'left': left});
            previous_fs.css({'transform': 'scale('+scale+')', 'opacity': opacity});
        },
        duration: 800,
        complete: function(){
            current_fs.hide();
            animating = false;
        },
        //this comes from the custom easing plugin
        easing: 'easeInOutBack'
    });
});

$(".submit").click(function(){
    return false;
})

A: Move your script tags to the bottom.
If written at the top, they have nothing to reference. For instance, $(".next") isn't actually matching anything since the elements with that class haven't been created.

A: |FlaskApp
----|FlaskApp
--------|templates
----------- html files are here
--------|static
----------- css and javascript files are here
script type="text/javascript" src="{{ url_for('static', filename='javascript.js') }}"


text:
Q: YaMap, поле поиска, шаблон С помощью ymaps.SuggestView сделал поле поиска.
При поиске выпадают список адресов.
При выборе нужного, заполняется поле поиска.
В всплывающем списке видим, улица - город - страна
При выборе адреса, поле заполняется-> Страна город улица.
Хочу привести к одному виду, поменять шаблон адреса в поле поиска, после клика на нужный адрес из списка.


text:
Q: Get Distinct Rows By Two Columns With Ordering Desc I have ms sql table like following.

ID
Num1
Num2
Range

3
1
2
1

4
2
1
2

5
3
1
1

6
2
3
1

7
4
1
1

8
1
4
2

9
1
4
3

I want to get distinct rows by num1 & num2 with highest range.
Query should return result like this.

ID
Num1
Num2
Range

4
2
1
2

5
3
1
1

6
2
3
1

9
1
4
3

Num1 & Num2 values are grouped (please note that 2,1 and 1,2 are considered as same). If the ere are multiple 1,2 rows with the highest range is selected from that group.
So far I could return following but it contains Num1 & Num2 swapped rows (1,2 & 2,1...).
Query should return the column as in the 1st table and Num1&Num2 data cannot be swapped.

ID
Num1
Num2
Range

3
1
2
1

4
2
1
2

5
3
1
1

6
2
3
1

7
4
1
1

9
1
4
3

Query I've tried
Select Max([ID]) As 'ID'
      ,Max([Num1]) As 'Num1'
      ,Max([Num2]) As 'Num2'
      ,Max([Range]) As 'Range'
    From [dbo].[Range]
    Group by Concat([Num1], [Num2])
    Order By Range desc

A: We can use a least/greatest trick here along with aggregation.  Actually, we can't do that on SQL Server, which doesn't support these scalar functions, but we can still use CASE expressions:
WITH cte AS (
    SELECT *, MAX([Range]) OVER (PARTITION BY
                  CASE WHEN Num1 < Num2 THEN Num1 ELSE Num2 END,
                  CASE WHEN Num1 < Num2 THEN Num2 ELSE Num1 END) AS MaxRange
    FROM yourTable
),
cte2 AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY
                  CASE WHEN Num1 < Num2 THEN Num1 ELSE Num2 END,
                  CASE WHEN Num1 < Num2 THEN Num2 ELSE Num1 END
                  ORDER BY MaxRange DESC) rn
    FROM cte
)

SELECT ID, Num1, Num2, [Range]
FROM cte2
WHERE rn = 1
ORDER BY ID;

A: Provided you're using SQLServer 2017+ you can use string_agg via an apply to create the condensed groupings required (this would easily support more than 2 columns if required) and a row_number solution for ordering by range:
with g as (
  select *, Row_Number() over(partition by grp order by range desc)rn
  from t
  cross apply (
    select String_Agg(n, '') within group(order by n)
    from (values(num1), (num2))v(n)
  )s(grp)
)
select Id, num1, num2, Range
from g
where rn = 1
order by id;

See Demo Fiddle
Edit:
on SQL server 2014 you could substitute for the for xml path hack:
with g as (
  select *, Row_Number() over(partition by grp order by range desc)rn
  from t
  cross apply (
    select top(2) n
    from (values(num1), (num2))v(n)
    order by n
    for xml path('')
  )s(grp)
)
select Id, num1, num2, Range
from g
where rn = 1
order by id;


text:
Q: scope value change doesn't get caught by $watch in directive I am following the documentation from here. Here's the directive I created as suggested.
.directive('setFocusIf', function() {
  return {
    link: function($scope, $element, $attr) {
      $scope.$watch($attr.setFocusIf, function(value) {
        if (value) { $element[0].focus(); }
      });
    }
  };
});

And my markup:
<input set-focus-if="hasFocus" ng-focus="hasFocus = false">

<button type="button" ng-click="addItem()">Add</button>

addItem() function does something and sets the value of hasFocus to true. But, this doesn't work and the element doesn't get focus. While debugging I found out that the $watch itself isn't getting called.
However, when I set the value like ng-click="hasFocus = true" in the button instead of setting hasFocus to true in the addItem() function, it works perfectly fine.
I tried enclosing it in $apply but doesn't seem to work, and I am not very clear on its internals. I think I am missing some fundamentals here, can someone please point out what's the difference between these two approaches.
Here's a plunker showing the problem

A: Ok, after trying out different stuff, I figured out that it has something to do with the dot in scope.
I changed this
<input set-focus-if="hasFocus" ng-focus="hasFocus = false">

to this
<input set-focus-if="focus.hasFocus" ng-focus="focus.hasFocus = false">

And ofcourse, addItem now sets $scope.focus.hasFocus = true;
It works perfectly now...
On a side note, I need to understand if setting the focus this way is right or not. Because this won't work for multiple element requiring focus on different occasions/events unless the directive is modified to work accordingly. But still it wouldn't be efficient since $watch would be called for every element that has set-focus-if directive.


text:
Q: Explain how Python decorator works This is an example for python decorator. I am unable to understand the way it works. Please explain me the given example's control flow. I will be highly obliged.
def helloSolarSystem(original_function):
   def new_function(*args, **kwargs):
        original_function(*args, **kwargs)
        print("Hello, solar system!")
   return new_function

def helloGalaxy(original_function):
    def new_function(*args, **kwargs):
        original_function(*args, **kwargs)
        print("Hello, galaxy!")
    return new_function

@helloGalaxy
@helloSolarSystem
def hello(targetName=None):
     if targetName:
        print("Hello, " +  targetName +"!")
     else:
        print("Hello, world!")
hello("Earth")

A: Decorators are syntactic sugar for applying higher-order functions in Python. A higher-order function is a function that takes one or more functions as inputs and returns a function. i.e.
h(x) = f(g(x))

where here f() is a higher-order function that takes a function of a single argument, g(x), and returns a function of a single argument, h(x). You can think of f() as modifying the behaviour of g().
Higher-order functions are composable (by definition), so in your specific example, the decorator syntax,
@helloGalaxy
@helloSolarSystem
def hello(targetName=None):
    ...

is equivalent to,
hello = helloGalaxy(helloSolarSystem(hello))

By substituting hello into helloSolarSystem, then the result of that into helloGalaxy, we get the equivalent function call,
def hello(targetName=None):
    if targetName:                            |
        print("Hello, " + targetName + "!")   |  (1)  |
    else:                                     |       |  (2)   |
        print("Hello, world!")                |       |        |  (3)
    print("Hello, solar system!")                     |        |
    print("Hello, galaxy!")                                    |

where (1) is the application of the original hello(), (2) is the application of,
def helloSolarSystem(original_function):
    def new_function(*args, **kwargs):
        original_function(*args, **kwargs)   <-- (1)
        print("Hello, solar system!")
    return new_function

and (3) is the application of,
def helloGalaxy(original_function):
    def new_function(*args, **kwargs):
        original_function(*args, **kwargs)   <-- (2)
        print("Hello, galaxy!")
    return new_function

A: This is simply the observation that in Python, functions are objects like everything else. Ah, function containing variable, you're not so special!
>>> issubclass(int, object) # all objects in Python inherit from a common baseclass
True
>>> def foo():
...     pass
>>> foo.__class__ # 1
<type 'function'>
>>> issubclass(foo.__class__, object)
True

In your example,
@helloGalaxy implies hello = helloGalaxy(hello)
similarly, @helloSolarSystem implies hello = helloSolarSystem(hello)
when you called
@helloGalaxy
@helloSolarSystem before hello() function
hello will be decorated by helloGalaxy and helloSolarSystem
so it new_function() will be overridden by helloSolarSystem().
Before hello("Earth") is called the function hello is decorated by newFunction() of helloSolarSystem() and helloGalaxy() decorators.


text:
Q: Android loading of large bitmaps I'm making an Android app and I need to load an image (bitmap) in a cavas and resize it using the "pinch zoom" gesture. When the image is over a certain size, however, the application crashes (OutOfMemory exception). How do I optimize the loading and manipulation of the image?
To load the image I use:
BitmapFactory.decodeResource (ctx.getResources (), R.drawable.image)

To draw it:
imgCanvas.drawBitmap (image, posX, posY, null),

To change its size:
Bitmap.createScaledBitmap (originalBitmap, neww, NEWH, true);

A: This is not trivial.
Based on the current scale of the image and the currently visible part of the image, only load a part of that image at the appropriate resolution:
https://developer.android.com/reference/android/graphics/BitmapRegionDecoder.html
When zoomed-out and you want to show the entire image scaled down, use the methods from this BitmapRegionDecoder class that take a BitmapFactory.Options parameter and set it inSampleSize to a value larger than 1 (preferably a value that is a power of 2):
https://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize
When zooming in, first zoom in the lower resolution that is already shown (where you used a value of inSampleSize > 1) and lazily load a higher resolution version (where inSampleSize is smaller than the previous value you used) using the BitmapRegionDecoder and fade in the higher resolution version gradually.
When the user zooms in, keep doing this until your inSampleSize is 1.


text:
Q: Importing image into powerpoint I am using Microsoft Powerpoint 2010. When I import an image from visio or a pdf version of that image into powerpoint, the image gets some blurry.
Any solution to this?

A: Depending on how you import the image you might end up with a low-resolution pixel-based image
If I get you right, you want to input a high-quality version of something created in Visio into a PowerPoint slide.
In my oppinion the best way to achieve this is to export the image as .emf from Visio and use this in PP. If you do this, sometimes the image seems blurry while editing the PP slide, but will look nice if printed or if you do a full-screen presentation. I was not able to find out why this is.
BTW: if you just drag&drop a Visio 2010 file into PP 2010 you will end up with an EMF file being inserted. You can check this by opening the pptx file manually and looking into the \ppt\media\ folder. (pptx files are normal zip-archives)


text:
Q: Criterion causing memory consumption to explode, no CAFs in sight Basically I have a simple function call, which
when used in conjunction with Criterion, results in
the memory consumption exploding.
Suppose I have the following program :
{-# OPTIONS_GHC -fno-cse #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import Criterion.Main
import Data.List

num :: Int
num = 10000000

lst :: a -> [Int]
lst _ = [1,2..num]

myadd :: Int -> Int -> Int
myadd !x !y = let !result = x + y in
  result

mysum = foldl' myadd 0

main :: IO ()
main = do
  print $ mysum (lst ())

Then this program (compiled with O0) runs fine, without
the memory exploding.
If we use cabal build -v to yield a dump of the compilation
commands invoked, and then tag -ddump-simpl -fforce-recomp -O0 -dsuppress-all (suggested in IO/Monadic assign operator causing ghci to explode for infinite list) to the end of the ghc --make -no-link ... command, we get the following core :
num
num = I# 10000000

lst
lst = \ @ a_a3Yn _ -> enumFromThenTo $fEnumInt (I# 1) (I# 2) num

myadd
myadd =
  \ x_a3Cx y_a3Cy ->
    case x_a3Cx of x1_X3CC { I# ipv_s4gX ->
    case y_a3Cy of y1_X3CE { I# ipv1_s4h0 ->
    + $fNumInt x1_X3CC y1_X3CE
    }
    }

mysum
mysum = foldl' myadd (I# 0)

main
main =
  print
    $fShowInt (mysum (enumFromThenTo $fEnumInt (I# 1) (I# 2) num))

main
main = runMainIO main

It seems that no CAFs are being produced, which is consistent
with the fact that the program does not explode. Now if I
run the following program which uses criterion 1.1.0.0 :
{-# OPTIONS_GHC -fno-cse #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import Criterion.Main
import Data.List

num :: Int
num = 10000000

lst :: a -> [Int]
lst _ = [1,2..num]

myadd :: Int -> Int -> Int
myadd !x !y = let !result = x + y in
  result

mysum = foldl' myadd 0

main :: IO ()
main = defaultMain [
  bgroup "summation"
    [bench "mysum" $ whnf mysum (lst ())]
  ]

then the memory consumption explodes. However printing
the core yields :
num
num = I# 10000000

lst
lst = \ @ a_a3UV _ -> enumFromThenTo $fEnumInt (I# 1) (I# 2) num

myadd
myadd =
  \ x_a3Cx y_a3Cy ->
    case x_a3Cx of x1_X3CC { I# ipv_s461 ->
    case y_a3Cy of y1_X3CE { I# ipv1_s464 ->
    + $fNumInt x1_X3CC y1_X3CE
    }
    }

mysum
mysum = foldl' myadd (I# 0)

main
main =
  defaultMain
    (: (bgroup
      (unpackCString# "summation"#)
      (: (bench
            (unpackCString# "mysum"#)
            (whnf mysum (enumFromThenTo $fEnumInt (I# 1) (I# 2) num)))
         ([])))
       ([]))

main
main = runMainIO main

and it seems that no CAFs are being produced. Therefore why
does the latter program, which uses criterion, result in the memory consumption exploding, whereas the former program
does not? I am using GHC version 7.8.3

A: You don't need to inspect the source of criterion to know that lst () will be shared: any subexpression will be shared (and therefore computed at most once) during the evaluation of the body of the immediately surrounding lambda. Additional lambdas may be introduced by overloading, various syntactic sugar constructs, and compiler optimizations, but none of that happens here as you can see from the Core.
If you don't want lst () to be shared then you should refactor the arguments of whnf to something like whnf (mysum . lst) ().

A: In your version without criterion, the list returned by lst () gets produced lazily and then incrementally garbage collected while mysum consumes it, since there are no other references to the list.
For the criterion version, however, look at the definition of whnf:
whnf :: (a -> b) -> a -> Benchmarkable
whnf = pureFunc id
{-# INLINE whnf #-}

and pureFunc:
pureFunc :: (b -> c) -> (a -> b) -> a -> Benchmarkable
pureFunc reduce f0 x0 = Benchmarkable $ go f0 x0
  where go f x n
          | n <= 0    = return ()
          | otherwise = evaluate (reduce (f x)) >> go f x (n-1)
{-# INLINE pureFunc #-}

It seems like x in go above would eventually become bound to the list returned by your lst (), while n is the number of iterations for the benchmarking.  When the first benchmark iteration is finished, x will all have been evaluated, but this time it cannot be garbage collected: It is still kept in memory because it is shared with the following iterations through the recursive go f x (n-1).


text:
Q: How to remove line from input type color I have an input type color.Choose color
The problem is the line inside the input type. My code looks like this
.input-field-color{
  background-color : #000033 !important;
  color : #000033 !important;
  max-width: 90px;
  padding-left: 0.5rem;
  padding-right: 0.5rem;
  box-shadow: none;
  outline-style:none;
  border-color:transparent;
  border:0;
  outline:none;
}

And on the page.
<input type="color" name="chooseColor" id="chooseColor" class="form-control input-field-color" [(ngModel)]="chooseColor" #chooseColor="ngModel" required maxlength="15">

A: to remove the line you just need to use following css code
input::-webkit-color-swatch { border: none; }


text:
Q: Why is Flask saying that my table is undefined? I have created a flask app with Flask-Sql-Alchemy, however flask in't recognising the database table User_Plans I created and trying to query.
It gives the following error:
NameError: name 'User_Plans' is not defined.
I could be wrong, but it feels like the error is a scoping issue.
I have included my code below.
Can you help? Many thanks in advance.
database.py
from flask_sqlalchemy import SQLAlchemy
from flask_user import UserManager, UserMixin, SQLAlchemyAdapter
from datetime import datetime

def create_db(app):

    db = SQLAlchemy(app)

    class User(db.Model, UserMixin):
        id=db.Column(db.Integer,primary_key=True)
        username = db.Column(db.String(50),nullable=False,unique=True)
        password = db.Column(db.String(255),nullable=False, server_default='')
        active=db.Column(db.Boolean(),nullable=False,server_default='0')
        email = db.Column(db.String(255),nullable=False,unique=True)
        confirmed_at = db.Column(db.DateTime())
        plan_id=db.Column(db.Integer, db.ForeignKey('plans.id'),default=1)

    db_adapter = SQLAlchemyAdapter(db,User)
    user_manager = UserManager(db_adapter,app)

    class User_Plans(db.Model):
        id=db.Column(db.Integer,primary_key=True)
        user_id=db.Column(db.Integer, db.ForeignKey('user.id'))
        plan_id=db.Column(db.Integer, db.ForeignKey('plans.id'))
        start_date = db.Column(db.DateTime())
    class User_APIs(db.Model):
        id=db.Column(db.Integer,primary_key=True)
        user_id=db.Column(db.Integer, db.ForeignKey('user.id'))
        api_id=db.Column(db.Integer, db.ForeignKey('tools.id'))
        api_key=db.Column(db.String(50),nullable=False,unique=True)

    class Tools(db.Model):
        id=db.Column(db.Integer,primary_key=True)
        tool=db.Column(db.String(50),nullable=False,unique=True)

    class Plans(db.Model):
        id=db.Column(db.Integer,primary_key=True)
        plan=db.Column(db.String(50),nullable=False,unique=True)
        price=db.Column(db.Float(5),nullable=False)
        credit=db.Column(db.Integer,nullable=False)

    class Usage(db.Model):
        id=db.Column(db.Integer,primary_key=True)
        user_id=db.Column(db.Integer, db.ForeignKey('user.id'))
        task_id=db.Column(db.Integer, db.ForeignKey('tasks.id'))
        datetime=db.Column(db.DateTime())

    class Tasks(db.Model):
        id=db.Column(db.Integer,primary_key=True)
        task=db.Column(db.String(50),nullable=False,unique=True)
        credit=db.Column(db.Integer,nullable=False)

    class Status(db.Model):
        id=db.Column(db.Integer,primary_key=True)
        status=db.Column(db.String(20),nullable=False,unique=True)

__init__.py
from flask import Flask
from flask import render_template

from flask_mail import Mail
from config import config
from database import create_db
from flask_user import login_required, current_user
from dateutil.relativedelta import relativedelta
from datetime import datetime

def create_app(config_name):
    print(config_name)
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    create_db(app)
    mail = Mail(app)

    @app.route('/')
    @login_required
    def index():
        user_id = current_user.id
        start_date=User_Plans.query.with_entities(User_Plans.start_date).filter(User_Plans.user_id==user_id).first()
        return '
Hello {}, you started your plan on {}
'.format(current_user.username,start_date.strftime('%d-%m-%Y'))

manage.py
from app import create_app
app = create_app('development')

if __name__== '__main__':
    app.run()

A: It isn't talking about your table, it's talking about the name User_Plans, which is indeed not defined in your main code. You need to import it - and any other models you use - into that file.
from models import User_Plans


text:
Q: How to be a verified publisher? I wrote an app and I want to sell it online, so I uploaded it to my website and tried to download and run it as a test, but a window appeared, it said : "The publisher could not be verified. Are you sure you want to run this software ?", and it also said : "Publisher : Unknown Publisher". It's actually a self-signed Java jar file wrapped into an exe file, I self-signed it with Netbeans6.7.
I wonder what should I do to be a "known" publisher ?
Frank

A: You need to sign it with an approved signing certificate an example is at
http://codesigning.ksoftware.net

A: You'll need to sign the EXE with a code signing certificate from a trusted root certification authority.
http://www.thawte.com/code-signing/
https://www.verisign.com/code-signing/
You'll find more CAs with a simple Google search.
Keep in mind, even though this is a Java JAR, the dialog you're seeing is from Windows complaining about the EXE being unsigned.  You'll need a MS Authenticode signing certificate to sign the EXE.  I'm not too familiar with Java, so you may or may not need a certificate to sign the JAR as well.  (Note a self-signed certificate will never be recognized as fully Trusted and Valid on any computer other than your own.)


text:
Q: Trouble in installing WxWidgets When i trying to install wxwidgets i getting this error message:

What should I do?

A: You have some other gcc in your path, the normal one definitely understands all of these options and, contrary to a comment above, no space is needed after -MT. Try running where gcc to find out where is it coming from and set up your PATH to exclude it.
FWIW I've just tried building wxWidgets with TDM 5.1.0 and it worked without any problems.

A: The Problem is that some files from your compiler are missing
Solution:
Try reinstalling you Compiler. If you are using CodeBlocks, reinstall it because it contains compiler with its installer.


text:
Q: Quote POSIX shell special characters in Python output There are times that I automagically create small shell scripts from Python, and I want to make sure that the filename arguments do not contain non-escaped special characters. I've rolled my own solution, that I will provide as an answer, but I am almost certain I've seen such a function lost somewhere in the standard library. By "lost" I mean I didn't find it in an obvious module like shlex, cmd or subprocess.
Do you know of such a function in the stdlib? If yes, where is it?
Even a negative (but definite and correct :) answer will be accepted.

A: pipes.quote():
>>> from pipes import quote
>>> quote("""some'horrible"string\with lots of junk!$$!""")
'"some\'horrible\\"string\\\\with lots of junk!\\$\\$!"'

Although note that it's arguably got a bug where a zero-length arg will return nothing:
>>> quote("")
''

Probably it would be better if it returned '""'.

A: The function I use is:
def quote_filename(filename):
    return '"%s"' % (
        filename
        .replace('\\', '\\\\')
        .replace('"', '\"')
        .replace('$', '\$')
        .replace('`', '\`')
    )

that is: I always enclose the filename in double quotes, and then quote the only characters special inside double quotes.


text:
Q: Translating formula from excel to java I'd like to translate these formula in java:
=100*((0.1/G10)+1)*EXP(-0.1/G10)

Where my G10 is my spacing1. I did it these way:
Double rqd1, rqd2, rqd3;

rqd1 = (0.1 / spacing1 + 1) * 100;
rqd2 = Math.exp (-0.1 / spacing1);
rqd3 = rqd1 * rqd2;

rqd3 will be the answer. Am I doing it the right way?

A: Why not
rqd1 = (0.1 / spacing1 + 1) * 100 * Math.exp (-0.1 / spacing1);


text:
Q: Get the ID after performing an insert statement in laravel I have this code to insert the information about the user in the database:
DB::table('users')->insert(
       array(
        'first_name'   =>   $first_name,
        'last_name' => $last_name,
        'birth_date' => $birthDate,
        'email' => $email,
        'password' => $password,
        'profession' => $profession,
        'gender' => $gender,
        'age' => $age
    )
   );

It runs sweet and then I have the user redirected to a dashboard page. But, I need the id of the user to get info about him/her. So, How do I get the id returned after the insert statement has been done!

A: use insertGetId();
$id = DB::table('users')->insertGetId(
   array(
    'first_name'   =>   $first_name,
    'last_name' => $last_name,
    'birth_date' => $birthDate,
    'email' => $email,
    'password' => $password,
    'profession' => $profession,
    'gender' => $gender,
    'age' => $age
   )
);

or just laravel eloquent
$users = User::create([
'first_name'   =>   $first_name,
'last_name' => $last_name,
'birth_date' => $birthDate,
'email' => $email,
'password' => $password,
'profession' => $profession,
'gender' => $gender,
'age' => $age
]);

dd($user->id); // If you modified Id add into model $primaryKey = "modified_id" $user->modified_id;


text:
Q: Why does Android insist on squishing my Button? I have a nice, pretty, facebook button image:

But my Android layout keeps squishing it:

Could anyone please help, here is a look at my layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/tagline"
        android:layout_centerHorizontal="true"
        android:layout_margin="10dp"
        android:contentDescription="@string/app_description"
        android:src="@drawable/logo" />

    <TextView
        android:id="@id/tagline"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:gravity="center"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:text="@string/tagline"
        android:textSize="22sp" />

    <Button
        android:id="@+id/loginButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tagline"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:background="@drawable/login_button_normal"
        android:text="@string/login"
        android:textStyle="bold" />

</RelativeLayout>

A: You are using a Button with a text inside. The property android:layout_width="wrap_content" applies on the width of the text, not on the width of your drawable background.
You can either:

*

*Integrate the text in your .png file.

*Use 9-patch

*Create a drawable to define the blue corners-rounded rectangle and create an image with only the white 'f' with the vertical line. Then you can use an TextView with a drawable inside:
 <TextView
     ...
     android:text="Log in"
     android:drawableLeft="{Your image (white f)}"
     android:background="{Your drawable (blue background)}"
     ... />

A: Thats because you are setting the background to your button:
android:background="@drawable/login_button_normal"

android:background doesnot preserve the aspect ratio of the image. Try giving some big text then you might start wondering why it is enlarged. Also for your purposes a 9-patch png's are preferred.


text:
Q: In wagtail how do I setup the v2 api to attach the full base url ( e.g. http://localhost:8000" ) to steamfield images and richtext embeds? I am currently using nuxt.js as a frontend for my wagtail headless cms. When I load a richtext field or an image block within a streamfield I am unable, or don't know how to, attach the full base url of the wagtail server so when it gets rendered on the nuxtjs site it resolves to src="/media/images/image.png which in the end tries to find the image on the nuxtjs site http://localhost:3000 and it needs to find it on the wagtail server side http://localhost:8000. For standard images I can intercept and prepend the server base url, but not when it comes to anything inside a streamfield.

A: [EDIT: Better answer below]
I'm not 100% certain this is the "proper" way to do it, but I managed to get what I needed by adding a server middleware that detects anything that starts with the directory /media and prepends the server base url.
// in nuxt.config.js
export default {
    serverMiddleware:[
      '~/serverMiddleware/redirects'
    ],
}

then in `serverMiddleware/redirects.js
export default function(req, res, next) {
    if (req.url.startsWith('/media')) {
        res.writeHead(301, {Location: `http://localhost:8000${req.url}`})
        res.end()
    } else {
        next()
    }
}

This is a quick workaround for now I'll see if there is anything better.
Ok, I believe this is the proper solution. It just seemed to evade me :P
Instead of using a redirect simply add a proxy to nuxt.config.js
modules: [
    '@nuxtjs/axios',
],
axios: {proxy: true},
proxy: {
    '/api/v2/': 'http://localhost:8000',
    '/media/': 'http://localhost:8000'
}


text:
Q: Android Alert manager delete I have set an alert manager for every event created by user. If any user delete the event after that, I want to delete the alert manager set for the specific event. How to delete any specific alert programmatically?

A:
I have set an alert manager for every event created by user.

I am going to assume that you really mean that you have set an alarm with AlarmManager.

How to delete any specific alert programmatically?

Call cancel() on AlarmManager with a PendingIntent for an equivalent Intent. Here is a sample project that demonstrates this (see OnBootReceiver.java).


text:
Q: element click intercepted (click work perfectly)(selenium python)(popup) I'm trying to automate a website using python selenium.
# ----- click on the sign up popup
popup = driver.find_element_by_xpath("/html/body/div[1]/div[4]/section[1]/div/div/div[2]/div/p/a")
popup.click()

click is working fine and the pop-up message is showing perfectly. but after that my I get this error:
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element ... is not clickable at point (1263, 589). Other element would receive the click:

  (Session info: chrome=89.0.4389.82)

and the code stop working. what can I do?
please help!

A: You need to get rid of the overlay. Without the HTML I can only offer a couple of solutions:

*

*Find the dismiss button of the overlay, click it.

*Use Javascript to remove the overlay from the DOM

*Wait until the overlay disappears

A: Could it be that you are receiving a described error after you are trying to find an element from that pop-up window? So it's not the line you are thinking that is producing the error. If that is the case, then when you are trying to for example click something in that pop-up window, try the following:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,""))).click()

You need to import:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

A: popup = driver.find_element_by_xpath("/html/body/div[1]/div[4]/section[1]/div/div/div[2]/div/p/a")
driver.execute_script("arguments[0].click();", popup)

Try invoking click directly to the element so that it bypasses the overlay or click it's close button.


text:
Q: Inserting data into mySQL table from mutlidimensional input form I wonder what's the best way to insert data into a database from a multidimensional form. The name of my form inputs is something like below:
name="order[][quantity]"
name="order[][description]"
name="order[][article]"
name="order[][price]"
name="order[][tax]"
name="order[][discount]"

How to insert this data into my database? Below is a image of my form:

As you can see the user can add many sections and all are to be handled by one submit button. Number of orders is a variable.
How do I resolve this?

A: What I'm assuming is..
SomePage.php
<input type='text' name='quantity[]'>
<input type='text' name='description[]'>
<input type='text' name='article[]'>
<input type='text' name='price[]'>
<input type='text' name='tax[]'>
<input type='text' name='discount[]'>

Submit_Some_Page.php
<?
extract($_POST);

$TotalArticle=sizeof($article);

for($i=0;$i<$TotalArticle;$i++)
{
    $Article=$article[$i];
    $Quanity=$quantity[$i];
    $Price=$price[$i];
    $Tax=$tax[$i];
    $Discount=$discount[$i];
    $Description=$description[$i];

    <-- Now, Write Insert Query Here..
    $Query="INSERT INTO TableName SET Col1Name=$Article,Col2Name=$Quanity,Col3Name=$Price,Col4Name=$Tax,Col5Name=$Discount,Col6Name=$Description";
      ..... Write Mysql Query To Execute It
}
?>

A: You're going to have to define the array for PHP to follow. In other words, you can't use an empty key for this, you'll need to autonumber them
name="order[0][quantity]"
name="order[0][description]"
name="order[0][article]"
name="order[0][price]"
name="order[0][tax]"
name="order[0][discount]"

And then do order[1] etc


text:
Q: What's the difference betwen parameterizations and variable substitution for solving integrals? Asumming I have the following integral to solve in the complex plane:
$$\int \frac{dz}{z+1} $$ while $|z|=5$ which means a contour of radius 5 around zero.
Is it possible to solve this integral using:
$$z+1=5e^{it}$$ while $t$ runs from $0$ to $2\pi$ ?
if this move is legit, what excactly am I doing? is it a parameterization or is it a varbile substitution?

A: That doesn't seem right.
$$z+1=5e^{it}$$
isn't a correct parameterization of the circle with radius 5 and the center as origin.
A correct parameterization would be: $z=z(t) = 5e^{it}$ which would lead to the integral:
$$\int_0^{2\pi}\frac{1}{5e^{it}+1}\cdot ie^{it} \text{d}t$$
Is it a variable substitution?
No, then you would need to apply the 'transformation of contour integration'-theorem:

If $w$ holomorphic on $\Gamma$ and $f$ continous on $w(\Gamma)$ then
  $$\int\limits_{w(\Gamma)} f(w) \operatorname dw = \int\limits_\Gamma f(w(z)) w'(z) \operatorname dz$$

Which would imply that you need to change the contour itself when transforming $z+1=5e^{it}$
How do I solve it?
There are various ways of solving this. You could use the residue theorem (which seems a bit overkill here).
Another possibility is to use the transformation of contour integrals and transforming $z +1 =w$, where the contour would shift 1 to the left.
Since the new contour still encloses the origin, you probably know the result: $2\pi i$


text:
Q: Display value of an array that has numbers as it's key (within an ng-repeat) I have the follow array of arrays in my controller (script.js file):
angular.module('myApp', [])
  .controller('oneController', ['$scope', function($scope) {
    $scope.countries = [{
      "name": "Aruba",
      "code": "ABW",
      "1960": 54208,
    }];

In my index.html file, I am running an ng-repeat to display a table with country name, code, and population in 1960.

Challenge Three

        {{ country.name }}
         {{ country.code }}
         {{ country.1960 }}

country.name and country.code show up in the table, but country.1960 does not. Is there a certain syntax I have to use for "1960" to make it work properly?

A: You need to access it using brackets:
{{ country["1960"] }}

A: You should also be able to use the following:


text:
Q: How to connect Microsoft Access database in linux server? I am using php and MS Access. In my local system its working fine.
How I can implement the same thing in server. I am using a Linux server. I have done lots of project with mysql database.This is the first time I am working php and MS Access.
Please give me a solution
Thank you