text:
Q: ObjectInputStream$BlockDataInputStream.peekByte when using program on internet I created an application with TCP, it works nice when I used it on a local network with 127.0.0.1 but the server refused to works when a client try to connect to him from an another network.
I don't know what this error means and how to resolve it and I can't anderstand that an application could works only on LAN.
public class Reception {

InputStream inObjet = null;
BufferedReader inString = null;
ObjectInputStream recVec2i = null;

public Reception(Socket socket) {
    try {
        this.inObjet = socket.getInputStream();
        this.inString = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        this.recVec2i = new ObjectInputStream(inObjet);
    } catch (IOException ex) {
        Logger.getLogger(Reception.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public Vecteur2i recevoir() {
    Vecteur2i to = new Vecteur2i();
    try {

        to = (Vecteur2i) recVec2i.readObject();

    } catch (IOException | ClassNotFoundException ex) {
        Logger.getLogger(Reception.class.getName()).log(Level.SEVERE, null, ex);
        to = new Vecteur2i(1000, 1000);
    }
    return to;
}

public String recevoirString() {
    String chaine = "";
    try {
        chaine = inString.readLine();
    } catch (IOException ex) {
        Logger.getLogger(Reception.class.getName()).log(Level.SEVERE, null, ex);
    }
    return chaine;
}

public void fermerReception() {
    try {
        inString.close();
    } catch (IOException ex) {
        Logger.getLogger(Reception.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        inObjet.close();
    } catch (IOException ex) {
        Logger.getLogger(Emission.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        recVec2i.close();
    } catch (IOException ex) {
        Logger.getLogger(Reception.class.getName()).log(Level.SEVERE, null, ex);
    }
}
}

And here the exception :

avr. 22, 2015 9:33:33 PM Snake.Reception recevoir Grave: null
  java.io.EOFException  at
  java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2597)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1316)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
    at Snake.Reception.recevoir(Reception.java:41)  at
  Snake.Partie.cycleDeJeu(Partie.java:55)

Regards,

A: You can't mix different types of stream via the same socket when one or more of them is buffered, and both BufferedInputStream and ObjectInputStream are buffered. The buffers will 'steal' data from each other. In your case you should do all the I/O via the object stream. It has String-based methods.


text:
Q: How to check if submitted element value already exists? So, as for an assignment I'm coding a PHP versed page that allows you to submit order id's to an XML  config, so it filters desired orders out.
All works fine and great, but I want to alert the user the moment the submitted ID already exists in the config.
XML elements
<filter><!-- Copy filter-item and put the order-id in as the value to skip it-->
<filter_item>1142575860</filter_item><filter_item>1142495027</filter_item>
</filter>

    if (isset($_POST['btnAddId']))
{
    $addID = $_POST['idFilter'];
    $xml = simplexml_load_file('Config.xml');

    if(empty($addID))
    {
        echo '<script> alert("Input value is empty");</script>';
    }
    else if(!is_numeric($addID))
    {
        echo '<script> alert("input is not numeric");</script>';
    }
    else if(??)
    {
        echo '<script> alert("ID already exists in the filter");</script>';
    }
    else{

        $orderFilter = $_POST['idFilter'];
        $sxe = new SimpleXMLElement($xml->asXML());

        $itemsNode = $sxe->filter;

        $itemsNode->addChild('filter_item', $orderFilter);
        $sxe->asXML('Config.xml');

        echo $LocScript;
    }
}

A: You can use XPath to search for a <filter_item> element which has the same content as the ID they have entered...
if ( count($xml->xpath('//filter_item[.="'.$addID.'"]')) > 0 )
{
   echo '<script> alert("ID already exists in the filter");</script>';
}

Which gives an XPath expression of (for example)
//filter_item[.="1142495027"]

as this matches one of the items, it will return a list containing 1 item.  The condition with count() will then trigger that an item already exists.

redpajama_set_name: RedPajamaStackExchange


text:
Q: localStorage, saving a class using toggleClass I am  clueless when it comes to localStorage it seems. I want to set up a way favorite any div in a group of div's by toggling a class. I can get the toggleClass to work on the individual div and be saved but localStorage saves all the div's as favorites, not just the one with the toggleClass set. Obviously I am missing something.
jsfiddle simple example
localStorage code:
if (typeof (localStorage) == 'undefined') {
document.getElementById("result").innerHTML = 'Your browser does not support HTML5 localStorage. Try upgrading.';
} else {
if (localStorage.getItem("fav") != null) {
    getFav = localStorage.fav;
    $(".item").addClass('favorites');
}
}
$(document).ready(function () {
$('.btn').on('click', function () {
    getFav = localStorage.fav;
    //$(".item").removeClass('favorites');
    //localStorage.removeItem('background');
    $(this).closest(".item").toggleClass('favorites');
    if ($(this).closest(".item").hasClass('favorites')) {
    localStorage.setItem('fav', 'favorites');

}else{
    localStorage.removeItem('fav');
}

});
});

The issue resides in
$(".item").addClass('favorites');

It adds the class to all .items and obviously it should not.
Any help would be appreciated!

A: In case the other answers questions do not suffice here is a solution that allows you to have multiple divs that will maintain state after reload rather than just one.
http://codepen.io/anon/pen/WvmEbX
if (typeof(localStorage) == 'undefined') {
  document.getElementById("result").innerHTML =
    'Your browser does not support HTML5 localStorage. Try upgrading.';
} else {
    $(".item").each(function(i, el) {
      if (localStorage['fav' + i] == 'favorites') {
        $(this).addClass('favorites');
      }
    });
}
$(document).ready(function() {
  $('.btn').on('click', function() {
    var $item = $(this).closest('.item');
    var index = $('.item').index($item);
    $item.toggleClass('favorites');
    if ($item.hasClass('favorites')) {
      localStorage.setItem('fav' + index, 'favorites');
    } else {
      localStorage.removeItem('fav' + index);
    }
  });
});

A: You have 2 class HTML divs try using the ID property instead of using class, however make sure you specify two different IDs as currently the classes are clashing.

Test

          <button class="btn">Toggle</button>

Test

          <button class="btn">Toggle</button>

As you can see I have assigned the ID property to each one, now you'd add a style to that specific ID so that way they don't clash.

A: Based on your reply to a previous answer (ID's are too cumbersome)
Here is another approach. You can use their index as the localStorage value. HOWEVER, the number of the item elements must not change AND they don't change ordering.
if (typeof(localStorage) == 'undefined') {
  document.getElementById("result").innerHTML =
    'Your browser does not support HTML5 localStorage. Try upgrading.';
} else {
  // highlight the selected item
  if (localStorage.getItem("fav") != null) {
    getFav = localStorage.fav;
    $('.item').eq(getFav).addClass('favorites');
  }
}

$(document).ready(function() {
  $('.btn').on('click', function() {
    getFav = localStorage.fav;

    // clear all highlights
    $(".item").removeClass('favorites');

    // get the selected item then its index, then store in getFav
    var selectedItem = $(this).closest(".item");
    getFav = $('.item').index(selectedItem);
    selectedItem.toggleClass('favorites');

    // store the value in localStorage
    if (selectedItem.hasClass('favorites')) {
      localStorage.setItem('fav', getFav);
    } else {
      localStorage.removeItem('fav');
    }

  });
});

Here is a codepen: http://codepen.io/anon/pen/pJYroL
NOTE I really recommend that you apply ID to the elements if you can. That will be more flexible. :)


text:
Q: To solve the given limit For each of the following find the limit with clear justifications if it exists, or explain why it does not exist.
$(i)$ $\displaystyle \lim_{x \to 0}\frac{\ln(1+x)}{x}$
$(ii)$ $\displaystyle \lim_{x \to 0}\frac{\ln(1+|x|)}{x}$
$(iii)$ $\displaystyle \lim_{x \to 0}\frac{\ln(1+|x|)}{x}\:\sin x$
Question (i) can be solved by using the L'Hôpital's law, I was able to compute that the given limit equals to one. Generally to prove whether a limit exists, would be to use the definition. Should I first compute the limit of the questions manually and then utilise the definition to prove the same?
Also I am not aware as to how to go about solving the limits with the modulus signs, is there a particular way to go about doing the same?

A: Hint. Concerning the second limit, one may write, as $x \to 0$,
$$
\frac{\ln(1+|x|)}{x}=\frac{\ln(1+|x|)}{|x|}\cdot \frac{|x|}{x}
$$ then consider separately $x \to 0^-$ and $x \to 0^+$ using the first limit.
Concerning the last limit, one may observe that
$$
\left|\frac{\ln(1+|x|)}{x}\cdot \sin x\right|\le \frac{\ln(1+|x|)}{|x|}\cdot \left|\sin x\right|\le\frac{\ln(1+|x|)}{|x|}
$$ then one may use the first limit.

A: (1) when expansion of ln(1+x) is divided by x and x tending to zero we will get its limit as 1
(2) left hand limit and right hand limit of the function is different hence limit doesn't exist
(3) limit exist and using algebra of limit it will be 1 as sinx makes the function tending to same limit from left as well as right hand side


text: Q: Finding approximation methods for a function and its derivative I need to find numerical methods to approximate a map $y=h(x)$ where $h: R^n \to R^m$ on the compact sets $D_x \times D_y$. More specifically, I need to find appropriate methods that ensure that, for every given $\varepsilon \geq 0$, $ | h(x) - \bar{h}(x) | \leq \varepsilon$ where $\bar{h}$ is the approximation of $h$. I am also interested in knowing the upper bound of the difference between their derivatives on the compact set, i.e. $| \frac{\partial h}{\partial x} - \frac{\partial \bar{h}}{\partial x} |$.


text:
Q: Understanding pulleys and tension
In the above setup, there is a single piece of rope that is passed through three pulleys.The T1 and T2 parts of the rope are angled at theta to the horizontal. On the end there is a weight. I want to determine the tension in the final part of the rope (A). The weight and friction of all pulleys and rope involved can be ignored. System in equilibrium.
My method is to say that the weight of the counterweight is equal to the vertical component of T1:
$$ T_1\sin\theta = W $$
Because the forces are balanced, there must be an opposing vertical force:
$$ T_2\sin\theta = W $$
And the sum of the horizontal components must equal the tension in part A of the rope:
$$ T_1\cos\theta + T_2\cos\theta = T_3 $$
And as:
$$ T_1 = T_2 $$
$$ T_3 = 2T\cos\theta $$
That's what I've done but I have no confidence it's right. If anyone can answer these questions:

*

*Does $T_1 = T_2$?

*If so, do they both have vertical components equal to the weight W but in opposite directions

*Is the tension in A the resultant of the horizontal components of T1 and T2?

A: Here goes:

*

*Yes. $T_1=T_2 =W$. The tension is the same everywhere in a rope in static equilibrium.

*No. The vertical components are given by $Wsin(\theta)$.

*Yes. $A = T_1cos(\theta) + T_2cos(\theta) = 2Wcos(\theta)$


text:
Q: Intercept and divert graphic output before it hits the linux framebuffer, not using X11 I have been researching this issue for about a week, and it may be that I don't know the right questions to ask.
I am running a debian distro (Raspbian Stretch on the RaspberryPi). I am not using X11. Instead, I am booting straight to the command line, and will eventually probably boot straight up headless, starting a program at startup or sshing in to interact.
What I need to do is to start an application (a game engine specifically) that draws graphics to the framebuffer. Then, I need to intercept that stream before it makes it into the framebuffer, so I can work with it in real time.
Ultimately, I am using ffmpeg to compress and stream video of the output to another Pi. So, I want to be able to start an application and stream its output over a LAN, while still being able to interact with the command line in a separate thread.
I have the ffmpeg command to pull from /dev/fb0, and have successfully started the graphics application and streamed the content. But, is there anyway to intercept, capture, or redirect that application's output so it never actually hits the framebuffer? In my searching I have found many examples of writing to or reading from the framebuffer, but nothing about stopping content before it reaches the buffer.
I am happy with any solution that uses an existing package or application, or for C or RUST code that accomplishes what I need.
Thank you


text:
Q: how to export kendo-chart to pdf am using kendo data vizualization api to render dashboard page with charts
user does some selection on page which triggers ajax call and draws the charts on this dashboard page.
i need to add the feature to export the dashboard page with multiple charts to pdf
i tried phantom js but am not clear how to make it work in this context where current user is already logged in and on dashbaord page and clicks on export to pdf button.
my web layer is using asp.net 3.5 and i dont want to mix the mvc.dll solution as posted on kendo site in my project.
has any one tried this before ? please hlp.
thanks.

A: This JS code exports all rendered to container element with ID 'your_container_with_charts_inside' charts to PDF:
$( document ).ready(function() {

    var $element = $('#your_container_with_charts_inside');

    kendo.drawing.drawDOM($element)
    .then(function (group) {
        return kendo.drawing.exportPDF(group, {
            paperSize: "auto",
            margin: { left: "1cm", top: "1cm", right: "1cm", bottom: "1cm" }
        });
    })
    .done(function (data) {
        kendo.saveAs({
            dataURI: data,
            fileName: "export.pdf",
        });
    });

});

Also you might want to check Chart API / PDF Export demo


text:
Q: Upgrade from Windows 7 to 8.1 using the upgrade assistant with an MSDN subscription I have an MSDN subscription, and want to use this to upgrade from Win 7 to 8.1; however, the upgrade assistant doesn't allow me to enter a product key - I simply get an option to buy Windows.
Is there a way to persuade Windows that I already have a key during this process?

A: Can you skip it? If so, you can input the product key after the installation.
Right click start menu - System - Change Product Key

A: If you have an MSDN subscription, go to your downloads page, download the ISO, burn to disc or USB and upgrade.
If you don't want to risk one of your activations getting used, try a GVLK during the install.  It won't activate you, but will allow you complete the install.
http://technet.microsoft.com/en-us/library/jj612867.aspx


text:
Q: Downloading pdf file I am trying to download a pdf file from a server to the device. Here is the code that I am using
- (id)initwithURL:(NSString*)remoteFileLocation andFileName:(NSString*)fileName{

    //Get path to the documents folder
    NSString *resourcePathDoc = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]resourcePath]stringByDeletingLastPathComponent]stringByAppendingString:@"/Documents/"]];
    localFilePath = [resourcePathDoc stringByAppendingString:fileName];

    BOOL fileExists = [[NSFileManager defaultManager]fileExistsAtPath:localFilePath];
    if (fileExists == NO) {
        NSURL *url = [NSURL URLWithString:remoteFileLocation];
        NSData *data = [[NSData alloc] initWithContentsOfURL: url];

        //Write the data to the local file
        [data writeToFile:localFilePath atomically:YES];
    }
    return self;
}

