text:
Q: Next.js-Passport How to get user data after succesfull login?[client side routing] I am trying to access user data after succesfull login and also from every component.This is how i login the user:
    router.post("/user/login",(req,res,next)=>{

    passport.authenticate('local', function(err, user, info) {
        console.log(JSON.stringify(user)) // here i got user data
        if (err) { return next(err); }
        if (!user) { return res.send("fail"); }
        req.logIn(user, function(err) {
          if (err) { return next(err); }
          return res.send("success") // when client gets success message,it will do Router.push("/dashboard")

        });
      })(req, res, next);

})

Server configuration:
  server.use(cookieParser())
  server.use(bodyParser.json())
  server.use(passport.initialize());
  server.use(session({
  secret: 'jumpingdonger',
  resave: true,
  saveUninitialized: true,
  cookie : { secure : false, maxAge : (4 * 60 * 60 * 1000) }, // 4 hours
}))
//Passport Middleware
server.use(passport.initialize())
server.use(passport.session())

DashBoard page:
import Header from '../components/Header'

import Layout from '../components/MyLayout.js'
import React, { Component } from 'react';
import axios from 'axios';
import Router from 'next/router'

export default class DashBoard extends Component{

  constructor(props) {
    super(props);

    this.state = {

    };
  }
  componentWillMount(){
console.log(this.props)

  }

  logout =()=>{
    axios.get('/api/user/logout').then((result)=>{

            if(result.data=="success"){
                Router.push("/")
            }

    })

  }
  render(){
    if(this.props.userData == undefined){
      return(
        <Layout>

First you must login!

    </Layout>
      )
    }else{
      return(

        <Layout>

Welcome to your dashboard {this.props.userData.userName}

               logout
            </Layout>

        )

    }

  }

}
DashBoard.getInitialProps = async function(context) {

  if(context.req !=undefined){ // which means that we are from server
    return {
      userData:context.req.user

       };
  }else{
    return{}
  }

  }

So after succesfull login,i am redirected to dashboard page.Now in dashboard component i am trying to get userdata on getInitialProps.The problem is since i am redirected by client using Router.push(),i cant get data on getInitialProps unless i dont refresh the page from browser.If i refresh,context.req.user is populated by user data.So how do i access userdata with client side routing from dashboard page and also every other page ? What i couldnt understand is, is this puting user data into a cookie which i can access from client or is this a server side session ?
thanks
EDIT:
I solved the problem by transfering userData from server to client on succesfull login and seting a cookie in client side.I wonder is this a correct solution in this case ?

A: If user is logged in. passport will create user object in req for every request in express.
if (req.user) {
  // logged in
} else {
  // not logged in
}

In next.js when you use getInitialProps you have access to server with context.req.
like this:
static async getInitialProps({req}){
 if(req){
   // called on server
   // here you can check for that user object
 } else {
  // called on client
 }

}
However this cod will work if you have a SSR request in your next.js app (refresh page or put url and press enter).
You authenticate in server, so there is no way to find out if you have the same in front-end, Unless you use the token and verify the token in front-end as well.
Have a look at Express session which will help you with cookies.

A: You will need to use a redux store to solve this problem. If you have set up your redux store, you need to hydrate that into your redux store.
In your _app.js file add this code. Your pages can connect to the store.
  componentDidMount () {
   const { pageProps: { user }, reduxStore: { dispatch } } = this.props
   if (user) {
     dispatch({
       type: FETCH_USER,
       payload: user
    })
   }
  }


text:
Q: Select text on focus does not work for multiline textInputs The text inside my multiline textInput is not being selected even though 'selectTextOnFocus' is set to true.
I know that the text will be selected if multiline is not set to true, but I want this textInput to have multiple lines. I read the React Native docs for textInput but did not see anything to address this problem I am facing.
<TextInput placeholder={'test'} multiline={true} selectTextOnFocus={true}/>

I expect to click on the multiline textInput and have the text selected on focus.
I am using React Native version 0.59 and running the code on the latest iOS on both my iPhone 7+ and iPad 6th gen.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to run a NodeJS server while the Mac display is off or the Mac is locked? I'm running a Node JS server on my Mac.  I want to lock the Mac and/or put it to sleep but keep the Node process running.  Is that possible?  How do I do that?
Thank you.


text:
Q: Error while executing async get of Outlook item property Why am I getting Could not complete the operation due to error 80043200 sometimes while getting Outlook item property (for example, Subject) in email Compose mode?
Call stack:
Error
   at n.prototype.execute (appsforoffice.microsoft.com/lib/1.1/hosted/outlook-win32-16.02.js:11:86635)
   at u.DDA.OutlookAppOm.prototype.callOutlookDispatcher (appsforoffice.microsoft.com/lib/1.1/hosted/outlook-win32-16.02.js:11:150300)
   at u.DDA.OutlookAppOm.prototype.invokeHostMethod (appsforoffice.microsoft.com/lib/1.1/hosted/outlook-win32-16.02.js:11:150169)
   at u.DDA.OutlookAppOm.prototype._standardInvokeHostMethod$i$0 (appsforoffice.microsoft.com/lib/1.1/hosted/outlook-win32-16.02.js:11:148443)
   at r.ComposeSubject.prototype.getAsync (appsforoffice.microsoft.com/lib/1.1/hosted/outlook-win32-16.02.js:11:190544)

We use following code for getting a field from an Outlook item:
sfMailApp.OfficeManager.prototype._reloadField = function (name, defaultValue) {
var deferred = $.Deferred();
defaultValue = defaultValue || '';

var item = this.getItem();

if (item.isFake) {
    deferred.resolve('');
    return deferred.promise();
}

var field = item[name];
if (field && this._isComposeMode && field.getAsync) {
    var _this = this;
    try {
        field.getAsync(function (result) {
            if (result.status === Office.AsyncResultStatus.Succeeded) {
                _this[name] = _this._processOfficeData(result.value) || defaultValue;
                deferred.resolve(_this[name]);
            }
            else {
                _this._onError(result);
                deferred.reject();
            }
        });
    } catch (e) {
        deferred.reject();
    }
} else {
    this[name] = this._processOfficeData(field) || defaultValue;
    deferred.resolve(this[name]);
}

return deferred.promise();}

Code for getItem function:
sfMailApp.OfficeManager.prototype.getItem = function () {
var item = Office && Office.context && Office.context.mailbox && Office.context.mailbox.item ? Office.context.mailbox.item : null;

if (!item) {
    item = {
        isFake: true
    }
}

return item;}

One more error we're getting sometimes while trying to get user identity token:
{"name":"AccessRestricted","message":"Internal protocol error: -2147467259'.","code":9017 }

How should we handle that?


text:
Q: Keras LSTM input shape I am not sure whether I understand the shape of the input I should feed into the LSTM in keras. So I have the following setup:
    self._model = kr.models.Sequential()
    self._model.add(kr.layers.LSTM(100, batch_input_shape=input_shape, stateful=True, return_sequences=True))

    self._model.add(kr.layers.Dense(4))

The input_shape is (4,20,3) where 20 is the time step and 3 is the dimensionality of my feature vector. and 4 should be the batch size I think. Lets assume that I have a time series T and I select 4 random staring point P. so then my input to the network is constructed as follows:
  input = [T[p:p+20] for p in P]

I increase each p in P by 20 after every train_on_batch call and reset the state based on a random variable. As I understand the input has now 4 different batch each having its own distinct state. It is like training the network 4 times with different starting points.
The target labels are contained in a different time series L and it is constructed as follows:
  target_label = [L[p:p+20] for p in P]

I am getting some weird results and I wanted to make sure I get the initial idea right. So could you help to re insure me that it works as I have just described or tell me where I got it wrong?
Thanks


text:
Q: Exec doesn't work with functions and variables I am making a plugin system that works with .py files. When I do exec() with that plugin (.py file) and it has a function or variable it gives a NameError.

NameError: name 'editor_nf' is not defined

I've already googled it but I didn't find anything that helps me.
I only did:
plugin = open("plugin.py","r").read()
exec(plugin)

and the plugin.py file is:
import tkinter as tk

def editor_nf():
    enf = tk.Tk()
    enf.title("New file")
    enf.config(bg="white")
    enf.geometry("500x500")

    enf.mainloop()

def editor():
    editor = tk.Tk()
    editor.title("Website Editor")
    editor.config(bg="white")
    editor.geometry("1400x700")

    editor_nf_btn = tk.Button(editor,text="New file",bg="gray",fg="black",font="Arial",command=editor_nf)
    editor_nf_btn.grid(row=0,column=0)

    editor.mainloop()

editor()

So I want it to work with functions so people can create WORKING functions.
I don't want it to show:

NameError: name 'editor_nf' is not defined

dcg answered and it helped but then I converted it to exe and I got this

A: Let me give a simple example of what I was telling you in the comments. This is my folder structure:
/sample
   - plugins/
       - __init__.py # not necessary, but maybe you want to apply some logic
                     # before importing the plugins
       - plugin1.py
       - plugin2.py
       - plugin3.py
   - __init__.py
   - test.py

Every plugin prints what plugins it is (e.g., print('plugin 1')). test.py is as follows:
import os

if __name__ == '__main__':
    # load plugins
    plugins = [p for p in os.listdir('plugins') if not p.startswith('_')]
    for p in plugins:
        __import__('plugins.'+p[:-3])

The output is:
plugin 1
plugin 2
plugin 3

Which means I successfully imported all those modules (plugins) by using __import__. Note that __import__ returns a reference to the imported module, so you can store it for later manipulation. Hope it helps!

A: I said I editted it with the error and stuff, but I fixed it on my own. Thanks for helping!


text:
Q: Layering UIItems How does on layer objects in a view?
I have a number of movable UIImageViews and would like to add a button which should always be a "layer" above the images.
Meaning that the images should not overlap the button when they are moved. They should move behind rather.
How is this done?
Thanks

A: When you add you image views make sure that they are behind your button. You can use 1 of the following approaches for that:

*

*Add them using insertSubview:belowSubview: method with your button as 2nd parameter

*After adding imageViews call bringSubviewToFront: method with your button as parameter


text:
Q: How does Windows 7 calculate the color to use for taskbar "color hot-tracking"? This has intrigued me for quite some time.
Does anyone know the algorithm Windows 7 Aero uses to determine the colour to use as the hot-tracking hover highlight on taskbar buttons for currently-running apps?

It is definitely based on the icon of the app, but I can't see a specific pattern of where it's getting the colour value from.
It doesn't seem to be any of the following:

*

*An average colour value from the entire icon, otherwise you would get brown all the time with multi-coloured icons like Chrome.

