text:
Q: Spring Boot Microservice -> Docker Issue : API Gateway cannot connect to configserver (ResourceAccessException) I have a problem about running all services on docker. The only thing which I cannot handle is related with connection problem between api gateway and configserver. Config server is based on git file based system and it fetchs all values from github repo.
When I try to run api gateway, I get this issue shown below.
Caused by: org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://configserver:9296/API-GATEWAY/default": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused (Connection refused)

Here is the related part of docker-compose.yml file
configserver:
    image: 'microservicedailybuffer/configserver:0.0.1'
    container_name: configserver
    ports:
      - '9296:9296'
    environment:
      - EUREKA_SERVER_ADDRESS=http://serviceregistry:8761/eureka
    healthcheck:
      test: [ "CMD", "curl", "-f", "http://configserver:9296/actuator/health" ]
      interval: 10s
      timeout: 5s
      retries: 5
    depends_on:
      - serviceregistry
    networks:
      - backend

  apigateway:
    image: 'microservicedailybuffer/apigateway:0.0.1'
    container_name: apigateway
    ports:
      - '9090:9090'
    environment:
      - EUREKA_SERVER_ADDRESS=http://serviceregistry:8761/eureka
      - CONFIG_SERVER_URL=configserver
      - ZIPKIN_URL=http://zipkin:9411
      - REDIS_URL=redis://redis:6379
    depends_on:
      - configserver
      - zipkin
      - redis
      - serviceregistry
    networks:
      - backend

How can I fix the issue?
Here is the application.yml file of api gateway : Link
Here is the git based file system file : Link
Here is the docker-compose.yml file : Link


text:
Q: Where to troubleshoot wake-up from 'suspend'? CONFIGURATION:

*

*HP Elitebook 8440p: NVIDIA Corporation GT218M [NVS 3100M] (rev a2)

*Ubuntu 16.04

SYMPTOMS of failed wake-up from suspend:

*

*"TV Static"

*black screen: suspend invoked by lid-close

*white screen: suspend invoked by power button

What test can be done to determine the root cause \ corrective action?
Update: Driver status screenshot

A: You should start from https://wiki.ubuntu.com/Kernel/Debugging, and more specifically:

*

*Debugging Kernel Suspend -- Help debugging kernel suspend/resume problems

*Debugging Kernel Hibernate -- Help debugging kernel hibernate/resume problems

Then probably you should submit a bug report. If you get confused or need help on what you did find you may ask here.

*

*One thing may worth to try:

*

*Switch to console tty1 using AltCtrlF1

*Login & run
sudo pm-suspend

If it does suspend, try resume

*

*Press power on

*When you are back to tty1, AltCtrlF7 to go back to Desktop (tty7)

*Second way to try, it works for me in XFCE/Mate 16.04 with nvidia proprietary driver.

*

*After resume, switch to console tty1 using AltCtrlF1

*Login

*Search for any screen-saver or screen-locker
ps aux | grep -i -e saver -e locker

Example: light-locker, xscreensaver ...

*Kill them
sudo kill <PID>

*Check again with step 3
It fine, either they disappear or have different PID's (means they restarted)

*Switch back to tty7, AltCtrlF7 to go back to Desktop

A: use the NVIDIA proprietary drivers listed in the screenshot you provided.
Choose the top choice:
NVIDIA binary driver - version 340.96 from nvidia-340

A: For me, what works, is press Ctrl+Alt+F8, to wake the computer up,
then do Ctrl+Alt+F7, to go back to your desktop.
Same issue on my HP Stream 11 (with Intel Celeron N3060)

A: After several trials, I was able to hibernate my Inspiron 531.
Edit the file:
/var/lib/polkit-1 /localauthority/ ...
or
/etc/polkit-1/localauthority/...
Create a Desktop Entry file as follows:
[Desktop Entry]
Encoding = UTF-8
Version = 1.0
Type = Application
Terminal = true
Icon [en_US] = gnome-panel-launcher
Exec = sudo pm-hibernate
Name = Hibernate

A: Here is not a solution but a workaround you can live till real solution is available.
I tried many solutions including updating NVIDIA driver to recent ones. But nothing worked.
I upgraded to 17.1 but no solution. Now, in 17.1, I see when I lock screen and it goes to suspend then it can wakeup correctly. So, try in older version as well as workaround. Otherwise, it was very painful to reboot system. Now, just lock before you leave your system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dropdown list populated from database I have populated a dropdownlist from a database. Now on select of a particular item I want the data to come from the database and get displayed in a label, but, when I am selecting a particular item, the page gets loaded again and in the dropdownlist --SELECT-- comes again and not the value which I previously selected.
My code is-
aspx page-

https://stackoverflow.com/editing-help
codebehind-
protected void Page_Load(object sender, EventArgs e)
{

    if (Session["UI"]==null)
    {
        Response.Redirect("AdminLogin.aspx");
    }

    else
    {
        if (!IsPostBack)
        {
            AddVehicle vb = new AddVehicle();
            DataSet tt = vb.populatedropdown();
            DropDownList1.DataSource = tt;
            DropDownList1.DataTextField = "DealerID";
            DropDownList1.DataValueField = "DealerID";
            DropDownList1.DataBind();
        }
    }

}


text:
Q: Laravel GuzzleHttp response empty I'm trying to retrieve the value of a URL but it returns a null response. Not sure what I'm doing wrong I've been trying to retrieve the value but I get an empty value. Below is my code
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://fantasy.premierleague.com/api/bootstrap-static/');

dd($response->getBody()->getContents());

When trying to dump the response I get the below response

When trying to read the getBody() of the response I get this output

I'm using guzzle "guzzlehttp/guzzle": "^6.4"

A: OK I found the solution to my problem. It's got nothing to do with

$response->getBody()->getContents()

But the problem was the Endpoint/URL might require a user agent as part of the parameter of the url
my code I was able to retrieve the value using the code below
$url = 'https://fantasy.premierleague.com/api/bootstrap-static/';
$client = new \GuzzleHttp\Client();

$response = $client->request('GET', $url, [
    'verify' => false,
    'headers' => [
        'User-Agent' => 'CUSTOM_AGENT_YOU_WANT' // THIS IS WHAT I ADDED TO MAKE IT WORK
    ]
]);

dd(json_decode($response->getBody()->getContents(), true));


text:
Q: Beat detection circuit with elect mic and arduino I need some kind of sound sensing in my microcontroller project. I have a condenser microphone and some transistors around, so while prototyping I found this circuit:

With my parts on hand and removing the C2 cap because it didn't work, I got this working circuit:

However, the signal amplitude is very low, I get peaks only when clapping. The noise floor is around 225mV and my peaks are at 230mV at best.
So which parts in my circuit do I have to change to get stronger peaks?
Do I add another transistor or change some resistors?
Also is there a better solution for this usecase like a dedicated chip? Ideally I want something like the sparkfun sound detection modules but integrated on my own PCB.

A: Reducing  C6 towards 10nF will remove the bass as well as hum.
R12 must be removed for a lot more sensitivity.
Then increase R9 till you get the desired threshold from 100k to 1M


text:
Q: how to authorize google picker with oauth2 token from app engine I am developing an App Engine Java program that uses OAuth2 at login. In other words, user must give approval before using the app.  I now want to integrate Google Picker functionality without having to authenticate (request permission again) on the client.
What I've done was pass an object(loginInfo is a json object) with the token as a property.
While the token works perfectly fine on the server side, on the client I am getting an UnAuthorized 401 error.
EDIT
I should mention that the scope on the server side includes all the necessary permissions for the Views on the Picker and that my Picker Api is enabled as well as the Drive API.
My question is now, what would be the best way to handle this situation? Is it even safe to post authToken on the client? How can I achieve this scenario so that the user doesn't approve twice and still use Picker? Are there better solutions than Picker for upload to Drive, Picassa, or other Google Services?

A: First of all, let me apologize as I forgot to mention that I was using GWT to program the app.  That being said It seems that the error was coming using the GWT-Ajaxloader library; apparently it must be calling to the api in an antiquated manner.   So the solution for me was to hard code the request into the html
as thus
 <!--  The Following proves that picker works with oAuth2 -->
  <script type="text/javascript">
      // Use the API Loader script to load google.picker and gapi.auth.
      function onApiLoad() {
        gapi.load('picker');
      }
    </script>
    <script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>

Once this was done I was able to use the picker object already loaded and put in the setDeveloperKey() method.   Now everything is gravy.  One more caveat...
Make sure that the AccessKey has not expired on the server.   On the Java Api
this can be done by checking when it will expire Credential.getExpiresInSeconds()  I personally gave myself an hour
if(cred.getExpiresInSeconds() <= 3600){
   cred.refreshToken();}

And this is the fix that has worked for me.


text:
Q: GPU for web browsing, developing? I owned a 10-year old laptop with Core2 Duo chip and Radeon HD 4650 GPU, running Windows 7 Pro. I was able to use Chrome or Firefox with 100+ tabs open and have very few problems or glitches.
Now I run a newer laptop with a Core i5-4310U chip, no GPU, running Windows 10 Pro. I regularly have memory issues, causing Chrome to crash. It generally is preceded by a "blackout" screen, like this: (blackout screen example)
Both have the same 8 GB RAM. I do zero gaming. I do a lot of developing -- 100+ web tabs, VS Code, Slack, Android Studio, database IDE, running node and python in the console.
I am looking to buy a new, more powerful laptop with at least 16gb RAM. The 2 biggest differences between the 2 older machines are Win 7 vs 10 and GPU vs Integrated Graphics. I assume a dedicated GPU is a must. My question is threefold:

*

*is the lack of dedicated GPU likely the cause of the crashes?

*what GPUs do not have "regulators" like nVidia Optimus, which seems to only allow the GPU to work with specific applications -- with web browsers not one of them (according to an email exchange w/ Nvidia support a few years ago)

*or are the crashes most likely due to a much higher level of graphics/ads/video and typical web pages, not really an issue with the GPU capabilities, there's just too much to decode

Some people state "integrated GPU is fine for web browsing, GPU is only for gaming/CAD/video editing" -- I do none of these, but my graphics don't seem to be capable of keeping up. Thank you for your help.