where remoteFileLocation is a NSString and has the value http://topoly.com/optimus/irsocial/Abs/Documents/2009-annual-report.pdf
On running the app crashes, just on NSData giving a SIGABRT error. The only useful information it gives is
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURL length]: unrecognized selector sent to instance 0xc87b600'
How can this be fixed ?

A: As your PDF file is too large in size so if you do Synchronous Download, it will take too Long to download, so i insist you to create an Asynchronous Downloader and Use it. I have put code for the same.
Step 1 :Create a file 'FileDownloader.h'
#define FUNCTION_NAME   NSLog(@"%s",__FUNCTION__)

#import <Foundation/Foundation.h>

@protocol fileDownloaderDelegate <NSObject>

@optional
- (void)downloadProgres:(NSNumber*)percent forObject:(id)object;

@required

- (void)downloadingStarted;
- (void)downloadingFinishedFor:(NSURL *)url andData:(NSData *)data;
- (void)downloadingFailed:(NSURL *)url;

@end

@interface FileDownloader : NSObject
{

@private
    NSMutableURLRequest *_request;
    NSMutableData *downloadedData;
    NSURL *fileUrl;

    id <fileDownloaderDelegate> delegate;

    double totalFileSize;
}

@property (nonatomic, strong) NSMutableURLRequest *_request;
@property (nonatomic, strong) NSMutableData *downloadedData;
@property (nonatomic, strong) NSURL *fileUrl;

@property (nonatomic, strong) id <fileDownloaderDelegate> delegate;

- (void)downloadFromURL:(NSString *)urlString;

@end

Step 2 : Create a .m file with FileDownloader.m
#import "FileDownloader.h"

@implementation FileDownloader

@synthesize _request, downloadedData, fileUrl;
@synthesize delegate;