*The colour used the most in the image, otherwise you'd get yellow for the SQL Server Management Studio icon (6th from left). Also, the Chrome icon used red, green and yellow in equal measure.

*A colour located at certain pixel coordinates within the icon, because Chrome is red - indicating the top of the icon - and Notepad++ (2nd from right) is green - indicating the bottom of the icon.

I asked this question on ux.stackoverflow.com and it got closed as off-topic, but someone answered with the following:

As described by Raymond Chen in this MSDN blog article:

Some people ask how it's done. It's really nothing special. The code
  just looks for the predominant color in the icon. (And, since visual
  designers are sticklers for this sort of thing, black, white, and
  shades of gray are not considered "colors" for the purpose of this
  calculation.)

However I wasn't really satisfied with that answer because it doesn't explain how the "predominant" colour is calculated. Surely on the SQL Management Studio icon, the predominant colour, to my eyes at least, is yellow. Yet the highlight is green.  I want to know, specifically, what the algorithm is.

A: From Welcome to the Windows 7 Desktop at exactly 35 minutes in:

It's a normalized color histogram across 27 different buckets, and we extract blacks, whites, alpha channels, and grays, and use the most dominant RGBV [sic] value...

I'm fairly certain the speaker meant to say "RGB", since "RGBV" doesn't seem to be a thing. The "normalized" part doesn't really matter; it's effectively counting how many pixels fall into each "bucket." Each pixel, therefore, is put into one of the 27 buckets (arranged in a three-dimensional array; the cube root of 27 is 3) based on the position of each of its channels' value. Windows determines for each color channel whether that color's intensity is in the bottom, middle, or top chunk of the range. It would appear that the ranges are about 0-60, 60-200, and 200-255. Completely transparent pixels are not included at all.
Windows then finds which bucket has the most pixels, ignoring the black, white, and gray ones (the buckets where all three channels were in the same third of the range). That explains the SQL Server Management Studio icon - much of what appears yellow to us actually gets dumped in the "white" bucket and is ignored.
If there are no pixels in any of the acceptable buckets, the program gets a light blue overlay regardless of the system color scheme. (See the command prompt.) If a program has no icon, it gets a white/translucent overlay even though the Windows default icon would otherwise produce a blue or green overlay.
There is nothing to stop multiple programs from having the same highlight color. The newest Chrome icon, for instance, gets the same yellow as Windows 8's Explorer.
If there are ties, there is a predetermined order that does not depend on the order of the colors in the image. This is probably just a result of the way the maximum is found - buckets that are checked earlier will continue to be the max even if a later one ties. It appears that yellow is one of the first buckets checked.
Once the winning bucket is discovered, the highlight color seems to be set to a color somewhere in the middle of the bucket's range.
Test cases (numbers provided are RGB value):
 (255, 247, 209) → default highlight
 (47, 0, 0) → default highlight
 (60, 0, 0) → dark red
 (66, 0, 0) → dark red
 (165, 0, 0) → red
 (128, 128, 128) → default highlight
 (0, 148, 255) and (255, 0, 0) → red
 (0, 255, 0) and (255, 216, 0) with same area → yellow
 same but flipped → yellow
 (255, 180, 180) → light red
 (255, 210, 210) → default highlight
 pure blue, pure yellow, pure red, and pure green with same area → yellow
 (255, 61, 61) → red
 (82, 0, 0) → dark red

A: My guess would be that for each color, starting from the top, you get the R, G, and B values, and from them you take the highest and lowest of the three and compare them.  The color with the biggest gap between the highest and lowest would be the brightest color in the image.  Now in the case of, say, the Chrome icon, there might be several colors tied for biggest gap, but the red is on the top, so it's encountered first, and thus that's what dominates for that image.  (I suppose you could test this by designing your own icon, like rotate the Chrome logo 120 degrees and see if the green or yellow dominates instead.)

A: From the way I understand it - The OS takes more than a few factors into account when determining the color.

*

*Has a color already been assigned by the OS to this application? If so, skip to 7.

*Is this color defined in the program code? If so, use the predefined color from the program. (Yes, there is a variable setting for windows programs that controls this, no, I do not know the exact variable name)

*if 1=false (Meaning no predefined color), define the dominant color of the icon used. (For this, the colors Black, white and grey are ignored)

*If 2 cannot define a single color that is used, and more dominant than the other colors used, define the average RBG value of the icon. If a defined color is achieved, use this. For the purpose of this, the colors White, Black, Grey and Brown are completely ignored.

*If 3 results in one of the blacklisted colors (Black white or grey), randomly assign a color that most closely represents the average RBG value, without infringing upon the blacklist colors.

*Upon successful assignment of the color is complete, store the color information in the registry for quicker color assignment later.

*If the color assigned matches a color already used by another application currently open, offset the color by a random hue amount within 15% of the assigned color.

*Display color.

This may very well be wrong, and is mostly speculation, but, this gives you a easy to understand method the OS could very well be using to determine the colors. It also explains how a program without a predefined color, and an icon using equal amounts of colors, isn't assigned white/brown/black, and why black, white and grey are never assigned.
Also you should note, that programs that don't have an Icon (there are some still) show a transparent hot-tracking color, which simply causes the icon to be 'brighter' when hovered over.

A: It has already worked with HTML, a server-side language that crosses the hashtags and evaluates the code, then by changing the font color in a page several entries are written, each once to be sent to the HTC One-time, and because it's Hypertex The protocol lock transfer is again sent to the contact's server, in order to lock that the server is not behind the screen so that it can be answered by pressing the button.Also see the shadows of the 0077 cc that acts like a message or SMS on receiving messages or splitting on the wealth dilsideways. In this SMS, HTML and receive messages are the HTML message.
007,0077cc
006bb7
005fa3
00538
00477
3b66
That later, the tint percentage, monochrome color, and shadow text on the hashtag should be encoded

A: Here is some VB code that averages the RGB colours of an image:
Function AverageRGB(ByRef P As PictureBox) As Long

Dim Count As Long
Dim Red As Long
Dim Green As Long
Dim Blue As Long
Dim Hexed As String
Dim X As Long
Dim Y As Long
Count = 0

For X = 0 To P.Width Step P.Width \ 32

    For Y = 0 To P.Height Step P.Height \ 32
        Hexed = Right("00000" & Hex(P.Point(X, Y)), 6)
        Red = Red + CLng("&h" & Right(Hexed, 2))
        Green = Green + CLng("&h" & Mid(Hexed, 3, 2))
        Blue = Blue + CLng("&h" & Left(Hexed, 2))
        Count = Count + 1
    Next

Next

AverageRGB = RGB(Red \ Count, Green \ Count, Blue \ Count)
End Function

It's not really optimized for use in an OS, but it should give you a basic idea -Source


text:
Q: how to calculate days between two dates in oracle? I wanted to find the number of days between two dates in oracle.So,I tried:
select to_date('03/09/2011','MM/DD/YYYY') -to_date('03/09/2010','MM/DD/YYYY') "Days" from dual;

the output is 365.Its ok ,but when I tried:
  select to_date(sysdate,'mm/dd/yyyy') -to_date('03/09/2010','MM/DD/YYYY') "Days" from dual;

i got error as:
ORA-01858: a non-numeric character was found where a numeric was expected

And also suppose ,if I calculate the no of days between 2010 and sysdate then the year which contains leap year will be also handled by oracle itself?

A: you can try this:  (sysdate is already date format so you can use like this)
  select trunc(sysdate) -to_date('03/09/2010','MM/DD/YYYY') "Days" from dual;


text:
Q: Grouping records and excluding I have a single table name Products with columns:
ProductID int,
ProductName varchar(50),
FromDate DATETIME,
ToDate DATETIME,
Modified DATETIME,
ModifiedBy int

This table contains same ProductNames. Modified is also a date type column which tells about any changes made to the product on that Modified date. When any change is made to the product ToDate and Modified will be updated according to the change other wise both will be null
Now my requirement is :

*

*I want a productname having ToDate with a value
and also with null in two columns

*Excluding those Productname with no change means having only ToDate and Modified as NULL

*Need Result set of Loca and Mocca

I have tried this code
select  *
from     Products cpp with (nolock)
where   (TODATE is not null and Modfied is not null)
        or (TODATE is null and Modified is null)
order by ProductID desc

Table Data

A: I think your question is a bit ambiguous. Try this one, even the result does not bring you the double null in the two columns but it will eliminates productname which is not modified at all:
select  productname, todate, modified
from    Products
group by productname, todate, modified
having sum(case when (TODATE is not null and Modfied is not null) then 1 else 0 end) > 0

A:     select  *
    from   Products cpp with (nolock)
    where NOT (TODATE is not null and Modfied is  null)
    order by ProductID desc


text:
Q: Extract rows from pandas dataframe with at least one value greater than or equal to values from array I have the following dataframe:
    mba_p   ssc_p   hsc_p   degree_p etest_p

0   58.80   67.00   91.00   58.00   55.0
1   66.28   79.33   78.33   77.48   86.5
2   57.80   65.00   68.00   64.00   75.0
3   59.43   56.00   52.00   52.00   66.0
4   55.50   85.80   73.60   73.30   96.8
... ... ... ... ... ...
210 74.49   80.60   82.00   77.60   91.0
211 53.62   58.00   60.00   72.00   74.0
212 69.72   67.00   67.00   73.00   59.0
213 60.23   74.00   66.00   58.00   70.0
214 60.22   62.00   58.00   53.00   89.0

I would like to filter the data based on this condition:
Extract all the rows where at least one value is greater than any of the values in this list:
[66.255, 75.7, 73.0, 72.0, 83.5]

tl;dr: the first row is a candidate since 67 and 91 are greater than more than one value in the list above (the values in the list are the 75th percentile of every column basically). Similarly, extract all such rows.
I tried using np.where() using the steps shown here but since that is filtering based only on one value and not a list, I can't figure how to extend that to this situation. A simple condition check would return rows only where all values are greater than equal I guess (unless I'm missing anything). Sorry if this sounds a little convoluted but not able to crack it yet.

A: You can use a mask of dataframe to get rows with values greater than the minimum in the array
num = min(66.255, 75.7, 73.0, 72.0, 83.5)
print(df.loc[df[df > num].any(axis=1)])

Output
   mba_p  ssc_p  hsc_p  degree_p  etest_p
0  58.80  67.00  91.00     58.00     55.0
1  66.28  79.33  78.33     77.48     86.5
2  57.80  65.00  68.00     64.00     75.0
4  55.50  85.80  73.60     73.30     96.8
5  74.49  80.60  82.00     77.60     91.0
6  53.62  58.00  60.00     72.00     74.0
7  69.72  67.00  67.00     73.00     59.0
8  60.23  74.00  66.00     58.00     70.0
9  60.22  62.00  58.00     53.00     89.0