A: This is an XY problem.
Those crashes are not caused by lack of dedicated GPU. By the screenshot it looks more like a driver problem, but that's a separate issue. Insufficient GPU performance causes slowdowns, not blackouts (unless you're running out of video memory, but that's very unlikely in desktop applications).
Edit: If you're low on RAM, it makes running into video memory problems slightly more probable, as iGPU "steals" its VRAM from main RAM. But there's a minimal amount reserved at all times and I'd expect it to be enough. Anyway, 8 GB of RAM is not a lot for a developer nowadays. 16 GB is a minimum. You may want to upgrade later so make sure it's not soldered in and the CPU will support over 16 GB. Getting all 16 GB in one stick will make it easier to upgrade later, but will be slightly slower than 2x8 GB because it won't take advantage from dual-channel.
Integrated GPU in 4th generation Intel i5s is more than sufficient for everyday tasks and even works fine for light gaming. I couldn't find benchmark results, but I wouldn't be surprised if it's comparable to Radeon HD 4650 in terms of performance. Unless you're explicitly targeting GPU as a computational unit, and I suppose you don't, you don't need a dedicated one.

what GPUs do not have "regulators" like nVidia Optimus

That's not exactly a GPU-tied feature. Dedicated mobile GPUs are designed to work in tandem with an iGPU because latter ones are way more power-efficient and reasonably competent in common workloads. The dGPU in most configurations is not a complete graphics card, it lacks video outputs and only passes rendered frames to iGPU. A few generations ago some high-end business-oriented laptops had a full-featured NVIDIA GPU that could completely take over Intel's, but I'm not sure if such configurations are still available, as it increases complexity and cost, but doesn't provide any real value.

[…] which seems to only allow the GPU to work with specific applications -- with web browsers not one of them (according to an email exchange w/ Nvidia support a few years ago)

You can choose which programs run with NVIDIA GPU in the NVIDIA Control Panel accessible from desktop's right-click menu. There's also an option there to use it for all applications by default. Enabling dGPU for Chrome may solve your problems, but it's a workaround that will increase energy consumption and heat dissipation (= more noisy fans).

If you haven't yet, update your iGPU drivers to the latest version.


text:
Q: how to solve CFData (store) memory increase? I have the following code to read PDF page.
The problem is at each time I read the a page the instruments analyzing give me about 1MB increase of CFData (store)? any help is appreciated.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context;