- (void)downloadFromURL:(NSString *)urlString
{
    [self setFileUrl:[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];

    self._request = [NSMutableURLRequest requestWithURL:self.fileUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0f];
    NSURLConnection *cn = [NSURLConnection connectionWithRequest:self._request delegate:self];
    [cn start];
}

#pragma mark - NSURLConnection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if([delegate respondsToSelector:@selector(downloadingStarted)])
    {
        [delegate performSelector:@selector(downloadingStarted)];
    }

    totalFileSize = [response expectedContentLength];
    downloadedData = [NSMutableData dataWithCapacity:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [downloadedData appendData:data];

    if([delegate respondsToSelector:@selector(downloadProgres:forObject:)])
    {
        [delegate performSelector:@selector(downloadProgres:forObject:) withObject:[NSNumber numberWithFloat:([downloadedData length]/totalFileSize)] withObject:self];
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    if([delegate respondsToSelector:@selector(downloadingFailed:)])
    {
        [delegate performSelector:@selector(downloadingFailed:) withObject:self.fileUrl];
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if([delegate respondsToSelector:@selector(downloadingFinishedFor:andData:)])
    {
        [delegate performSelector:@selector(downloadingFinishedFor:andData:) withObject:self.fileUrl withObject:self.downloadedData];
    }
}

@end

Step 3 : Import file #import "FileDownloader.h" and fileDownloaderDelegate in your viewController
Step 4: Define following Delegate methods in .m file of your viewCOntroller
- (void)downloadingStarted;
- (void)downloadingFinishedFor:(NSURL *)url andData:(NSData *)data;
- (void)downloadingFailed:(NSURL *)url;

Step 5 : Create Object of FileDownloader and set URL to Download thats it.
FileDownloader *objDownloader = [[FileDownloader alloc] init];
[objDownloader setDelegate:self];
[objDownloader downloadFromURL:@"Your PDF Path URL here];

Step 6 : Save your file where you want in
    - (void)downloadingFinishedFor:(NSURL *)url andData:(NSData *)data; method.

A: It appears that your remoteFileLocation parameter value is really an NSURL object and not an NSString. Double check how you get/create remoteFileLocation and verify it really is an NSString.
There are also several other issues with this code. The proper way to create a path to the Documents directory is as follows:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = paths[0];
NSString *localFilePath = [resourcePathDoc stringByAppendingPathComponent:fileName];

BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:localFilePath];
if (!fileExists) {
    NSURL *url = [NSURL URLWithString:remoteFileLocation];
    NSData *data = [[NSData alloc] initWithContentsOfURL:url];

    //Write the data to the local file
    [data writeToFile:localFilePath atomically:YES];
}

A: GCD can be used for massive files. You can download the file synchronous on a second thread and post back to the main thread if you like. You can also use Operation queues.
You can indeed also use the delegate method from NSURLConnection allowing you to handle the callbacks on the main thread. It is however obsolete to define your own delegate since you can just implement the delegate from NSURLConnection itself.


text:
Q: How to connect manually to seed of torrent data (OS: Windows 7, 64 bit)? How to connect manually to seed of torrent data (OS: Windows 7, 64 bit)?
(I performed multiple web searches including on superuser.)

A: Torrents occur as a layer 7 application, rather than a simple network protocol. This means that to do it "manually" is to write your own client program, in the language of your choice.
The connections discovered, created, and managed by a torrent client are the result of complicated application logic, so its not a simple invocation like telnet'ing into a ftp server and running a GET, or using curl to operate a api. A full featured torrent client would use hundreds or thousands of these kinds of primitives to perform its tasks over the duration of a session.
if you would like to see how torrent clients work, there are many opensource implementations that you might look at:

*

*https://github.com/transmission/transmission

*https://github.com/rakshasa/rtorrent

*https://dev.deluge-torrent.org/wiki/GitRepo
If you are just looking for a cli torrent client that you can script around or otherwise automate, I suggest you refine your search in those terms, and perhaps start here: Torrent Client - Command line - Windows


text:
Q: Can someone explain this equation? Okay, here is the exact phrasing:
We want to get two values $A$ and $B$, where we test many values of $A$ to get the smallest value of $B$.
$B$ is the coefficient of $x^{15}$ in the result of: $(1 + x)^A \pmod{p, x^{38} - 5}$.
$p = 2975390752039679348694694675193$, a prime number. $x^{38} - 5$ is an irreducible polynomial in the field $F_p[x]$.
The range of allowable values of $A$ and $B$ are:
$1 \le A \le p^{38} - 1$ and
$0 <= B < p$


text:
Q: Docker-compose with redis, sidekiq, rails SocketError I am perplexed about the error in my docker-compose config. I am adding redis alongside sidekiq to the existing rails app that uses docker-compose but I am failing hard on attempts to make the containers communicate with each other. I have tried several different options and looked at pretty much every reasonable topic on SO that touches this subject but I keep failing on basically the same thing. Here is my current config (or at least the relevant parts of it) and error:
docker-compose.yml
services:
  web:
    <<: *common-settings
    build:
      context: .
      dockerfile: docker/development/Dockerfile
      target: web
    command: dumb-init bash -c "(bundle check || bundle install) && rails s -b 0.0.0.0 -p 3000"
    depends_on:
      - db
      - redis
      - elasticsearch
    ports:
      - '3000:3000'
    expose:
      - 3000

  redis:
    image: 'redis:5-alpine'
    ports:
      - '6379:6379'
    volumes:
      - 'redis:/data'

  sidekiq:
    depends_on:
      - db
      - redis
      - web
    build: .
    command: bundle exec sidekiq
    volumes:
      - .:/app:cached
      - bundle:/bundle
    env_file:
      - ./.env

config/initializers/sidekiq.rb
Sidekiq.configure_server do |config|
  config.redis = { url: 'redis://redis:6379/12' }
end

Sidekiq.configure_client do |config|
  config.redis = { url: 'redis://redis:6379/12' }
end

Yes this is hardcoded right in the open currently, but I have tried configs that just use ENV variables and the results are exactly the same, no matter where I get the values from the result is the same. Trying out stuff like this right now since it made no difference.
Here is the error when I try to access localhost:3000/sidekiq
Error connecting to Redis on redis:6379 (SocketError)
Application Trace | Framework Trace | Full Trace
redis (4.4.0) lib/redis/client.rb:384:in `rescue in establish_connection'
redis (4.4.0) lib/redis/client.rb:365:in `establish_connection'
redis (4.4.0) lib/redis/client.rb:117:in `block in connect'
redis (4.4.0) lib/redis/client.rb:330:in `with_reconnect'
redis (4.4.0) lib/redis/client.rb:116:in `connect'
redis (4.4.0) lib/redis/client.rb:403:in `ensure_connected'
redis (4.4.0) lib/redis/client.rb:255:in `block in process'
redis (4.4.0) lib/redis/client.rb:342:in `logging'
redis (4.4.0) lib/redis/client.rb:254:in `process'
redis (4.4.0) lib/redis/client.rb:148:in `call'
redis (4.4.0) lib/redis.rb:307:in `block in info'
redis (4.4.0) lib/redis.rb:70:in `block in synchronize'
/usr/local/lib/ruby/2.6.0/monitor.rb:235:in `mon_synchronize'
redis (4.4.0) lib/redis.rb:70:in `synchronize'
redis (4.4.0) lib/redis.rb:306:in `info'
sidekiq (6.2.2) lib/sidekiq.rb:120:in `block in redis_info'
sidekiq (6.2.2) lib/sidekiq.rb:98:in `block in redis'
connection_pool (2.2.5) lib/connection_pool.rb:63:in `block (2 levels) in with'
connection_pool (2.2.5) lib/connection_pool.rb:62:in `handle_interrupt'
connection_pool (2.2.5) lib/connection_pool.rb:62:in `block in with'
connection_pool (2.2.5) lib/connection_pool.rb:59:in `handle_interrupt'
connection_pool (2.2.5) lib/connection_pool.rb:59:in `with'
sidekiq (6.2.2) lib/sidekiq.rb:95:in `redis'
sidekiq (6.2.2) lib/sidekiq.rb:114:in `redis_info'
sidekiq (6.2.2) lib/sidekiq/web/helpers.rb:177:in `redis_info'
.
.
.

Same error occurs when I try to run a worker from the web app, or go there and use bundle exec sidekiq
Here is what gets logged out when I run docker-compose up
redis_1          | 1:C 12 Oct 2021 11:44:19.103 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1          | 1:C 12 Oct 2021 11:44:19.103 # Redis version=5.0.14, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1          | 1:C 12 Oct 2021 11:44:19.103 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
redis_1          | 1:M 12 Oct 2021 11:44:19.105 * Running mode=standalone, port=6379.
redis_1          | 1:M 12 Oct 2021 11:44:19.105 # Server initialized
redis_1          | 1:M 12 Oct 2021 11:44:19.105 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
redis_1          | 1:M 12 Oct 2021 11:44:19.105 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain
the setting after a reboot. Redis must be restarted after THP is disabled.
redis_1          | 1:M 12 Oct 2021 11:44:19.105 * DB loaded from disk: 0.000 seconds
redis_1          | 1:M 12 Oct 2021 11:44:19.106 * Ready to accept connections

sidekiq_1        | 2021-10-12T11:44:26.712Z pid=1 tid=ouccdy1p5 INFO: Booting Sidekiq 6.2.2 with redis options {:url=>"redis://redis:6379/12"}
sidekiq_1        | 2021-10-12T11:44:27.174Z pid=1 tid=ouccdy1p5 INFO: Booted Rails 5.2.6 application in development environment
sidekiq_1        | 2021-10-12T11:44:27.174Z pid=1 tid=ouccdy1p5 INFO: Running in ruby 2.6.6p146 (2020-03-31 revision 67876) [x86_64-linux-musl]
sidekiq_1        | 2021-10-12T11:44:27.174Z pid=1 tid=ouccdy1p5 INFO: See LICENSE and the LGPL-3.0 for licensing details.
sidekiq_1        | 2021-10-12T11:44:27.174Z pid=1 tid=ouccdy1p5 INFO: Upgrade to Sidekiq Pro for more features and support: https://sidekiq.org

As for using ENV variables I usually tried it with setting a value like this in the .env file
REDIS_URL=redis://redis:6379/12

When I check with docker ps, redis container is there normally.
If I understand correctly, the URL redis://redis:6379/12 uses redis as the name of the host and that corresponds to the name of the service I specified in the docker-compose.yml and should allow the containers to talk to each other. This file originally has more services like elasticsearch for example and they work just fine.
I have tried quite a few different setups but I feel like I'm banging my head against the fall. What am I missing?

A: You are probably not exposing redis port to the sidekiq service try exposing this in docker compose. This probably may work.

A: Turns out I missed an important detail about the config
networks:
  app:

After adding
    networks:
      - app

To redis and sidekiq, everything was able to talk to each other nicely.


text:
Q: How can I schedule a script in BigQuery? At last BigQuery supports using ; in the queries, so I can write more than one query in one "block", if I seperate them with semicolon.
If I run the code manually, it works. But I cannot schedule that.
When I want to schedule, I have two choices:

*

*(New) Web UI: I must give a destination table. If I don't do it, I could not save the scheduled query. But all my queries are updates and inserts with different "destination tables". Like these:

UPDATE project.exampledataset.a
SET date = current_date()
WHEN TRUE
;
INSERT INTO project.otherdataset.b
SELECT c,d
FROM project.otherdataset.c
So I cannot even make a scheduling in the Web UI.

*Classic UI: I tried this, because the official documentary states, that I should leave the "destination table" blank, and Classic UI allows it. I can setup the scheduling, but it doesn't run, when it should. I get the error message in email "Error status: Dataset specified in the query ('') is not consistent with Destination dataset 'exampledataset'."

AIK scripting (and using semicolon) is a very new feature in BigQuery, but I hope someone can help me.
Yes, I know that I could schedule every query one by one, but I would like to resolve it with one big script.

A: Looks like the scheduled query was defined earlier with destination dataset defined with APPEND/TRUNCATE type transaction. While updating the same scheduled query to a DML query, GUI doesn't show the dataset field / table name to update to NULL. Hence this error is coming considering the previously set dataset and table name in the scheduled query.
Hence the fix is to delete the scheduled query and create it from scratch with DML query option. It worked for me.

A: Scripting is supported in scheduled query now. However, scripting query, when being scheduled, doesn't support setting a destination table for now. You still need to use DDL/DML to make change to existing table.
E.g.:
CREATE OR REPLACE TABLE destinationTable AS
SELECT *
FROM sourceTable
WHERE date >= maxDate

A: As of 2022, the BQ Console UI will let you create a new scheduled query without a destination dataset, but it won't let you update a prior SELECT to use DDL/DML block syntax. However, you can use the BigQuery Data Transfer API to update the destinationDatasetId field, via transferconfigs/patch. Use transferconfigs/list to get the configId for a given scheduled query.
Note that you can either use the in-browser API Explorer, if you have the appropriate credentials, or write a programmatic solution. Also seems useful for setting/updating any other fields, including renaming scheduled queries.


text:
Q: XAML can't see a class My xaml goes like this:
<DataGrid.Resources>
    <Helpers:EnumHelper x:Key="EnumHelper" />
</DataGrid.Resources>

And my class is defined like this:
namespace MyProj.View.UserControlHelpers {
    public class EnumHelper { }
}

The error I get is this:

The name "EnumHelper" does not exist in the namespace "clr-namespace:MyProj.View.UserControlHelpers".

I've cleaned this project from the studio, then I've deleted every file in bin and obj subdirectories, I've even changed class name, still without success - I'm still getting this error.
EDIT:
My xaml headers are lik this:
<UserControl x:Class="MyProj.View.Partials.TableWindow.Columns"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
             xmlns:cmd="http://www.galasoft.ch/mvvmlight"
             xmlns:Helpers="clr-namespace:MyProj.View.UserControlHelpers"
             xmlns:Model="clr-namespace:MyProj.Model"
             xmlns:ModelHelpers="clr-namespace:MyProj.Model.Helpers"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">

A: Your class namespace is
MadMin.View.UserControlHelpers

but you refer to it in xaml as
MyProj.View.UserControlHelpers


text:
Q: DockerHub API: List ongoing builds I am trying to fetch data from DockerHub from this URL using the API:
https://cloud.docker.com/u/{account}/repository/docker/{account}/{app}/builds

However, the equivalent API URL is invalid. It returns 404:
https://cloud.docker.com/v2/repositories/{account}/{app}/builds/

On the other hand, the following URL is a valid, but it is not listing the ongoing builds:
https://cloud.docker.com/v2/repositories/{account}/{app}/tags/

Overall, what I would like to do is to get, from the API, the list of images being built in DockerHub. How can I achieve that?

A: You can use this API to list the builds.
https://cloud.docker.com/v2/repositories/{account}/{app}/buildhistory/

Then append the build_code of a build to see the full detail.
https://cloud.docker.com/v2/repositories/{account}/{app}/buildhistory/{build_code}

I'm not aware of any official documentation for these endpoints. In the past I've used the following source code as a reference.
https://github.com/RyanTheAllmighty/Docker-Hub-API/blob/master/src/api.js


text:
Q: Apply a git patch to a file that has been modified internally? I would like to know if there is a method to apply a patch in a more "smart" way. I want to apply an old patch to a file where I have inserted new lines of code. Normally, in this situation "git apply" gives an error message. There is a way to solve this?
For instance:
I have an original file called test file.txt:
Test File

My favourite colour is : Green

Then , I make a git commit, and modify the file like this:
Test File

My favourite colour is : Orange

Again, I make a new commit, and create a patch file with git format-patch to the previous version. Let's call this file Orange-fix.patch
Now, I roll back to the first commit with git checkout
I modify again the test file file, so it looks like this:
Test Files

1 New line added
2 Other new line added

-- My favourite colour is : Green

If I try to apply the Orange-fix.patch to this file with git apply, I get a "error: testfile.txt: patch does not apply" error message, because new lines have been inserted.
Thanks


text:
Q: Jquery Get Textarea.val() with newlines I need to get the text entered into textarea and detect newlines (preferably
). I traced it until serverside and am sure that there are newlines because I'm printing the value with .val(). On serverside, I access to the same controls value and I see no newlines. I'm starting to think that '\n's don't appear on server side. I really don't want to replace all newlines with a character.
Any ideas?
Thanks

A: This is what I did to get NewLines in the server side:
string TextAreaText = txt.InnerHtml;
string ReplacedText = TextAreaText.Replace(System.Environment.NewLine, "
");
Response.Write(ReplacedText);

Sorry for the bad format. I am very new here and am not good at formatting code. Hopefully it helps.
Hanlet

A: I could guess that, if you try to render a textarea with nice format, you can see it with newline charater
<textarea>
</textarea>

So you just use: <textarea></textarea>.


text:
Q: How to include Authorization header in cURL POST HTTP Request in PHP? I'm trying to access mails of a user through Gmails OAuth 2.0, and I'm figuring this out through Google's OAuth 2.0 Playground
Here, they've specified I need to send this as a HTTP REQUEST:
POST /mail/feed/atom/ HTTP/1.1
Host: mail.google.com
Content-length: 0
Content-type: application/json
Authorization: OAuth SomeHugeOAuthaccess_tokenThatIReceivedAsAString

I've tried writing a code to send this REQUEST like this:
$crl = curl_init();
$header[] = 'Content-length: 0
Content-type: application/json';

curl_setopt($crl, CURLOPT_HTTPHEADER, $header);
curl_setopt($crl, CURLOPT_POST,       true);
curl_setopt($crl, CURLOPT_POSTFIELDS, urlencode($accesstoken));

$rest = curl_exec($crl);

print_r($rest);

Not working, please help. :)
UPDATE: I took Jason McCreary's advice and now my code looks like this:
$crl = curl_init();

$headr = array();
$headr[] = 'Content-length: 0';
$headr[] = 'Content-type: application/json';
$headr[] = 'Authorization: OAuth '.$accesstoken;

curl_setopt($crl, CURLOPT_HTTPHEADER,$headr);
curl_setopt($crl, CURLOPT_POST,true);
$rest = curl_exec($crl);

curl_close($crl);

print_r($rest);

But I'm not getting any output out of this. I think cURL is silently failing somewhere. Please do help. :)
UPDATE 2: NomikOS's trick did it for me. :) :) :) Thank you!!

A: You have most of the code…
CURLOPT_HTTPHEADER for curl_setopt() takes an array with each header as an element. You have one element with multiple headers.
You also need to add the Authorization header to your $header array.
$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: OAuth SomeHugeOAuthaccess_tokenThatIReceivedAsAString';

A: @jason-mccreary is totally right. Besides I recommend you this code to get more info in case of malfunction:
$rest = curl_exec($crl);

if ($rest === false)
{
    // throw new Exception('Curl error: ' . curl_error($crl));
    print_r('Curl error: ' . curl_error($crl));
}

curl_close($crl);
print_r($rest);

EDIT 1
To debug you can set CURLOPT_HEADER to true to check HTTP response with firebug::net or similar.
curl_setopt($crl, CURLOPT_HEADER, true);

EDIT 2
About Curl error: SSL certificate problem, verify that the CA cert is OK try adding this headers (just to debug, in a production enviroment you should keep these options in true):
curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);

A: use "Content-type: application/x-www-form-urlencoded" instead of "application/json"


text:
Q: Comparing the fit of Tweedie and gamma hurdle models I am comparing several modeling approaches to semi-continuous data (many exact zeros and continuous positive cost outcomes) to assess the effect of the main predictor "disease" on cost.
The models I'm comparing are a Tweedie model and a gamma hurdle model.
The Tweedie model is in the form:
glm(cost ~ disease + age + gender + offset(log(days_in_study)), data = df, family = tweedie(link.power = 0, var.power = xi.max)
The hurdle model is in the form:
binary component:
glm(cost ~ disease + age + gender + offset(days_in_study), data = df, family = "binomial")
continuous component:
glm(cost ~ disease + age + gender + offset(log(days_in_study)), data = subset(data, cost > 0), family = Gamma(link = "log"))
How do I compare these models to choose between them? The Tweedie model indicates that the variable "disease" is strongly predictive of costs. The hurdle model indicates that it is not. So while I know no model is per se "right," my choice of model determines the entire outcome. Common measures like the AIC don't seem to be well-defined for two-part models, per various CrossValidated posts.


text:
Q: How to combine textbox with image when sending mail in c#? I want to send mail with text which have size, font, position and else, but also want to include signature which is of course image. So I try to use this code
    string htmlBody = "
This is simple text.

";
    AlternateView avHtml = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);

    // Create a LinkedResource object for each embedded image
            LinkedResource pic1 = new LinkedResource("C:\\Users\\Admin\\Pictures\\a.jpg", MediaTypeNames.Image.Jpeg);
            pic1.ContentId = "Pic1";
            avHtml.LinkedResources.Add(pic1);

            mail.AlternateViews.Add(avHtml);

            mail.IsBodyHtml = true;

but it's working only with simple text.
How to send mail which get text from textbox or pasted text from word and also include signature?


text:
Q: Does anybody know what means ShellHook message HSHELL_RUDEAPPACTIVATED? I am writing application which establishes shell hooks to get shell events (I am using C# if it matters).
I am using this example: http://msbob.spaces.live.com/blog/cns!DAFD19BC5D669D8F!132.entry
Hook is working fine but I do not receive message on which I am interested: HSHELL_WINDOWACTIVATED (all other window-related events work well).
Instead I am receiving message with code 32772 which should be HSHELL_RUDEAPPACTIVATED (some googling helped).
But I can't understand why I am not receiving HSHELL_WINDOWACTIVATED at all and what this HSHELL_RUDEAPPACTIVATED message means. MSDN does not have any mention of it.
Can anybody explain it to me?

A: HSHELL_RUDEAPPACTIVATED is 32772, which is just HSHELL_WINDOWACTIVATED with the high bit set.  From what little I can glean on various Web sites, it appears that Windows sends this message when a full screen app is activated.  Kind of hard to tell for sure.
Have you tried treating that message the same as `HSHELL_WINDOWACTIVATED'?


text:
Q: How to match multiple lines words using regex expression As title describled,I want to match multiple lines words with regex expression begin with "No" and end with "e".Here is the sample below:
Special Instructions
No
t fo
r c
us
tom
er
sig
na
tur
e
Table Of Contents
Customer Details 1
Site Details 2
Tom Tom Sales B.V. German Branch 2
Dynamic Bandwidth 6
Billing Details 7
What I really want is like this:
Special Instructions

Table Of Contents
Customer Details 1
Site Details 2
Tom Tom Sales B.V. German Branch 2
Dynamic Bandwidth 6
Billing Details 7
Any help will be appreciated.

A: You can use this pattern with multiline and singleline options:
@"^No\r?\n.*?^e\r?\n"

example:
Regex rgx = new Regex(@"^No\r?\n.*?^e\r?\n",
      RegexOptions.Multiline|RegexOptions.Singleline);
string result = rgx.Replace(yourstr, "");

pattern description:
^        # anchor for the start of the line (because the multiline option is
         # used, otherwise ^ is an anchor for the start of the string)
No
\r?\n    # an optional carriage return and a line feed
.*?      # all characters zero or more times (the dot can match newlines since
         # the singleline option is used, the dot can't match newlines with the
         # default behavior)
^        # anchor for the start of the line
e        #
\r?\n    # if you want to preserve the last CRLF you could replace this with $
         # ($ is an anchor for the end of the line in multiline mode, in default
         # mode, $ means "end of the string")


text:
Q: C# start program with arguments containing strings I want to start a program using this code:
private void PBox_Banner_Click(object sender, EventArgs e)
{
    string JavaPath = @"C:\Program Files\Java\jre8\bin\javaw.exe";
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.FileName = JavaPath;
    startInfo.Arguments = @"-Xmx1024-jar "D:\Log4-cg.jar"";
    Process.Start(startInfo);
}

The problem is that I have to use a string within the argument string.
I am using Microsoft Visual Studio Express 2012 for Windows Desktop.

A: Doubling up on the quotes should fix it.
startInfo.Arguments = @"-Xmx1024-jar ""D:\Log4-cg.jar""";

A: If David's solution doesn't work, the old-school fallback should:
startInfo.Arguments = "-Xmx1024-jar \"D:\\Log4-cg.jar\"";


text:
Q: Android Expressions in a String Hello I am developing a new feature of my app where I have to write a String parser.
I am still designing the solution and not sure what is the best approach for it.
Example :
         I can get a String looking like "!CALC(${value-1}*!CALC(${value-2}-{value-3}))"
The "!" sign indicates the beginning of a function and the  "&" sign indicates the beginning of a parameter.
As you can see I can also have a function call inside another function and the result of that function to be treated as a parameter afterwards.
I have already implemented the method for performing the CALC but I am still not a 100% sure how to properly parse the String. Any suggestions or examples will be highly appreciated.

A: Here is the code I wrote to parse a !CALC string. It works for the four basic operators. Note that I added a $ for every value. Where you wrote ${value-2}-{value-3}, I wrote ${value-2}-${value-3}. In the example in the code below, the result is 12*4-2. Only minor changes have to be made to the code to perform the calculation as well. Note: this only works for the CALC command. You can surely make improvements here.
private void parse()
{
    String expression = "!CALC($12*!CALC($4-$2))";
    String result = this.parseExpression(expression);
}

private String parseExpression(String expression)
{
    String[] parts = this.splitCalc(expression);
    String numberOne;
    String numberTwo;

    if(parts[0].startsWith("$"))
        numberOne = parts[0].substring(1);
    else
        numberOne = this.parseExpression(parts[0]);

    if(parts[2].startsWith("$"))
        numberTwo = parts[2].substring(1);
    else
        numberTwo = this.parseExpression(parts[2]);

    return numberOne+parts[1]+numberTwo;
}

//splits an expression in the form of !CALC(a*b) in ["a", "*", "b"]
private String[] splitCalc(String expression)
{
    expression = expression.substring(6, expression.length() - 1);
    String[] expressions = new String[3];

    if(expression.startsWith("$"))
    {
        int valueStopIndex = this.getValueStopIndex(expression, 0);
        expressions[0] = expression.substring(0, valueStopIndex);
        expressions[1] = expression.substring(valueStopIndex, valueStopIndex+1);
        expressions[2] = expression.substring(valueStopIndex+1);
    }
    else //starts with !CALC
    {
        int calcStopIndex = this.getCalcCloseIndex(expression, 6);
        expressions[0] = expression.substring(0, calcStopIndex);
        expressions[1] = expression.substring(calcStopIndex, calcStopIndex+1);
        expressions[2] = expression.substring(calcStopIndex+1);
    }

    return expressions;
}

//returns the index of the closing bracket ')'
private int getCalcCloseIndex(String fullExpression, int startIndex)
{
    int level = 0;

    char[] chars = fullExpression.toCharArray();
    for(int i = 0; i < chars.length; i++)
    {
        if(chars[i] == '(')
        {
            level++;
        }
        else if(chars[i] == ')')
        {
            level--;
            if(level == 0 && i >= startIndex)
                return i;
        }
    }

    return startIndex;
}

private int getValueStopIndex(String fullExpression, int startIndex)
{
    int firstOperatorIndex = fullExpression.length();
    int currentOperatorIndex = fullExpression.indexOf('+');
    if(currentOperatorIndex >= startIndex && currentOperatorIndex < firstOperatorIndex)
        firstOperatorIndex = currentOperatorIndex;
    currentOperatorIndex = fullExpression.indexOf('-');
    if(currentOperatorIndex >= startIndex && currentOperatorIndex < firstOperatorIndex)
        firstOperatorIndex = currentOperatorIndex;
    currentOperatorIndex = fullExpression.indexOf('*');
    if(currentOperatorIndex >= startIndex && currentOperatorIndex < firstOperatorIndex)
        firstOperatorIndex = currentOperatorIndex;
    currentOperatorIndex = fullExpression.indexOf('/');
    if(currentOperatorIndex >= startIndex && currentOperatorIndex < firstOperatorIndex)
        firstOperatorIndex = currentOperatorIndex;
    return firstOperatorIndex;
}


text:
Q: how to animate itemSize from UICollectionViewFlowLayout? I'm using a UICollectionView to display a set of graphics on several rows and columns. User can use pinchGesture to zoom in / zoom out.
When user zoom in the graph size increases and user zoom out the graph size decreases. To change the size of graph I'm just changing the property itemSize from UICollectionViewFlowLayout. It works great but I'm unable to animate the change with the following code:
    [UIView transitionWithView:self.theCollectionView
                  duration:0.5f
                   options:UIViewAnimationOptionCurveLinear
                animations:^() {
                    _theFlowLayout.itemSize = cellSize;
                }
                completion:nil];

Any idea how to animate this change?
Regards,
Sébastien.

A: You can use the collection view's performBatchUpdates method which will invalidate and re-query your layout, animating to any new values.
Something like this:
_theFlowLayout.itemSize = cellSize;
[self.theCollectionView performBatchUpdates:nil completion:nil];

You don't get to control the timing or curve of the animation, unfortunately.


text:
Q: Ruby/Rails: Circular dependency when including concern in ApplicationRecord I have a concern that creates a class macro that I want available for all the models in my Rails application. So I'm including it in ApplicationRecord. The code is as follows:
# application_record.rb

class ApplicationRecord < ActiveRecord::Base

  include ::TestConcern

end

# app/concerns/test_concern.rb

module TestConcern

  extend ActiveSupport::Concern

  class_methods do

    def some_class_macro_all_models_must_have

      User.some_class_instance_variable << self

    end

  end

  included do
    User.include(UserModule)
  end

  module UserModule

    def self.included(base)
      base.class_eval do

        def self.some_class_instance_variable
          @some_class_instance_variable ||= Set.new
        end

      end
    end

  end

end

As you can see, the class macro will actually interact with a class instance variable in the model User.
So that's why, on the included hook of the concern, I'm trying to class_eval the User model to have that class instance variable initialized. The plan was to do it like this because otherwise any model can be invoking the class macro BEFORE the class instance variable is initialized in the User model.
However, this errors out with Circular dependency detected while autoloading constant User. As far as I can understand, ApplicationRecord loads, it includes the module, the module included hooks is called, it references the User model, and so the User model is loaded, which inherits from ApplicationRecord (which didn't finish loading yet), so it causes the circular dependency.
How to avoid this circular dependency paradox, knowing that many models will invoke this class macro, and those classes might be loaded before the User class itself, so I can't even count on defining the some_class_instance_variable class method in the User model itself?

A: After giving it some extra thought, I decided to simply store the some_class_instance_variable in the concern itself, and since the model User also called the some_class_macro_all_models_must_have, I decided to include the UserModule when it was invoked, effectively eliminating both the circular dependency and the load order issue.
The real code is much more complex than this contrived example, but the end result was something like this:
module TestConcern

  def self.some_class_instance_variable
    @some_class_instance_variable ||= Set.new
  end

  extend ActiveSupport::Concern

  class_methods do

    def some_class_macro_all_models_must_have

      User.include(UserModule) if self == User

      TestConcern.some_class_instance_variable << self

    end

  end

  included do
  end

  module UserModule

    def self.included(base)
      base.class_eval do

        # Class macro invocations, class method and instance method definitions

      end
    end

  end

end


text:
Q: Is extending UIViewController to access the app delegate an antipattern? I'm using an API that recommends keeping its client in the app delegate and accessing it through there. If I extended UIViewController to make it easier to access the app delegate, is this any way an antipattern?
extension UIViewController {
    var appDelegate: AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }
}

class SomeViewController: UIViewController {
    ...
    appDelegate.someClient.someMethod()
    ...
}

By antipattern I mean that is it overkill to extend the entire UIViewController class for this simple convenience? Are there any negative impacts, overall, of extending classes like this? Does every view controller, even if it doesn't access the API, implicitly point to the app delegate now?

A:
If I extended UIViewController to make it easier to access the app
  delegate, is this any way an antipattern?
extension UIViewController {
    var appDelegate: AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }
}

No; quite the contrary. It is quite common to need to access the app delegate and cast it to its actual class so as to be able to access a property or call a method in the app delegate. If this might need to be done in multiple places, a computed property is the standard notation for providing a shorthand. (There is no need to use an extension for this purpose, but there's no harm in doing so, and there may be a notational advantage; for example, the extension can be located in the app delegate file.)

In a comment, you muse about the wisdom of extending UIViewController. I imagine you have, say, two view controllers that need to access the app delegate, and many others that do not.
Now, in the first place, that doesn't really change my answer. I can't see what harm it would do or how it is in any way an antipattern to give all your view controllers the ability to access the app delegate via a shortcut even if many of them never actually do so. All view controllers have the ability already to do lots of things that most of them will never actually do.
But let's say you feel otherwise. Then you could just implement appDelegate explicitly in each relevant view controller (at the cost of violating DRY).
Or (here's the cool part) you could declare a protocol and a protocol extension, and have only the relevant view controllers adopt it. So, here's your AppDelegate.swift file:
import UIKit

protocol AppDelegateAccesser {}
extension AppDelegateAccesser {
    var appDelegate: AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    // ....
}

Now let's say that only the MyViewController class actually needs to access the app delegate. Then you just say
extension MyViewController : AppDelegateAccesser {}

This injects appDelegate into MyViewController but no other class. So you would just do that for each view controller that needs to access the app delegate, and no others. I think that's a totally unnecessary exercise, as opposed to your original proposed solution, but it does solve the problem of injecting code only into some classes.

NOTE: In Swift 5 it will be legal to declare that only a UIViewController subclass may adopt this protocol. You might like that.

A: Put this function to AppDelegate file so you can access AppDelegate throughout your project.
class func shared() -> AppDelegate {
     return UIApplication.shared.delegate as! AppDelegate
}

You can use like :
AppDelegate.shared()


text:
Q: setText is not updating Here is the code and i want to setText the Array of Textview after the random Images selected.. its not updating the textVew.  I am passing Context and view to the constructor of this class of my other activity ? this is non activity class how to achieve the same?
public class DisplayObject {
    Random _randomGenerator = new Random();
    int hudDisplay[] = {
        R.id.HUD_Text_Element1,
        R.id.HUD_Text_Element2,
        R.id.HUD_Text_Element3,
        R.id.HUD_Text_Element4,
        R.id.HUD_Text_Element5,
        R.id.HUD_Text_Element6,
        R.id.HUD_Text_Element7
    };

    static View[] _hiddenObjects;
    int NO_OF_OBJECTS = 15;
    TextView[] _HudTextDisplay = new TextView[7];

    public HiddenObject(Context context, View v) {
        // TODO Auto-generated constructor stub

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View huddisplay = inflater.inflate(R.layout.gameplay, null);
        /*NO_OF_OBJECTS = context.getResources().getInteger(R.integer.NO_OF_OBJECTS_AVAILABLE_PER_LEVEL);*/
        _hiddenObjects = new View[NO_OF_OBJECTS];
        random();

        for (int i = 0; i < hudDisplay.length; ++i) {
            _HudTextDisplay[i] = (TextView) huddisplay.findViewById(hudDisplay[i]);
            _HudTextDisplay[i].setText(_hiddenObjects[i].getTag().toString());
        }
    }

    public void random() {
        List<Integer> generated = new ArrayList<Integer>();
        for (int i = 0; i < NO_OF_OBJECTS; ++i) {
            while (true) {
                Integer next = _randomGenerator.nextInt(GamePlayActivity._hiddenObjects.length);
                if (!generated.contains(next)) {
                    _hiddenObjects[i] = GamePlayActivity._hiddenObjects[next];
                    Log.d("Check", "Image is " + _hiddenObjects[i].getTag());

                    generated.add(next);
                    break;
                }
            }
        }
    }
}

how to setText the textview ?

A: for anyone who is having this problem, you may have to place your setText method inside this
    ((Activity) context).runOnUiThread(new Runnable() {
        @Override
        public void run() {
            ((EditText)editText).setText(text);
        }
    });

A: You should call postInvalidate() after setText(...), not in advance !
 ...
 _HudTextDisplay[i].setText(_hiddenObjects[i].getTag().toString());
 _HudTextDisplay[i].postInvalidate();
 ...


text:
Q: Resolving $c^2+c^2$ For a program I was making I needed to calculate the diagonal movement in a way that it would have the same speed as normal movement along the axis of the 2d world.
My approach was that $speed^2 = c^2 + c^2$. In this case speed would be 800, so I know that $6400 = c^2 + c^2$
How would I calculate c?

A: Ok,
$$
c=\frac{speed}{\sqrt2}.
$$


text:
Q: Is there a numerical overview over your XP progression? In Borderlands 2, you always have the XP bar and your current level right at the bottom of your screen. However, there's no numerical indication of my total amount of XP earned, XP needed for the next level and so on. I have checked all the ingame menues but can't seem to find any information/overview screen with this information. Is there an (ingame) way to see numerical values for your XP progression?
I know I can look up the amount of XP needed per level online, but I would like to know if it's shown anywhere ingame as well. The reason I'm asking is because since there's no indication about how much XP is needed for the next level, I have no idea how much any amount of XP I get from kills and missions is 'worth'. So is there anything I have overlooked?

A: In Borderlands 2, it is possible to view your experience in 2 places. The first is the large EXP bar that is at the very bottom of the HUD:

The other place to view your experience, and also the only place that will display the exact numerical amount, is on the left-most menu page, shown here:

The experience is represented as:

Total Experience Earned / Total Experience to Next Level

A: Its under the My Missions tab, at the bottom.  See this screenshot:


text:
Q: How to know when AVPlayerItem is playing I am having a problem with AVPlayerItem and AVQueuePlayer. Currently i have a lot of music files which are 1-2 sec long and a queue Player for playing them in sequence.
What I want is to know when a music file has just started playing and not when it has finished playing(via AVPlayerItemDidPlayToEndTimeNotification).
This is because i want to run a function when a new file is loaded and played.
My code:
 for (NSUInteger i = 0; i < [matchedAddr count]; i++)
{
    NSString *firstVideoPath = [[NSBundle mainBundle] pathForResource:[matchedAddr objectAtIndex:i] ofType:@"wav"];
    //NSLog(@"file %@",firstVideoPath);
    avitem=[AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:firstVideoPath]];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(currentItemIs:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:avitem];

    [filelist addObject:avitem];
}
 player = [AVQueuePlayer queuePlayerWithItems:filelist];
[player play];

- (void)currentItemIs:(NSNotification *)notification
{
    NSString *asd=[seqArray objectAtIndex:currentColor];
    currentColor=currentColor+1;
    AVPlayerItem *p = [notification object];
    [p seekToTime:kCMTimeZero];

    if([asd isEqual:@"1"])
    {
        [UIView animateWithDuration:0.01 animations:^{
           one.alpha = 0;
        } completion:^(BOOL finished) {

            [UIView animateWithDuration:0.01 animations:^{
               one.alpha = 1;
            }];
        }];
    }
}

As you can see,the currentItemIs void is called but it runs when the track has finished playing.I want to be called when the track is at the beginning.
EDIT:
Updated version of Winston's snippet:
NSString * const kStatusKey         = @"status";

        [avitem addObserver:self
                              forKeyPath:kStatusKey
                                 options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
                                 context:@"AVPlayerStatus"];
- (void)observeValueForKeyPath:(NSString *)path
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {

    if (context == @"AVPlayerStatus") {

        AVPlayerStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
        switch (status) {
            case AVPlayerStatusUnknown: {

            }
                break;

            case AVPlayerStatusReadyToPlay: {
                // audio will begin to play now.
                NSLog(@"PLAU");
                [self playa];
            }
                break;
        }
    }
}

A: First you need to register your AVPlayerItem as an observer:
[self.yourPlayerItem addObserver:self
                      forKeyPath:kStatus
                         options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
                         context:AVPlayerStatus];

Then on your player Key Value Observer method you need to check for AVPlayerStatusReadyToPlay status, like so:
- (void)observeValueForKeyPath:(NSString *)path
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {

     if (context == AVPlayerStatus) {

        AVPlayerStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
        switch (status) {
            case AVPlayerStatusUnknown: {

            }
            break;

            case AVPlayerStatusReadyToPlay: {
                // audio will begin to play now.
            }
            break;
   }
}

A: Following should work:
Observe the Player's State:
let playerItem: AVPlayerItem = AVPlayerItem(asset: videoPlusSubtitles, automaticallyLoadedAssetKeys: requiredAssetKeys)

playerItem.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [], context: nil)

player = AVPlayer(playerItem: playerItem)

Respond to a State Change:
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == #keyPath(AVPlayerItem.status) {
        let status: AVPlayerItem.Status

        if let statusNumber = change?[.newKey] as? NSNumber {
            status = AVPlayerItem.Status(rawValue: statusNumber.intValue)!
        } else {
            status = .unknown
        }

        // Switch over status value
        switch status {
        case .readyToPlay:
            print("Player item is ready to play.")
            break
        case .failed:
            print("Player item failed. See error")
            break
        case .unknown:
            print("Player item is not yet ready")
            break
        @unknown default:
            fatalError()
        }
    }
}


text:
Q: Using Hangfire, connection string given in Startup.cs throws Cannot attach file as database error I'm utilizing Hangfire in my ASP .Net MVC Web App, it had installed successfully. I'd like to use the same LocalDb to store queued jobs for Hangfire to dequeue and process as I've used to stored data. However I'm running into the below error when I provided its connectionString or name defined in Web.config in Startp.cs. I've had no trouble adding, deleting updating data in the same localDb before hangfire.
Cannot attach the file 'c:\users\jerry_dev\documents\visual studio 2013\Projects\Hangfire.Highlighter\Hangfire.Highlighter\App_Data\aspnet-Hangfire.Highlighter-20150113085546.mdf' as database 'aspnet-Hangfire.Highlighter-20150113085546'.

Startup.cs:

public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            app.UseHangfire(config =>
            {
                string hangfireConnectionString = @"Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Hangfire.Highlighter-20150113085546.mdf;Initial Catalog=aspnet-Hangfire.Highlighter-20150113085546;Integrated Security=True";
                config.UseSqlServerStorage(hangfireConnectionString);
                config.UseServer();
            });
        }