A: a = np.array([66.255, 75.7, 73.0, 72.0, 83.5])

df[df.apply(lambda x: (x.to_numpy() > a[:, None]).any(), axis = 1)]

     mba_p  ssc_p  hsc_p  degree_p  etest_p
0    58.80  67.00  91.00     58.00     55.0
1    66.28  79.33  78.33     77.48     86.5
2    57.80  65.00  68.00     64.00     75.0
4    55.50  85.80  73.60     73.30     96.8
210  74.49  80.60  82.00     77.60     91.0
211  53.62  58.00  60.00     72.00     74.0
212  69.72  67.00  67.00     73.00     59.0
213  60.23  74.00  66.00     58.00     70.0
214  60.22  62.00  58.00     53.00     89.0


text:
Q: Inno Setup ExtractTemporaryFile causes wizard to freeze I've made custom pages to manage specific redist tools install depending on the user choice.
Those tools are linked to checkboxes checked by the user if he wants or not install those tools.
Then come a page only there to show the user the progression of the installation of each tool.
The issue I have here is that the progress page is shown only when first ExtractTemporaryFile of the setups for the tools is done, showing the last page as if it has frozen.
The only way I have to let the progress page be shown before the ExtractTemporaryFile happens is to put a MsgBox before any install function.
But even in this case, when the ExtractTemporaryFile is launched, the progress bar animation is frozen until the ExtractTemporaryFile is done...
Here is the part of the code doing this:
procedure CurPageChanged(CurPageID: Integer);
begin
  If CurPageID=PageInstallationPersonnalisee.ID then
    begin
      ProgressBarLabelPageInstPerso.Caption := 'Initialisation...';
      if InstallTool1 = True then
        begin
          ProgressBarLabelPageInstPerso.Caption := 'Installing InstallTool1...';
          F_InstallTool1();
        end;
      if InstallTool2 = True then
        begin
          ProgressBarLabelPageInstPerso.Caption := 'Installing InstallTool2...';
          F_InstallTool2();
        end;
      if InstallTool3 = True then
        begin
          ProgressBarLabelPageInstPerso.Caption := 'Installing InstallTool3...';
          F_InstallTool3();
        end;

      ProgressBarPageInstPerso.Style := npbstMarquee;
      //ProgressBarPageInstPerso.Style := npbstNormal;
      ProgressBarPageInstPerso.Position := 100;

      CancelWithoutPrompt:=True;
      WizardForm.Close;
    end;
end;

Note that ExtractTemporaryFile() is made in each F_InstallTooln() function.
Others part of Setup and File Sections that could help:
[Setup]
SolidCompression=no

[Files]
;Temporary redists
Source: "{#MyRessourcesPath}InstallTool1_Setup.exe"; DestDir: "{tmp}"; \
  Flags: deleteafterinstall noencryption dontcopy
Source: "{#MyRessourcesPath}InstallTool2_Setup.exe"; DestDir: "{tmp}"; \
  Flags: deleteafterinstall noencryption dontcopy
Source: "{#MyRessourcesPath}InstallTool3_Setup.exe"; DestDir: "{tmp}"; \
  Flags: deleteafterinstall noencryption dontcopy

Here, the page PageInstallationPersonnalisee is not shown until first ExtractTemporaryFile is done...
I'm aware that ExtractTemporaryFile can cause some delay in install process, but why should it cause the wizard to freeze?
So my question is: in my scenario, is there a way to force the wizard refreshing so that he shows up before any ExtractTemporaryFile procedure is launched?

A: The ExtractTemporaryFile really hangs the wizard form. As most code does.
The only custom page that allows forcing Windows message queue to get pumped is the TOutputProgressWizardPage (created by the CreateOutputProgressPage).
You can do something like this:
function NextButtonClick(CurPageID: Integer): Boolean;
var
  ProgressPage: TOutputProgressWizardPage;
begin
  if CurPageID = wpReady then
  begin
    ProgressPage := CreateOutputProgressPage('Preparing installations', '');
    ProgressPage.Show;
    try
      ProgressPage.Msg1Label.Caption := 'Installing 1 ...';
      ProgressPage.SetProgress(0, 100);
      ExtractTemporaryFile('1.exe');
      Exec(...);

      ProgressPage.Msg1Label.Caption := 'Installing 2 ...';
      ProgressPage.SetProgress(33, 100);
      ExtractTemporaryFile('2.exe');
      Exec(...);

      ProgressPage.Msg1Label.Caption := 'Installing 3 ...';
      ProgressPage.SetProgress(66, 100);
      ExtractTemporaryFile('3.exe');
      Exec(...);

      ProgressPage.SetProgress(100, 100);
      ProgressPage.Hide;
    finally
    end;
  end;
  Result := True;
end;

Though it does not work really well either on modern versions of Windows that have fancy progress bar with animation, if you cannot call the SetProgress frequently. Note that the SetProgress call is what does pump the message queue behind the scenes. So it makes sense to call it even when its parameter do not change. But you cannot, as the ExtractTemporaryFile blocks.

Alternatively, you can leave the deployment to the [Files] section and have the installers be executed from the AfterInstall event.
[Files]
;Temporary redists
Source: "{#MyRessourcesPath}InstallTool1_Setup.exe"; DestDir: "{tmp}"; \
  Flags: deleteafterinstall noencryption dontcopy; AfterInstall: Install1
Source: "{#MyRessourcesPath}InstallTool2_Setup.exe"; DestDir: "{tmp}"; \
  Flags: deleteafterinstall noencryption dontcopy; AfterInstall: Install2
Source: "{#MyRessourcesPath}InstallTool3_Setup.exe"; DestDir: "{tmp}"; \
  Flags: deleteafterinstall noencryption dontcopy; AfterInstall: Install3

A: I know this is an old thread but I was facing a similar situation where some of the files I was extracting using the ExtractTemporaryFile function were significantly slower than the others.
After some investigation I found this on Inno Setup help pages:

When solid compression is enabled, be sure to list your temporary files at (or near) the top of the [Files] section. In order to extract an arbitrary file in a solid-compressed installation, Setup must first decompress all prior files (to a temporary buffer in memory). This can result in a substantial delay if a number of other files are listed above the specified file in the [Files] section.

This means that for optimal performance you should move the files that you want to extract using that function to the top of the [Files] section.


text:
Q: How to display ICollection not equal to null in a Get request ASP.NET Core Web API? I have two models and two dtos, and I want to know if there's any way to display all the collection values in the get request?
Model Estado:
using System.ComponentModel.DataAnnotations;

namespace AppEstados.Models
{
    public class Estado
    {
        public int Id { get; set; }

        [Required]
        public string? Nombre { get; set; }

        public ICollection<Municipio>? Municipios { get; set; }
    }
}

Model Municipio:
using System.ComponentModel.DataAnnotations;

namespace AppEstados.Models
{
    public class Municipio
    {
        public int Id { get; set; }

        [Required]
        public  string? Nombre { get; set; }

        public int EstadoId { get; set; }

        public Estado? Estado { get; set; }
    }
}

EstadoDto:
using AppEstados.Models;
using System.ComponentModel.DataAnnotations;

namespace AppEstados.DTOs
{
    public class EstadoDto
    {
        public int Id { get; set; }

        [Required]
        public string? Nombre { get; set; }

        public ICollection<Municipio>? Municipios { get; set; }
    }
}

MunicipioDto:
using AppEstados.Models;
using System.ComponentModel.DataAnnotations;

namespace AppEstados.DTOs
{
    public class MunicipioDto
    {
        public int Id { get; set; }

        [Required]
        public string? Nombre { get; set; }

        public int EstadoId { get; set; }

        public string? Estado { get; set; }

    }
}

EstadoController:
// GET: api/Estado
[HttpGet]
public async Task<ActionResult<IEnumerable<EstadoDto>>> GetEstados()
{
    var listaEstados = await _context.Estados
                                     .Include(x => x.Municipios)
                                     .Select(x => new EstadoDto
                                                  {
                                                      Id = x.Id,
                                                      Nombre = x.Nombre,
                                                      Municipios = x.Municipios
                                                  })
                                     .ToListAsync();

    return listaEstados;
}

MunicipioController:
[HttpGet]
public async Task<ActionResult<IEnumerable<MunicipioDto>>> GetMunicipios()
{
    var municipio = await _context.Municipios
                                  .Select(x => new MunicipioDto
                                               {
                                                   Id = x.Id,
                                                   Nombre = x.Nombre,
                                                   EstadoId = x.EstadoId,
                                                   Estado = x.Estado.Nombre
                                               })
                                  .ToListAsync();

     return municipio;
}

As you can see, I get all of the values for municipio, except the
Estado field which for some reason is returned as null. Do I have
to be more specific with my dto, or is there a way for that field, to
not equal to null?

It is worth mentioning that if a send a get request to the Municipio
do get all the list of records.

Solution

// GET: api/Estado
[HttpGet]
public async Task<ActionResult<IEnumerable<EstadoDto>>> GetEstados()
{

    var listaEstados = await _context.Estados
        .Select(x => new EstadoDto
        {
            Id = x.Id,
            Nombre = x.Nombre,
            Municipios = x.Municipios.Select(m => new MunicipioDto
            {
                Id = m.Id,
                Nombre = m.Nombre,
                EstadoId = m.EstadoId,
                Estado = m.Estado.Nombre
            }).ToList()
        })
        .ToListAsync();
    return listaEstados;
}

A: In EstadoDto make this change
public ICollection<MunicipioDto>? Municipios { get; set; }
And change the fetch method to
var listaEstados = await _context.Estados
                                     .Select(x => new EstadoDto
                                                  {
                                                      Id = x.Id,
                                                      Nombre = x.Nombre,
                                                      Municipios = x.Select(m => new MunicipioDto
                                               {
                                                   Id = m.Id,
                                                   Nombre = m.Nombre,
                                                   EstadoId = m.EstadoId,
                                                   Estado = m.Estado.Nombre
                                               }).ToList()
                                                  })
                                     .ToListAsync();


text:
Q: Python Post request parsering data problem enter code here i want to monitor one site i have the header,data,api but something i do wrong can anyone help me?
import requests
import json

headers = {
 'accept': 'application/json',
 'accept-encoding': 'gzip, deflate, br',
 'accept-language': 'el-GR,el;q=0.9,en;q=0.8',
 'content-length': '2191',
 'content-type': 'application/x-www-form-urlencoded',
 'origin': 'https://www.bstn.com',
 'referer': 'https://www.bstn.com/',
 'sec-ch-ua': '"Google Chrome";v="107", "Chromium";v="107", "Not=A?Brand";v="24"',
 'sec-ch-ua-mobile': '?0',
 'sec-ch-ua-platform': '"Windows"',
 'sec-fetch-dest': 'empty',
 'sec-fetch-mode': 'cors',
 'sec-fetch-site': 'same-site',
 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 }'
 }