context = CGBitmapContextCreate(NULL,
                                    width,
                                    height,
                                    8,
                                    width* 4,
                                    colorSpace,
                                    kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextClipToRect(context, CGRectMake(0, 0, pageSize.width*2, pageSize.height*2));

CGContextSaveGState(context);
CGPDFPageRef page = CGPDFDocumentGetPage(pdf, index + 1);
CGRect rect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
CGRect rectClip = CGContextGetClipBoundingBox(context);
CGAffineTransform transform = aspectFit(rect,rectClip);
CGContextConcatCTM(context, transform);
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextSetRenderingIntent(context, kCGRenderingIntentDefault);
CGContextDrawPDFPage(context, page);
CGContextRestoreGState(context);

CGImageRef image = CGBitmapContextCreateImage(context);
CGContextRelease(context);

UIImage *img = [UIImage imageWithCGImage:image];
CGImageRelease(image);

A: I was having the same issue and found your question while searching for an answer.
In my case I was converting the pdf pages into jpegs and then saving them to disk. My trouble seems to have been in the ownership and release of the CGPDFDocumentRef and the CFURLRef.
Using a _bridge cast on NSURL *pdfURL fixed the issue for me.

I thought this answer did a good job of explaining bridged casts: ARC and bridged cast
The Analyze tool in XCode is very helpful in these types of situations.
- (void) drawRect:(CGRect)rect {
    NSURL *pdfURL = [NSURL fileURLWithPath:self.filePath];

    CGPDFDocumentRef document = CGPDFDocumentCreateWithURL((__bridge CFURLRef)pdfURL);

    for (int i = 1; i <= (int)CGPDFDocumentGetNumberOfPages(document); ++i){
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetRGBFillColor(context, 1.0,1.0,1.0,1.0);
        CGContextClearRect(context, self.bounds);
        CGContextFillRect(context, self.bounds);

        CGPDFPageRef pageRef = CGPDFDocumentGetPage(document, i);

        CGRect pageRect = CGPDFPageGetBoxRect(pageRef, kCGPDFMediaBox);

        CGFloat scale = MIN(self.bounds.size.width / pageRect.size.width, self.bounds.size.height / pageRect.size.height);

        CGContextSaveGState(context);
        CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextScaleCTM(context, scale, scale);

        CGContextSetInterpolationQuality(context, kCGInterpolationLow);
        CGContextSetRenderingIntent(context, kCGRenderingIntentDefault);
        CGContextDrawPDFPage(context, pageRef);

        CGContextRestoreGState(context);

        CGImageRef image = CGBitmapContextCreateImage(context);

        NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@_%i.jpg", self.sourceId, i]];
        [UIImageJPEGRepresentation([UIImage imageWithCGImage:image], 1) writeToFile:jpgPath atomically:YES];

        CGImageRelease(image);
    }

    CGPDFDocumentRelease(document);
}

Hope this helps someone!

Kevin

A: After long tracing I found the problem was I did not close the pdf document after I finished using it
CGPDFDocumentRelease(pdfDoc);

if not you keep all allocated pages inside the problem


text:
Q: Circe custom decoder missing map from Result I am trying to build a custom decoder. Tried running example from documentation
import io.circe.{ Decoder, HCursor }

class Thing(val foo: String, val bar: Int)

implicit val decodeFoo: Decoder[Thing] = new Decoder[Thing] {
  final def apply(c: HCursor): Decoder.Result[Thing] =
    for {
      foo <- c.downField("foo").as[String]
      bar <- c.downField("bar").as[Int]
    } yield {
      new Thing(foo, bar)
    }
}

And I get errors of missing map and flatMap from io.circe.Decoder.Result[String]


text:
Q: Determinant of a $5\times 5$ matrix using properties Apparently the determinant of the following matrix can be transformed into the determinant of a $2\times 2$ matrix multiplied by a scalar. Would anyone show me how?
$$ \left( \begin{array}{ccccc} 0 & 0 & 1 & 0 & 0 \\
2 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 3 & 0 \\
0 & 0 & 0 & 0 & 4 \\
0 & 5 & 0 & 0 & 0\end{array} \right)$$

A: I agree with the rest that permutations of rows and columns is sufficient.
Another way is by doing Laplace expansion.
\begin{align}  \begin{vmatrix} 0 & 0 & 1 & 0 & 0 \\
2 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 3 & 0 \\
0 & 0 & 0 & 0 & 4 \\
0 & 5 & 0 & 0 & 0\end{vmatrix} &= \begin{vmatrix}
2 & 0  & 0 & 0 \\
0 & 0  & 3 & 0 \\
0 & 0  & 0 & 4 \\
0 & 5  & 0 & 0\end{vmatrix} \\ &=  2\begin{vmatrix}
 0  & 3 & 0 \\
 0  & 0 & 4 \\
 5  & 0 & 0\end{vmatrix} \\ &=
2(5)\begin{vmatrix}
    3 & 0 \\
    0 & 4 \\
   \end{vmatrix} \end{align}


text:
Q: Pointers inside function in C #include<stdio.h>

int q = 10;

void fun(int *p){
    *p = 15;
    p = &q;
    printf("%d ",*p);
}

int main(){
  int r = 20;
  int *p = &r;
  fun(p);
  printf("%d", *p);
  return 0;
}

I was playing with pointers. Could not understand the output of this.
Output is coming as 10 15.
Once p is pointing to address of q, why on returning to main function it's value changes? Also why it changed to the value '15' which was assigned to it in the function before '10'.

A: Because p is fun() is not the same p in main(). p , in each function, is local. So changing one doesn't affect other.

A: In C, all function parameters are passed by value, including pointers.
*p = 15; will set r to 15 as *p is pointing to the memory occupied by r in main() prior to its reassignment to &q;
Your reassignment p = &q; does not change what p points to in the caller main(). To do that, you'd need to doubly indirect the pointer, i.e. change the function prototype to void fun(int **p){, call it using fun(&p);, and reassign using *p = &q;.

A: Two steps:

*

*First call to fun(), assigning the address of global int q [holding value 10] to p inside the fucntion scope and printing it. The first output ==> 10;

*Once the call returns from fun(), it will hold the previous address, [passed from main()] and hence, will print the value held by that address [which is 15, modified inside fun()].


text:
Q: Visual studio Forms not working in production I have a basic form built in .net 6. It was a very rough and ready bit of code to do a one or check on some data.
It populates a datatable from SQL thid data includes file paths. (32k rows)
It then loops through all the the rows of the data table using a foreach loop.
The loops check to see if the directory from the row exists. If it does, it then counts the files in the folder. (approx. 120 files per folder)
It then does some checks up dates a valid or invalid counter. If invalid it then adds a row to another datatable that is export to an excel document once the foreach loop is complete
This all works perfectly in visual studio using F5.
If I run it via other method. Ctrl + f5, from the bin folder or publish. It works to check about 900+ folders (50,000) files and the just hangs.
What is going on??
I know its something to to with the files as if I strip the Foreach down to just looping through the data table it all works, but as soon as I add the directory.exists it hangs several seconds in.
public void CheckFolder()
        {
            int matched = 0;
            int notmatched = 0;
            lb_mismatchCount.Text = notmatched.ToString();

            lb_MatchedCount.Text = matched.ToString();

            lb_mismatchCount.Visible = true;
            lb_MatchedCount.Visible = true;
            lbTotalPhotos.Text = null;
            lbTotalPhotos.Visible = true;
            try
            {

                foreach (DataRow row in dt.Rows)
                {

                    if (Directory.Exists($@"My directory path here{row[3].ToString()}"))
                    {

                        int fileCount =  GetFileCount($@"My directory path here{row[3].ToString()}", false);

                        totalfiles = totalfiles + fileCount;
                        lbTotalPhotos.Text = totalfiles.ToString("N0");

                        lbTotalPhotos.Refresh();

                        if (fileCount / 2 == Convert.ToInt32(row[4].ToString()))
                        {

                            matched++;
                            lb_MatchedCount.Text = matched.ToString("N0");
                            lb_MatchedCount.Refresh();
                        }
                        else
                        {

                            DataRow newRow = output.NewRow();
                            newRow[0] = row[0].ToString();
                            newRow[1] = row[2].ToString();
                            output.Rows.Add(newRow);

                            notmatched++;
                            lb_mismatchCount.Text = notmatched.ToString("N0");
                            lb_mismatchCount.Refresh();
                        }

                    }
                    else
                    {
                        notmatched++;
                        lb_mismatchCount.Text = notmatched.ToString("N0");
                        lb_mismatchCount.Refresh();
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }

        }

If I change the foreachloop to the below it still hangs.
                foreach (DataRow row in dt.Rows)
                {

                    if (Directory.Exists($@"My directory path here{row[3].ToString()}"))
                    {}
                }


text:
Q: tslint error: Cannot find module 'redux/todo/actions'.ts(2307) I have read many posts and articles about getting absolute imports working in a TypeScript project but I am not having a problem with that. My project is successfully working with absolute imports.
However, in VS Code, all absolute imports have the red squiggly underline with the message such as
Cannot find module 'redux/todo/actions'.ts(2307)

My assumption is that this is a tslint issue, but I have not been able to find resolution.
tsconfig.json
{
  "compilerOptions": {
    "baseUrl": "./src", // must be set to /src for abs imports
    "outDir": "build/dist",
    "module": "esnext",
    "target": "es5",
    "lib": ["es6", "dom"],
    "sourceMap": true,
    "allowJs": true,
    "jsx": "react",
    "moduleResolution": "node",
    // "rootDir": "src",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "importHelpers": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true
  },
  "exclude": [
    "node_modules",
    "build",
    "scripts",
    "acceptance-tests",
    "webpack",
    "jest",
    "src/setupTests.ts"
  ]
}

I have tried various configurations for "paths"
"paths": {
  "*": [
    "*",
   "redux/*"
    ]

},

and
"paths": {
  "redux*": ["/redux/*]
}

I also tried
"rootDir": "src"

Also went through the telint documentation but found nothing relevant.

A: This is not a TSLint issue. This is a TypeScript issue. TSLint adds static analysis ("linting") on top of the TypeScript language & services. Your error is from TypeScript saying it can't find a file/module.
It's hard to help more concretely without code samples, but since you mentioned the error went array, hooray!
For future reference, restarting the VS Code window (Ctrl/Cmd + Shift + P > Reload Window) generally gets rid of these complaints.


text:
Q: Possible to prove strong induction implies weak induction? I have managed to formally prove (using my own system, not ZFC) that weak induction implies strong induction. I started with Peano's 5 Axioms for the natural numbers, constructed (in order) the addition function, partial ordering and strict ordering as sets of ordered n-tuples of $N$. Then I proved that strong induction will hold:
$\forall P\subset N: [0\in P ~\land~  \forall x \in N:[\forall y \in N:$
$[y \leq x \to y\in P]~ \to x+1 ~\in P] ~\to ~P=N]$
What about proving the converse? How can I show that the strong induction implies weak induction when I needed weak induction to construct addition and the orderings?

A: [rewritten in response to the OP's comment]
You don't need addition to state strong induction, if you have succession; but you do need order.
Two notions (untested):

*

*Define order independently of addition, as $a \leq b$ if and only if $b$ is contained in the closure of $\{a\}$ under succession.

*Replace the Peano axioms with the requirements that the set of natural numbers is non-empty and well ordered and satisfies an induction axiom, either strong or weak induction. Then prove the equivalence of the Peano axioms, the weak-induction version of the new axioms, and the strong-induction version.
[Original answer follows.]
How can I show that the strong induction implies weak induction?
You don't.  Axiom 5 of the Peano axioms (in the version you reference) just is weak induction.


text:
Q: How to load 'n' (latest) items in Recycler view every time scrolling down .So it doesn't download whole database to load all on/ offscreen items Hey there I only want to load the first 2 items from the Firebase Realtime database to my recycler view but the problem is it returns only 2 images and I want to load the first 2 images out of 'n' no. of image (for ex. return the first 2 images out of 'n' then scrolling down return 2 new images (like that in Instagram) and not download all images offscreen and show it on scrolling). Here is the code but I get only 2 fixed items. Help!
    public int getItemCount() {
            int size = mClicks.size();

          return (size > 2 ? 2 : size);
    }

A:
How to load the first n items in RecyclerView every time scrolling down?

What you're looking for is called pagination. This means that you need to load the data progressively in smaller chunks. This was already covered a lot of times before, and this question already has a lot of solutions for the Realtime Database:

*

*https://stackoverflow.com/search?q=Firebase+Realtime+Database+Pagination+Android
However, if you consider at some point in time trying using Cloud Firestore, I think that this answer will help:

*

*How to paginate Firestore with Android?
If you want to go further and try using Jetpack Compose, then I think that this resource will help:

How to implement pagination in Firestore using Jetpack Compose?

A: You should use Integer.MAX_VALUE. Something like this.
 public int getItemCount() {
      return Integer.MAX_VALUE;
}

or simply use
public int getItemCount() {
      return itemList.size();
}


text:
Q: Is an ISymbol from different compilations considered equal in an IIncrementalGenerator One of the stated benefits benefits of using the IIncrementalGenerator over ISourceGenerator is that different stages of the pipeline can recognize that the results of the current iteration is the same as a previous iteration and use cached results.
In order for this to work, presumably the type parameter of any IncrementalValueProvider or IncrementalValuesProvider would need to be value equatable, (as opposed to the default reference equatable) which is presumably why you see a lot of source generators implemented using record
This leads to the question, if the IncrementalValueProvider equality function includes an ISymbol representing the same semantic object, will they be considered equal for the purposes of the caching comparison during different iterations of the pipeline?
Would it be better to just forgo referencing an ISymbol and just extract the data I need out of it (name, namespace, members, etc.)?
I have dug into the Equals functions of the Symbol implementations, and it is unclear, the base class Symbol.Equals() does use reference comparison, but this appears to be overridden in most (possibly all) of the derived classes. and a spot check of these overrides appear that they are attempting to have a value equality, but again, there are a lot to check, and even if it does end up using the reference equality check, it is also possible that the symbol references are cached between runs and even a reference equals check will be true.
Would it be better to just forgo referencing an ISymbol and just extract the data I need out of it (name, namespace, members, etc.)?

A: Don't include symbols in the pipeline. Not only that they will compare unequal, but they also root compilations in memory and can lead to high memory usage.
The following small snippet shows how symbols compare unequal, even if they are resulting from the exact same syntax tree:
var trees = new[] { SyntaxFactory.ParseSyntaxTree("public class C  { }") };

var comp1 = CSharpCompilation.Create(null, trees);
var s1 = comp1.GetTypeByMetadataName("C");

var comp2 = CSharpCompilation.Create(null, trees);
var s2 = comp2.GetTypeByMetadataName("C");

Console.WriteLine(s1.Equals(s2, SymbolEqualityComparer.Default));

But even if you provide your own equality comparer, rooting compilations is still an issue.


text:
Q: "local variable 's' referenced before assignment" error. How do I fix? I am trying to make a list that takes in numbers and removes all the old numbers in the list and returns s the result, but it keeps on giving me the error "local variable 's' referenced before assignment" How do I fix it?
def purify(lst):
    for item in lst:
        if item%2 != 0:
            lst.remove(item)
    s.append(lst)
    s = []
    return s

A: You need to assign s to empty list first and then append.
   def purify(lst):
        for item in lst:
            if item%2 != 0:
                lst.remove(item)
        s = []
        s.append(lst)

        return s

As @jonrsharpe  suggested, don't remove the item while iterating over list. The good approach is using the list comprehension:
[i for i in lst if i%2!=0]

A: It isn't clear why you want to return a list containing a single list. Why not just return the "purified" list?
def purify(lst):
    return [item for item in lst if item % 2 == 0]

This uses a list comprehension. Demo:
>>> purify([1, 2, 3, 4, 5])
[2, 4]

For more flexibility, you could also make a version where you pass your own rule:
def purify(lst, rule):
    return [item for item in lst if rule(item)]

Demo:
>>> purify([1, 2, 3, 4, 5], lambda i: i % 2)
[1, 3, 5]

A: You should not remove items while iterating, because the list should not be changed when using iterators (this is what you do with "in").
def purify(lst):
    s = []
    for item in lst:
        if item%2 == 0:
            s += [item]
    return s

btw: This can be done very fast with numpy.
import numpy as np
...
def purify(lst):
     indices = np.where(np.mod(lst,2) == 0)
     return np.array(lst)[indices]

A: Simplify your life with filter:
filter(lambda x: x % 2 == 0, range(5))


text:
Q: SonarScanner on Virtual environment sonar-scanner for python choose only global python environment. My global python is set to python 3.5 and I have a pip virtualenv on python 2.7 with required libraries.
Even if I execute sonar-scanner code in the virtual environment, It choose the global python 3.5. I found it because there were issues to use print statement with ()
Is there anyway I can use my virtual env path as a option to sonar scanner


text:
Q: In JavaScript Class, super cannot access attributes, but can modify attributes? The super attribute cannot be accessed, but can be modified?
What does super stand for? Some people say it is prototype? I know that the function of Class is in the prototype of the object, but why can super.name ='Lucy'; modify the properties of the object instance?

class a {
  name = 'jack';
  speak() {
    console.log(this.name);
  }
}

class b extends a {
  count() {
    super.name = 'Lucy';
    console.log(super.name) // undefined
    super.speak();
  }
}

new b().count(); // Lucy

A: Assigning to super.prop is useful when prop is defined on the parent's prototype, not when it is defined as an instance property, as is the case with name in your code. Realise that the assignment name = 'jack' happens on the instance that is created by new b, not on some other object.
So when you do super.name = 'Lucy', you are doing nothing else than this.name = 'Lucy'. This change is not visible when you consult super.name after that assignment, because that will scan the parent's prototype chain, not the instance object. And there is no name defined anywhere on that prototype chain...
The difference between how super.name acts when used for lookup and for assignment is specific: for (non-setter) assignment, it is no different than assigning on this, while for lookup (including setter lookup), it skips this and starts the lookup in the parent's prototype chain.
The power of the super.prop syntax only reveals itself when you have to deal with methods that have been created on the prototype.
To demonstrate this, let's define name as a getter/setter function on the prototype:

class A {
  _name = 'jack';
  speak() {
    console.log(this.name);
  }
  get name() {
      return this._name;
  }
  set name(name) {
      return this._name = name + " (A)";
  }
}

class B extends A {
  count() {
    super.name = 'Lucy'; // This will not call the setter of B.prototype, but of A.prototype
    super.speak();
  }
  get name() {
      return this._name;
  }
  set name(name) {
      return this._name + " (B)";
  }
}

new B().count(); // Lucy (A)

Note that here super.name is first identified to be a function in the upper prototype chain, and thus the assignment becomes a function call. If it would have been a property-modifying assignment, it would have happened on this.
See for an elaborate analysis of the specification in this respect in this answer to "ES6 inheritance: uses super to access the properties of the parent class"


text:
Q: Turning multidimensional array into one-dimensional array I've been banging my head on this one for a while now.
I have this multidimensional array:
Array
(
    [0] => Array
        (
            [0] => foo
            [1] => bar
            [2] => hello
        )

    [1] => Array
        (
            [0] => world
            [1] => love
        )

    [2] => Array
        (
            [0] => stack
            [1] => overflow
            [2] => yep
            [3] => man
        )

And I need to get this:
Array
(
    [0] => foo
    [1] => bar
    [2] => hello
    [3] => world
    [4] => love
    [5] => stack
    [6] => overflow
    [7] => yep
    [8] => man
)

Any ideas?
All other solutions I found solve multidimensional arrays with different keys. My arrays use simple numeric keys only.

A: array_reduce($array, 'array_merge', array())

Example:
$a = array(array(1, 2, 3), array(4, 5, 6));
$result = array_reduce($a, 'array_merge', array());

Result:
array[1, 2, 3, 4, 5, 6];

A: The PHP array_mergeDocs function can flatten your array:
$flat = call_user_func_array('array_merge', $array);

In case the original array has a higher depth than 2 levels, the SPL in PHP has a RecursiveArrayIterator you can use to flatten it:
$flat = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)), 0);

See as well: How to Flatten a Multidimensional Array?.

A: foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}

where $a is your array name.
for details

A: As of PHP 5.3 the shortest solution seems to be array_walk_recursive() with the new closures syntax:
function flatten(array $array) {
    $return = array();
    array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
    return $return;
}

A: As of PHP 5.6 this can be done more simply with argument unpacking.
$flat = array_merge(...$array);

A: This is really all there is to it:
foreach($array as $subArray){
    foreach($subArray as $val){
        $newArray[] = $val;
    }
}

A: In PHP5.6 there other way to solve this problem, combining the functions, array_shift() to remove the first elemente of the original array, array_pus() to add items an new array, the important thing is the of ... splapt/elipse operator it will unpack the return of array_shitf() like an argument.
<?php

$arr = [
        ['foo', 'bar', 'hello'],
        ['world', 'love'],
        ['stack', 'overflow', 'yep', 'man', 'wow']
    ];

$new = [];
while($item = array_shift($arr)){
    array_push($new, ...$item);
}

print_r($new);

Output:
Array
(
    [0] => foo
    [1] => bar
    [2] => hello
    [3] => world
    [4] => love
    [5] => stack
    [6] => overflow
    [7] => yep
    [8] => man
    [9] => wow
)

Example - ideone

A: I had used this code to resolve same type of problem. so you can also try this.
function array_flatten($array) {

 if (!is_array($array))
{
  return FALSE;
}
  $result = array();
foreach ($array as $key => $value)
{
  if (is_array($value))
  {
   $result = array_merge($result, array_flatten($value));
  }
  else  {
  $result[$key] = $value;
  }
}
return $result;
}

A: This will make
array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });

A: $blocked_dates = array(
                    '2014' => Array
                        (
                            '8' => Array
                                (
                                    '3' => '1',
                                    '4' => '1',
                                    '6' => '1',
                                    '10' => '1',
                                    '15' => '1',
                                    '25' => '1'

                                )

                        ),
                    '2015' => Array
                        (
                            '9' => Array
                                (
                                    '3' => '1',
                                    '4' => '1',
                                    '6' => '1',
                                    '10' => '1',
                                    '15' => '1',
                                    '25' => '1'

                                )

                        )

                );

RESUTL(ONE DIMENTIONAL ARRAY) :
$unavailable_dates = array();
foreach ($blocked_dates as $year=>$months) {

    foreach ($months as $month => $days) {

        foreach ($days as $day => $value) {

            array_push($unavailable_dates,"$year-$month-$day");
        }

    }
}

$unavailable_dates = json_encode($unavailable_dates);
print_r($unavailable_dates);

OUTPUT : ["2014-8-3","2014-8-4","2014-8-6","2014-8-10","2014-8-15","2014-8-25","2015-9-3","2015-9-4","2015-9-6","2015-9-10","2015-9-15","2015-9-25"]

A: The quickest solution would be to use this array library:
$flattened = Arr::flatten($yourArray);

which will produce exactly the array you want


text:
Q: 'this' doesn't refer to the context from where it is called (for Arrow functions) Context of  this  doesn't work as expected. I have described my issue in as comments in the code below.
const dog = {

    //arrow function
    bark: () => {
        console.log(this);
    },

    makeBark(){
        // this here refers to the dog object
        // (as it is a normal function)
        // so inside the bark function , shouldn't
        // this refer to the dog object ?
        this.bark();
    },

};

dog.makeBark(); // this is the problematic function

I dont understand WHY dog.makeBark() prints window object . The parent scope of bark function is the dog object

A: The this of arrow function will be the this of its parent scope where its declared not where its called.
In the above example you are just calling bark from another function. This code doesn't change this of bark. Also this for an arrow function will remain same throughout the code and can never be changed implicitly or explicitly.


text:
Q: I am using command npm install in react but I am getting the errors npm WARN read-shrinkwrap This version of npm is compatible with lockfileVersion@1, but package-lock.json was generated for lockfileVersion@2. I'll try to do my best with it!
npm ERR! code EBADPLATFORM
npm ERR! notsup Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm ERR! notsup Valid OS:    darwin
npm ERR! notsup Valid Arch:  any
npm ERR! notsup Actual OS:   win32
npm ERR! notsup Actual Arch: x64

How can I solve this issue?


text:
Q: If I compile java with javac do I need JVM? I recently learned about how Java uses the JVM to make itself platform independent and I often write code and compile it with the javac command in terminal (Mac OS X). So my question is whether javac compiles it for JVM or if it is compiled directly to machine code? which would make it platform dependent.

A: The java compiler (javac) produces bytecode from source code. This bytecode is the instruction set of the JVM. It is run on the JVM so whilst the bytecode is platform independent, the JVM is not.


text:
Q: xpath: skip child node with an given id I have to configure our enterprise search engine and the indexing of documents is done via xpath selectors.
In the current setup there is an xpath
.//div[@id='content']

Which selects basically all elements of the main part of a website. Meanwhile there is an additional div with a lot of nonsense included, so I tried to modify this xpath to skip this div-tag. I am struggling with the documentation regarding "not" but withou any luck so far.

   ...

   foo

   ...

While I see that the hints in the comments helped me so far, I still have an issue with child elements in the div-tag I want to skip. Let's say, there is a span-tag inside. If I select
//div[@id='content']/*[not(@id='i-do-not-want-this')]
my result still includes this span-content. So I guess, I need a query for all elements below id="content" which do not have a parent id="i-do-not-want-this". Right?

A: Use the following query. It will select all child elements which id is not i-do-not-want-this.
//div[@id='content']/*[@id != 'i-do-not-want-this']

or - the same logic - using the ǹot() function (thanks @paul_t)
//div[@id='content']/*[not(@id='i-do-not-want-this')]

Update
When I said the same logic then this isn't really correct. Pleases visit the comment from @IanRoberts


text:
Q: Socket exception while running client windows application form I have main window application form written in C# which has two option:

*

*build server

*build client

Both are build new window form after enter ipaddress and port with different behaviour. Client application run without problem with another server (server run independly). When I run server from this main form Client return:

System.Net.Sockets.SocketException (0x80004005)

My server is multithread and this is method which run server:
  public int Server()
  {
      this.tcpListener = new TcpListener(IPAddress.Any, port);
      this.listenThread = new Thread(new ThreadStart(ListenForClients));
      this.listenThread.Start();
      this.listenThread.Join();
      return 0;
  }

It's run without exception in windows console application. When I try this code with windows form application it does not work and return exception as I write above.


text:
Q: How do I expand a node (parent node) in an ASP.NET Dynamic TreeView Control upon click of the text of the node? I have a treeview control, the nodes and their children of which I populate on the server side from a DataTable.
How do I expand any node of the control upon click of it's rendered text?
Altering the TreeNodeSelectAction property of the node doesn't help.
I know that this property works for Tree View Controls that are not populated dynamically.
Any help is appreciated.

A: Sorry forgot getting back to this. I messed around using the built in "TreeView_ToggleNode" javascript function, that gets rendered along with the TreeView Control. Got exactly what I needed.


text:
Q: Display list of categories that contain products with a specific tag I've tagged some products with 'tag1', 'tag2' or sometimes both.
I want to list the categories that contain products with a specific tag, so 'Cat1' will only be listed if it has a product that is tagged 'tag1'.

A: There's probably a few ways to do this. The key will be cutting down on the number of loops you need to make it more efficient.
I think this will work:
$query = new WP_Query( array(
    'post_type' => 'product',
    'posts_per_page' => '-1', // unlimited posts
    'tax_query' => array(
       array(
         'taxonomy' => 'product_tag',
         'field' => 'slug',
         'terms' => array( 'tag1' ),
       ),
    ),
) );

$categories = array();

while( $query->have_posts() ){
   $query->the_post();
   $post_categories = get_the_terms( $post, 'product_cat' );
    foreach( $post_categories as $_cat ){
       if( ! isset( $categories[$_cat->term_id] ) ){
         $categories[$_cat->term_id] = $_cat;
       }
    }
}

wp_reset_postdata();

foreach ($categories as $category){
  echo $category->name . '<br />';
}