My project Solution is named "Hangfire.Highlighter"
Web.config:

<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Hangfire.Highlighter-20150113085546.mdf;Initial Catalog=aspnet-Hangfire.Highlighter-20150113085546;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

A: I too know this is old, but ran into this recently. Here is my fix:

*

*In Visual Studio, go to 'View -> SQL Server Object Explorer'

*Connect to the Data Source if it isn't already connected. In the example above it was '(LocalDb)\v11.0'

*Right click on 'Databases' -> 'Add New Database'

*Fill Database name = Ex: 'aspnet-Hangfire.Highlighter-20150113085546' or whatever you've named the database in the connection string.

*Fill Database location = This should be the Data Directory in your application, 'App_Data' for the MVC project.

This fixed the issue in my case.

A: I know this is old - but its been 9 months and I pulled my hair out over this as well - and decided to do a write-up on it here.
My solution was to just create a quick and dirty DbContext, point it to the proper connection string, and call Database.CreateIfNotExists in the constructor:
public class HangfireContext : DbContext
{
    public HangfireContext() : base("name=HangfireContext")
    {
        Database.SetInitializer<HangfireContext>(null);
        Database.CreateIfNotExists();
    }
}

In the HangfireBootstrapper.Start() method I do something like this:
public void Start()
{
    lock (_lockObject)
    {
        if (_started) return;
        _started = true;

        HostingEnvironment.RegisterObject(this);

        //This will create the DB if it doesn't exist
        var db = new HangfireContext();

        GlobalConfiguration.Configuration.UseSqlServerStorage("HangfireContext");

       // See the next section on why we set the ServerName
        var options = new BackgroundJobServerOptions()
        {
            ServerName = ConfigurationManager.AppSettings["HangfireServerName"]
        };

        _backgroundJobServer = new BackgroundJobServer(options);

        var jobStarter = DependencyResolver.Current.GetService<JobBootstrapper>();

        //See the Recurring Jobs + SimpleInjector section
        jobStarter.Bootstrap();

    }
}