data={"requests": [{"indexName": "magento2_eu_products_first_release_date_desc", "params" : "page=0&highlightPreTag=__ais-highlight__&highlightPostTag=__%2Fais-highlight__&ruleContexts=%5B%22magento_filters%22%2C%22magento-category-448%22%5D&hitsPerPage=96&clickAnalytics=true&enablePersonalization=true&maxValuesPerFacet=9999&query=&facets=%5B%22is_sustainable%22%2C%22gender%22%2C%22raffle_is_active%22%2C%22raffle_is_expired%22%2C%22sizefootwear_conf.level1%22%2C%22group%22%2C%22groupextra%22%2C%22brand%22%2C%22sizeapparel%22%2C%22sizeaccessory_conf%22%2C%22discount.EUR.default_range%22%2C%22color%22%2C%22coming_soon%22%2C%22raffle%22%2C%22bstn_collection%22%2C%22created_timestamp%22%2C%22further_reduced%22%2C%22new_to_sale%22%2C%22price.EUR.default%22%2C%22categories.level0%22%2C%22categories.level1%22%2C%22categories.level2%22%5D&tagFilters=&facetFilters=%5B%22raffle_is_active%3AYes%22%2C%5B%22categories.level1%3AMen%20%2F%2F%2F%20Upcoming%22%5D%5D&numericFilters=%5B%22visibility_catalog%3D1%22%5D"}]}
url = f'https://scdn.bstn.com/1/indexes/*/queries?x-algolia-agent=Algolia for JavaScript (3.35.1); Browser; instantsearch.js (4.15.0); Magento2 integration (3.2.0); JS Helper (3.4.4)&x-algolia-application-id=5TWEGKOBK7&x-algolia-api-key=baf572958616d5dfd81813df9dc0d67a2ced20fde1d8997f1754147b1c1a46ed'

html = requests.post(url=url , headers=headers, data=data, verify=False, timeout=20)
output = json.loads(html.text)
print(html)


text:
Q: how to get Soft key input for the enter and delete/backspace regardless of the soft keyboard the user uses I want a way to detect the backspace and the enter key strokes.
The most recommended way I found was the OnKeyListener. but, that isn't working for me. I tried Logging and turns out it just wasn't detecting any keystrokes.
Even it's documentation says it won't get triggered always.
I use Microsoft's swiftkey keyboard.
I also got a suggestion for addTextChengedListener. but, that won't detect backspaces. So, can't use it.
here's the code that isn't working -
editText.setOnKeyListener { view, i, keyEvent ->    //not working
    Log.i(TAG, "onKeyListener working")
    when (i) {
        KeyEvent.KEYCODE_ENTER -> {
            fileChanged(
                position,
                editText.text.toString(),
                note.isAListItem,
                note.listItemIsChecked
            )
            listAdder(position)
            true
        }
        KeyEvent.KEYCODE_DEL -> {
            fileChanged(
                position,
                editText.text.toString(),
                note.isAListItem,
                note.listItemIsChecked
            )
            if (editText.text.isNullOrEmpty() && position != 0) {
                listRemover(position)
            }
            true
        }
        else -> false
    }
}

Also, I think the code is being discarded while compiling because the setOnKeyListener function doesn't get highlighted [yellow highlight] as the addTextChangedListener function. This is after the code was compiled. see below -


text:
Q: How to return a Flux of a DTO when fetching child records of a collection? I'm trying to basically do nested loops with reactive/spring webflux.  How would I go about iterating through a Flux, fetching child records, and ultimately return a Flux of DTOs (with the child records in each user dto)?
Here's the gist of it, although probably still way off.
public Flux<UserDTO> getUsers(String name) {
     Flux<User> users = userRepo.findByNameLike(name);

     return users.flatMap(u -> {
            Flux<Phone> phoneNumbers = phoneNumberRepo.findByUserId(u.getUserId());

            return phoneNumbers;
       }).flatMap(r -> {
            UserDto userDto = new UserDto();
            userDto.setUserId(u.getUserid());
            userDto.setPhoneNumbers(phoneNumbers);

            return userDto;
       });
}

A: you need to use map instead of flatMap on transfer to dto

A: You should collect the child entities to list before mapping.
    public Flux<UserDto> getUsers(String name) {
        Flux<User> users = userRepo.findByNameLike(name);

        return users.flatMap(u -> phoneNumberRepo.findByUserId(u.getUserId())
                .collectList()
                .map(phoneNumbers -> {
                    UserDto userDto = new UserDto();
                    userDto.setUserId(u.getUserId());
                    userDto.setPhoneNumbers(phoneNumbers);
                    return userDto;
                }));
    }


text:
Q: The Laplacian of the composition of a function with an orthogonal transformation
Define a "rotation of u" by $R_{A}u\doteq u\circ A $ with A an orthogonal $n\times n$ matrix and "$\circ$" means composition. Show that $\Delta (u\circ A )=(\Delta u)\circ A$. (Note: $u(x)\in C^{m\geqslant 2} (\mathbb{R}^{n}) $)

I tried to treat u as merely a number in $\mathbb{R}^{n}$ and then take the Laplacian to each entry of the matrix. Then I compared the LHS and the RHS and found they are equal. Is this correct? I felt this way is kind of trivial as you don't use the condition "orthogonal".

A: Hint: Write down everything explicitly. A orthogonal matrix $A$ satisfies $A A^T =  I$. Thus
$$\sum_{j=1}^n a_{ij} a_{kj} = \delta_{ik},$$
where $\delta_{ik} = 1$ if $i=k$ and $0$ if $i\neq k$.
By definition,
$$(u \circ A)(x_1, \cdots , x_n ) = u(A(x_1, \cdots x_n)) = u(\sum_{i=1}^n a_{1i} x_i, \cdots , \sum_{i=1}^n a_{ni} x_i)$$
Now take $\frac{\partial }{\partial x_i}$ to the above equation and apply chain rule.


text:
Q: select2.js - How to make selection active from data attribute I have the following html code:

     <select id="multi" class="js-dropdown-from-code">
         <optgroup class='def-cursor' label='Code' data-city='Description'>
             <option data-city="" data-id="0">Select unit...</option>
             <option data-city="New York" data-id="1">USA</option>
             <option data-city="London" data-id="2">UK</option>
         </optgroup>
     </select>

Where the select is converted into a Select2 dropdown list with two columns.
$('#multi').select2({
    width: '100%',
    formatResult: formatResultMulti,
    dropdownCssClass: 'bigdrop'
});

Using this functionality.
function formatResultMulti(data) {
    var city = $(data.element).data('city');
    var classAttr = $(data.element).attr('class');
    var hasClass = typeof classAttr != 'undefined';
    classAttr = hasClass ? ' ' + classAttr : '';
    var $result = $(
        '
' +
        '
' + data.text + '
' +
        '
' + city + '
' +
        '
'
    );
    return $result;
}