This is completely untested and rather quickly put together, but I think it should do what you want. You'll need to replace product_cat and product_tag with the correct taxonomy names if those aren't right (I don't use WooCommerce regularly).
Basically, using a tax_query, we're first finding all the posts that have the required tag. We then loop through those posts and construct a list of categories, finally looping through those categories to print them out.
This results in a list of categories that contain products with that specific tag.

A: OK, so most efficient way to obtain such list will be a custom SQL query. You have to do 6 JOINS in it, but this way the database will do all the work and you won't need to get all posts, nor terms.
The query should look something like this:
SELECT categories.* FROM
    wp_terms categories
    INNER JOIN wp_term_taxonomy ctax ON (categories.term_id = ctax.term_id)
    INNER JOIN wp_term_relationships crel ON (crel.term_taxonomy_id = ctax.term_taxonomy_id)
    INNER JOIN wp_posts posts ON (posts.ID = crel.object_id)
    INNER JOIN wp_term_relationships trel ON (posts.ID = trel.object_id)
    INNER JOIN wp_term_taxonomy ttax ON (trel.term_taxonomy_id = ttax.term_taxonomy_id)
    INNER JOIN wp_terms tags ON (ttax.term_id = tags.term_id)
WHERE
    ctax.taxonomy='product_cat'
    AND posts.post_type = 'product'
    AND posts.post_status = 'publish'
    AND ttax.taxonomy = 'product_tag'
    AND tags.term_id = <TAG_TERM_ID>
GROUP BY categories.term_id

Of course you should use $wpdb to execute it, put $wpdb->prefix in it and use proper escaping of params. So you'll end up with something like this:
function get_categories_with_product_in_tag( $tag_term_id ) {
    global $wpdb;

    return $wpdb->get_results( $wpdb->prepare(
        "SELECT categories.* FROM ".
        "{$wpdb->prefix}terms categories ".
        "INNER JOIN {$wpdb->prefix}term_taxonomy ctax ON (categories.term_id = ctax.term_id) ".
        "INNER JOIN {$wpdb->prefix}term_relationships crel ON (crel.term_taxonomy_id = ctax.term_taxonomy_id) ".
        "INNER JOIN {$wpdb->prefix}posts posts ON (posts.ID = crel.object_id) ".
        "INNER JOIN {$wpdb->prefix}term_relationships trel ON (posts.ID = trel.object_id) ".
        "INNER JOIN {$wpdb->prefix}term_taxonomy ttax ON (trel.term_taxonomy_id = ttax.term_taxonomy_id) ".
        "INNER JOIN {$wpdb->prefix}terms tags ON (ttax.term_id = tags.term_id) ".
        "WHERE ".
        "ctax.taxonomy='product_cat' ".
        "AND posts.post_type = 'product' ".
        "AND posts.post_status = 'publish' ".
        "AND ttax.taxonomy = 'product_tag' ".
        "AND tags.term_id = %d ".
        "GROUP BY categories.term_id",
        $tag_term_id
    ) );
}

Not tested, but something like this should work OK.
P.S. It is also possible to make query for multiple tag ids:
Replace:
tags.term_id = <TAG_TERM_ID>
With:
tags.term_id IN (TAG_TERM_ID_1,2,3)


text:
Q: Why i am getting too many response from the API call I am not able to stop the api call. what should be the right approach to handle this situation.
const successCallback = (position) => {
    console.log("in success");
    setCoord({ ...coord, latitude: position.coords.latitude.toFixed(4), longitude: position.coords.longitude.toFixed(4) })
  }
  const failCallback = () => {
    alert("Give Location Permission for currect Location.")
  }
  if (window.navigator.geolocation) {
    window.navigator.geolocation.getCurrentPosition(successCallback, failCallback)
  } else {
    alert("Geolocation is not supported by this browser.")
  }
  const url3 = `http://api.openweathermap.org/data/2.5/weather?lat=${coord.latitude}&lon=${coord.longitude}&appid=MYKEY`
  const fetchWeather = async () => {
    const responce = await Axios.get(url3)
    console.log(responce);
  }
  useEffect(() => {
    fetchWeather()
  }, [coord])

A: Add options to throttle how often successCallback is callded
const options = {
  enableHighAccuracy: true,
  timeout: 10000,
  maximumAge: 20000
};
window.navigator.geolocation.getCurrentPosition(successCallback, failCallback, options)

or if you want it to be called only once, use
const options = {
  timeout: 0
};


text:
Q: Prevent animation from scrolling to top when Fragment is popped I have a fragment with a RecyclerView, and if the RecyclerView has more than a certain number of items, I increase the height of the root layout so that I can scroll down (I know RecyclerView can scroll on its own, I wanted to scroll the whole layout). Now, if I press back after I scroll to the bottom, the pop back animation I set occurs, as usual:
<!-- slide_out_right.xml -->
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" android:shareInterpolator="false" >
    <translate android:duration="250" android:fromXDelta="0%" android:toXDelta="100%"/>
    <alpha android:duration="250" android:fromAlpha="1.0" android:toAlpha="0.0"/>
</set>

However, this animation causes the fragment to scroll to top before disappearing. At first I thought this was due to the ScrollView I wrap around the FrameLayout I am using for placing fragments; however, this issue was gone when I disabled the fragment animations. I have played around with the XML file for the custom animation, but could not prevent it from scrolling to top. Is there a way to do this so that the "fragment view state" does not change before the animation?
Note: I have tried the android:fillAfter and android:fillBefore attributes, but they did not help.
EDIT:
Where I set the custom transitions:
// ITEM FRAGMENT
public void launchItemFragment(String itemId, String itemName, ActivityDetail activityDetail) {
  if (mItemFrag == null) {
     mItemFrag = new ItemFragment(); //ItemFragment.newInstance(itemId, itemName, activityDetail);
  }
  Bundle bundle = new Bundle();
  bundle.putString("itemId", itemId);
  bundle.putString("itemName", itemName);
  bundle.putParcelable("activityDetail", activityDetail);
  mItemFrag.setArguments(bundle);
  FragmentTransaction ft = fm.beginTransaction();
  ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right_scroll);
  ft.replace(R.id.main_container, mItemFrag, "fragment_item").addToBackStack(null).commit();

Handling back presses: I popBackStack() if getBackStackEntryCount() > 0.
MainActivity relevant layout section (root layout is ConstraintLayout):
<ScrollView
  android:layout_width="0dp"
  android:layout_height="0dp"
  android:fillViewport="true"
  android:overScrollMode="never"
  app:layout_constraintBottom_toBottomOf="parent"
  app:layout_constraintLeft_toLeftOf="@+id/guideline_cart_right"
  app:layout_constraintRight_toLeftOf="@+id/guideline_main_right"
  app:layout_constraintTop_toTopOf="@+id/guideline_top_nav_bottom"
  tools:layout_constraintBottom_creator="1"
  tools:layout_constraintLeft_creator="1"
  tools:layout_constraintRight_creator="1"
  tools:layout_constraintTop_creator="1">
  <FrameLayout
     android:id="@+id/main_container"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:theme="@style/MainFragStyle"/>
</ScrollView>

Layout xml of the fragment in question:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                         xmlns:app="http://schemas.android.com/apk/res-auto"
                                         xmlns:tools="http://schemas.android.com/tools"
                                         android:id="@+id/root_fragment_item"
                                         android:layout_width="match_parent"
                                         android:layout_height="match_parent">

<View
  android:layout_width="0dp"
  android:layout_height="0dp"
  android:id="@+id/header_section_background"
  android:background="@color/colorItemHeaderBackground"
  app:layout_constraintBottom_toTopOf="@+id/guideline_header_bottom"
  app:layout_constraintLeft_toLeftOf="parent"
  app:layout_constraintRight_toRightOf="parent"
  app:layout_constraintTop_toTopOf="parent"/>

<View
  android:id="@+id/header_section_triangle"
  android:layout_width="40dp"
  android:layout_height="22dp"
  android:layout_marginLeft="8dp"
  android:layout_marginRight="8dp"
  android:background="@drawable/triangle"
  app:layout_constraintBottom_toBottomOf="@+id/guideline_header_bottom"
  app:layout_constraintHorizontal_bias="0.15"
  app:layout_constraintLeft_toLeftOf="parent"
  app:layout_constraintRight_toRightOf="parent"/>

<TextView
  android:id="@+id/header_item_title"
  style="@style/ItemHeaderTitle"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_marginLeft="32dp"
  android:text="Title"
  app:layout_constraintBottom_toTopOf="@+id/guideline_header_bottom"
  app:layout_constraintLeft_toLeftOf="parent"
  app:layout_constraintTop_toTopOf="parent"
  app:layout_constraintVertical_bias="0.2"/>

<TextView
  android:id="@+id/header_item_duration"
  style="@style/ItemHeaderSubtitle"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_marginLeft="32dp"
  android:text="Duration"
  app:layout_constraintBottom_toTopOf="@+id/guideline_header_bottom"
  app:layout_constraintLeft_toLeftOf="parent"
  app:layout_constraintTop_toTopOf="parent"
  app:layout_constraintVertical_bias="0.65"/>

<android.support.v7.widget.RecyclerView
  android:id="@+id/item_details"
  android:layout_width="0dp"
  android:layout_height="0dp"
  android:layout_marginBottom="8dp"
  android:layout_marginLeft="8dp"
  android:layout_marginRight="8dp"
  android:layout_marginTop="8dp"
  android:overScrollMode="never"
  app:layout_constraintBottom_toBottomOf="parent"
  app:layout_constraintLeft_toLeftOf="parent"
  app:layout_constraintRight_toRightOf="parent"
  app:layout_constraintTop_toBottomOf="@+id/guideline_header_bottom"/>

<android.support.constraint.Guideline
  android:id="@+id/guideline_header_bottom"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  app:layout_constraintGuide_begin="172dp"/>

</android.support.constraint.ConstraintLayout>

How I resize the layout (will maybe help):
if (mItemDetails.size() > 6) {
     DisplayMetrics dm = getActivity().getResources().getDisplayMetrics();
     float toolbarPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, dm);
     float height = dm.heightPixels - toolbarPx;
     mConstraintLayout.getLayoutParams().height = Math.round(height) + Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50*(mItemDetails.size()-6), dm));
  }


text:
Q: Limit Shipping to specific countries I have two Sites one for GBP and one for Euro.
For the Euro version I have set:
Stores > Configuration > General > General > 'Default Country' = 'Ireland'
Stores > Configuration > General > General > 'Allow Countries' = 'Ireland'
Stores > Configuration > Sales > Shipping Methods > 'Ship to Applicable Countries' = 'Specific Countries'
Stores > Configuration > Sales > Shipping Methods > 'Ship to Specific Countries' = 'Ireland'

And for the UK I have set:
Stores > Configuration > General > General > 'Default Country' = 'United Kingdom'
Stores > Configuration > General > General > 'Allow Countries' = 'United Kingdom'
Stores > Configuration > Sales > Shipping Methods > 'Ship to Applicable Countries' = 'Specific Countries'
Stores > Configuration > Sales > Shipping Methods > 'Ship to Specific Countries' = 'United Kingdom'

My default config for both Sites is:
Stores > Configuration > General > General > 'Default Country' = 'Ireland'
Stores > Configuration > General > General > 'Allow Countries' = 'Ireland'
Stores > Configuration > Sales > Shipping Methods > 'Ship to Applicable Countries' = 'Specific Countries'
Stores > Configuration > Sales > Shipping Methods > 'Ship to Specific Countries' = 'Null'

I have it set up to allow customer accounts globally so someone can create an account on one Site and have a saved address in one country but if they are accessing the Site for the other country they shouldn't see the saved addresses for the other Site.
However when I go to the Cart or Checkout the dropdown menu includes both countries for both Sites. Any ideas how I can change this so that there is no drop down for the country but that the correct country for the correct Site is shown by default?
Cart Summary:

Checkout:

I am using Magento 2.1.11


text:
Q: Ruby creating instance variables outside a class What does it mean to create an instance variable, say @foo in a file outside any class definition. Say there is a file, test.rb and the entire contents of the file are given below.
# test.rb
@foo = "bar"
puts @foo

It prints "bar", but is this an instance variable in some sort of wrapping class?
Testing using two files indicates that there is a main object that everything is wrapped inside. Is this understanding correct?
Contents of a.rb
@me = self
@a = "from-a"

Contents of b.rb
require "./a"

@b = "from-b"
puts @me == self # true (self refers to the same object)
puts self.class  # Object
puts self.instance_variables # [@a, @b, @me]

A: Everything is an object in ruby. So you are actually in the main object right now, which is an instance of Object.
In your file, if you put puts self.class, you will see you are operating under main, and the class being Object.
Even in irb, for example:
ruby-1.9.2-p136 :001 > self
 => main
ruby-1.9.2-p136 :002 > self.class
 => Object


text: Q: SAGA tool is showing issues or it is not competible in QGIS 3.16.11 LTR I have installed in my Windows QGIS 3.16.11 LTR and wanted to use some of the function from SAGA tools, when I open the function it is telling that the SAGA officially does not support for this version of QGIS.


text:
Q: PHP Update giving error if no data is edited Thanks for asking me to make my question clearer.
I have a form which is used to save content in a database.
The user is also allowed to update any content by editing the fields in the form and submitting it.
The update query looks something like this:-
$res = mysql_query("UPDATE freight SET .... WHERE id='$id'") or die ( mysql_error());
    if(mysql_affected_rows() > 0){
        //do some stuff
        return true;
    }
    else{
        return false;
    }

Now my problem is this: If the user changes some field while updating the form, mysql_affected_rows() is > 0 so I am able to "//do some stuff".
But if the user does not change any field in the form and simply submits, mysql_affected_rows return 0 and I reach the false block.
I was under the impression that UPDATE should overwrite every time thereby mysql_affected_rows() should return 1 irrespective of whether any fields have been changed or not.
I use the return value to display an appropriate success or error message in the screen. Hence this is a serious bug.
Can you suggest whats the right way to achieve the correct functionality?
Thanks,
Vish

A: mysql_affected rows() -1 will be returned if the query itself can not be issued to the server, possibly because of syntax error AND if the last query was not either an INSERT or UPDATE statement.

When using UPDATE, MySQL will not update columns where the new value
  is the same as the old value. This creates the possibility that
  mysql_affected_rows() may not actually equal the number of rows
  matched, only the number of rows that were literally affected by the
  query.

so your solution can be achieved by below logic ( but this is not safe)
if(mysql_affected_rows()!=-1){
}

A: if( $_POST['message'] != '' ) {
   // add the field to your query
} else { // this is optional
   // don't add it to your query
}

// do the mysql update here


text:
Q: Integrating Facebook Login with Firebase using Swift only loads a white screen I am trying to create a Facebook login integration with Firebase. Yesterday when I done it is used to work. Since yesterday, only small UI changes leaded to a blank safari controller that should be the Facebook permissions page in order to login.
I already logged in because In my Firebase console I have my Facebook user stored, so the login functionality used to work before the UI changes. I reverted the UI changes, I've reconfigured everything, cleaned the app from the device, reinstalled pods to see if there is a newer version but still can't make it.
This is the white screen I'm talking about:

Also, the console log tells me:

[ViewService] Failed to get remote view controller with error: Error: domain=_UIViewServiceInterfaceErrorDomain, code=2

These are my AppDelegate methods implemented for FacebookSDK:
/* App Delegate */
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    FIRApp.configure()
    FBSDKApplicationDelegate.sharedInstance().application(application,
                                                          didFinishLaunchingWithOptions:launchOptions)
    return true
}

@available(iOS 9.0, *)
func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any])
    -> Bool {
        return self.application(application,
                                open: url,
                                sourceApplication:options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String,
                                annotation: [:])
}

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    return FBSDKApplicationDelegate.sharedInstance().application(application,
                                                                 open: url,
                                                                 sourceApplication: sourceApplication,
                                                                 annotation: annotation)
}

And this is my IBAction for the Facebook login:
/* didPressFacebookLogin(_sender: Any) */
@IBAction func didPressFacebookLogin(_ sender: Any) {
    let facebookLoginManager = FBSDKLoginManager()
    facebookLoginManager.logIn(withReadPermissions: ["public_profile", "email"],
                               from: self) { (result, error) in
        if let error = error {
            print("Failed to login: \(error.localizedDescription)")
            return
        }

        guard let accessToken = FBSDKAccessToken.current() else {
            print("Failed to get access token")
            return
        }

        let credential = FIRFacebookAuthProvider.credential(withAccessToken: accessToken.tokenString)
        FIRAuth.auth()?.signIn(with: credential, completion: { (user, error) in
            if let error = error {
                print("Login error: \(error.localizedDescription)")
                let alertController = UIAlertController(title: "Login error",
                                                        message: "Something went wrong while trying to login.",
                                                        preferredStyle: .alert)
                let okAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
                alertController.addAction(okAction)
                self.present(alertController, animated: true, completion: nil)

                return
            }
        })
    }
}

I was searching for that console problem that tells me that it failed to get remote view controller... Still, no idea. Anybody had this problem with Facebook?

UPDATE: Works on iPad with iOS 10.3.2

A: Updating iOS to 10.3.2 fixed the issue.


text:
Q: Hard Drive Clone Proofing or Licensing to One Computer only Is there any way possible to prevent others from cloning my hard drive? or set one hard drive to work only with one computer? i tried to research but i did not see any topic related to it.
I have one original hard drive to be cloned, what i want to know is if it is possible that the cloned hard drives will never be cloned again and work only to one particular computer.
I hope someone could help with this one, thank you in advance.

A: I've rewritten answer so it will reflect the two-part question better.
In short: yes, it's possible. You can do it in two ways: simple way or safe way.
Simple way is to put password on a hard drive in BIOS. This way disk is unusable unless password have been provided. Without password drive is unresponsive to commands. It is detected, but that's about it. Downside is - with certain vendors - if you forget password, disk is bricked. So forget any meaningful data recovery. I say some vendors because some drives store password unencrypted in firmware, so someone equipped with proper tools can access it. However, most modern SSD are resilient to that sort of attack and you may end up with a bricked drive if you forget password. So think hard on that one.
Another way is to encrypt drive. This, again, presents you with two basic options: hardware encryption and software encryption.
If you do not let your computer out of your hands, then software style is enough. It's because normally encryption keys are stored in RAM, so if someone gets his hands on your computer which is not powered down, they can extract keys from memory and have access to computer later, without your knowledge.
So Definitely go for OPAL standard (as described in second link) if you want to be secure - which would be, incidentally second option - hardware encryption.
I'm not sure how to classify TPM under my choice classification (it could be OPAL-compatible, but it's only one, most secure option out of several available). This one offers, I think, best safety-to-any-issues ratio. It combines hardware platform (TPM) and encryption (BitLocker for example) so that you can link drive to specific computer - for example if someone will take your drive out of computer and will try to clone it on his machine, disk will be inaccessible, as check is performed if it is connected to known, TPM-equipped system. If not, Bitlocker clams up.
Unfortunately, a lot of it rides on hardware in order to be achieved. First of all, you have to have a TPM compatible system, and at least v1.2 at that.
Then BitLocker ancryption needs to be activated.
One definite thing to check is how this affects non-boot drives (that is: how about second drive?). I am unsure how this works in that case.
Second thing to check is backup. Usually data needs to be decrypted in order to be backed up, so you need to be sure you have safe storage location for backups. And I definitely recommend backing up regularly when on SSD (no matter if encrypted or not - "hardware" failure rate on SSD is still way to high.
Also, some backup software do not support encryption (I'm simplifying here.). So check if you can do backup at all.
I am unfamiliar with cloning-counter technologies, so cannot help you with limiting number of times drive can be cloned. You can definitely do it with right software, but I don't think there's anything on the market, and even if, the requirement for it to work at all would be to put encryption on the drive in the first place.
More details:
http://web.mit.edu/cron/documentation/dell-server-admin/en/SUU/tpm.htm
http://www.samsung.com/global/business/semiconductor/minisite/SSD/global/html/whitepaper/whitepaper06.html

A: Your question has two (sort of related) parts so I'll answer them individually:

*

*Unless your disk controllers have some kind of security mechanism to prevent the controller being used in a different machine than the one it was originally tied to you will never get around someone "cloning" the disk. At present a disk controller is used before the disk contents are accessed (disk information, instruction sets etc.). Even if someone did obtain physical access to the disk they could swap the board for one that hasn't been tied to a machine (thus tying it to their own machine and being able to use the controller). Additionally, someone could even transplant the disk platters to another enclosure or clean environment and use recovery tools to copy the platter data.

*As @AcePL's answer states, you can "tie" data to a particular device by means of encrypting the disk and use a TPM so that only that TPM can decrypt the disk. By using a TPM you can be assured that (if the TPM is truly unique!) if someone did clone your disk then they will never be able to decrypt it - much like public key encryption, you can have hundreds of copies of the disk but only one TPM will decrypt it - making it completely useless to anyone who has a copy of your disk but not the TPM.

Disk encryption can also work using a password (and other means such as a certificate on, say, a USB) which gives you other options so that you can put the disk into another machine and you enter your password to decrypt. This particular method - keeping to your question - wouldn't be very useful because the disk isn't tied to a particular hardware


text:
Q: playlist is not created on EXTERNAL_CONTENT_URI using contentresolver I am trying to create a playlist using the following code
public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ContentValues cv = new ContentValues();

        cv.put(MediaStore.Audio.Playlists.NAME, "123456");

        //Uri uri = getContentResolver().insert(MediaStore.Audio.Playlists.getContentUri("external"), cv);
        Uri uri = getContentResolver().insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, cv);
        if (uri != null)
        {
            Toast.makeText(getApplicationContext(),uri.toString(),
                    Toast.LENGTH_LONG).show();
        }
    }

this just would not create any playlist
if i try INTERNAL_CONTENT_URI the playlist is created but even the default app for music in my phone would not show new playlist created

A: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

was the real issue.


text:
Q: How to switch to iframe using Id I am newbie to selenium..
I do have a home page which has create account. If i click Create Account which pops up me to enter Email address and password and submit button.
I have used below one navigate to first iframe.
driver.switchTo().frame(0);