Not sure why Hangfire has such a hard time with LocalDb - maybe it can only handle full-blown SQL instances? Either way this works for me, new team members, and new dev/staging/prod instances that get stood up.

A: Jack's answer didn't work for me, because I ran into this problem: No connection string named could be found in the application config file
I got it to work with the following modifications:

*

*Remove "name=" from the string in the base initializer. Thanks to: https://stackoverflow.com/a/37697318/2279059

*This moves the error to the call of UseSqlServerStorage. So instead of passing "HangfireContext" to it, I just copy the connection string from the dummy database context.

Complete setup code:
public class HangfireContext : DbContext
{
    public HangfireContext() : base("HangfireContext")  // Remove "name="
    {
        Database.SetInitializer<HangfireContext>(null);
        Database.CreateIfNotExists();
    }
}

public partial class Startup
{
    public static void ConfigureHangfire(IAppBuilder app)
    {
        var db = new HangfireContext();

        GlobalConfiguration.Configuration.UseSqlServerStorage(db.Database.Connection.ConnectionString);  // Copy connection string

        app.UseHangfireDashboard();
        app.UseHangfireServer();
    }
}

A: Is the DB already created? Can you try using a different conneciton string format?something like this,
"Server=.;Database=HangFire.Highlighter;Trusted_Connection=True;"