All of this is working, my question is when I am trying to load the select2 with a specific value to start.
Normally I would use the $('#multi).val('').trigger('change') to set the value, but as i am using an option group, i am not sure on how to do the same.
Can anyone please rescue me from my ignorance.
UPDATE:
I have added the missing HTML option tags. As you can see I am not using the value tag, but a data attribute data-id.
I have found that using the following works
$("#multi option[data-id='30']").prop("selected", true).trigger('change');

but it is not setting the underlying values, so on submitting the form, validation is not recognising the change trigger.

A: Try Using
$("#multi").val("").trigger('change.select2');


text:
Q: VB.NET Changing Database Column Header Names Using Datagridview I change the header name of a datagridview using the following code
Me.DataGridView1.Columns(0).HeaderText = "xxxx"

How can I apply this change to the Access database? Like when I rename first column in datagrid view I want the first column in database to be the same.

A: There isn't a .Net API that allows changes to the gridview's headers to propagate back to the database's columns.  The gridview object supports binding to multiple sources (among those MS Access, Sql Server, Oracle, Object collections etc.) and does not contain the DDL logic required to update the SQL based data sources.  Therefore, you will need to perform two separate actions: one on the access database and one within the asp.net code.


text:
Q: Keep a table out of schema.rb during migrations As a follow-on to an earlier question about not reloading a huge, persistent table when I run my tests, I need to keep this table out of schema.rb when I run my migrations.  This table gets loaded directly from a mysqldump, so I'm not worried about keeping track of it.
So, how can I keep a specific table out of schema.rb?

A: Turns out there's an option for just this situation!
I found it in activerecord-2.3.4/lib/active_record/schema_dumper.rb:
##
# :singleton-method:
# A list of tables which should not be dumped to the schema.
# Acceptable values are strings as well as regexp.
# This setting is only used if ActiveRecord::Base.schema_format == :ruby
cattr_accessor :ignore_tables
@@ignore_tables = []

So all I had to do was stick this at the end of environment.rb:
ActiveRecord::SchemaDumper.ignore_tables = ["table_name"]

If ActiveRecord.schema_format == :ruby, the array can also contain RegExp. For example, to ignore all tables starting with "MS":
ActiveRecord::SchemaDumper.ignore_tables = [/^MS/]

A: I think that if you keep the migration to generate the table out of your migrations folder, then it won't get run, and in turn won't be used to generate the development database, which should keep it out of the schema.rb.
You can probably figure out some way to run that single migration if you need to outside of the rake task (should just be establishing the connection and then running up on the migration class)


text:
Q: Calculate value-wise mean and value-wise sum among groups in Pandas groupby Let's say I have a dataframe like this:
cluster A     B     C
  a     1     2     3
  a     10    20    30
  a     100   200   300
  b     4     5     6
  b     40    50    60
  b     400   500   600
  c     7     8     9
  c     70    80    90
  c     700   800   900

I'd like to firstly group the dataframe by cluster, then calculate the value-wise mean for column A and B, and calculate the value-wise sum for column C among the groups.
Expected result:
cluster A     B     C
  d     4     5     18
  d     40    50    180
  d     400   500   1800

Thanks in advance.

A: you can groupby the cumcount of the cluster and then perform the aggregate functions:
s = df.groupby('cluster').cumcount()
df = df.groupby(s).agg({'A':'mean', 'B':'mean', 'C':'sum'})
df.insert(0,'cluster','d')
df
Out[1]:
  cluster    A    B     C
0       d    4    5    18
1       d   40   50   180
2       d  400  500  1800


text:
Q: How to reset all scope values in Angular Controller on Click? I am trying to reset all the scope values in a controller. I searched they provide $location to redirect but i want to reset all the scope on ng-click.

A: Assume you are trying to reset all controller scope values, you can do like the following:
angular.controller('MainCtrl', function($scope){
  init();
  $scope.click = function() {
    init();
  }
  function init() {
    $scope.foo = 'foo';
    $scope.bar = 'bar';
  }
})


text:
Q: Does the fluctuations-dissipation theorem hold in active matter for macroscopic physical quantities? I am trying to understand how the fluctuation–dissipation theorem applies to active matter.
I simulated a system with active motors which may consume energy from the environment to move and exert force on fibers.
All the chemical reactions have both positive on and off rates.
Assume I define a macroscopic physical quantity $x(t)$:

*

*Is detailed balance preserved when applying FDT to the macroscopic order parameter, $x(t)$?

*Do the fluctuations in $x(t)$ around its mean value $\langle x\rangle_0$ correspond to the power spectrum $S_x(\omega) = \langle \hat{x}(\omega)\hat{x}^*(\omega) \rangle$?

*Is it still true to say that FDT relates $x$ to the imaginary part of the Fourier transform $\hat{\chi}(\omega)$ of the susceptibility $\chi(t)$ by:
$$S_x(\omega) = \frac{2 k_\mathrm{B} T}{\omega} \mathrm{Im}\,\hat{\chi}(\omega)$$

*Maybe the proper way to draw insight on such a system is to use detrended fluctuation analysis, is it right?

A: In general, the fluctuation-dissipation theorem does not hold for active matter systems.
A way to see it, is that fluctuation dissipation theorems usually require the system to be at equilibrium or close to equilibrium, a condition that is broken for most active matter systems.
However, you have  several works related to this question, in particular whatever generalized FDT could hold for some active matter systems, see this recent arxiv (https://arxiv.org/abs/1909.03726 ) for a general overview of the FDT (case of active matter system is treated in sec. III.D)

A: Detailed balance states that at equilibrium, each elementary process is in equilibrium with its reverse process. Or in other words: the diatribution function does not change as time going on.
The active matter system is not in balance, thus it doesn't satisfy detailed balance.


text:
Q: Uncaught TypeError: Cannot read property 'locals' of undefined I've made bundle.js and bundle.css to use in my web app,
My package.json looks like this:
  "dependencies": {
    "bootstrap": "^4.5.3",
    "jquery": "^3.5.1",
    "popper.js": "^1.16.1"
  },
  "devDependencies": {
    "@babel/core": "^7.12.10",
    "@babel/plugin-proposal-object-rest-spread": "^7.12.1",
    "@babel/preset-env": "^7.12.11",
    "babel-loader": "^8.2.2",
    "css-loader": "^5.0.1",
    "file-loader": "^6.2.0",
    "mini-css-extract-plugin": "^1.3.3",
    "node-sass": "^5.0.0",
    "sass-loader": "^10.1.0",
    "style-loader": "^2.0.0",
    "url-loader": "^4.1.1",
    "webpack": "^5.11.0",
    "webpack-cli": "^4.2.0"
  },

My webpack.config.js:
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = (env, argv) => {
    return {
        //Define entry point
        entry: ['./src/index.js', './src/css/index.scss'],

        //Define output point
        output: {
            path: path.resolve(__dirname, 'wwwroot/dist'),
            filename: 'bundle.js'
        },

        module: {
            rules: [
                {
                    test: /\.s[c|a]ss$/,
                    include: path.resolve(__dirname, 'src'),
                    use: [
                        'style-loader',
                        MiniCssExtractPlugin.loader,
                        'css-loader',
                        'sass-loader'
                    ]
                },
                {
                    test: /\.js$/,
                    include: path.resolve(__dirname, 'src'),
                    loader: 'babel-loader',
                    options: {
                        presets: ["@babel/preset-env"],
                        plugins: ['@babel/plugin-proposal-object-rest-spread']
                    }
                },
            ]
        },
        plugins: [
            new webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery'
            }),
            new MiniCssExtractPlugin({
                filename: 'bundle.css'
            })
        ]

    };
};

My src structure is like this:
src
index.js:
import 'jquery';
import 'bootstrap';
import './js/login';
import './js/helpers';

index.scss:
@import 'bootstrap';
@import 'util.scss';
@import 'login.scss';
@import 'site.css';

I am getting this error in console:
Console
bundle.js
Everything else is working fine, i have no problem with javascript, but it bugs me that i don't know how to fix this error.
PS:
I am new to web development in general, started using webpack yesterday, the idea was to use only bundle.js and bundle.css in my html without adding jquery and bootstrap tags for them separately

A: Don't use 'style-loader' along with mini-css-extract-plugin, modify your rule to match the below:
{
    test: /\.s[c|a]ss$/,
    include: path.resolve(__dirname, 'src'),
    use: [
            //'style-loader',
            MiniCssExtractPlugin.loader,
            'css-loader',
            'sass-loader'
         ]
},

You can find more details here: https://github.com/webpack-contrib/mini-css-extract-plugin/issues/613

A: Try to set the option esModule to false for MiniCssExtractPlugin
use: [
    'style-loader',
    {
        loader: MiniCssExtractPlugin.loader,
        options: {
            esModule: false,
        },
    },
    'css-loader',
    'sass-loader'
]

A: Similar to @Dina's answer but without MiniCssExtractPlugin :
use: [
    {
      loader: "style-loader",
      options: {
        esModule: false,
      },
    },
    "css-loader",
    "sass-loader",
  ]


text:
Q: Using Google Apps and Amazon SES together on Amazon Route 53 DNS settings Currently, I am using Google Apps to receive an email to my verified domain address.
Now, I would like to use Amazon SES as well to use S3 action on email route to my specific email address on my verified domain.
So, lets say my domain address is "sample.com". I was using only Google Apps before so my DNS settings MX records was :
5 ALT1.ASPMX.L.GOOGLE.COM.
5 ALT2.ASPMX.L.GOOGLE.COM.
1 ASPMX.L.GOOGLE.COM.
10 ALT3.ASPMX.L.GOOGLE.COM.
10 ALT4.ASPMX.L.GOOGLE.COM.

Then I add the line :
20 inbound-smtp.us-east-1.amazonaws.com.

to my "sample.com" DNS settings MX record set to use Amazon SES as well.
And the line :
"some_relevant_text="

to _amazonses.sample.com. TXT record set.
Then I created receive rule for my email address, lets say my specific email address is "sample-email@sample.com".
I did follow every single procedure on tutorial.
http://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-getting-started.html
But unfortunately, it does not work. And I could not figure out why.
If you have had this kind of issues before and can help me to figure out the reason, it will be great.
Thanks in advance


text:
Q: How do I lazily-load a collection from a service method? I'm using Hibernate 5.1.3.Final with Spring 5.1.  I'm having trouble loading a lazily-loaded collection.  In my entity I have
@OneToMany(fetch = FetchType.LAZY)
@JoinTable(name = "sb_product_object", joinColumns = { @JoinColumn(name = "PRODUCT_ID") }, inverseJoinColumns = { @JoinColumn(name = "MY_OBJECT_ID") })
private List<MyObject> myObjects;

Then I have a service method where I load the objects
@Override
@Transactional
public List<MyObject> getMyObjectsByProduct(final String productId)
{
    final Product product = productService.findById(productId);
    return product.getMyObjects();
}

but when I try and iterate over the objects,
        final List<MyObject> ret = m_myobjectsvc.getMyObjectsByProduct(productId);
        for (final MyObject assmt : ret)

I get this error ...
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.mainco.subco.ecom.domain.Product.myObjects, could not initialize proxy - no Session
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:582)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:201)
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:561)
    at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:132)
    at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:277)
    at org.mainco.subco.MyObject.mvc.MyObjectViewControllerIT.testSetDisplayTABIcon(MyObjectViewControllerIT.java:87)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:539)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:761)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:461)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:207)

How do I lazily load a collection from my service method?

A: In your situation, if you always iterate your collection,
so i think you should avoid to use the lazy load because it causes N+1 problems and might impact to your performance.
Advanced solution: you should use "entity graph" in jpa 2.2, to load what you need.
For simply solution, just make sure collections is loaded by calling collections.size() in the same transaction.
No transaction anti pattern may be quite dangerous in my opinion. So avoid to use

A: Create session on enable Hibernate property enable_lazy_load_no_trans
<property name="hibernate.enable_lazy_load_no_trans" value="true"/>

https://vladmihalcea.com/the-hibernate-enable_lazy_load_no_trans-anti-pattern/


text:
Q: How to use "results" variable (callback function) inside query mysql in another function (Nodejs mysql) I have a project, to store every message that pass through mosquitto (mqtt) installed in CentOS7 to mysql database. I use Nodejs to store message that pass through.
And then I display that message in my website. I put "add device" function to add new table in database based on total data every device. (If i had device named "device1" that store temperature and humidity, it will create new table named "device1" and 3 column, id, humidity, and temperature.)
I have a problem. I want to use "results" variable from callback function inside query mysql in javascript. I want to use that variable outside that function.
Here is the code:
var sql= "SELECT count(*) AS hitung FROM information_schema.columns WHERE table_name = 'device' ";

connection.query(sql, function (error, results) {
    if (error) throw error;
    console.log(results[0].hitung);
});

Based on the example I gave above (device1). Console.log will print '3' (because of 3 columns).
I want to use it (the results[0].hitung value) in another function like:
function example() {
    for (i=1; i<=results[0].hitung; i++) {
        console.log(i);
    };
};

But it show error, that I can use that variable.
Im new in website development, because i have interest in only networking.
Sorry for my bad english, hope you understand my problem. Im new in this community. Thank you.

A:
I want to use it (the results[0].hitung value) in another function like

To do that, you'll need to call example from within your query callback function, exactly like you did with console.log, e.g.:
connection.query(sql, function (error, results) {
    if (error) throw error;
    example(results); // <===
});

That's because:

*

*results is scoped to that callback, and

*You have to wait for the callback before you have the results

You might look into using promises, and into using async functions (which create and consume promises). You can use util.promisify to convert Node callback-style functions to promises, although most APIs are actively adopting promises, and there are promise wrapper libs for a lot of other APIS (for instance, mysql-promise for mysql and mysql2). That might help by allowing you to write asynchronous code using standard flow-control mechanisms that used to only work for synchronous code.

A: You can add a parameter to your function like this:
function example(results) {
    for (i=1; i<=results.length; i++) {
        console.log(results[0].hitung)
    };
};

Then you call the function from your query callback:
connection.query(sql, function (error, results) {
    if (error) throw error;
    example(results);
});