It is working perfectly for me.
On click of submit button on iframe 1, there is another iframe which shows me to enter firstName, lastName, gender, and One time passsword.
I am using below snippet to navigate to the iframe and to enter firstName. it is not working
driver.switchTo().defaultContent();
driver.switchTo().frame("login-iframe");
driver.findElement(By.xpath("//input[@id='fname']")).sendKeys("Test");

Can any one tell me is it correct or not?? I have tried setting back to defaultContent and not setting to defaultContent() both..
Source code here:

             Complete your details to create XXX Cash Wallet

                    First name
                    <input id="fname" type="text" value="" name="fname" maxlength="25"/>
                    Enter your First Name

                    Last name
                    <input id="lname" type="text" value="" name="lname" maxlength="25"/>

                <input id="male" type="radio" name="gender" value="Male"/>Male
                <input id="female" type="radio" name="gender" value="Female"/>Female

Verified
                <input id="userEmail" type="text" value="" name="userEmail"/>
                Enter your Email where we will send you a verification link once you proceed
                Enter a valid Email where we will send you a verification link once you proceed
                The entered Email is invalid. Please enter a valid Email where we will send you a verification link once you procced.
                We already have a XXX account with this Email. Enter a different Email or Sign in using this.
                Sorry, there's been an error sending mail.

We have sent a verification link to  . Please verify the same once you proceed or Change Email

VerifiedMobile number
                <input id="userNumber" type="text" value="" name="userNumber" maxlength="10"/>
                Enter your MobileEnter a valid Mobile
                The entered Mobile is incorrect, update this to verify the new Mobile
                This Mobile exists in other xXXX accounts. Update this and to verify the new Mobile
                Sorry, there's been an error sending OTP.

Enter One Time Password (OTP) sent to your Mobile   or Change Mobile

Resend OTP
                Enter OTP
                <input id="enterOTP" type="text" name="enterOTP" value="" maxlength="6"/>

                One Time Password (OTP) has been resent. If you still do not receive the  OTP within 15 minutes, please contact us at care@xxx.com

<button id="skipVerifyDetails" type="submit" class="btn btn-primary">Skip</button>

<button id="confirmVerifyDetails" type="submit" class="btn btn-primary">Confirm</button>

A: From your html source, it looks like input with id fname is NOT part of iframe with name login-iframe because it ends and the input is below that in the default content.

So I think you should search for the input within defaultContent. Did you try this?
driver.switchTo().defaultContent();
driver.findElement(By.xpath("//input[@id='fname']")).sendKeys("Test");

On a side note you could use just By.id instead of By.xpath to find the element since it has id.


text:
Q: Radioactive Decay Calculus After 2 mins, there is 4.1g of a substance left. One minute later (at t=3 mins), there is 3.4g left. How do I find the half-life of the substance and the original amount present?