A: Answer as per AspNetCore 3.1 and Hangfire 1.7.17
Hangfire should create all the tables provided there is an existing database with the specified database name.
If you want to use LocalDb, you can use the following registrations (see below).
services
    .AddHangfire(
        (serviceProvider, config) =>
        {
            //read settings or hardcode connection string, but this is cleaner
            var configuration = serviceProvider.GetService<IConfiguration>();
            var connectionString = configuration.GetValue<string>("Hangfire:ConnectionString");
            var sqlServerStorageOptions =
               new SqlServerStorageOptions
               {
                    CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
                    SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
                    QueuePollInterval = TimeSpan.Zero,
                    UseRecommendedIsolationLevel = true,
                    DisableGlobalLocks = true
               };
            config
                .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                .UseSimpleAssemblyNameTypeSerializer()
                .UseRecommendedSerializerSettings();
                .UseSqlServerStorage(connectionString, sqlServerStorageOptions);
        });

The connection string is read, in my example, from the appsettings, so it'd look like this
"Hangfire": {
  "ConnectionString": "Data Source=(localdb)\\MsSqlLocalDb; Database=Hangfire;"
}

Again, notice how the connection string has the name of the database (e.g: Hangfire) that MUST exist in localdb. If you remove the Database=xxx parameter altogether, it'll pick the master database by default and create all the tables there.