text:
Q: avoid sub-modules and external packages in a module's namespace I'm writing a module to load a dataset.  I want to keep the interface/API as clean as possible - so I've made internal functions and variables hidden by prefacing their names with __.  Awesome.  My module, however, imports other packages (e.g. numpy) which still appear in my module's namespace, how can I avoid this?
i.e. my file looks something like:
Loader.py:
import numpy as np

__INTERNAL_VAR1 = True
EXTERNAL_VAR = True

def loadData():
    data = __INTERNAL_FUNC1()
    ...
    return data

def __INTERNAL_FUNC1():
    ...
    return data

and when I import my module np is exposed:
> import Loader
> Loader.[TAB]
  Loader.EXTERNAL_VAR   Loader.loadData   Loader.np

A: If the autocompletion you are using is correctly implemented, it should honour the __all__ attribute of modules, if set.
Add a list of all names your module exports in that name:
__all__ = ['loadData', 'EXTERNAL_VAR']

The __all__ variable is used to determine what names are imported if you use a from modulename import * wildcard import, as well as by the help() function when documenting your module.
There is no point in using double-underscore names as globals; it is a single underscore at the start that marks such names as 'internal' (by convention).

A: Another solution could be to create an __init__.py that contains a line that imports the functions and variables you need:
from Loader import EXTERNAL_VAR,loadData

This file should be placed inside a folder containing your module:
└── Loader
    ├── __init__.py
    └── Loader.py

Now when you import Loader you can access directly only EXTERNAL_VAR and loadData while all the other classes and modules are in Loader.Loader.
This solution should be independent of your autocompletion system.


text:
Q: Break strings into sentences in Java: BreakIterator fails on second occurrence of "Dr." I would like to split a string into sentences. As this is not straightforward (due to many "." that are not end of sentences) I am using a BreakIterator as follows:
public static List<String> textToSentences(String text) {
    BreakIterator iterator = BreakIterator.getSentenceInstance(Locale.US);
    iterator.setText(text);
    List<String> sentences = new ArrayList<String>(); // empty list
    String oneSentence = "";
    int start = iterator.first();
    int ctr = 0;
    for (int end = iterator.next(); end != BreakIterator.DONE; start = end, end = iterator.next()) {
        oneSentence = text.substring(start,end);
        System.out.println(ctr + ": " + oneSentence);
        sentences.add(oneSentence);
        ctr += 1;
    }
    return sentences;
}

If I test this now on:
String text = "This is a test. This is test 2 ... This is test 3?  This is test 4!!! This is test 5!?  This is a T.L.A. test. Now with a Dr. in it. And so associate-professor Dr. Smith said that it was 567 B.C.. Hi there! There is one thing: go home!";

The result is:
0: This is a test.
1: This is test 2 ...
2: This is test 3?
3: This is test 4!!!
4: This is test 5!?
5: This is a T.L.A. test.
6: Now with a Dr. in it.
7: And so associate-professor Dr.
8: Smith said that it was 567 B.C..
9: Hi there!
10: There is one thing: go home!

In sentence 6 it correctly ignores the Dr. but in sentence 7 it breaks after the Dr. (7+8 should be one sentence) . Why is this the case and how do I fix it?


text:
Q: Markers ignored when using Plot.extend() With this code:
from sympy import symbols, plot, sin, pi
from numpy import linspace

x = symbols('x')
s = linspace(-2 ,10, 3)

def plot_one(a):
    return plot(sin(2*x) / x + x + a, (x, -2*pi, 2*pi),
                markers=[{'args': (0, a, 'ro')}], show=False)

plots = None
for v in s:
    one_plot = plot_one(v)
    if plots: plots.extend(one_plot)
    else: plots = one_plot

plots.aspect_ratio = (1, 1)
plots.show()

markers created by the function are ignored except the first one:

I can imagine a solution merging the markers manually and using markers keyword only in a final call, but is there a more simple way to fix this problem?

A: Unfortunately, markers is not taken into consideration by the extend method. One way to solve the problem is to attach all the markers to the first plot:
from sympy import symbols, plot, sin, pi
from numpy import linspace

x = symbols('x')
s = linspace(-2 ,10, 3)

def plot_one(a):
    return plot(sin(2*x) / x + x + a, (x, -2*pi, 2*pi), show=False)

markers = [{"args": (0, a, 'ro')} for a in s]
p0 = plot_one(s[0])
p0.markers = markers

for i in range(1, len(s)):
    p0.extend(plot_one(s[i]))

p0.aspect_ratio = (1, 1)
p0.show()


text:
Q: What's the difference between @file_put_contents() and file_put_contents()? I've come across some PHP that triggers file_put_contents() as follows:
@file_put_contents($path_name_to_write_to, $string);
What's the significance of @ before the function call - if any? How is this different from file_put_contents($path_name_to_write_to, $string); - if at all?
Thanks.

A: From PHP manual: "PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored."
Source: http://www.php.net/manual/en/language.operators.errorcontrol.php

A: As per the doc:

PHP supports one error control operator: the at sign (@). When prepended to an expression   in PHP, any error messages that might be generated by that expression will be ignored.

documentation


text:
Q: Using GraphQL machinery, but return CSV A normal REST API might let you request the same data in different formats, with a different Accept header, e.g. application/json, or text/html, or a text/csv formatted response.
However, if you're using GraphQL, it seems that JSON is the only acceptable return content type. However, I need my API to be able to return CSV data for consumption by less sophisticated clients that won't understand JSON.
Does it make sense for a GraphQL endpoint to return CSV data if given an Accept: text/csv header? If not, is there a better practise way to do this?
This is more of a conceptual question, but I'm specifically using Graphene to implement my API. Does it provide any mechanism for handling custom content types?

A: Yes, you can, but it's not built in and you have to override some things. It's more like a work around.
Take these steps and you will get csv output:

*

*Add csv = graphene.String() to your queries and resolve it to whatever you want.

*Create a new class inheriting GraphQLView

*Override dispatch function to look like this:
def dispatch(self, request, *args, **kwargs):
    response = super(CustomGraphqlView, self).dispatch(request, *args, **kwargs)
    try:
        data = json.loads(response.content.decode('utf-8'))
        if 'csv' in data['data']:
            data['data'].pop('csv')
            if len(list(data['data'].keys())) == 1:
                model = list(data['data'].keys())[0]
            else:
                raise GraphQLError("can not export to csv")
            data = pd.json_normalize(data['data'][model])
            response = HttpResponse(content_type='text/csv')
            response['Content-Disposition'] = 'attachment; filename="output.csv"'

            writer = csv.writer(response)
            writer.writerow(data.columns)
            for value in data.values:
                writer.writerow(value)
    except GraphQLError as e:
        raise e
    except Exception:
        pass
    return response

*Import all necessary modules

*Replace the default GraphQLView in your urls.py file with your new view class.
Now if you include "csv" in your GraphQL query, it will return raw csv data and then you can save the data into a csv file in your front-end. A sample query is like:
query{
  items{
    id
    name
    price
    category{
        name
    }
  }
  csv
}

Remember that it is a way to get raw data in csv format and you have to save it. You can do that in JavaScript with the following code:
req.then(data => {
    let element = document.createElement('a');
    element.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(data.data));
    element.setAttribute('download', 'output.csv');

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
})

This approach flattens the JSON data so no data is lost.

A: I have to implement the functionality of exporting list query into a CSV file. Here is how I implement extending @Sina method.
my graphql query for retriving list of users (with limit pagination) is
query userCsv{
    userCsv{
        csv
        totalCount
        results(limit: 50, offset: 50){
            id
            username
            email
            userType
        }
    }
}

Make CustomGraphQLView view by inheriting from GraphQLView and overide dispatch function to see if query has a csv also make sure you update graphql url pointing to this custom GraphQLView.
class CustomGraphQLView(GraphQLView):
    def dispatch(self, request, *args, **kwargs):
        try:
            query_data = super().parse_body(request)
            operation_name = query_data["operationName"]
        except:
            operation_name = None
        response = super().dispatch(request, *args, **kwargs)
        csv_made = False
        try:
            data = json.loads(response.content.decode('utf-8'))
            try:
                csv_query = data['data'][f"{operation_name}"]['csv']
                csv_query = True
            except:
                csv_query = None
            if csv_query:
                csv_path = f"{settings.MEDIA_ROOT}/csv_{datetime.now()}.csv"
                results = data['data'][f"{operation_name}"]['results']
                # header = results[0].keys()
                results = json_normalize(results)
                results.to_csv(csv_path, index=False)
                data['data'][f"{operation_name}"]['csv'] = csv_path
                csv_made = True
        except GraphQLError as e:
            raise e
        except Exception:
            pass
        if csv_made:
            return HttpResponse(
                status=200, content=json.dumps(data), content_type="application/json"
        )
        return response

Operation name is the query name by which you are calling. In previous example given it is userCsv and it is required because the final result as a response came with this key. Response obtained is django http response object. using above operation name we check if csv is present in the query if not present return response as it is but if csv is present then extract query results and make a csv file and store it and attach its path in response.
Here is the graphql schema for the query
class UserListCsvType(DjangoListObjectType):
    csv = graphene.String()
    class Meta:
        model = User
        pagination = LimitOffsetGraphqlPagination(default_limit=25, ordering="-id")

class DjangoListObjectFieldUserCsv(DjangoListObjectField):
    @login_required
    def list_resolver(self, manager, filterset_class, filtering_args, root, info, **kwargs):
        return super().list_resolver(manager, filterset_class, filtering_args, root, info, **kwargs)

class Query(graphene.ObjectType):
    user_csv = DjangoListObjectFieldUserCsv(UserListCsvType)

Here is the sample response

{
  "data": {
    "userCsv": {
      "csv": "/home/shishir/Desktop/sample-project/media/csv_2021-11-22 15:01:11.197428.csv",
      "totalCount": 101,
      "results": [
        {
          "id": "51",
          "username": "kathryn",
          "email": "candaceallison@gmail.com",
          "userType": "GUEST"
        },
        {
          "id": "50",
          "username": "bridget",
          "email": "hsmith@hotmail.com",
          "userType": "GUEST"
        },
        {
          "id": "49",
          "username": "april",
          "email": "hoffmanzoe@yahoo.com",
          "userType": "GUEST"
        },
        {
          "id": "48",
          "username": "antonio",
          "email": "laurahall@hotmail.com",
          "userType": "PARTNER"
        }
      ]
    }
  }
}

PS: Data generated above are from faker library and I'm using graphene-django-extras and json_normalize is from pandas. CSV file can be download from the path obtained in response.

A: GraphQL relies on (and shines because of) responding nested data. To my understanding CSV can only display flat key value pairs. This makes CSV not really suitable for GraphQL responses.
I think the cleanest way to achieve what you want to do would be to put a GraphQL client in front of your clients:
+------+  csv  +-------+  http/json  +------+
|client|<----->|adapter|<----------->|server|
+------+       +-------+             +------+