A: This is a job for the exponential growth/decay model:
$$y=Ce^{kt}$$
$C$ is the initial amount (the amount of the substance present at time equals zero). $t$ is time which is the independent variable. $k$ is a constant.
In the case of your problem, $t=0$ corresponds to $0$ minutes. Using the given data, we get a system of equations with two unknowns that can be solved:
$$
\left\{
\begin{array}{c}
4.1=Ce^{k2}\\
3.4=Ce^{k3}
\end{array}
\right.
$$
$$
\frac{4.1}{e^{k2}}=\frac{3.4}{e^{k3}}\implies k=\ln{\frac{3.4}{4.1}},\\
C=\frac{4.1}{e^{\ln{\frac{3.4}{4.1}}\cdot 2}}=\frac{4.1^3}{3.4^2}.
$$
Your model now should look like this:
$$
y=\frac{4.1^3}{3.4^2}\left(\frac{3.4}{4.1}\right)^t.
$$
Your task now is to find the time it takes for the substance to be reduced in half (that's what the half-life, $t_{1/2}$, is):
$$
\frac{\frac{4.1^3}{3.4^2}}{2}=\frac{4.1^3}{3.4^2}\left(\frac{3.4}{4.1}\right)^{t_{1/2}}\implies\\
t_{1/2}=\log_{\frac{3.4}{4.1}}{\frac12}=\frac{\ln{\frac{1}{2}}}{\ln{\frac{3.4}{4.1}}}\approx 3.7\ min.
$$


text:
Q: Calculated mysql5 table size different from ibdata I am trying to calculate the total size of all tables in mysql:
SELECT sum( data_length + index_length ) / 1024 / 1024 "Mb" FROM information_schema.TABLES;

+--------------+
| Mb           |
+--------------+
| 942.02298263 |
+--------------+

The size of /opt/mysql5/data/ibdata is 3.1 GB. Why is there such a difference between the two numbers?

A: The ibdata is the busiest file in the InnoDB infrastructure. It houses many different classes of information.

*

*Table data

*Table indexes

*Table metadata

*MVCC data

You can see a graphic representation here.
Here are several links to discussions on this topic.

*

*MySQL: reducing ibdata file size for MyISAM tables

*Best way to reduce the size of ibdata

*And of course the docs
What (if any) action you choose will obviously depend on your setup and goals. I would however consider adjusting the inndb_log_file_size in your my.cnf file as these can get very large very quickly.


text:
Q: how to pass the ID in wrapper class here is my vf page where i am trying to connect two object field's i.e. Pricebookentry & opportunityLineItem and insert into opportunityLineItem. for this i am also getting id of the opportunity but i don't know how to pass that id in these records so that i'll be able to insert these records in opportunityLineItem Related list that will be visible in opportunity. Actually here i am trying to make Add product stanadard functionality of opportunity using VF pages.
here is the image

here is my controller-------------
public class GEN_ProductSelectionController {

 ID cid = ApexPages.currentPage().getParameters().get('id'); //opportunity Id

 public PageReference Reset() {
        return null;
 }

 Public List<OpportunityLineItem> opportunityLineItemList{get;set;}
 public List<wrapOpportunityLineItem> wrapper{get;set;}
 public List<wrapProduct> wrapProductList {get; set;}
 public List<PricebookEntry> selectedProducts{get;set;}
 public List<OpportunityLineItem> closeProduct{get;set;}

 public String searchstring {get;set;}

 public void search(){
         wrapProductList = new List<wrapProduct>();
         string searchquery='select name,id,ProductCode,UnitPrice,product2.Type__c from PricebookEntry where name like \'%'+searchstring+'%\' Limit 20';

         for(PricebookEntry a: Database.query(searchquery)) {
              wrapProductList.add(new wrapProduct(a));
         }
 }

public GEN_ProductSelectionController(){
         wrapProductList = new List<wrapProduct>();

         for(PricebookEntry a: [select Id, Name,ProductCode,UnitPrice,product2.Type__c from PricebookEntry]) {
         wrapProductList.add(new wrapProduct(a));
         }
}

public class wrapProduct {
        public PricebookEntry pro {get; set;}
        public Boolean selected {get; set;}

        public wrapProduct(PricebookEntry p) {
            pro = p;
            selected = false;
        }
}

public class wrapOpportunityLineItem{

        public OpportunityLineItem oppLineItem{get;set;}
          public PricebookEntry selProd{get;set;}

        public wrapOpportunityLineItem(OpportunityLineItem oli, PricebookEntry sp)
        {

           oppLineItem = oli;
           selProd = sp;
        }

}

public PageReference closeProduct() {
        selectedProducts = new List<PricebookEntry>();

        for(wrapProduct wrapProductObj : wrapProductList) {

             if(wrapProductObj.selected == true) {
              selectedProducts.add(wrapProductObj.pro);
             }
        }
        system.debug('selectedWrapperList size ---------'+selectedProducts.size());
        PageReference pagePrice = new PageReference('/apex/GEN_MultiEdit?id='+cid);
        opportunityLineItemList = [Select Quantity,UnitPrice,Monthly_Revenue__c,Contract_Start_Date__c,Full_Revenue_Date__c,Service_Start_Date__c,OpportunityId from OpportunityLineItem ];

           wrapper = new List<wrapOpportunityLineItem>();
        for(Integer i=0; i<selectedProducts.size();i++)
        {
           wrapper.add(new wrapOpportunityLineItem(opportunityLineItemList[i],selectedProducts[i]) );
        }

        pageprice.setRedirect(false);
        return pageprice;

}

public void closeAccou(){
        selectedProducts = new List<PricebookEntry>();

        for(wrapProduct wrapProductObj : wrapProductList) {

           if(wrapProductObj.selected == true) {
               selectedProducts.add(wrapProductObj.pro);
           }
        }
          insert selectedProducts;

}

}

A: So I believe you want to create new OLI then create instance of OLI with opportunity id
Like below..
It will create new OLI related to that opportunity
Id objCurrentOppId = ApexPages.currentPage().getParameters().get('id');
for(Integer i=0; i<selectedProducts.size(); i++)
{
    // Pass new OLI with opportunity id

wrapper.add(new wrapOpportunityLineItem(new OpportunityLineItem(OpportunityId = objCurrentOppId),
                                       selectedProducts[i]) );
}

Updates
First collect all OLI from wrapper list
and then add into OLI list and then insert that list
List<OpportunityLineItem> lstOLI = new List<OpportunityLineItem>();
for(wrapOpportunityLineItem obj :wrapper)
{
  lstOLI.add(obj.oppLineItem);
}

insert lstOLI;


text:
Q: Передача элемента страницы в объект Как передать моему объекту элемент страницы для дальнейших манипуляций с ним внутри этого же объекта ?
Ниже привёл не рабочий пример для дополнительной ясности в вопрос:
var elem = {
    foo: $('#a'),

    bar: function(){
        this.foo.text('aabbcc');
    }
}

elem.bar();

A: Похоже, что вы хотите сделать что-то вроде своего плагина.

(function($) {

  $.fn.bar = function() {
    var foo = function() {
      $(this).text('New text');
    };
    return this.each(foo);
  };

}(jQuery));

$('.el').bar();

Old text

Other element

Old text


text:
Q: Rails 3.0 + Test::Unit - I18n.locale diverges from config.i18n.default_locale If I put the following in my unit test:
puts Inventarizace::Application.config.i18n.default_locale
puts I18n.locale

i get :cz for the first one (as expected), but :en for the second, resulting in locale lookup failures (with keys starting with 'en.'), since this is a czech app and not all keys are translated to english. This is a legacy app which I just upgraded from rails 2.3 to 3.0, don't know if this worked before, since I found this out after I broke that test during the upgrade. Can provide more info if needed. Thanks


text:
Q: exchanging values of 2 maps 2D arrays in ipython, I'm a beginner in python, and I wrote a code:
g=rand_image
for i in range(100):
    for j in range (100):
        G = np.fft.fft2(g)
        theta = angle(G)
        G_prim = image ** 0.5 * exp(1j * theta)
        g_prim = np.fft.ifft2(G_prim)
        for k in range(300):
            for l in range(300):
                if g_prim[k, l].imag > 1e-8 or g_prim[k, l] < 0:
                    g[k,l]=g[k,l]-(2-0.02*i)*g_prim[k,l]
                else:
                    g[k ,l] = g_prim[k,l]

where I compare 2 images, rand_image and image. It takes 2hours to run such code. I would like to make it faster somehow replacing the 2 loops in the bottom (comparing 2 images with 300px*300px size) with maybe a map of 2 pictures and replacing certain values? Although I'm not sure if that is possible.
I nead to increment value of i and run the code multiple times for each i value.

A:                               ^ ^
for i in range(100):          | |
    for j in range (100):     | |
        G = np.fft.fft2(g) #--- |
        theta = angle(G) #-------

The first two statements in the j suite do not make use of i or j so move them out of the loops.

            if g_prim[k, l].imag > 1e-8 or g_prim[k, l] < 0:
                g[k,l]=g[k,l]-(2-0.02*i)*g_prim[k,l]
            else:
                g = g_prim

In this innermost loop suite you repeatedly assign different values to individual pixels of g if the condition is met.

*

*g_prim relies on j so the condition ONLY relies on j

*the calculation in the suite ONLY relies on i.

The value assigned makes use of the outermost loop's value, i but the condition does NOT. For every j that results in a True condition there will be 100 i's.

*

*if the condition is met when j equals two then there will be one-hundred i,j pairs that meet the condition - (0,2), (1,2), ... (99,2)

*each iteration of the k,l loop(s) will assign to g[k,l] when the condition is met.

*the only i that matters is when i equals 99 because it will overwrite each previous calc when j was two.

The net affect is that only the terminal value (99) of i matters.  You are doing a lot of wasted operations.
To make matters worse if the condition is not met, you overwrite ALL previous individual assignments making them useless.
It actually looks as if the entire outer loop is superfluous and can be discarded - i isn't used anywhere except that conditional suite - g[k,l]=g[k,l]-(2-0.02*i)*g_prim[k,l].
If your example is faithfully presented, the inner two (k,l) loops can be replaced using boolean indexing as @nio suggested.
Make a mask that represents your condition and its inverse
mask = np.logical_or(g_prim.imag > 1e-8, g_prim < 0)
not_mask = np.logical_not(mask)

Use the mask to make the assignments when the condition is met
#(2-0.02*i) .. i = 99!!
k = 2 - .02 * 99
g[mask] = g[mask] - k*g_prim[mask]

Assuming you did NOT intend to overwrite the previous conditional assignment,
use the inverse mask to make the rest of the assignments.
g[not_mask] = g_prim[not_mask]


text:
Q: Mutiple client webrequests - object structure approach needed (edited) I'm seeking for a approach for the following problem: I'm doing gps tracking. The data is being provided over http post requests by a gps data provider. The application should handle about one hundred trackings and poll each position max every second.
My approach so far: Out of a collection every object sets off async web requests triggered by a timer. The async request fails, while the sync request is successful. Needs to be fixed or checked (different problem) Another approach would be: every trace object sets off a backgroundworker thread with a sync httprequest and on completion it starts the next request.
What approach would you choose?

A: We need more data to answer this question. First, you said that Async download is failing. How exactly is it failing? What exceptions are you getting?

A: I came up with a timer approach, where I get background working behaviour from. The timer helps me set pauses between pollings easily.


text:
Q: convert a html book to a pdf file? How can I convert a html book (consisting of a number of html files linked to each other) to a pdf file on Ubuntu?
Hope the resulting pdf file can have bookmarks according to the structures of the html book.
The html book can be downloaded from here. Extract it, and go to help, and the directory manual is the html book.

A: Just use wkhtmltopdf
https://github.com/wkhtmltopdf
On my Fedora:

*

*install via
dnf install wkhtmltopdf

*use as
wkhtmltopdf in.html out.pdf

A: First off, not sure I can get the bookmarks and such made automatically, as nice as that would be.
You can manually add them, though, afterwards.
Try opening the HTML file in firefox, and going to file -> print (ctrl+p).
Then, click "Print to File" and click 'PDF'. Then type your file name and select the folder to save it in.

If you want to automate it, maybe you want wkhtmltopdf?
To install it (in ubuntu or debian or linuxmint or similar), type:
sudo apt-get install wkhtmltopdf

A: You can use package htmldoc, which is much easier to get working than pandoc.
It takes a list of html files and resolves the hyperlinks between them to
produce a single pdf with working links, and includes the images.
htmldoc $(find help/manual -name '*html' | sort) --outfile  /tmp/out.pdf

Of course, it would help to know in what order to collate the html files. I
just sorted them on name.
Unfortunately, on my fedora 20 I got core dumps when I tried to put more
than half the audacity files through at the same time. I got to 440 pages of output though.
Perhaps just not enough memory. YMMV.
Remember for safety to prefer the real
audacity web site or your OS package manager
rather than sourceforge.

A: You can use chrome headless
wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
yum localinstall google-chrome-stable_current_x86_64.rpm
./chrome --headless --no-sandbox --disable-gpu --print-to-pdf index.html

A: You probably alredy have Libreoffice installed so you already have the tool at hand. Here is how:
$ libreoffice --headless --norestore --convert-to pdf:writer_pdf_Export MY_HTML_FILE.html

If you use windows just replace libreoffice for the equivalent .exe file ( probably libreoffice.exe ).
If you dont have libreoffice installed just go to libreoffice.org for instructions on how to install it.
On unbutu $ sudo apt install libreoffice

A: Some other alternatives:
weasyprint - more up to date and better support for print css commands than something like wkhtmltopdf
pagedjs / pagedjs-cli - similar; uses headless chromium in the backend, but abstracts away some of the difficulties
I recommend reading this tutorial at print-css.rocks, which summarizes a bunch of methods.

A: I have print to pdf a bunch of html files using "chromium headless" (the chrome base browser).
chromium --headless --disable-gpu --print-to-pdf=./${filename}.pdf --no-margins ./${filename}.html

A bash script to do the job:
#!/usr/bin/env bash

for files in $(ls . )
do
    filename=`echo $files | cut -d. -f1`
    chromium --headless --disable-gpu --print-to-pdf=./${filename}.pdf --no-margins ./${filename}.html
done


text:
Q: How does signing a token work? (Invalid Signature Error) Background: I'm running integration tests inside a .NET Core Web API that uses Auth0 to authorize on my endpoints. My tokens coming back from Auth0 contain an "invalid signature" when I paste them into the JWT.io verifier.
I'm having some trouble understanding at which point in my Authorization flow that my token is being signed, who signs it, and how it is signed.
I started a new development API in Auth0 ("My Dev API") that uses HS256 Signing Algo to sign my tokens. As I understand it, with HS256, there is one secret key that is used sign tokens (the signing secret), and the Machine to Machine flow looks like this:
I post some credentials to Auth0, like this:
clientID: exampleID
clientSecret: exampleSecret
audience: https://myaudience.com
grant_type: client_credentials

Auth0 sends me back an access token:
access_token: exampleToken1234

When I paste this token into JWT.io, I am told that the token has an invalid signature.
In my .NET application, I have some setup does some kind of configuration:
   static void AddAuthentication(IServiceCollection services)
       {
           services.AddAuthentication(options =>
           {
               options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
               options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(options =>
        {
              options.TokenValidationParameters = new TokenValidationParameters
         {
               ValidIssuer = auth0Config.Domain,
               ValidAudience = auth0Config.Audience,
               IssuerSigningKey = new
                        SymmetricSecurityKey(Encoding.UTF8.GetBytes(auth0Config.SigningSecret))
         };
     });
 }

Can anyone explain if I'm supposed to add code to sign this token, if it arrives already signed (and if so, why is JWT.io telling me there's an invalid signature) and what the config above is actually doing?
Also, is it necessary to create a standalone Dev API or can I send autho requests to the pre-built management-api?
Thanks in advance!

A:
My tokens coming back from Auth0 contain an "invalid signature" when I paste them into the JWT.io verifier.

https://jwt.io can't verify the signature unless you paste the secret (that was used to sign token) into the field in the right column under "VERIFY SIGNATURE". So first paste the secret there, then paste the token into the left column. The order of is important!

I'm having some trouble understanding at which point in my Authorization flow that my token is being signed, who signs it, and how it is signed.

AuthO creates a signed token for you when the user is authenticated according to the presented credentials. To create a token first header and payload are created, then a signature is calculated as a hash of header and payload and secret. Read up on the basics here

Can anyone explain if I'm supposed to add code to sign this token, if it arrives already signed (and if so, why is JWT.io telling me there's an invalid signature)

You don't need any additional signature, you get a signed token from AuthO.

and what the config above is actually doing?

The config above tells your API that JWT based authentication is used and that incoming request should be checked for a valid JWT according to the configured parameters (validate issuer, audience and signature based on the values from auth0Config)


text:
Q: No known RoleID Vault Agent I'm using vault approle auth method to fetch secrets from vault. Below is my vault agent configmap.
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
data:
  config-init.hcl: |
      "auto_auth" = {
        "method" = {
          "config" = {
            "role" = "test"
            "role_id_file_path" = "roleid"
            "secret_id_file_path" = "secretid"
            "remove_secret_id_file_after_reading" = false
          }
          "type" = "approle"
        }

        "sink" = {
          "config" = {
            "path" = "/home/vault/.token"
          }

          "type" = "file"
          "wrap_ttl" = "30m"
        }
      }

      "vault" = {
        "address" = "https://myvault.com"
      }

      "exit_after_auth" = true
      "pid_file" = "/home/vault/.pid"

Then I'm referencing the above configmap in the deployment file.
annotations:
        vault.hashicorp.com/agent-inject: 'true'
        vault.hashicorp.com/agent-configmap: 'my-configmap'

But I get below error
vault-agent-init 2022-07-20T10:43:13.306Z [ERROR] auth.handler: error getting path or data from method: error="no known role ID" backoff=4m51.03s

A: Create a secret file in Kubernetes by using the RoleID and SecretID and pass the below annotation
vault.hashicorp.com/extra-secret: "secret-file"