text:
Q: Convert for loop from Java 7 to Java 8 (Lambda) Want to convert following for loop from Java 7 to Java 8 (lambda).
for (Employee e : list) {
    session.evict(e);
}

Here, session is Hibernate Session. My intention here is to change the above mentioned working java 7 code to Java 8 with feature of lambda or method reference.

A: You can switch the expression to method reference lambda:
list.forEach(session::evict);

Note that if Session.evict throws an Exception then you'll need to either trap / convert to RuntimeException in order for the above to compile, or use a longer form of lambda in the loop.
list.forEach(e -> {
    try {
        session.evict(e);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
});


text:
Q: How to create a metadata json member for an openlayers layers object and display in extjs grid? I want to do the following: add
metadata: "this is the layer metadata"

....to my openlayers layer config.
This should then be presented in an extjs grid. I can use
alert(layername.metadata);

to display the string inside the config member so I know it works.
To display this in the extjs grid I have used the following code
var myData = [];
var x=mapPanel.map.layers;
for (var i=0; i<x.length; i++) {
  // alert(mapPanel.map.layers[i].metadata);
    myData.push(mapPanel.map.layers[i].metadata);
}

var store = new Ext.data.ArrayStore({
        fields: [
           {name: 'metadata'}
        ]
        });

store.loadData(myData);

var myStore = new GeoExt.data.LayerStore({
    map: map,
    layers: mapPanel.layers
});

var grid = new Ext.grid.GridPanel({
        title: "Available Map Layers",
        region: "center",
        height: 300,
        viewConfig: {forceFit: true},
        store: store,
        columns: [
            {
                header: "metadata",
                dataIndex: "metadata",
                sortable: true
            }
        ]
    });

var metadataWin = new Ext.Window({
                title: "Map layers",
                layout: 'fit',
                width: '600',
                height: 'auto',
                border: false,
                closable: true,
                collapsible: true,
                x: 450,
                y: 100,
                resizable: true,
                closeAction: 'hide',
                plain: true,
                items: [grid]
           });
    metadataWin.show();

the grid show the correct amount of rows, but only the first letter is shown....this is probably a newbie javascript error.
Can anyone see where i´m going wrong?
yours,
Rob

A: i have done adding this metadata with this following code:
var vectorLayer = new OpenLayers.Layer.Vector("Building", {
    stylemap: styles,
    visibility: false,
    rangeOfZoom: '9-12',
    metadata: 'write What you Want'
});

map.addLayer(vectorLayer);

and you can reach all layer's metadata as ...:
var layers = map.layers;
for(var a = 0; a < layers.length; a++){
   alert(layers[a].metadata)
};

i hope it helps you


text:
Q: How to create view db2/iseries with not default permissions? Everytime I create a new view I have to change the permissions to all, and it's quite painfully to do a lot of times the same thing.
I also ask if is possible to change some default options in the database I create the view in order the permissions to be set to public.
Thanks

A: It sounds like you are using SQL naming.  Use System naming instead, this will grant public authority according to the QCRTAUT system value.  See Birgitta Hauser's article.
System naming has the added advantage of using the job's library list to resolve unqualified object references.  By not hard-coding schema names, but allowing the system to find them according to the library list, enabling your code to work in different environments (ex. development, testing, training, production) without modifying the code, simply by running with a different library list.  Therefore you can install code into production exactly the same code that was tested.

A: The following is from the V6R1 documentation:
Authorization

The privileges held by the authorization ID of the statement must
  include at least one of the following:
The privilege to create in the schema. For more information, see
  Privileges necessary to create in a schema.
Administrative authority
The privileges held by the authorization ID of the statement must
  include at least one of the following:
The following system authorities:   *USE to the Create Logical File
  (CRTLF) CL command   *CHANGE to the data dictionary if the library
  into which the view is created is an SQL schema with a data dictionary
  Administrative authority
The privileges held by the authorization ID of the statement must also
  include at least one of the following:
For each table and view referenced directly through the fullselect,
  or indirectly through views referenced in the fullselect:   The SELECT
  privilege on the table or view, and   The system authority *EXECUTE on
  the library containing the table or view   Administrative authority

View ownership: If SQL names were specified:

If a user profile with the same name as the schema into which the
  view is created exists, the owner of the view is that user profile.
  Otherwise, the owner of the view is the user profile or group user
  profile of the job executing the statement.
If system names were specified, the owner of the view is the user
  profile or group user profile of the job executing the statement.

View authority:

If SQL names are used, views are created with the system authority of
  *EXCLUDE on *PUBLIC. If system names are used, views are created with the authority to *PUBLIC as determined by the create authority
  (CRTAUT) parameter of the schema.
If the owner of the view is a member of a group profile (GRPPRF
  keyword) and group authority is specified (GRPAUT keyword), that group
  profile will also have authority to the view.
The owner always acquires the SELECT privilege WITH GRANT OPTION on
  the view and the authorization to drop the view.
The owner can also acquire the INSERT, UPDATE, and DELETE privileges
  on the view. If the view is not read-only, then the same privileges
  will be acquired on the new view as the owner has on the table or view
  identified in the first FROM clause of the fullselect. These
  privileges can be granted only if the privileges from which they are
  derived can also be granted.


text:
Q: Terms in a geometric sequence Find the maximum number of terms in a strictly increasing geometric sequence, where each term is an integer between $100$ and $1000$ (inclusive). I tried making many cases but it didn't help.

A: Proof there is no sequence of length $7$:
Let $\frac{p}{q}$ be the ratio with $(p,q)=1$ and $a_0=b$ . Then $a_6=\frac{bp^6}{q^6}$ Hence $q^6|b$.
Since the only numbers in $[100,1000]$ which are divisible by a sixth power are $2^7,2^8,2^9$ We must have that $b$ is equal to one of these. And therefore $q$ must be a power of $2$. However if $q=2^k$ with $k\geq 2 $ then $(2^{k})^6=2^{6k}$ will not divide $b$. So if we want for the sequence to have more than six terms we must have $q=2$.
From here $p\geq 3$ and therefore $a_6\geq 2^7\frac{3^6}{2^6}=2\cdot3^6>1000$.
Therefore no sucession of length $7$ exists and $6$ is indeed the max.

A: While trying to optimize number of terms in sequence you desire by keeping the common ratio quite small, as well as keep all of the terms an integer between 100 and 1000, you need a first term which is quite small, and which will result in only integer values between 100 and 1000. I can just think of r=3/2 and starting term to be 128, as $2^7 = 128$, meaning it will only result in integer values between 100 and 1000 (As it has 7 twos in its prime factorisation).
So I think 128, 192, 288, 432, 648, 972 is the longest geometric sequence; 6 terms
In fact, since 2 is the smallest integer factor besides one, the starting term $2^7$ will yield most terms for the common ratio (Which again has 3/2, smallest integer factors for denominator and numerator respectively (Because we wish to optimise the number of terms in the sequence and keep the denominator a factor capable of resulting in only integer values between 100 and 1000)). So I have more assurance now that this is the correct answer...


text:
Q: App.config patches/updates How can I patch a user's App.config properly when performing an upgrade?
Overwriting the old file is problematic as configuration changes are lost, however, if new values are added / old ones are changed, I can't just keep the old one.

A: Well, it depends how you are processing the upgrade process and how well you have designed and planned in advanced for minor/major version upgrades. There's no real rocket science behind it as one of the comments stated, you are just dealing with xml files. Moreover, there's a well-designed built-in API in the .NET Framework that allows developers to deal with config files...residing in the System.Configuration namespace.
Now, I've done this in the past (the old school way...I don't think much has changed) when I was doing desktop development...I had a web service running somewhere with two endpoints that exposed the latest version of the application and another one that exposed a packaged version of the latest application installer, the application installed on the end-user's desktop would call this service every time the user starts the application, if an upgrade was available the application would start a separate process (the updater) that would handle the version migration and installation. This would take care of all settings migration including config file, local storage (if any), etc.
I'm not claiming it is the best solution or anything, but it gives you a lot of flexibility and control over the process and most importantly it works. That's exactly the same process many big software company follow. But, it does require a bit of planning.

A: The solution I've used now is just apply machine specific settings to user.config. Works perfectly!


text:
Q: I am trying to develop a specific adapter for sqlite3 with node.js This is similar sails-mysql as devised. I do not know how to start OracleDialect.prototype.describe = function (connection, collection, callback) {

    var tableName = this.normalizeTableName(collection.tableName);
    var queries = [];
    queries[0] = "SELECT COLUMN_NAME, DATA_TYPE, NULLABLE FROM USER_TAB_COLUMNS WHERE TABLE_NAME = '" + tableName + "'";
    queries[1] = "SELECT index_name,COLUMN_NAME FROM user_ind_columns WHERE table_name = '" + tableName + "'";
    queries[2] = "SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner "
            + "FROM all_constraints cons, all_cons_columns cols WHERE cols.table_name = '" + tableName
            + "' AND cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner "
            + "ORDER BY cols.table_name, cols.position";

    asynk.each(queries, function (query, nextQuery) {
        connection.client.raw(query).asCallback(nextQuery);
    }).serie().done(function (results) {
      var schema = results[0];
      var indexes = results[1];
      var tablePrimaryKeys = results[2];
      if (schema.length === 0) {
        return callback({code: 'ER_NO_SUCH_TABLE', message: 'Table ' + tableName + ' doesn\'t exist.'}, null);
      }
      // Loop through Schema and attach extra attributes
      schema.forEach(function (attribute) {
          tablePrimaryKeys.forEach(function (pk) {
              // Set Primary Key Attribute
              if (attribute.COLUMN_NAME === pk.COLUMN_NAME) {
                  attribute.primaryKey = true;
                  // If also a number set auto increment attribute
                  if (attribute.DATA_TYPE === 'NUMBER') {
                      attribute.autoIncrement = true;
                  }
              }
          });
          // Set Unique Attribute
          if (attribute.NULLABLE === 'N') {
              attribute.required = true;
          }

      });
      // Loop Through Indexes and Add Properties
      indexes.forEach(function (index) {
          schema.forEach(function (attribute) {
              if (attribute.COLUMN_NAME === index.COLUMN_NAME)
              {
                  attribute.indexed = true;
              }
          });
      });
      //console.log("describe schema: ",schema);
      callback(null, schema);
    }).fail(function(err) {
      return callback(err, null);
    });
};