The good thing here is that your adapter would only have to be able to translate the queries it specifies to CSV.
Obviously you might not always be able to do so (but how are you making them send GraphQL queries then). Alternatively you could build a middleware that translates JSON to CSV. But then you have to deal with the whole GraphQL specification. Good luck translating this response:
{
  "__typename": "Query",
  "someUnion": [
    { "__typename": "UnionA", "numberField": 1, "nested": [1, 2, 3, 4] },
    { "__typename": "UnionB", "stringField": "str" },
  ],
  "otherField": 123.34
}

So if you can't get around having CSV transported over HTTP GraphQL is simply the wrong choice because it was not built for that. And if you disallow those GraphQL features that are hard to translate to CSV you don't have GraphQL anymore so there is no point in calling it GraphQL then.


text:
Q: Booting Linux from external HDD, with persistence I am trying to install Linux, specifically Lubuntu or BackTrack 5 on an external HDD (Seagate FreeAgent GoFlex) but I have had no luck using YUMI, or UNetbootin to get it working. I do not have a CD to install from.
I want the hard drive to be able to save the data within Linux – as in: if I install a program, it will stay there.  I also tried doing this with a flash drive, which does boot, but it does not save data. I tried following Pendrive's tutorial on creating a casper-rw file and adding "persistent" to various files, but I cannot get it to save files.
Basically, I just want a form of Linux on a portable device that will save files and settings between boots.

A: I have tried Slackware, GNU/Debian and Slax on usb drive, and works fine in persistent mode.
So maybe you might try with one of those distributions.
GNU/Debian, specially offer a minimal version that can be installed into a usb drive. Here is
http://cdimage.debian.org/debian-cd/6.0.5-live/i386/usb-hdd/
You can make it booteable executing from a GNU/linux terminal:
dd if=<path-to-img-file> of=/dev/sdX

where X identify your memory stick. Almost always /dev/sda is the hard disk, so usb stick must be /dev/sdb or /dev/sdc or...
NOTE: Your memory stick must have a fat32 partition.
And you will need a extra partition to save your works, which must be labeled as live-rw and can be ext2, ext3, or whatever you want!.

A: On top of sgmarts answer trying using multiboot software for installing it as I find they usually work best for making portable linux with distros with persistence, xboot is one you could use for example, yumi I always found had this flaw.


text:
Q: Driver for triac Can you explain this schematic:
Especially part where are optotriac and triac. I can't understand why if turn on optotriac \ then main triac will be open. Because I made a real scheme and accidentally burned optotriac, by reason of it I connected pins 4 and 6 directly. And happened not what I assumed. Load which is bulb 60W didn't light. Even for a moment when I plug in to net socket.
So what difference with opto and without him? I think when we open optotriac no current will flows through gate of main triac.

A: When the triac called U4 (sic) is 'off', then there can be a voltage from MT2 to MT2. Recall that MT1 to gate is a low resistance and you need to feed some current into that gate to get the triac to turn on. In general the triac will behave well if you give it the same polarity of current as the voltage that is across MT2 (top connection) to MT1 (bottom connection)- in other words if MT2 is at +10V, give the gate +50mA and the triac will turn on. Same thing with MT2 negative, give the gate -50mA. After the triac turns on, the voltage across it drops to a volt or two.
For the purposes of this discussion, you can ignore R1 and R2- assume they're shorted, and C1- assume it's open. The optotriac is like a switch that closes when there is sufficient current flowing through the LED, so current simply flows from MT2 to the gate, and turns the triac on. Once the triac turns on, the gate current drops to a negligible amount (since there is little voltage across the triac) and therefore the resistors don't get hot.
The resistors R1, R2 and C1 limit the current under transient conditions and prevent spikes from turning on the triac.
Shorting where 6 and 4 on the optocoupler are connected should turn the triac on, if they don't then something is wrong (probably with the triac or triac wiring). Obviously if the triac does not turn on (for example, if you were to short the gate and MT2) then the resistor will be effectively in series with the load and will quickly burn up.
Not possible with your schematic, but if the triac load is on the MT2 side, then connecting R2 to the wrong side of the load would have a similar effect, because the triac would turn on, but the gate current would never drop.
Below is a triac "static switch". The low-current switch turns the triac on when it is closed.

simulate this circuit – Schematic created using CircuitLab


text:
Q: How can a udp broadcast packet be received by wireshark but not socket listener I have a C# app that works on several machines, but for some reason not on another. All are Windows XP.
I simply open up a port and listen:
void Open()
{
var myIpAddress = UdpComm.GetPcIpAddress(target);

listenEndPoint = new IPEndPoint(myIpAddress, RemotePort);

System.Windows.Forms.MessageBox.Show("Creating listener: " + target.ToString() + " - " + listenEndPoint.ToString());
_client = new UdpClient(listenEndPoint);
_client.EnableBroadcast = true;
_client.BeginReceive(ReceiveCallback, null);
}

public void ReceiveCallback(IAsyncResult ar)
{
  System.Windows.Forms.MessageBox.Show("Data received");
}

When I run the program, I see that the Open method runs successfully, and that the addresses and ports look correct.
When I look at this on Wireshark I also see that the data being sent from the remote address correctly, but I never see a message box from the callback.
I don't have any errors being thrown. Any ideas of what could cause the data to show up on Wireshark, but not in my app?

A: My callback began being called once I changed the subnet mask of the NIC to be 255.255.255.0 instead of 255.255.252.0.
I am not sure why wireshark could see the traffic, but not the UdpClient, but that change seemed to have made the difference.

A: Wireshark captures EVERYTHING, while your application only gets what gets after filtering.
The problem might be in sender's side. In essence, subnet mask define which part of address defines network and which node. Therefore, with subnet mask being 255.255.252.0 network address is 22 bits long.
Let's say your client is at 10.0.16.100\22. For broadcasting purposes node address with highest possible address is reserved. Many applications expect netmask to be 24 bits long (255.255.255.0) and would broadcast to 10.0.16.255. Which is wrong, because only 8 last bits are set. Proper broadcast address in such subnet would be 10.0.19.255

A: You must end the asynchronous receive process in order to capture the incoming data. When you call _client.BeginReceive() it spawns a thread that receives the incoming data for you. In order to capture this data you should add the following code below to your ReceiveCallback.  Then you will be able to use the incoming byte[] as you see fit.
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] incomingBytes = _client.EndReceive(ar, ref endPoint);

Additionally, you can reference the UdpClient class on MSDN at the following link:
http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.endreceive.aspx


text:
Q: Control cannot override Page_Load in hierarchy A ChildClass user control I'm working with has a chain of parent classes, ultimately inheriting from System.Web.UI.UserControl.
public BasestClass : AnotherClassExtendingUserControl
{
    private void Page_Load(object sender, EventArgs e)
    {
        // do some stuff
    }
}

public BaseClass : BasestClass
{
    // no Page_Load
}

Two parent classes up the chain, Page_Load is marked private. The 'middle' class obviously doesn't override it, but I need to add something to the Page_Load of the ChildClass user control.
public ChildClass : BaseClass
{
    // think I need to override Page_Load here,
    // but there is no acceptable method to override
}

What can I do to get into the Page_Load of ChildClass? There are controls in that control that I need to manipulate that do not exist in BaseClass or BasestClass.

A: The Page_Load (or Load) event  gets raised during execution of the OnLoad event method, so I would suggest moving your logic there. You shouldn't have a problem overriding the OnLoad method from your child class.

A: I copied your classes and just changed two things:
BasestClass : System.Web.UI.UserControl

That shouldn't alter anything, since you said that BasestClass ultimately inherits from UserControl.
I also added this to BasestClass.Page_Load:
Response.Write("BasePage_Load");

Now, to solve your problem:
You can add a constructor to ChildClass and add an event handler for the Load event.
public ChildClass()
{
        Load += new EventHandler(_Default_Load);
}

void _Default_Load(object sender, EventArgs e)
{
        Response.Write("Event Handler");
}

You can also override OnPreRender:
protected override void OnPreRender(EventArgs e)
{
       base.OnPreRender(e);
       Response.Write("OnPreRender");
}

Doing all of the above, this is output in the response:
Event Handler
BasePage_Load
OnPreRender

If you want to be sure that the Page_Load method of BasestClass has already run before your new code, OnPreRender is the place to do your thing.


text:
Q: How to check all of items in Android I want develop test application and for this I want use this API : https://www.themealdb.com/api/json/v1/1/lookup.php?i=52772
In this API for show some info use many field, such as strIngredient1, strIngredient2, strIngredient3 and more to strIngredient15.
I want first check each of this items, and when not empty. then show this.
There are 15 items and I don't want check each of items!
I want check all of this items and each item not empty then show it!
How can I it? Is such a thing possible?

A: I checked the response, in some case response may be like this due to bad code from backend developer and things will not be in our control.
We can do some hack to sort out your problem. Check out this code snippet:
val meals = response.getJSONArray("meals")
    val meal = meals.getJSONObject(0)
    for(i in 1..20){
        val gradient = meal.getString("strIngredient${i}")
        if(!gradient.isNullOrBlank()){
            println(gradient)
            //Do whatever you want
        }
    }

I have just created a loop and the concat index with hard-coded string that will make a required attribute name and you can get the data from that json object.


text:
Q: UIImage detecting touch and dragging Fairly common question this, to which I have a few answers and I'm nearly there. I have a button which when pressed, will create an image (code as follows)
(numImages is set on load to ZERO and is used as a count up for the tag numbers of all images created)
UIImage *tmpImage = [[UIImage imageNamed:[NSString stringWithFormat:@"%i.png", sender.tag]] retain];
UIImageView *myImage = [[UIImageView alloc] initWithImage:tmpImage];

numImages += 1;

myImage.userInteractionEnabled = YES;
myImage.tag = numImages;
myImage.opaque = YES;
[self.view addSubview:myImage];
[myImage release];

I then have a touchesBegan method which will detect what's touched. What I need it to do is to allow the user to drag the newly created image. It's nearly working, but the image flickers all over the place when you drag it. I can access the image which you click on as I can get it's TAG, but I just cannot drag it nicely.
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touch.view];

    if (touch.view.tag > 0) {
        touch.view.center = location;
    }

    NSLog(@"tag=%@", [NSString stringWithFormat:@"%i", touch.view.tag]);

}

- (void) touchesMoved:(NSSet *)touches withEvent: (UIEvent *)event {
    [self touchesBegan:touches withEvent:event];
}

It works, in that I get an output of the tag for each image as I click on them. But when I drag, it flashes... any ideas?

A: In answer to my own question - I decided to create a class for handling the images I place on the view.
Code if anyone's interested....
Draggable.h
#import <Foundation/Foundation.h>
@interface Draggable : UIImageView {
    CGPoint startLocation;
}
@end

Draggable.m
#import "Draggable.h"
@implementation Draggable

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    // Retrieve the touch point
    CGPoint pt = [[touches anyObject] locationInView:self];
    startLocation = pt;
    [[self superview] bringSubviewToFront:self];
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
    // Move relative to the original touch point
    CGPoint pt = [[touches anyObject] locationInView:self];
    CGRect frame = [self frame];
    frame.origin.x += pt.x - startLocation.x;
    frame.origin.y += pt.y - startLocation.y;
    [self setFrame:frame];
}
@end

and to call it
UIImage *tmpImage = [[UIImage imageNamed:"test.png"] retain];
UIImageView *imageView = [[UIImageView alloc] initWithImage:tmpImage];

CGRect cellRectangle;
cellRectangle = CGRectMake(0,0,tmpImage.size.width ,tmpImage.size.height );
UIImageView *dragger = [[Draggable alloc] initWithFrame:cellRectangle];
[dragger setImage:tmpImage];
[dragger setUserInteractionEnabled:YES];

[self.view addSubview:dragger];
[imageView release];
[tmpImage release];

A: Usually you get an implicit animation when you change center. Are you messing with -contentMode or calling -setNeedsDisplay by any chance?
You can explicitly request animation to avoid the delete and re-draw this way:
if (touch.view.tag > 0) {
    [UIView beginAnimations:@"viewMove" context:touch.view];
    touch.view.center = location;
    [UIView commitAnimations];
}

Do note that NSLog() can be very slow (much slower than you'd expect; it's much more complicated than a simple printf), and that can cause trouble in something called as often as touchesMoved:withEvent:.
BTW, you're leaking tmpImage.


text:
Q: Does precomposition with opposite functor preserve colimits? For $F: \mathcal{C} \to \mathcal{D}$ we can define a functor $- \circ F^{op}: Set^{\mathcal{D}^{op}} \to Set^{\mathcal{C}^{op}}$ which sends an object $X$ to $X \circ F^{op}$ and natural transformation $(\mu_D)_{D \in \mathcal{D}}$ to $(\mu_{FC})_{C \in \mathcal{C}}$.
Does this functor preserve colimits? Certainly, if $(X, \mu)$ is a limiting cone for $G: \mathcal{I} \to Set^{\mathcal{D}^{op}}$, we have that $(X \circ F^{op}, \mu F)$ is a cone for $(- \circ F^{op}) \circ G$.
Normally, we would assume a cone for $(- \circ F^{op}) \circ G$, then turn it into a cone of $G$ and do something with the unique morphism for $G$ to get a unique morphism for $(- \circ F^{op}) \circ G$, but I do not see how to do that here.

A: Consider

where $i \to j$ is an arrow in $\mathcal I$ and the double arrows indicate that they are natural transformations. By functoriality, this is certainly a cone $(X \circ F^{op}, \mu F^{op})$ under $(- \circ F^{op}) \circ G$.
Then for each $c \in \mathcal C$, we have the following commutative diagram

by dissembling the above cone.
Now since $F^{op}$ is a functor, we may write $F^{op}c = d$ for $d \in \mathcal D$. Thus we have the following commutative diagram

Since $(X, \mu)$ is a colimit cone under $G$, there is a unique map $Xd \to Zd$ for any cone with nadir $Z$ under $G$. Assembling these maps for each $F^{op}c = d$, we obtain the unique morphism for $(- \circ F^{op}) \circ G$ as desired.


text:
Q: How to get wikipedia out-links of an article in python? I want to get the out-links of wikipedia articles. What I mean by out-linkes are the links in What links here section in wikipedia articles.
For instance, consider the data mining wikipedia article. What links here section of this article is in: https://en.wikipedia.org/wiki/Special:WhatLinksHere/Data_mining
I tried to used pywikibot as follows.
import pywikibot as pw

site = pw.Site('en', 'wikipedia')
print([
    cat.title()
    for cat in pw.Page(site, 'data mining').categories()
    if 'hidden' not in cat.categoryinfo
])

However, it seems like the categories in pywikibot is different to out-links of wikipedia articles. Therefore, I am wondering how to do this in python.
Note: I am not limited to pywikibot and happy to explore other libraries such as mediawiki.
I am happy to provide more details if needed.

A: Try Page.embeddedin() and Page.backlinks() methods. You could also directly use the equivalent modules of MediaWiki's API:

*

*Backlinks

*Embeddedin


text:
Q: Check if python version is compatible with script before executing I have a Python script that has been written using in Python 2.7. However it will be deployed to a number of different servers, some of which are running Python 2.4. In this case I am happy for the script to simply not run on the servers running Python 2.4. Is there a way I can do this in my Python script or would it be best to put a wrapper around the script?
I have tried doing this:
if sys.version_info[0] < 2.7:
    raise Exception("Python 2.7 or a more recent version is required.")

However because Python compiles the code before running it fails during compile when it hits part of the script that does not work in 2.4.

A: sys.version_info[0] is the major version only. So, it'll be 2 for all python 2.x versions. You're looking for sys.version_info[1], with the minor version:
# check for python 2
if sys.version_info[0] != 2:
    raise Exception("Please use Python 2")
# check for 2.7+
if sys.version_info[1] < 7:
    raise Exception("Please use Python 2.7+")

Alternatively, for more descriptive naming, you can use sys.version_info.major instead of sys.version_info[0] and sys.version_info.minor instead of sys.version_info[1].
Also, make sure you add this near the top of your script so there are no incompatibilities before the line is hit and the exception is raised.
If your code uses incompatible syntax, then you should put the non-version checking code in a main function in a separate file, then import that after the check so that Python doesn't try to parse it.


text:
Q: Compare 2 values in 2 different work sheets and automatically copy a range of values I've been trying to do this for some time but I keep hitting a roadblock.
I have a sheet in Excel that has a column by name -  Index with values 1 to 10.
I have columns F to U that has some data for each index value.
I created a new sheet with columns Index and remaining columns similar to first sheet.
I want a macro so that when I type 2 as Index value, it will automatically populate values from Sheet 1 - columns F to U corresponding to index value 2 to new sheet. This should work for any new index value added in Sheet 1.
I tried doing a formula but it did not work.
Any ideas?
Example
Sheet 1
Columns    Index
         1       q w e r s t u v a b c d e f g h
         2       a b c d e f g h i j k l m n o p

Sheet 2
When I type value 2 under Column Index in Sheet 2, it must populate corresponding values from a to p automatically.
2   a b c d e f g h i j k l m n o p

A: I don't know if this is going to be a good solution for you, but it does work.
In Sheet 2, lets say row 1 is reserved for column headings, and A2 is where you put your index value, then put the following formula in F2 on sheet 2 and copy across to U2:
=OFFSET(Sheet1!F2:F11,Sheet2!$A$2-1,0,1,1)

For the first column (F), this references the F column in sheet 1, and uses the index you type into sheet 2, to move to the correct row and copy the value from sheet 1 to sheet 2.
Edit.. Rereading your question, I modified my solution slightly:
=OFFSET(Sheet1!F:F,Sheet2!$A$2,0,1,1)

This allows for adding any number of additional indices, and so long as the indices are all in order from 1 to whatever, the behaviour you are expecting in sheet 2 will work. Note that subtracting 1 is not necessary, as offset 0 is the row reserved for column headings.


text:
Q: How to pass class instance to a static method? I actually managed this creating this code:
class Foo{
    public void test(){
         Keyboard.input(this);
    }

    public void menu(){
          Console.WriteLine("This is a menu");
    }
}

class Keyboard{
     public static string input(object class_name){
           new class_name().menu(); //call from dynamic object the method
     }
}

How you can see I have a class called Foo this contains the method test that read some input from the user keyboard, essentially this method allow me to recognize if the user press a particular key the code call the method menu. In this example it's just called the method menu. Now I pass the instance of the class Foo to the Keyboard class that have a static method called input, this method should create a new instance of the passed class and call the menu method. But I actually got an error on this line:
new class_name()

object is an object but is used as a type

what I did wrong?

A: Since class_name is an instance of class not a type, you should cast it to Foo type and call the function.
Change
new class_name().menu();

to
((Foo)class_name).menu();

Update
If you wish it to use on multiple classes, you should create an interface for them to inherit.
// All classes passed into 'Keyboard.Input' should inherit this interface
interface IMenu
{
    public void menu();
}

class Foo : IMenu
{
    public void test()
    {
        Keyboard.input(this);
    }
    public void menu()
    {
        Console.WriteLine("This is a menu");
    }
}

and change the lines from
public static string input(object class_name)
{
    new class_name().menu(); //call from dynamic object the method
}

to
public static string input(IMenu class_name)
{
    ((IMenu)class_name).menu();
    return "Something you want to return";
}

A: You need to use generic method with new constraint and pick menu method into base abstract class:
public abstract class MenuClass
{
    public abstract void menu();
}

class Keyboard
{
    //if you can pass class name
    public static string input<TClassName>() where TClassName : MenuClass, new()
    {
        new TClassName().menu();
    }

    //if you can not pass class name
    public static string input<TClassName>(TClassName obj) where TClassName : MenuClass, new()
    {
        new TClassName().menu(); //if you want to create new instance
        obj.menu(); //if you want to use already existing object
    }
}

You can use first method if you can pass required class name, and if you cannot - use the second method without generic parameter:
Keyboard.input(yourObj);

Compiler will automatically get type parameter from usage

UPDATE
As you have not abstract classes or interfaces you should cast your object to required class before calling method:
 public static string input(object class_name){
        if (class_name as Foo != null)
        {
            ((Foo)class_name).menu();
        }
 }

or if you do not know the input type of an object and can not use generics, but you should to create new instance of the same class, use reflection:
 public static string input(object class_name){
        if (class_name != null)
        {
            Foo newObj = Activator.CreateInstance(class_name.GetType());
            newObj.menu();
        }
 }


text:
Q: Svm Predict next number in sequence I was asked to compare an svm model to a linear regression model to determine difference in predictions. Input data (x) is 0 to 8, i create a "label" in the next column that represents the class of next value (y), and then i try to see how the svm performs. It actually works fine for inputs from 0 to 7 but then it doesnt work ok. Can i improve this or svm is limited because of the sequential data?
My code:
library(e1071)
Dataset <-data.frame("x"=c(0:8),"y"=c(1:9))
test=data.frame("x"=c(0:15))
mymodel<-svm(y~x, data=Dataset)
pred<- predict(mymodel,test)
table(Predicted = pred,test$x)