I hope all my questions can be answered with a link to a good documentation!
Thank you!
I hope all my questions can be answered with a link to a good documentation!
this is for orcale adapter


text:
Q: json data fields and php json functions Seems I cannot use JSON inside MYSQL tables - there is no such an option when choosing data type for a field - phpMyAdmin ver 4.8.3.
Question - if I use php functions json_encode and json_decode to get and set values inside varchar or text field - do I need JSON fields at all?

A: You can store you JSON Object as a string in a string field or you can use it in a field which hold data of JSON type
This is valide with MySQL version 8
Advantage

*

*The Advantage with this type is that It perform automatic validation of JSON documents stored in JSON columns and invalid documents produce an error.

*Optimized storage format. JSON documents stored in JSON columns are converted to an internal format that permits quick read access to document elements

You can read the entire documentation here The JSON Data Type
The Cons
If you choose to use a VARCHAR OR TEXT field to store you JSON data as a String, It's up to you to parse the Data correctly after you have retrieve It from the database for that to behave like a correct JSON object

A: Yes you do, unless you don't want to perform searches on the key-values of those json strings. MySQL Json Type allows you to do that, apart from storing the json in an efficient way.
You could use a blob or a text  type. Varchar is too short for a json, unless you have jsons that are less than 255 chars long.
A blob could be a good idea. You can map that to a resource in php (not loading the whole file into memory) and then use a json stream parser like this one to read the contents of your file.
But again, storing a json as a string will not allow you to query in an efficient way using your json data.

NOTE: Mysql supports the Json Type from 5.7.8. PhpMyAdmin is another piece of software. If your json type is not there, is probably because of your MySQL version. Run mysql -V in your terminal to check.

A: As per the official documentation

As of MySQL 5.7.8, MySQL supports a native JSON data type defined by RFC 7159 that enables efficient access to data in JSON (JavaScript Object Notation) documents.

Check your MySQL version to find out if it supports JSON datatype.
An answer to your question:
You can json_encode your data and store it in a text field. After retrieving it from the database table, do ajson_decode.


text:
Q: In django, what is the optimal way to access data in a OnetoMany relationship to output to template? I'm working in django and my objective is to output to a template a table consisting of all my customers and a corresponding amount equal to the total amount they have spent.
I have the classes/models Customers and Transactions with a OneToMany relationship. Every time a customer makes a purchase, the transaction is recorded as is the amount they spent (tx_amount). I have the following set a code that works but I believe is not optimal since its running in O(x * y) time, i.e., running a full loop over Transactions for every customer.
Q1: What is the optimal way for accomplishing this task?
When I originally tried to get my template to work, instead of using local_customer, I was using setattr(customer[x],"value",tx_amount) which worked in the django shell but did not work in the template. My workaround was to create a local class which I would use to population my context variable.
Q2: When combining data models to output in a template, is it necessary to use some sort of local class like my local_customer implementation below or is there a better way?
Pseudo-code below:
models.py:
class Customers(models.Model):
    name = models.CharField(max_length=70)
    def __str__(self):
        return self.name

class Transactions(models.Model):
    customers = models.ForeignKey(Customers, on_delete=models.CASCADE)
    tx_amount = models.DecimalField(max_digits=9, decimal_places=2

views.py:
class Local_Customer:
    name = ""
    total_spent = 0

    def __str__(self, name):
        self.name = name

def customer_view(request):

    customer = Customers.objects.all()
    customer_context = [] # list of objects we'll pass to render

    for x in range(len(customer)):
        local_customer = Local_Customer(customer[x].name)
        customer_txs = Transactions.objects.filter(customer__name=customer[x])

        for y in customer_txs:
            local_customer.total_spent += y.tx_amount
        customer_context.append(local_customer)

     context = {'customers' : customer_context}

    html_template = loader.get_template( load_template )
    return HttpResponse(html_template.render(context, request))

template.html:
{% for customer in customers %}
    {{customer.name}}
    {{customer.total_spent}}
{% endfor %}

A: You can .annotate(…) [Django-doc] to do this at the database side:
from django.db.models import Sum
from django.shortcuts import render

def customer_view(request):
    customers = Customers.objects.annotate(
        total_spent=Sum('transactions__tx_amount')
    )
    context = {'customers' : customers}
    return render(request, load_template, context)
This will thus generate a query that looks like:
SELECT customers.*, SUM(transactions.tx_amount) AS total_spent
FROM customers
LEFT OUTER JOIN transactions ON transactions.customers_id = customers.id
and thus fetches all data in a single query.
If there are no transactions, total_spent will be None (NULL), not 0, you can use Coalesce [Django-doc] to use zero instead:
from django.db.models import Sum, Value
from django.db.models.functions import Coalesce
from django.shortcuts import render

def customer_view(request):
    customers = Customers.objects.annotate(
        total_spent=Coalesce(Sum('transactions__tx_amount'), Value(0))
    )
    context = {'customers' : customers}
    return render(request, load_template, context)


text:
Q: content security policy (csp) issue for subdomain with nginx as reverse proxy and node express as backand I have an issue with content security policy headers. Scripts and styles are blocked.
It seams that nginx is overloading my express headers.
I tried a lot and my last state is this.
nginx server block
...
location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_cache_bypass $http_upgrade;

    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_set_header x-real-ip $remote_addr;
    proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Host  $host;
    proxy_set_header X-Forwarded-Port  $server_port;
}
....

express setup (domain name is changed to example.com)
const express = require('express');
const lusca = require('lusca');
const app = express();
...
app.use(lusca.xframe('SAMEORIGIN'));
app.use(lusca.xssProtection(true));
app.use(
  lusca.csp({
    policy: {
      "default-src": "'self' *.example.com",
      "img-src": "*"
    }
  })
);
...

In the browser console I get this:
content security policy the page's settings blocked the loading of a resource at ("default-src")
content security policy the page's settings blocked the loading of a resource at ("script-src")
content security policy the page's settings blocked the loading of a resource at ("style-src")

In broswsers answer field (csp is twice!):
content-security-policy: default-src 'self' *.example.com; img-src *
content-security-policy: default-src 'none'; frame-ancestors 'none'; script-src 'self'; img-src 'self'; style-src 'self'; base-uri 'self'; form-action 'self';

Does anyone have an idea why this configuration is not working? Or how to tell nginx to use express's headers and hold down the own?

A: I solved it by adding proxy_pass_header to the nginx server block:
location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_cache_bypass $http_upgrade;

    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_set_header x-real-ip $remote_addr;
    proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Host  $host;
    proxy_set_header X-Forwarded-Port  $server_port;

    // THIS DIRECTIVE SOLVED IT
    proxy_pass_header content-security-policy;
}


text:
Q: Puppeteer Not Finding Element iframe A form is embedded within an iframe. I am trying to use puppeteer to fill out the form. I can select most of the fields in the form but cannot select the submit button.
await page.waitForSelector("iframe");
const iframeElement = await page.$('iframe');
const frame = await iframeElement.contentFrame();
await frame.waitForSelector('#input_4'); //picks up the appropriate element
await frame.waitForSelector('button#input_2.form-submit-button.submit-button.jf-form-buttons.jsTest-submitField');//does not pick up the element

I have attached a link to the screenshot of the DOM showing where the button is in reference to the iframe.
Can anyone help? Much appreciated.
DOM

A: It seems you are using the selector incorrectly.
❌ Wrong usage:
Do not include tag name, id and all CSS classes without any separator between them, especially do not use them at the same time if they are all describing the very same element.
await frame.waitForSelector(button#input_2.form-submit-button.submit-button.jf-form-buttons.jsTest-submitField);

(Or you can separate them by commas like: #input_2, .form-submit-button, .submit-button, .jf-form-buttons, .jsTest-submitField. But it is very rare you need to go this way.)
✅ Correct usage:
You are good with the id, it identifies inside frame the element you are looking for.
await frame.waitForSelector('#input_2');

Did you know? If you right click on an element in Chrome DevTools "Elements" tab and you select "Copy": you are able to copy the exact selector or xpath of an element. After that you can switch to the "Console" tab and with the Chrome api you are able to test the selector's content, so you can prepare it for your puppeteer script. E.g.: $('#input_2').textContent should show the text of the button that you've expected to click on, otherwise you need to change on the access, or you need to check if there are more elments with the same selector etc. This may helps you to find more appropriate selectors.


text:
Q: Android studio multi var return value for url I want make url in android studio.
When I make multi var, I can see wrong word in emulate.
Below is source code.
content[i] has number and title[i] has text.
"content[1] = 1 content[2] = 2 content[3] = 3..."
"title[1] = test1 title[2] = test2 title[3] = test3..."
 for (int i = 0; i < nodeList.getLength(); i++) {

            Node node = nodeList.item(i);

            dist[i] = new TextView(this);
            contentid[i] = new TextView(this);
            title[i] = new TextView(this);

            Element fstElmnt = (Element) node;

            NodeList distList = fstElmnt.getElementsByTagName("dist");
            Element distElement = (Element) distList.item(0);
            distList = distElement.getChildNodes();

            NodeList contentidList = fstElmnt.getElementsByTagName("contentid");
            Element contentidElement = (Element) contentidList.item(0);
            contentidList = contentidElement.getChildNodes();
            contentid[i].setText(((Node) contentidList.item(0)).getNodeValue());

            NodeList titleList = fstElmnt.getElementsByTagName("title");
            Element titleElement = (Element) titleList.item(0);
            titleList = titleElement.getChildNodes();
            title[i].setText("TITLE = "
                    + ((Node) titleList.item(0)).getNodeValue() + ((Node) distList.item(0)).getNodeValue());

            title[i].setClickable(true);
            title[i].setMovementMethod(LinkMovementMethod.getInstance());

            String URL_ANSWER = "" + title[i] + "";
            title[i].setText(Html.fromHtml(URL_ANSWER));

            // addView is best used with setting LayoutParams.
            // eg addView(view, layoutParams). The following is for simplicity.

            layout.addView(title[i]);

        }

A: You're including your TextView on the url, try like this:
String URL_ANSWER = "" +"";