text:
Q: swift change theme using delegate and protocol on many view controller I'm trying to use delegate and protocol first time.
I want to change the theme across many view controller.
Then on any controller which has protocol to change theme
When I go to this controller now I expect theme to be new but is old.
I do not go from theme controller to where them has changed

My code
protocol ThemeDelegate: class {
    func changeTheme(theme: UIColor)
}

class FirstController: UICollectionViewController, UICollectionViewDelegateFlowLayout, ThemeDelegate {

    var newTheme: UIColor  = .red

    func changeTheme(theme: UIColor) {
        newTheme = theme
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = newTheme
    }
}

ThemeController {

    weak var themeDelegate: ThemeDelegate?

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let theme = .blue
        themeDelegate?.changeTheme(theme: theme)
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: themeCellId, for: indexPath) as! ThemeCell
        cell.themeImageView.image = UIImage(named: "theme cell image")
        return cell
    }
}

this is order
image2

A: I'll try to make it simple:-
1) First, declare a protocol:-
protocol ThemeDelegate{
    func changeTheme(theme: String, fontColor: UIColor, alpha: CGFloat)
}

2) Have a variable of that protocol in your ThemeController:
open var themeDelegate: ThemeDelegate? = nil

3) Call the delegate functions through themeDelegate:- (you've done this right till this step)
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    themeDelegate?.changeTheme(theme: theme, fontColor: fontColor, alpha: alpha)
}

4) You need to conform your AnyController as the delegate, like yourThemeControllerInstance.delegate = self and you've done that as well.
It doesn't work because you've declared a new instance of ThemeController and have conformed AnyController to be the delegate of that new instance which supposedly has the same old theme:
override func viewDidLoad() {
    let themeController = ThemeController() // This is a new instance which you have created, so gets initialised with old theme. You have made your class to be the delegate of this instance
    themeController.themeDelegate = self
}

In order for your delegate to work as expected, you need the same instance of ThemeController where you change your theme

A: You can set delegate but careful view needs a be load.
You do this also with notifications and send all viewControllers with conforms Theme
1 - Your Step
import UIKit

protocol ThemeDelegate: class {
    func changeTheme(theme: String, fontColor: UIColor, alpha: CGFloat)
}

class ThemeController: UIViewController {

    weak var themeDelegate: ThemeDelegate?

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        themeDelegate?.changeTheme(theme: theme, fontColor: fontColor, alpha: alpha)
    }

}

class XViewController: UIViewController {

    // Create an instance
    lazy var themeController = ThemeController()

    override func viewDidLoad() {
        super.viewDidLoad()

        // We need call loadView becase collectionView needs to be show
        themeController.loadView()
        themeController.themeDelegate = self

    }

}
extension XViewController: ThemeDelegate {
    // And we conform ThemeDelegate
    func changeTheme(theme: String, fontColor: UIColor, alpha: CGFloat) {
        // TODO UI
    }
}

2 - Observer Step
// Sometimes we need update multiple viewControllers and we should use notification and observers

// We create a model
struct Theme {
    let theme: String
    let fontColor: UIColor
    let alpha: CGFloat
}

// We need a protocol for we don't want all view controller listen theme
protocol Themeable: class {
    func listenTheme()
    func didThemeChange(theme: Theme)
}

// Global notification name
let themeableNotificationName = Notification.Name(rawValue: "ThemeableNotification")

// Our protocol extension and observer notification
extension Themeable where Self: UIViewController {
    func listenTheme() {
        NotificationCenter.default.addObserver(forName: themeableNotificationName, object: nil, queue: nil) { [weak self] notification in
            guard let theme = notification.object as? Theme else { return }
            self?.didThemeChange(theme: theme)
        }
    }

}

// Notification sender themeController
class NotifyThemeController: UIViewController {

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // Create a model and post
        NotificationCenter.default.post(name: themeableNotificationName, object: Theme(theme: "Lorem", fontColor: .red, alpha: 1.0), userInfo: nil)
    }

}

// YViewController
class YViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // We need call this method for observer
        listenTheme()
    }

}
// YViewController conforms Themeable
extension YViewController: Themeable {
    func didThemeChange(theme: Theme) {
        // TODO UI
    }

}
// ZViewController
class ZViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // We need call this method for observer
        listenTheme()
    }

}
// ZViewController conforms Themeable
extension ZViewController: Themeable {
    func didThemeChange(theme: Theme) {
        // TODO UI
    }

}

Have Fun!


text:
Q: How to Use Memcache with Javascript? I have web application of which major part is javascript.
I request images from the disk and rendered on the UI, it is a kind of ebook reader application. For every page of ebook I have corresponding image saved on the disk.
No my application has performance hit, it has very high disk io specifically disk read operation. To improve disk read operation, I am planning to use memcache.
So now i wanted to use memcache with by javascript calls to fetch images from memcache rather from disk. Guide me through this...
Thanks

A: Suppose your javascript is being used at browser-side, then you have to write some http server-side code to wrap image getting operation. Modifying only javascript code will do nothing.
For example, originally you request http://example.com/ebook1/page1.jpg, you should change it to http://example.com/ebook1/get_page.php?page=1(suppose you implement it in php), and use memcache inside that php.
For server-side js, there are several memcache lib built on node.js

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# compare two strings for matching words I have two strings containing letters and numbers separated by spaces. ex
"elza7ma wa2fa fel matab" and "2ana ba7eb el za7ma 2awy 2awy"
What is the fastest way to compare this two string to find out whether or not they have a word in common?
I tried to split one of them using string.split and use string.compare on the whole array of words. but this is very slow since I will be comparing a lot of strings.

A: I think the easiest way is to break up the strings into words and use a set structure like HashSet<string> to check for duplicates.  For example
public bool HasMatchingWord(string left, string right) {
  var hashSet = new HashSet<string>(
    left.Split(" ", StringSplitOptions.RemoveEmptyEntries));
  return right
    .Split(" ", StringSplitOptions.RemoveEmptyEntries)
    .Any(x => hashSet.Contains(x));
}

A: A LINQ solution
"elza7ma wa2fa fel matab".Split()
                         .Intersect("2ana ba7eb el za7ma 2awy 2awy".Split())
                         .Any();

// as a string extension method
public static class StringExtensions
{
    public static bool OneWordMatches(this string theString, string otherString)
    {
        return theString.Split().Intersect(otherString.Split()).Any();
    }
}

// returns true
"elza7ma wa2fa fel matab 2ana".OneWordMatches("2ana ba7eb el za7ma 2awy 2awy");

A: You could split the two strings by word and build two hashtables/dictionaries. Then go through both and add keys incrementing an int in a third dictionary (Dictionary<string, int>). If any key in the third dictionary have a count of more than one, that word is in both original strings.
I would think that any algorithm to solve this problem would be 'slow' - especially for large input strings/many words.

A: I'd probably take the initial performance hit and split the string and then order alphabetically and by word length.
If you just have to find out if one word matches, break as soon as you find one.
Once you have the split string arrays ordered alphabetically and by length, that limits the numbers of compares you would have to do.

A: *

*The easiest way would be to compare all words to any other word. This is an easy solution, but slow.

*Another way is to sort both lists, and then compare the top two entries. Like mergesort, but with the goal of finding equal words.

*Another way is to compile the list of words into a tree, and match the words against that tree. A regex can do this, or you can do this yourself. In your example, the first letter should be 2, b, e or z. This way, each word is only inspected once and the least number of characters are inspected.


text:
Q: Starting a Jenkins Job using Javascript Does anyone have an example of starting a jenkins job with auth and parameterized in Java Script?
Its like a curl post but I am not sure how to do that exactly and I couldn't find any example passing username and token as well as parameters.

A: You can use the jenkins npm library to perform actions on npm using a specific user:
import Jenkins = require('jenkins');

const jenkins

Jenkins({ baseUrl: `https://${ username }:${ password }@${ urlToJenkinsInstance }`, crumbIssuer: true })
      .then((_jenkins) => {
        jenkins = _jenkins;

        return new Promise((resolve, reject) => {
          // start building a job
          jenkins.job.build({
            name: jobName,
            // put all the parameters here:
            parameters: {
              PARAM1: 'hello',
              PARAM2: 'world'
            }
          }, function (err, data) {
            if (err) { return reject(err); }

            resolve(data);
          });
        });
      })
      .then((queueId) => {
        console.log('job queueId: ', queueId);
      })
      .catch(printErrorAndExit);

If you need to continue and monitor the flow, after the job is added to the queue, you need to wait for the job to start, which will add a jobId to the queue item using jenkins.queue.item(queueId, callback).
Then, you can monitor the actual job and check when it finished.
In the following code, I defined two functions called convertQueueIdToBuildId and waitForJobToFinish.
convertQueueIdToBuildId
This will wait for the queue item to get a permanent ID to start and checking for the job status. I defined the interval to check this every 5 seconds.
waitForJobToFinish
This will get the permanent jobId and check every 5 seconds what's the job's status. if it's SUCCESS, we can resolve the promise, and if we get either ABORTED or FAILURE, we error the promise to indicate something didn't go well. We can play with what makes the promise fail or resolve based on the use.
// continuing the previous promise chain:
  .then((queueId) => convertQueueIdToBuildId(jenkins, jobName, queueId, 5000))
  .then((buildId) => waitForJobToFinish(jenkins, jobName, buildId, 5000))
  .catch(printErrorAndExit);

function convertQueueIdToBuildId(jenkins, jobName, queueId, interval, spinner) {
  return convertQueueIdToBuildIdInner(queueId)
    .then((data) => {
      if (isNumber(data)) {
        return data;
      }

      return waitFor(interval)
        .then(() => convertQueueIdToBuildId(jenkins, jobName, queueId, interval, spinner));
    });

  function convertQueueIdToBuildIdInner(queueId) {
    return new Promise((resolve, reject) => {
      jenkins.queue.item(queueId, (err, data) => {
        if (err) {
          return reject(err);
        }

        resolve(data && data.executable && data.executable.number);
      });
    });
  }
}

function waitForJobToFinish(jenkins, jobName, buildId, interval) {
  return waitForJobToFinishInner(jobName)
    .then((data) => {
      if ('SUCCESS' === data.result) {
        return data;
      }

      if (['ABORTED', 'FAILURE'].indexOf(data.result) > -1) {
        const errorMessage = `JENKINS[${ jobName }:${ buildId }] job ${ data.result }`;
        throw new Error(errorMessage);
      }

      return waitFor(interval)
        .then(() => waitForJobToFinish(jenkins, jobName, buildId, interval));
    });

  function waitForJobToFinishInner(jobName) {
    return new Promise((resolve, reject) => {
      jenkins.build.get(jobName, buildId, function (err, data) {
        if (err) {
          return reject(err);
        }

        resolve(data);
      });
    });
  }
}

function waitFor(interval) {
  return new Promise((resolve) => setTimeout(() => resolve(), interval));
}


text:
Q: Reshaping database using reshape package I would like to reshaping some rows of my database. In particular I have some row that it replicate for the Id column. I would like to convert this row in column. I provide a code that it represent a example of my database.
I'm trying with t() and reshape but it doesn't do that I would. Can anyone give me any suggestions?
test<-data.frame(Id=c(1,1,2,3),
    St=c(20,80,80,20),
    gap=seq(0.02,0.08,by=0.02),
    gip=c(0.23,0.60,0.86,2.09),
    gat=c(0.0107,0.989,0.337,0.663))

A: setNames(data.frame(t(test))[2:nrow(data.frame(t(test))),], test$Id)

          1      1      2      3
St  20.0000 80.000 80.000 20.000
gap  0.0200  0.040  0.060  0.080
gip  0.2300  0.600  0.860  2.090
gat  0.0107  0.989  0.337  0.663

It helps to provide an expected output. It this what you expected?


text:
Q: Apply attributes from one NSAttributedString to another Browsing Attributed String Programming Guide and the documentation for NSAttributedString and NSMutableAttributedString, I can't see a straightforward way to take all the attributes from one string and apply them to another.
The only possibility I've found so far is to to use -[NSAttributedString enumerateAttributesInRange:options:usingBlock:] but that seems like a very long way around.
Am I missing something? Surely there must be a cleaner solution?
What I'm ultimately aiming to achieve is to take an attributed string from a static label I've configured in a Storyboard, change it to contain dynamic info and apply certain attributes over certain ranges.

A: Use - (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange to get the attributes at a specific index (e.g. 0 for the first character in string). Then use this attribute in - (void)setAttributes:(NSDictionary *)attributes range:(NSRange)aRange to set this attributes for all characters in range.


text:
Q: KNN Classification Test Accuracy Explanation I have run a K-Nearest Neighbor on some sleep data I am using for a project. I was able to run the model to about a 45% accuracy. What I am struggling to understand is that I graphed out the accuracy of my model based on the K number. After K > 36 the accuracy plateaus and never again varies. I will admit that the correlation between my data is not strong, but does anyone know why this plateau would occur and no longer decrease?
To give some background, I am using exercise data along with my sleep data and determining if the time of day that I exercise impacts my sleep quality. There is some correlation to late workouts and poorer sleep but otherwise values in the afternoon and morning can vary greatly and don't seem to be a strong impact.
The Y variable in analysis = Sleep Quality factor
The X variable in analysis = The hour of day of exercise.
Graph:   x = K number           y = Accuracy


text:
Q: terminal displays source error message at start up so recently I noticed that every time I open a new terminal window, the terminal would display this message first
-bash: source: -/: invalid option
source: usage: source filename [arguments]

I use macbook with MacOS Sierra. I don't know if this relates to the problem or not, but I recently edited ssh config file for a class.

A: This almost certainly means that you created a syntax error in the file you edited.
The output here is telling you that source is invoked incorrectly.  It looks like you have -/ instead of a proper option (are you missing the rest of a filepath or did you forget to use quotes or otherwise deal with spaces in your filepath?).
$ source -/
bash: source: -/: invalid option
source: usage: source filename [arguments]

In any case something is mangled in your usage of source.  You could run this in your home dir:
$ grep "source" ./*

To see which files are using source in your home directory (note, depending on what you've edited, the problem could be elsewhere). Notably, there are files in /etc// which would traditionally be using the source command.
Hope this helps.


text:
Q: JavaScript - quickest way to extract document meta fields I need to extract the document's "description" meta tag.
The default way would be to use document.getElementsByTagName('META') and then iterate through the array - as found in: http://www.rgagnon.com/jsdetails/js-0070.html
But I'm wondering if there's no other quicker, "one line of code" approach. I'm not familiar with xPath - but maybe that could work? Any ideas?

A: sure...
var desc = document.getElementsByName('description')[0].getAttribute('content');

This presumes that there is a Meta Tag named description of course.
To be more complete, this would catch the description regardless of case.
function getDesc(){
  var metas = document.getElementsByTagName('meta');
  for(var i=0;mLen=metas.length;i<mLen;i++){
    if(metas[i].getAttribute('name').toLowerCase() == 'description'){
      return metas[i].getAttribute('content');
    }
  }
  return null;//or empty string if you prefer
}
var desc = getDesc();

A: You can do it with XPath (in clients supporting document.evaluate) but that would probably be an overkill:
document.evaluate('//*[@name="description"]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);

A: Scunliffe, I think your suggestion will definitely do the trick, at least the multi-line function will.
I came up with a solution that doesn't run on Webkit (Chrome + Safari) but which is very compact:
var metas = document.getElementsByTagName('META');
var value = (metas.namedItem ("description") || metas.namedItem ("Description") || metas.namedItem ("DESCRIPTION") || {}).content;

This will utilize the namedItem() function over the NodeList object, looking for most likely ways another programmer might write "description". Note that this will retrieve the values of  tag's attribute, while ignoring case for attribute names:
<meta name="description" content="my description" />
<meta NAME="Description" CoNtEnT="my description" />

But alas (Oy Vey) the nameItem() doesn't work on Safari & Chrome :-( Maybe there's an alternative approach for those browsers...

A: It also depends on what you mean by 'quickest'- do you mean the shortest code you can write, or the fastest response from the browser?
For the quickest response, just look at the meta elements in the head element, and pick out any with the name 'description'.
{
  var s=[], metas=document.getElementsByTagName('head')[0].getElementsByTagName('meta');
  for(var i=0,L=metas.length;i<L;i++){
    if(metas[i].name=='description')s[s.length]=metas[i].content;
  }
  s= s.join(',');
}


text:
Q: High dimensional integral of exponentials I am attempting to marginalize a probability density function. But I got stuck on the following integral
$$
\int_{-\infty}^\infty\cdots\int_{-\infty}^\infty
\frac{\exp(\pmb x^T A\pmb z)}
{|\exp(A\pmb z )|_1^{n+|\pmb{x}|_1}}
\mathrm dz_1\cdots\mathrm dz_m
$$
where $\pmb x, \pmb z \in\mathbb R^n$, $x_i\ge 0$ with large $n,m \in\mathbb N$.
$|\cdot|_1$ is the sum of the components e.g. $|\pmb x|_1 = \sum_{i=1}^nx_i$.
$A\in\mathbb R^{n\times n}$ is orthogonal and the first $m$ coloums are also orthogonal to $(1,\dots,1)$.
I already stripped away some constants.
My goal is a fast evaluation of the integral on the remaining dimensions $z_{m+1},\dots,z_n$. Can anybody solve this? If there is no explicit form of the integral, a good approximation would also be very helpful!


text:
Q: fetch value from two fields (Date and Monetary) and convert it in text in Odoo I have two fields in Sale order, i need to get values from each one change its value in text and display in another field in custom model
Two fiedls in sale.order module:
amount_total = fields.Monetary(string="Total", store=True, compute='_compute_amounts', tracking=4)

date_order = fields.Datetime()

and this is my code so far:
from odoo import fields, models, api
from odoo.exceptions import ValidationError

import random

readonly_fields_states = {
        state: [('readonly', True)]
        for state in {'sale', 'done', 'cancel'}
}

class SaleOrder(models.Model):
    _inherit = "sale.order"

    test = fields.Many2one(string="Test",
                       comodel_name='sale.order',
                       default=lambda x: random.randint(1, 10),
                       states=readonly_fields_states,
                       )

    @api.constrains('test')
    def check_test_length(self):
        for rec in self:
            if rec.test:
                if len(rec.test) > 50:
                    raise ValidationError('Длина текста строки "test" должна быть меньше 50 символов!')
            else:
                pass

The goal is: get data from fields turn its type into text and display that data in fiedl test when the two from sale.order is changed. For now i get only names S00001, S00002.. etc.
I have no working solution. I have tried various fucntion but non of them seems to work or i doing something wrong. I realise that my case bit unclear thats because i can`t wrap my head around it. So ask me whatever needed if you want to help.

A: You can use odoo related field attribute.
In your custom model add a relational field with sale.order and then create related fields.
sale_order_id = fields.Many2one(comodel_name="sale.order")
sale_order_amount_total = fields.Monetary(related="sale_order_id.amount_total")
sale_order_date_order = fields.Datetime(related="sale_order_id.date_order")

Now in custom model views you'll be able to use created fields.
<field name="sale_order_amount_total" />
<field name="sale_order_date_order" />

Note that these fields will be directly related to your Many2one model instance (sale.order record)
Good practice is to set them to readonly=True
In case you are going to execute queries in your custom models using your related fields, you should consider using store=True as attribute.
For example
sale_order_amount_total = fields.Monetary(
  related="sale_order_id.amount_total",
  store=True,
  readonly=True
)


text:
Q: Force PostgreSQL clients to use SSL on Amazon RDS I'm running a PostgreSQL 9.4.x instance on Amazon RDS.  I can successfully connect to that server using SSL using a command line similar to this one:
psql "host=x.y.z.rds.amazonaws.com dbname=aaa user=bbb sslmode=verify-full"

How can I force clients to use SSL (to make eavesdropping harder)?  The following should fail to connect:
psql "host=x.y.z.rds.amazonaws.com dbname=aaa user=bbb sslmode=disable"

As far as I can tell, on Amazon RDS you can't edit pg_hba.conf, so I can't put hostssl entries in there.
This AWS blog post suggests how it could be done with MySQL, but I can't find links to similar information for PostgreSQL.
My motivation is to prevent myself (or other users) from accidentally transmitting sensitive information unencrypted across the network.

A: Looks like this has finally been added. From the docs:

You can use the rds.force_ssl parameter to force connections to your PostgreSQL database to use SSL. The default value is 0 (off). When you set this parameter to 1 (on) and restart your instance, your database will refuse any non-SSL connections. This parameter also sets the PostgreSQL parameter ssl to on as well as modifies your instance's pg_hba.conf to support this SSL configuration.


text:
Q: npm run dev command throwing error laravel 9.21.6 When i am opening a page it shows error
Vite manifest not found at: C:\xampp\htdocs\laravel_project\lara_project\public/build/manifest.json
and my command prompt showing error

@ dev C:\xampp\htdocs\laravel_project\lara_project
vite

internal/process/esm_loader.js:74
internalBinding('errors').triggerUncaughtException(
^
Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only file and data URLs are supported by the default ESM loader. Received protocol 'node:'
at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:756:11)
at Loader.resolve (internal/modules/esm/loader.js:85:40)
at Loader.getModuleJob (internal/modules/esm/loader.js:229:28)
at ModuleWrap. (internal/modules/esm/module_job.js:51:40)
at link (internal/modules/esm/module_job.js:50:36) {
code: 'ERR_UNSUPPORTED_ESM_URL_SCHEME'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ dev: vite
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Sudha\AppData\Roaming\npm-cache_logs\2022-07-24T09_53_42_124Z-debug.log


text:
Q: Password authentication failed- postgis/postgresql database to use geodjango I'm following the geodjango tutorial here:
https://docs.djangoproject.com/en/dev/ref/contrib/gis/tutorial/#introduction
I successfully completed the installation/setup.
When I try entering the first command at the command line:
createdb -T template_postgis geodjango
I get this error message:
createdb: could not connect to database postgres: FATAL:  password authentication failed for user "mss"
mss is my windows username.
Should I be using the password I entered when I installed postgresql?  The default username during the install was postgres... so in that case how do I change the username?
Thanks for your help!!
(I'm on Windows XP)

A:
so in that case how do I change the username?

Use the -U switch as documented in the manual:
createdb -U postgres -T template_postgis geodjango

The -U switch is used in all Postgres command line applications to specify the username. You will also need this for psql to run interactive queries (unless you use a different SQL tool)


text:
Q: G is a topological group acts on topological space $X$, is $f_{g}:X\rightarrow X, x\rightarrow g*x$ continuous? Let $G$ be a topological group acts on the topological space $X$, for an elememt $g\in G$, let's define the map $f:X\rightarrow X, f(x)=g*x$.
I am trying to find if $f$ is continuous?
my best thanks

A: When we say $G$ acts on some object $X$, we usually mean that each group element $g$ is assigned a map $f_g:X\to X$. The nature of this map depends on the context of the object. We should ask: To which category does $X$ belong? The category determines what the objects and maps are, and how maps are composed with one another. If $X$ is a set, the maps are ordinary functions. If $X$, however, is a topological space, the maps we are interested in are usually the continuous maps. So when $G$ acts on a topological space $X$, it is usually assumed that each $f_g$ is continuous.
This is automatic if the group action is continuous, meaning that the map $G\times X\xrightarrow \mu X, (g,x)\mapsto f_g(x)$, is continuous. In that case, for a fixed $g\in G$, the function $f_g$ is the composite $\mu\circ\text{in}_g$, where $\text{in}_g(x)=(g,x)$.


text:
Q: How to merge a single list using C# lambda I have a class like the following:
public class MyData
{
    public int Key { get; set; }
    public string MyString { get; set; }
    public bool MyFlag { get; set; }
}

I have a list of these classes:
var data = new List<MyData>();

Which is populated as follows:
data.Add(new MyData() { Key = 1, MyFlag = true, MyString = "Hello" });
data.Add(new MyData() { Key = 1, MyFlag = false, MyString = "Goodbye" });
data.Add(new MyData() { Key = 2, MyFlag = true, MyString = "Test" });
data.Add(new MyData() { Key = 2, MyFlag = false, MyString = "Merge" });
data.Add(new MyData() { Key = 3, MyFlag = false, MyString = "Data" });

What I want is a list as follows:
Key       true       false
1         Hello      Goodbye
2         Test       Merge
3                    Data

I need an anonymous type that reflects the three values above. I found a few posts and articles that seemed to suggest GroupJoin, but I'm unsure how I could use that in this case as it seems to allow joining two separate lists.

A: I suggest grouping (by Key property). If you want true and false properties we have to put it as @true and @false since true and false are keywords:
var result = data
  .GroupBy(item => item.Key)
  .Select(chunk => new {
     Key =  chunk.Key,
     @true = chunk.FirstOrDefault(item => item.MyFlag)?.MyString,
     @false = chunk.FirstOrDefault(item => !item.MyFlag)?.MyString,
   });

A: Please note that I am not in front of a PC right now (so I could not test it), but this should give you an idea at the very least.
data
.GroupBy(x => x.Key)
.Select(
    x => new {
        Key = x.Key,
        True = data.SingleOrDefault(y1 => y1.Key == x.Key && y1.MyFlag)?.MyString,
        False = data.SingleOrDefault(y2 => y2.Key == x.Key && !y2.MyFlag)?.MyString
    });


text:
Q: why is my navigationBar under my status bar? http://www.irovr.com/stackOverflow/overlap.png
- (void)viewDidLoad {
        [super viewDidLoad];
        [self setWantsFullScreenLayout:YES];
        [mainScrollView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onMainScrollTap:)]];
    }

- (void)onMainScrollTap:(id)sender {
    if(self.navigationController.navigationBar.hidden){
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        [self.navigationController setToolbarHidden:NO animated:NO];
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    }else{
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        [self.navigationController setToolbarHidden:YES animated:YES];
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent];
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];

    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.toolbar.translucent = YES;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self.navigationController setToolbarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.toolbar.translucent = NO;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController setToolbarHidden:YES animated:NO];
}

A: Using "performSelector" will work.
However, some may find it easier to add the following to "viewWillDisappear" even if there is already a statement that unhides the navigation bar.
[self.navigationController setNavigationBarHidden:YES animated:NO];
[self.navigationController setNavigationBarHidden:NO animated:NO];

A: It seems that hiding the status bar and navigation bar at the same time causes this problem.  I was able to resolve it by hiding/showing the navigation bar with performSelector:withObject:afterDelay, even with a delay of 0

A: Your view is set too large, so it's getting drawn underneath the status bar. If you're using Interface Builder to create it as a .xib, you need to enabled the setting for the status bar under "Simulated Interface Elements", or just reduce the height of your view manually.

A: - (void)fixNavigationBarUnderStatusbarBug
{
    //This method fix bug! Don't cut it
    //Bug: Statusbar hide navigationBar after device rotation.
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
        [center addObserverForName:UIDeviceOrientationDidChangeNotification object:nil
                             queue:mainQueue usingBlock:^(NSNotification *note) {
                                 UIApplication *currentApplication = [UIApplication sharedApplication];
                                 if (currentApplication.statusBarHidden) {
                                     [currentApplication setStatusBarHidden:NO];
                                     double delayInSeconds = .1;
                                     dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
                                     dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                                         [currentApplication setStatusBarHidden:YES];
                                     });
                                 }
                             }];
    }
}


text:
Q: Unique together in Django User Model I want to update Django User table, and add another field into it. This is how I do.
class User(AbstractUser):
    platform = models.CharField(max_length=10)
    USERNAME_FIELD = 'email'

Now, since there's a field USERNAME_FIELD which takes a unique field. However, I want that username and platform should be unique_together, not just username.
How can I achieve that?

A: AbstractUser is a mostly-complete model that defines a set of default fields, including username uniqueness. If that doesn't work for you, then you should inherit from AbstractBaseUser instead and define the full set of fields.

A: Uniqueness on the username field is only if you use the built-in authentication backend.
Directly from the django docs

If you use the default authentication backend, then your model must have a single unique field...A non-unique username field is allowed if you use a custom authentication backend that can support it.

Django Custom Authentication
Hope this helps

A: From your question and the comments its pretty clear(if i am not fully misunderstood) that you want to save an user with an email (an identifier) with multiple platform. If this is the case, you can use a postgres ArrayField  on your platform column if your database is Postgresql, or alternavely you can use JsonField provided by django.

*

*Postgresql Array Field available in django > 1.7

*Django Json Field

A: I might be too late to answer this but the solution I used recently for the same problem is:
class User(AbstractUser):
    platform_and_email = models.CharField(max_length=100, unique=True)
    username = models.CharField(max_length=20, blank=True, null=True)
    email = models.EmailField(_('email address'), unique=True)

    USERNAME_FIELD = 'platform_and_email'
    REQUIRED_FIELDS = ['username', 'first_name', 'last_name']

    class Meta:
        verbose_name = "App User"
        verbose_name_plural = "App Users"

You can use a single field and set it as unique. On the client side of your app you can authenticate user by doing 'platform_' + email behind the scenes.
You will also have to write your own custom backend and make it use your platform_and_email field to validate and authenticate.
Let me know if you need more explanation on this.


text:
Q: Is ado.net obsolete to use now? I'm creating an article related to ado.net. I want to verify if this is true or not because some people said that using ado.net in accessing database is obsolete now. And what's the difference between ado.net, entity framework, ORM, O/R, linq? Could someone enlighten me? thank you very much!

A: Both LINQ to Entities and Entity Framework use ADO.NET internally, so I wouldn't say it's obsolete.
There are certain cases when using ADO.NET is recommended more then L2SQL and EF, especially when performance really matters and you are able to sacrifice the ease of writing code in exchange to full control over what is send to database and when.

A: Entity Framework & O.R.M. using ADO.NET on back end. These framework are more optimized and efficient than the simple ADO.NET. While LINQ To SQL are more faster than ADO.NET because it doesn't use the functionalities of ADO.NET


text:
Q: How to make div fill full height of parent in tailwind I am using tailwind in my Vuejs app. I have this simple template
<template>

      <router-view />

</template>

The div with h-screen is the root or my app. The component has a tailwind height of h-32
The problem is that the second div causes the page to scroll at the bottom, the height of the  (h-32).
What I want to do
If there is no content, I want the second div to fill the remaining height of the screen but no more.
If there is content, I want it grow as necessary.

A: You can leverage .flex, .flex-col and .flex-1 for this. Check out docs.

    <router-view />

A: Usage of flex-1 is optimal for your solution to expand a certain component in the parent:

Use flex-1 to allow a flex item to grow and shrink as needed, ignoring its initial size:

Vertically

Header

I am the body

Output:

Horizontally

NavBar

I am the body

Output:


text:
Q: NodeJS how to import conditionally? The context is that I need to read the data from local memory instead of a database. I want to switch to a different memory object when I am testing. To achieve this, my plan is for my function that fetches the data to check the NODE_ENV, if it is "test", then import the data from directory A, else directory B.
However, doing if/else then import throws SyntaxError of unexpected identifier. Is there some way to do conditional import in NodeJS, or a more elegant way to achieve my purpose in general?


text:
Q: Use field calculator to return the word after "unit"? Working on ArcMap Desktop 10.5; the file in question lives in a file gdb. I have a polygon layer with a field of full property addresses (string) from which I need to extract ONLY the unit number, to be populated in a new blank field STUNIT (string). The addresses are all different lengths depending on presence of street direction, etc. so my addresses, for example, could look something like this:
1 BOXER ST UNIT 7A FARMINGTON
945 WILD TURKEY XING UNIT 116 TURTLE ISLAND
52 W CLAIRMONT DR UNIT J17 EASTHAVEN
I have already performed a selection to return only records which contain the word "UNIT", about 4000 records. My goal is to populate my STUNIT field using the python parser in field calculator, with ONLY the "word" directly following UNIT. I have tried variations of the split function which looks something like this
!AddressField!.split("UNIT")[0]

but, without fail, get the  following error messages:

*

*Whitespace is not allowed at this location

*This row contains a bad value (for both the shapefile itself and the field I tried to populate)

I have checked for spaces within/outside of the function but none exist. I have also tried a variant where I use find and replace to add a * to the end of the word "UNIT" and use the * as the delimiter in the function, but get identical results. Can a word in a string field be used as a delimiter for the split function in Arcpy? If so, what am I doing wrong/if not, is there another workaround that does not require a return on the nth object?
I have several years experience with ArcGIS but relatively new to python.

A: You can do this in the field calculator using regex.  Finds the word UNIT and returns the next word.  If it doesn't find UNIT then it won't return anything.
In the Field Calculator check Python parser, and Show Codeblock.  In the Pre-logic script code enter:
import re
def nextword(s):
    m = re.search('\\UNIT (\w+)', s)
    if m:
        return m.group(1)

And in the expression:
nextword(!AddressField!)

A: You may want to define a function for this because it will go beyond basic manipulation of the field value.
enable the show codeblock button in field caluclator and in the the pre-logic script code area try this:
def split(AddrField):
    target = ((AddrField.split("UNIT")[1]).split(" "))[1]
    return target

then in field cal area below pass the field as the function's parameter:
split(!AddressField!)


text:
Q: Determine Next Day 6PM <?php
$start_date = "12/10/2009 11:30";
echo "
start_date: $start_date
";

$due_date1   = date("m/d/Y H:i", strtotime("+1 day".$start_date));
$due_date2   = date("m/d/Y H:i", strtotime("+2 day 6pm".$start_date));
echo "
due_date1: $due_date1
";
echo "
due_date2: $due_date2
";
?>

See my code , I'm trying to get two dates from a start_date.
First one due_date1 is the exact 24 hours form the start_date and the second one due_date2 is 6pm after the second day of start_date
due_date1 is working correctly
What is wrong with due_date2 calculation?

A: you might as well go for
$due_date2   = date("m/d/Y 18:00", strtotime("+2 day".$start_date));


text:
Q: Angular routing via ng-template Hi What wrong am i doing. I am new to angular js and i am using ng-template for routing withing the views.
myApp.config(['$routeProvider','$locationProvider',function($routeProvider,$locationPro    vider) {
    $routeProvider.
      when('/', {
        templateUrl: 'add.html',
        controller: 'myAppCtrl'
      }).
      when('/edit',{
        templateUrl:'edit.html',
        controller:'myAppCtrl'
      }).
       otherwise({
        redirectTo: '/'
      });
$locationProvider.html5Mode(true);
   }]);
}])

But its not working. Please help me .
below is my part of html

A: You are confusing a couple of things:

*

*The controller that you defined in your body (ng-controller="my AppController") is also defined as controller for the route. I suspect you want one or the other but not both.

*Your script tag containing the template is inside the div that it will replace (
). The ng-view div should be empty (

)and the template defined outside of it, possibly in the header.

A: I looked through your code, got solution for your routing here is working fiddle
Fiddle
Here is code
//html

        Choose:
          add |
          Edit |

$location.path() = {{$location.path()}}

//app.js

    var myApp = angular.module('app', [], function($routeProvider, $locationProvider) {
      $routeProvider
      .when('/add', {
        templateUrl: 'add.html',
        controller: MainCntl
      })
      .when('/edit', {
        templateUrl: 'edit.html',
        controller: MainCntl,
      });
         // configure html5 to get links working on jsfiddle
      $locationProvider.html5Mode(true);
    });
    function MainCntl($scope, $route, $routeParams, $location) {
    }


text:
Q: Continuity with respect to the definite topology. Examples and applications So I understand with respect to cofinite topology if a given function is continuous, every closed set is closed in its preimage. But How do I apply that to show a function is continuous?
So for example given $f:\mathbb{R}\rightarrow\mathbb{R},\:f(x)=x^{2}$
I'm trying to show $f$ is continuous with respect to cofinite topology. I understand that all I need to do is given any $C$ closed its preimage is closed but given $C$ it is some finite set.


text:
Q: get mac address of client machine using asp.net web application I tried many solutions but i'm just getting mac address of the server. I need to get mac address of the client machine. Is this possible to get mac address of the client machine?
If not, is this possible to get any other unique id from client machine?

A: The short answer is: No
It is not possible to get the MAC address from the client using JavaScript as this will pose a serious security risk.
The only unique id you will be able to get is the IP address, but this will possibly not be unique as the user's machine might be NATed behind a router.
You could use an ActiveX control on Java applet to get the client machine's MAC address, but this would require installation of the chosen method on the client machine and will never be a fail-safe way of obtaining the MAC address.


text:
Q: Access 2000 - invalid character value for cast specification (#0) - Access to SQL Lately I have migrated my Access 2000 backend data and tables to a 2012 SQL server. In the access frontend I have linked the SQL tables that were migrated. Most of it is working fine except for (now) one form.
In this form the data is being loaded from the SQL server using this query:
SELECT * FROM qryAbonementens WHERE EindDatum is null or EindDatum>=now()

It also used a filter and sort:
((Lookup_cmbOrderNummer.Omschrijving="GJK"))

And the sort:
Lookup_cmbOrderNummer.Omschrijving

These things may be irrelevant but Ill just post as much as possible.
The data loads in the form perfectly, however when I try to change a record in the form, I keep getting the:

error invalid character value for cast specification (#0)

While checking out posts with the same problem I encountered this post:
MS Access error "ODBC--call failed. Invalid character value for cast specification (#0)"
This made me believe that I was missing a PK somewhere so First I checked the linked table in Access design mode:

Tekst = text, Numeriek = numeric, Datum/tijd = date (sorry for it being dutch).
The same table in SQL looked like this:

They both have PK so I guess this is not the problem.
Though, when looking at both datatypes you can see 2 differences on the  InkoopPrijs and VerkoopPrijs fields. In SQL these two are decimals(30,2) and in the design view in the linked access table they are, I guess unknown, and so they are being cast to text values. Perhaps this is the cause of my error message?
The record I am trying to change and which gives the error is this one (but it is on all the records):

I've read somewhere that adding a timestamp field to the SQL server could help but I have no clue it also works in my case or how to do this.

A: As you have guessed, the decimal(30, 2) columns are the problem.
They are too large for Access to be used as numbers.
I can reproduce the problem with Access 2010, although I can enter numeric data into the field. But when I enter text, I get the exact same error message.

decimal(18,2) works fine (it's the default decimal precision for Sql Server 2008).
Surely you don't have prices in the 10^30 range? :-)

You might also consider using the money datatype instead, although I don't know how well Access 2000 works with that.

A: Alright I got it fixed. @Andre451 post about changing the 30,2 decimal values in the SQL server to 18,2 gave me the the record is changed by another user error. This caused me to look differently at the problem and instead of fixing the

error invalid character value for cast specification (#0)

error I looked at the

record was changed by another user error

I came across this post: Linked Access DB "record has been changed by another user"
Here someone suggested to add a TimeStamp field to the SQL table. So I did and now it seems to work again! And it also seems to work with the original (decimal 30,2) value!


text: Q: Printing from a Nodejs deployed Server I am using this node-printer to print using my Nodejs server. I have buttons in my front end which sends POST request to my Nodejs Server, where I print info if the POST request is successful. This package is a life saver and is so easy to use and setup. However, I am going to have to eventually deploy my website to Heroku or some other server. Right now since my laptop is connected to the printer I can easily print whatever I want. Is it possible to print using a website that is hosted by a cloud servers using Nodejs?


text:
Q: context.RewritePath and jquery ajax not calling webmethod Question Background: This question is part of my other question, I posted this new question to make things easy to understand, the main question link is this: LINK , In this link you can find full brief information of my project and a solutions for loading CSS with context.rewritepath issue.
in my project, I wrote context.rewritepath in global.asax to redirect user request to different location without changing addressbar address.
Issue is: without context.rewritepath jquery ajax is working perfectly;calling webmethod with response back in json. but when i am using context.rewritepath then jquery ajax response back is html instead of json.
here are the live links:
jasbir.bhinderblink.com
bhinderblink.com/users/jasbir/default.aspx
both links are calling same page from server. first is with context.rewritepath and second is without context.rewritepath. As demo test, On this page you can click top second or third text box and it will give you a type box to save data to database.
You will notice that first link generates error and if you go to firebug java HelloWorld POST response then you will see it is returning html instead of json, second link returns json data

A: You can always try just returning the correct mime type. Also, you could use the full url to HelloWorld in your ajax post url.
   url: "/users/jasbir/default.aspx/HelloWorld",

UPDATE:
Your problem, based upon the linked question is that you are losing the /HelloWorld portion of your request when the rewrite is performed.
If Directory.Exists(Server.MapPath("~/users/" & parameters(i))) Then
    Context.RewritePath("/users/" & parameters(i) & HttpContext.Current.Request.Path, False)
    Return
Else
    Context.RewritePath("/error.aspx")
    Return
End If

A: Solution for Jquery ajax call to webmethod with vb.net context.rewritepath...
In main page I added this....
<base href="http://www.bhinderblink.com/users/jasbir/">

and this stackoverflow link helped to fix the issue with this code:-
<httpProtocol>
   <customHeaders>
   <add name="Access-Control-Allow-Origin" value="*" />
   <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
   </customHeaders>
</httpProtocol>


text:
Q: How can I use the same function template to save 3 different arrays to 3 different files? How can I use the same function template to save 3 different arrays to 3 different files? (one array per file)
The array types are int, float, and char
The closest I've gotten is the following code:
template <typename T>
    void saveToTextFile(T *arr, const int size)
    {
    ofstream outFile("arraytextfile.txt", ios::out);`

        for(unsigned int i = 0; i < size; ++i)
        {
            outFile << arr[i] << ' ';
        }// end for

        outFile << endl;

        outFile.close();
    }

This, of course, creates a new text file the first time it is called, then truncates the file when opened again.  I need to call this template 3 different times and have it save data to a new file each time. Each file should contain a different array.

A: Why don't you pass the filePath via parameter, using a pointer
 void saveToTextFile(T *arr, const int size, const char *outputFilePath) {
     ofstream outFile(outputFilePath , ios::out);`
 }

you'd pass the filePath to your function like:
const char * location = "a/c/d.text".c_str();
saveToTextFile(arr, 5, location) // or for short
saveToTextFile(arr, 5,"a/c/d.text".c_str())

A: If you're sure that you're calling this function with only three different types, and you're using at least C++11, a simple (but not really elegant)  solution is use type traits and check the type; something like
std::ofstream outFile(
   std::is_same<T, char>::value
      ? "file-char.txt"
      : (std::is_same<T, int>::value
         ? "file-int.txt"
         : "file-double.txt"), std::ios::out);

If you cant use C++11 or newer, you can simulate std::is_same with something as follows
template <typename, typename>
struct isSame
 { static const bool value = false; };

template <typename T>
struct isSame<T, T>
 { static const bool value = true; };

But for a more generic solution, you can use typeid(); by example
std::string  fName = "file-";

fName += typeid(*arr).name();
fName += ".txt";

std::ofstream outFile(fName, std::ios::out);

but take in count that the typeid() give a name() that is implementation dependent.


text:
Q: Correct database solution? So I work for a smaller company and currently we need to do our data processing with a desktop solution. We're running into memory limitations and the overall solution in most people's eyes (non-technical staff) is that setting up a database for the data and doing our work on a database instead of the massive flat files (SPS files mostly or the lesser known Triple-S) we currently work on.
I would likely be the one that would be working within this database to do all the data cleaning, validation and variable creation and so I'd like to make sure what I imagine is possible and to also see other possible options.
The data we are using is respondent level survey data. We will be updating the database every quarter with about 40,000 respondents and we have about 40,000 vectors of data per respondent (largely sparse data).
One of the more advanced calculations and operations I would need to do is, I would need to determine the standard deviation of a vector of data and then reduce a respondent's response to no more then 2 standard deviations away from the mean.
Also, creating new vectors of data. (When grouping respondents we will often mark them as apart of 1 of many groups and I would need a vector containing this data to work off of and this would most likely become its own table with various other data.)
I guess I'm just looking for some guidance, I have no problem learning SQL or using MySQL or whatever but I don't know if those are the correct solutions or if I should be looking at something else all together. I know what I need to do to the data but I don't know the best platform to do it on.
I apologize if this is too broad a subject but any guidance is appreciated.

A: My initial reaction is that you should have everything you need in a standard Microsoft SQL Server installation. Integration Services to do the ETL from your flat files into SQL DB engine. Then the T-SQL language and for your calculations and operations, .NET for more advanced operations. Analysis Services and Report Server engines for the online analysis/drilldowns and for producing reports for clients and staff. Couple that with MS Office, Excel and PowerPivot, and you'll have a complete suite of Business Intelligence tools for all your needs and more.
Just my 2c
Good luck!


text:
Q: Diacritics or meaning difference for deja vu Could be trivial but would like to know, what is the difference between
déjà vu and deja vu
Is it primarily the pronunciation difference or something else?

A: You should always spell phrases from other languages correctly if you can. In the past it was sometimes difficult to find the correct symbol on your keyboard or printing device. For example it was impossible to write déjà vu on a standard English-language typewriter.
The accents make a difference to the pronunciation using either English or French rules. In this particular example they do not help you much if you cannot read French but at least they remind you not to try to read it as English.
It makes a much bigger difference with e at the end of a word as this is silent, in both English and French, so cafe has one syllable but café two. There are complications though as some words have entered the English language without accents. Cafe and café both exist but often with different meanings and pronunciations.
Things are further complicated by different rules sometimes being applied. The BBC was notable for deliberately misspelling words by leaving out all accents on their website, so even people's names were misspelt such as *Beyonce but I am pleased to see that this rule is being quietly dropped.


text:
Q: Does it matter where I initialize my integer? I'm trying to understand something. I'm still a beginner to c++ and I just created this little program where you input a value and it tells you whether it's even or odd. To do this, I made an integer called "result" which takes value, and then does % 2 operation.
However, my first mistake was that I put int result above "cin >> value" so for some reason that messed up the program and the number would always be even no matter what. Then when I put int result below "cin >> value" the program worked like it should. Why is it doing this?
Any help would be appreciated thank you. I apologize if this is a duplicate but I don't know what to search for.
#include <iostream>
#include <string>
#include "Human.h"
#include <ctime>
using namespace std;

int main() {

    int value = 0; // where I input
    cin >> value;
    // if you put int result above cin program changes.
    int result = value % 2;

    if (result == 0) {
        cout << "Even number." << endl;
    }
    else {
        cout << "Odd number." << endl;
    }

    return 0;
}

A: Any code whichever programming language you use runs from top to bottom.
You need to first declare the variable, give it a value and then check for being even or odd.
When you used cin after setting the value of result = value%2; the compiler used the originally initialized value for value which is 0 to compute the value of result which will be 0%2.
That's why you need to use cin>>value; before setting result = value%2;.

A: C++ read the code top to bottom , line by line. So you will have to int your variable first.I made  a much more simpler version of the program if you want to read it:
#include <iostream>

using namespace std;

int main() {
int a;
cout << "a=";
cin >> a ;

if(a%2==0)
    {cout<<"a is even";}
else
    {cout<<"a is uneven";}
}

A: When you put int result = value % 2; before cin >> value;, your program will calculate the result before you put a value inside int value via your input.
So your program does calculate int result = 0 % 2;


text:
Q: intellisense doesn't recognise classes I was coding a small game, when i got an error from intelisense. I tried again with a simple pet class, but intellisense didn't think it was correct. here is the code and the errors:
#include <iostream>
class Pet{
public:
    int m_hunger;
    void Greet();
};
void Pet::Greet(){
    std::cout << "My hunger is " << m_hunger;
}
int main(){
    Pet dog();
    dog.m_hunger = 9;//Expression must have class type
    dog.Greet();//Expression must have class type
    return 0;
}

A: Pet dog(); does not create a Pet.  It creates a function named dog that returns a Pet and takes no parameters.
You can change it to Pet dog; which will create a Pet named dog.


text:
Q: Git rebase adding one commit created conflicts in files not related to commit? I had a git history like this:
   master         feature
     v               v
o----o-----o----o----o

I checked out master, then altered and committed file.txt, which existed in both branches:
git checkout master
...altered file
git add file.txt
git commit -m "altered file.txt"

So then my history looked like this:
       master
         v
o----o---o     feature
      \          v
       o----o----o

Then I rebased feature onto master:
git checkout feature
git rebase master

I figured that since I had only altered one line in a single file, if there were any merge conflicts they should only be with file.txt. Instead I had several minor conflicts along the way, none related to file.txt.
Example error message:
Falling back to patching base and 3-way merge...
error: The following untracked working tree files would be overwritten by merge:
    path/to/DifferentFile.php
Please move or remove them before you merge.
Aborting
error: Failed to merge in the changes.
Patch failed at ab12 my commit message
hint: Use 'git am --show-current-patch' to see the failed patch

What happened here? Doesn't rebase just play all your commits onto the new tip of the base branch? If the branches were in the same linear history before, how could adding one file and rebasing create merge conflicts with unrelated files?


text:
Q: Select2 AngularJS - How do i dynamically add a tag item? I have a select2 input box the defined like this:
<input id="searchbox" ui-select2="autoCompleteSearch" ng-model="searchedLeafs" style="width:80%;height:36px;" class="searchbox"/>

Basically, while the user can type text into the input box (and select from the suggested autocomplete list), i would also would like to enable the user to click on an angular-based button (on the same scope) which "inject" a tag into this input box (instead of the user typing it).
Does anyone can tell me how you can do it property in angularjs?  i know how to do it in the old plain select2, but coulnd't find how can you manually/dynamically add items (key/value) to the list of tags.
if you want to get a simple example, lets say that instead of you typing the tags that you want to associate with stackoverflow question, you would simply click on a link/button which would add it to the list of tags yourself.
Thx

A: Simply push a new object into the ng-model's array and assuming it's duck-typed to the rest of the objects it should show up fine.


text:
Q: Java, Generate a direct path of points between two points I currently have a bad method for doing this, it just translates the start point by 1/-1 depending on if the x/y coordinate is over or under the current coordinates and adds it to an ArrayList until the start point .equals(end), this is a bad solution because it creates a really bad path that looks like the black path below.

I'm trying to generate a direct path of points between two points (The same kind of line as Graphics.drawLine makes).
I'm guessing I need to use the Math class to get the angle, but I'm not very familiar with the Math API.

A: One somewhat naive way, is to work out the ratio of the slope, rather than the angle.
Something like:
float ratio = (y2 - y1) / (x2 - x1);

Then:
width = x2 - x1;
for(int i = 0; i < width; i++) {
    float x = x1 + i;
    float y = y1 + (ratio * i);
    points.add(new Point(x,y));
}

If float isn't what you need, you'll need to do some conversion.
You'll also need to handle the special case of x1 == x2, or you'll get divide-by-zero errors.
Using this method, the steeper the line, the fewer points you will generate. If you want the points evenly spaced no matter what the angle, you'll need to break out sin/cos/tan.
Write unit tests for lines in at least the main 8 compass directions, to iron out any glitches.

A: This is actually more of a math problems than a programming problem.  You need to find the vector that goes from start to end and then scale it and add it to start for the number of points that you want.
In pseudo code:
f(start,end,nPoints) -> (path)
   delta = (end-start) / nPoints //Find the best difference vector.
   current = start //Set the current point to the start.
   i = 0
   while(|current-end| < epsilon)
      current += delta
      path[i] = current
      i = i + 1

I'm assuming that the points are floating point (due to the division).  epslion should be chosen to be a small value (depends on your problem) to check equality (never use != for floating points!).

A: This is a very simple concept, but you've not been too clear on what exactly you want. By definition, there are an infinite number of points between any two points (and between two of those points, exist an infinite number of points. And so on.)
The simplest solution would be to calculate the formula for the line between point A and point B, and then decide how far apart you want your points to be, and calculate those points using your line formula.
Elementary geometry tells us that the slope between two points in the change in y over the change in x. So m = (y1 - y2)/(x1 - x2), where all of these values are doubles, and x1 and y1 belong to the same point.
Then the formula for the line between two points is y - y1 = m(x - x1). Then all you'd have to do is start plugging in values for, say, x, taking the resultant y, and drawing it.
This is, of course, the idea behind the whole thing. You'd be much better off using vectors.

A: Check out this previously answered question to calculate the angle.  And then use the distance formula to find the distance.
double dist = Math.sqr((x2 - x1)^2 + (y2 - y1)^2);  //obviously wont compile but you get the idea.


text:
Q: Modes of Convergence, Real Analysis Folland Ch.2 Problem 41 If $\mu$ is $\sigma$-finite and $f_n\rightarrow f$ a.e., there exists $E_1,E_2,\ldots\subset X$ such that $\mu\left(\left(\bigcup_{1}^{\infty}E_j\right)^{c}\right)$ and $f_n\rightarrow f$ uniformly on each $E_j$.
Proof: Since $\mu$ is $\sigma$-finite, then there exists an $$X = \bigcup_{1}^{\infty}E_j \ \ \text{where} \ \ E_j\in M \ \ \text{and} \ \ \mu(E_j) < \infty \ \forall j$$ Then by continuity from below we have $E_1,E_2,\ldots\subset X$ such that $\mu\left(\bigcup_{1}^{\infty}E_j\right) = \lim_{n\rightarrow\infty}\mu(E_j)$
I am not really sure where to go from here, any suggestions is greatly appreciated.

A: Since $X$ is $\sigma$-finite, let $X = \cup_{1}^{\infty}V_{n}$ with $\mu(V_{n}) < \infty$. By Egoroff's Theorem, on each $V_n$ we have a $E_n$ such that $f_n \rightarrow f$ uniformly on $E_n$ and $\mu(E_n^{c}) < 2^{-n}\epsilon$. Then we have that $\mu((\cup_{1}^{\infty}E_j)^{c}) = \mu(\cap_{1}^{\infty}E_j^{c}) < 2^{-n}\epsilon, \ \forall N$. So that $\mu((\cup_{1}^{\infty}E_j)^{c}) = 0$ and $f_n \rightarrow f$ uniformly on each $E_n$.

A: Let $X = \bigcup_{n=1}^{\infty} X_n$ where $(X_n)$ is a sequence of disjoint sets with finite measures.
By Egoroff's theorem, choose $E_{n, m}\subseteq X_n$ such that $\mu(X_n\setminus E_{n,m}) < 2^{-n}2^{-m}$, $E_{n, m}\subseteq E_{n, m+1}$, and $f_n \rightarrow f$ uniformly on $E_{n,m}$.
For each $m \in \mathbb N$,
$$\mu\left(\bigcap_{n=1}^{\infty} E_{n,m}^c \right) \leq \mu\left( \bigcup_{n=1}^{\infty}X_n \setminus E_{n,m} \right) \leq \sum_{n=1}^{\infty}2^{-n}2^{-m} = 2^{-m}$$
and
$$\bigcap_{n=1}^{\infty} E_{n,m}^c \supseteq \bigcap_{n=1}^{\infty} E_{n,m+1}^c$$
Therefore,
$$\mu\left(\left( \bigcup_{m=1}^{\infty}\bigcup_{n=1}^{\infty} E_{n,m} \right)^c\right) = \mu\left(\bigcap_{m=1}^{\infty}\bigcap_{n=1}^{\infty} E_{n,m}^c\right) = \lim_{m\rightarrow \infty}\mu\left(\bigcap_{n=1}^{\infty} E_{n,m}^c\right) = 0$$


text:
Q: Repairing my FFC connector - what to use? I'm using a Pi Camera v2.1 and a 15-pin FFC
My 150mm, 15-pin Flat Flax Connector (on 1 side) has 1 pin slightly shortened (metal torn). My Raspberry Pi 3 is not working with it. What should I do:

*

*Try to do a software fix

*Get a £2 new flex cable

*Fix the cable (How?)

A: Before getting a replacement, you can try cutting the cable with scissors to so that all pins go to the edge:

(picture borrowed from here)
Putting the cable between two sheets of paper (and cutting the whole sandwich together) helps to restrain the cable as you cut it, limiting the damage from deformation. clear plastic sheets work too, with the advantage that you get to see the cable as you cut it.
Worst case, you further damage your already damaged cable.


text:
Q: Outlook addin Pin add-in on desktop I've been create one add-in that gives support to clients when reading emails. The question is there a way to pin the add-in like the Insight add-in to keep helping the client as they open emails?

A: If you are creating an Outlook web add-in, this is possible by adding a pinnable task pane to your add-in manifest.
Please see the linked documentation for the full XML. If you already have a task pane, you can add the SupportsPinning element to it.
<Action xsi:type="ShowTaskpane">
  <SourceLocation resid="readTaskPaneUrl" />
  <SupportsPinning>true</SupportsPinning>
</Action>

It's also important to implement a handler for the ItemChanged event so your add-in can show updated information when the user selects a different message.

A: While reviewing Microsoft Outlook documentation, I did not find any way to add a pin on Desktop
The only note I got from the documentation is:
In Outlook, click File > Manage Add-ins.

Click Manage Add-ins

In Outlook Web App, click Settings Settings > Manage add-ins.

Under Manage add-ins, in the Turned on column, select the check box for the add-in you want to enable.

Turn on or off add-ins

Microsoft Outlook documentation


text:
Q: Value from Array Inside Array PHP Let say I have a function inside a controller of a CI
    public function mr_printing () {

    $code = $_POST ['item_id'] ;
    $count = count($code) ;
    for ($i=0; $i < $count; $i++) {
      $idline = $code [$i] ;
      $new ['item'] = $this -> model_prcsys -> get_line_data (md5(base64_decode($idline))) ;
      $arr = $this -> model_prcsys -> get_sum_received ($new ['item'] ['pr_line_id']) ;
      $sum = ($arr) ;
      print_r($sum);echo "

";
    }
}

by that, I have output :
Array ( [0] => Array ( [qty_incoming] => 5 ) [1] => Array ( [qty_incoming] => 2 ) )

Array ( [0] => Array ( [qty_incoming] => 3 ) )

From the first array, I need to get value from SUM for every array. In another word, I need output like this:
7

3

Anyone, please?

A: Try this
echo array_sum(array_column($arr, 'qty_incoming'));

A: 1)fetch the particular column from multidimentional array using  array_colum.
2)sum using  array_sum.
$total =  array_sum(array_column($array_values, 'qty_incoming'));
echo $total;

A: Try this
$sum = 0;
foreach ($arr as $item) {
    $sum += $item['qty_incoming'];
}
echo $sum;


text:
Q: web client request caching issue in wp7 app i'd created a json web service & used in my web site.
    Now i want use it in my windows phone app to show the data, which is receiving by that web service. So that i'v written the code below--->
//// some code

StartThread();
        }

            void StartThread()
            {
                DispatcherTimer TradeThread = new DispatcherTimer();
                TradeThread.Interval = TimeSpan.FromMilliseconds(1000);
                TradeThread.Tick += new EventHandler(BindData);
                TradeThread.Start();
            }

            void BindData(object sender, EventArgs e)
            {
                WebClient wc = new WebClient();
                wc.DownloadStringAsync(new Uri("some URL"));
                wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
            }

            void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
            {
                JObject jsonObject = JObject.Parse(e.Result);
                ///// some code

The code is working fine, But after some requests the data is not updating. So i think there is some caching problem & i dont know how to disable caching or any alternative way to get updated data on each requets bcoz i'v never used web client befor.
So if anyone have used the web services than plz check my code above & do comment or edit it if have any solution for this caching problem ...........thanx

A: An easy workaround is to append a value that changes on earch request at the end of the query string:
"?disablecache=" + Environment.TickCount

A: Add a no-cache header to the request:
wc.Headers.Add("Cache-Control: no-cache");

A: Try setting the "Cache-Control" header this way:
wc.Headers["Cache-Control"] = "no-cache";

A: I've also tried Oliver's trick and it worked!
I'm having some trouble using the extra parameter in my method which caters for requests with and without parameters.
So I tried this and it worked:
WebClient wc = new WebClient();
wc.Headers["If-Modified-Since"] = DateTimeOffset.Now.ToString();


text:
Q: How to validate certain string with regex in jQuery? Here I have 3 classes in an element i.e sfCol_20 tsfCol_100 msfCol_100. I want to get the value of the class which is sfCol_{digit} but following logic returns me 3 values. How can resolve this issue?

var matchedClass = $('div').attr('class').match(/sfCol_[0-9]+/g);
console.log(matchedClass);

var re = new RegExp("sfCol_[0-9]+", "g");
if ($('div').attr('class').match(re)) {
  matchedClass = $('div').attr('class').match(re).join(" ");
  console.log(matchedClass);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sfCol_20 tsfCol_100 msfCol_100">
  "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
</div>


text:
Q: Error "mount: mount point /mnt/boot/efi does not exist" when trying to reinstall grub I had to run fsck on the main partition and this led me to not have grub anymore. So I tried to reinstall it following the instructions here.
The first solution got me the error "mount: mount point /mnt/boot/efi does not exist".
I tried also with Boot Repair but it didn't show me the "Recommended repair" button.
Please help me.

A: Disks Showing Mounted Partition prior to Reinstalling GRUB

Image of Disks showing drive after running sudo mount /dev/sda5 /mnt prior to installing GRUB by running sudo grub-install --boot-directory=/mnt/boot /dev/sda.
Commands were run from a Live Kingston Thumb Drive.


text:
Q: Prove that $P^{-1}v$ is an eigenvector of $B$ corresponding to the eigenvalue $\lambda$. I'm having a difficutly proving the following:
Let $A,B \in M_{n\times n} (\mathbb{R})$ be similar matrices. Let $P \in M_{n\times n} (\mathbb{R})$ be an invertible matrix satisfying $P^{-1}AP = B.$ Let $v$ be an eigenvector of $A$ corresponding to the eigenvalue $\lambda$. Prove that $P^{-1}v$ is an eigenvector of $B$ corresponding to the eigenvalue $\lambda$.
I've tried looking the the common characteristic polynomial, but didn't get anywhere.

A: $BP^{-1}v=P^{-1}Av=P^{-1}\lambda v=\lambda P^{-1}v$...

A: In fact, we can verify the result by direct calculation:
since $P^{-1}AP=B$, we then have
$$A=PBP^{-1}.$$
Noticing that $\lambda v=Av=PBP^{-1}v$, we have by right-multiplying $P^{-1}$ on both sides
$$\lambda P^{-1}v=B(P^{-1}v),$$
which shows the result.

A: \begin{aligned}P^{-1}AP & = B\newline
\implies P^{-1}APP^{-1} &= BP^{-1} \newline
\implies  P^{-1}A  &= BP^{-1} \newline
\implies  P^{-1}A v &= BP^{-1} v \newline
\implies \lambda P^{-1} v &= BP^{-1} v\newline
\implies \lambda (P^{-1} v) &= B(P^{-1} v) \end{aligned}
The final line implies $P^{-1} v$ is an eigenvector of $B$, with eigenvalue $\lambda$.


text:
Q: Filter NSArraycontroller Core Data before searching I have an NSArrayController managing contacts stored in Core Data and presented in a NSTable. The table provides a search field to the user to look for contacts by name. Everything is implemented in Swift using Cocoa bindings and works well.
Now I want to add an additional filter before the user types his search string. The filter should limit the contacts via an additional attribute like a creation date. How can this be done? Via modifying the predicate or do I need to subclass NSArrayController?
Any help would be appreciated.

A: Meanwhile I tried the approach mentioned by Willeke. Setting a default fetch predicate for the array controller initially with the Interface Builder and executing the following code every time the date date value changes, worked fine.
 let fetchRequest = ContactArrayController.defaultFetchRequest()
 fetchRequest.predicate = NSPredicate(format: "events.@max.eventDate < %@", lastDate as NSDate)
 try? ContactArrayController.fetch(with: fetchRequest, merge: false)

where event is a related entity to the entity in the array controller.
However this appears to be an overhead to me, as the data needs to be fetched every time into the array controller instead of just applying a filter
Maybe there are better solutions


text:
Q: Issue in UITableViewCell while run on iOS7? I made app for iOS6, and as I run this on iOS7, so it disturbed my design outlook.
My Cell Code is as followed.
@interface Cell_ClubOffer : UITableViewCell

@property (nonatomic, retain) IBOutlet UILabel *titleName;
@property (nonatomic, retain) IBOutlet UILabel *description;
@property (nonatomic, retain) IBOutlet UILabel *distance;

@property (nonatomic, retain) IBOutlet UIImageView *cellImageView;
@property(nonatomic,retain)IBOutlet UIButton *plainButton;

@property (nonatomic, retain) IBOutlet UIImageView *backImageView;

@end

@implementation Cell_ClubOffer

@synthesize cellImageView;
@synthesize plainButton;
@synthesize backgroundView;
@synthesize backImageView;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end

Now my Cell Looks like as in iOS6

and on iOS7, it looks bad, like

What is proper way to migrate it from iOS6 to iOS7, simply.


text:
Q: How to Change button text of messagebox control in nsis? I want to change the Messagebox OkCancel of nsis to continue setup and remove .Is it possible to do with resource hacker.
Thanks in advance

A: Yes, This can be done with writing a custom plugin...
It is a normal win32 dll with exported functions. The only "documentation" is the example plugin and its header files.

A: Here is how to do it without using Resource Hacker.


text:
Q: Foreign Key Types on Joins I've read that when joining tables on FKs, the datatype of the column the join performed on affects performance.  For example, joining on int is faster than joining on varchar(128)  My question is, is that a true statement because joining on a field is faster based on the datatype or on the value within that datatype?
For example, if I do a join on the value of -2,147,483,648, is that faster than a join on the value of "J" because "J" takes up more space in the database, assuming "J" came from varchar(128) field?  Does a join on the value of 1 occur at the same speed as -2,147,483,648 if they both come from integer columns?

A: The main factor in the performance of an equality comparison (that does not involve type casting or converting) is the size of the datatype. The integer types in SQL Server have fixed sizes (4 bytes for an int, 8 bytes for a bigint, etc. - refer to the documentation for the full details), so the actual data is inconsequential. Varchars, on the other hand (and as opposed to chars), vary in their size depending on the size of the data (see the docs for details), so having shorter data may indeed affect a query's performance, but you'll have to have a pretty large number of rows to notice any difference.


text:
Q: STL iterable container like priority_queue I'm new to STL containers (and C++ in general) so thought I would reach out to the community for help. I basically want to have a priority_queue that supports constant iteration. Now, it seems that std::priority_queue doesn't support iteration, so I'm going to have to use something else, but I'm not sure exactly what.
Requirements:

*

*Maintains order on insertion (like a priority queue)

*Pop from top of list

*Get const access to each element of the list (don't care about the order in the queue for this stage)

One option would be to keep a priority_queue and separately have an unordered_set of references, but I'd rather not have two containers floating around. I could also use a deque and search through for the right insertion position, but I'd rather have the container manage the sorting for me if possible (and constant-time insertion would be nicer than linear-time). Any suggestions?

A: There are two options that come to mind:
1) Implement your own iterable priority queue, using std::vector and the heap operation algorithms (see Heap Operations here).
2) derive (privately) from priority_queue. This gives you access to the underlying container via data member c. You can then expose iteration, random access, and other methods of interest in your public interface.

A: Using a std::vector might be enough as others already pointed, but if you want already-ready implementation, maybe use Boost.Heap (which is a library with several priority queue containers): http://www.boost.org/doc/libs/1_53_0/doc/html/heap.html
Boost is a collection of libraries that basically complete the standard library (which is not really big). A lot of C++ developers have boost ready on their dev computer to use it when needed. Just be careful in your choices of libraries.

A: You can use (ordered) set as a queue. set.begin() will be your top element, and you can pop it via erase(set.begin()).

A: Have you observed heap (std::make_heap) ? It hasn't order inside of queue, but has priority "pop from top of list" which you need.


text:
Q: Limit for coins in plants versus zombies 2 Is there a limit for the amount of coins you can keep? What happens if you gain more than 99,999 ?

A: 6 digits can fit in the black area. It looks like the font size gets smaller to compensate for the additional digit.

I don't think there is a reasonable limit for coins, given that you're able to purchase 450,000 in the largest bundle.

A:
The player cannot have more than $999,990 on most versions; once that amount is reached, all money collected won't affect their total.

EDIT:

On the iOS and Android versions it is possible to earn up to $9,000,000!

see unofficial wiki


text:
Q: Does my Sinatra API application need a class declaration? Someone developed an API application for me that works well. Unfortunately, it doesn't log anywhere and there are no logs at all. The app runs with the "rackup" command and sits behind an nginx web server. The Sinatra errors are not logged to the nginx logs.
The app.rb file looks something like this:
require './libs'
require 'sinatra'
require 'sinatra/namespace'

set :bind, '::1'

before do
  content_type :json
  headers 'Access-Control-Allow-Origin' => '*',  'Access-Control-Allow-Methods' => ['OPTIONS', 'GET', 'POST']
end

namespace '/api/v1' do
  namespace '/getit/:thingtoget' do
    helpers do
      def myhelper1
        <stuff>
      end
      def myhelper1
        <stuff>
      end
   end

   before do
     myhelper1
     myhelper2
   end

   get '/info' do
     WidgetDomain::get_info(@va1, @var2).to_json
   end

   <more API paths here>

 end

Now this is working fine. But now I want to introduce logging. So I looked at the Sinatra README and it said I could enable logging like so:
class MyApp < Sinatra::Base
  configure :production, :development do
    enable :logging
  end
end

Do I put that above the namespace stuff? If I declare an app like that, does my namespace stuff need to be inside that app code somehow? I don't have a grasp of how this works at all.
It almost looks like it's trying to log in the nginx log, but here's what an error line looks like there:
2018/12/30 19:53:15 [error] 6615#0: *21522 connect() failed (111: Connection refused) while connecting to upstream, client: <someip>, server: api.example.com, request: "GET /api/v1/getit/thingtoget1/stuff/var1/var2/var3 HTTP/1.1", upstream: "http://[::1]:9292/api/v1/getit/thingtoget/stuff/var1/var2/var3", host: "api.example.com", referrer: "an HTML page from the nginx server"

It's almost like it's trying to connect back to the server to retrieve a message or something. But in case the logging has something to do with the way I've declared the server in the nginx configuration, here it is:
server {
    listen 443;
    listen [::]:443;
    server_name api.myapp.com;

    ssl on;
    ssl_certificate /etc/nginx/ssl/myapp_com.pem;
    ssl_certificate_key /etc/nginx/ssl/star_myapp_com.key;

    location / {
      proxy_pass http://localhost:9292;
    }

}

A: Have a look at Sinatra's README in the Logging section but I tend to set up a logger outside of the Sinatra app in case other bits get bolted on or several apps are used together and I can use the same logger for all of them. Simplest way is a global variable (one of the few places they're acceptable, but it's not the only way) :
require 'mono_logger' # because it's thread safe
require 'pathname'    # because paths aren't strings :)

log_path = Pathname(__dir__).join("logs/app.log")
$logger = MonoLogger.new(log_path)
$logger.level = MonoLogger::INFO

Then in a route or wherever:
get '/' do
  $logger.info "here"

In my terminal:
$ cat logs/app.log
I, [2019-01-07T13:03:52.989415 #64378]  INFO -- : here

As to configuration blocks, you don't need to worry about putting them within a class declaration unless you're using a modular app (see Modular vs. Classic Style in the README) and yours is in the classic style.
Configuration blocks aren't namespaced (Sinatra::Namespace handles things that take a route as an argument, like get and before) so follow convention and stick it near the top of the file.
Hope that helps.


text:
Q: How can I access output to stdout from a UWP console application in Windows 10? I have created a test C++ UWP console application ("app3.exe") in Visual Studio 2017 that prints a string to stdout. When run on Command Prompt or PowerShell, I can see the output, but nothing else can. For example, I can write the command output with app3.exe > a_file.txt and it creates a blank file. I suspect this has something to do with Windows wrapping the actual function (the one with output to stdout) in another calling layer that has no output to stdout. I just want to be able to access the stdout output from my program. Any advice is appreciated.
Here is the sample code:
int main()
{
    printf("This is output");
    std::cout << " to stdout.";
    return(0);
}

I've trimmed it down to the bare bones.
For what it's worth, I'm running on Windows 10 Pro version 1803, build 17134.915.

Further explanation
I want to get built-in sensor data (accelerometer, etc.) from a Microsoft Surface Pro into MATLAB. As I understand things, to access the sensors I need the UWP. I have tried all of the provided UWP console application templates with the same problem: no output registers from the command, as in the above image. Ideally I would run the application from MATLAB using the system command and parse the output there, however there is no output MATLAB or anything else (besides my own eyeballs) can detect when the application is run. After much trouble, I can write the output to a temporary file, but the location changes from device to device so telling MATLAB where to find it is nontrivial. I just want to be able to use the stdout output.

A: 2019/08/12 16:10 PM
I apologize for previous answers being not really that much specific to UWP, I was unaware of all its details, and I was answering considering more the use of the C++ language on the Windows platform in general.
So it turned out that Universal Windows Platform is a technology developed by Microsoft to allow developers write applications that runs on all Microsoft devices by accessing a common development and security model and a common API.
To be able to write UWP console applications you need to have installed in your Microsoft Visual Studio copy the UWV Console Templates. After you've installed them, you'll need to create a new Console App C++/CX (Universal Windows).
As you will see the template itself adds a Program.cpp file compiled with the following code:
#include "pch.h"

using namespace winrt;

int __cdecl main(){

    wprintf(L"Command line arguments:\n");

    for (int i = 0; i < __argc; i++){
        wprintf(L"__argv[%d] = %S\n", i, __argv[i]);
    }

    wprintf(L"Press 'Enter' to continue: ");
    getchar();
}

Here is the reference to the UWP console example. As specified in the documentation, by dfault UWP applications won't be able to access the filesystem beside the folder they are run from and below. In order to broaden the access to other filesystem location you need to edit the application capability declaration XML file by adding the rescap namespace and the broadFileSystemAccess capability as follows:
<Package
  ...
  xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
  IgnorableNamespaces="uap mp uap5 rescap">
...
<Capabilities>
    <rescap:Capability Name="broadFileSystemAccess" />
</Capabilities>

Without further ado I advice you to carefully read the documentation about the subject at https://learn.microsoft.com/it-it/windows/uwp/files/file-access-permissions to be able to achieve your goal.
As last note: when you will open the documentation with your browser by default it will show you C# code examples, which are not what you want. To see corresponding C++ examples you have to select the language at the top of the page as the following screnshot shows:

2019/07/30 6:41 PM
Considering setting the Subsystem to Console from linker options did not solve your issue, I digged al litte more. By reading at the Windows API documentation for creating a new console I found the following statements:

A graphical user interface (GUI) or console process that is not currently attached to a console can use the AllocConsole function to create a new console. (GUI processes are not attached to a console when they are created. Console processes are not attached to a console if they are created using CreateProcess with DETACHED_PROCESS.)

So basically after having included the Windows.h header this is the workflow you should follow:

*

*Create a console with AllocConsole

*Get the standard output handle with GetStdHandle(STD_OUTPUT_HANDLE)

*Write on the console with WriteConsole

*Release the console with FreeConsole
Here there is a full example that rebinds also C++ standard streams so that you can use directly them as usual in c++.

2019/07/30 3:45 PM
Did you try to set the SUBSYSTEM option in the solution properties or in the command line the Linker section?
/SUBSYSTEM:Console

It actually tells the Windows operating system how to execute the produced executable file. Specifically this option influence the choice of the entry point operated by linker. This  seems exactly the behaviour you are explaining in the question.

A: Have you tried:
fprintf(stdout, "Output.\r\n");

Or you can try:
freopen("CONOUT$", "w", stdout);
fprintf(stdout, "Output.\r\n");


text:
Q: Is there any XMLStream reader in xquery? I want to read an XML sequentially in xquery (MarkLogic DB) to identify start and end tags. Is there any stream reader available in xquery like Java's XMLStreamReader?

A: Welcome Ash,
In XQuery, there is no function same like as in java XMLStreamReader. DOC() function in XQuery, read the xml doc but not read sequentially automatic, for this, you need to use below Query:
    let $result :=
       for $x in fn:doc()
        let $first-element :=name($x/*/*[1])
        let $last-element  :=name($x/*/*[last()])
           return fn:concat("First Element: ", "'", $first-element, "'", " Second element: ", "'", $last-element, "'")
    return $result


text:
Q: Replicate rows with different values in one column Can anyone help on replicate rows in R:
I have a dataset like -
ID Study X Y Z Time
1  2     3 4 5 0
2  2     3 4 5 0
3  2     3 4 5 0

Also have a vector of time c(1,1.3,4,5,8,24,34,55,66)
I would like to replicate each row with new rows at column Time with values list above, such as:
ID Study X Y Z Time
1  2     3 4 5 0
1  2     3 4 5 1
1  2     3 4 5 1.3
1  2     3 4 5 4

A: One way to do it like this:
Data:
dt <- read.table(text=c("ID Study X Y Z Time",
  "1  2     3 4 5 0",
  "2  2     3 4 5 0",
  "3  2     3 4 5 0"), header=T)

Solution:
vect <- list(c(0,1,1.3,4,5,8,24,34,55,66)) #convert the vector to a list
dt$Time <- vect #use that converted list to add as column, it will replace the existing Time column
dt <- tidyr::unnest(dt, Time) #use tidyr::unnest to unnest the column time

OR as suggested by @thelatemail, you can use baseR like so(using the default vectorization in Base R):
newdt <- dt[rep(seq_len(nrow(dt)), each=length(vect)),]
newdt$Time <- vect #We can see the vectorization of values in R here

I have two assumptions here, The existing Time variable is completely zero, and you want a zero value of time for each of the IDs on top.
Output:
   #   ID Study X Y Z Time
   # 1   1     2 3 4 5  0.0
   # 2   1     2 3 4 5  1.0
   # 3   1     2 3 4 5  1.3
   # 4   1     2 3 4 5  4.0
   # 5   1     2 3 4 5  5.0

A: If I understand your question correctly, you want to modify time values starting from the second observation using the given vector. You can simply use the following expression, just be careful about lengths to prevent unintended recycling:
df$Time[-1] <- time_vec # alternatively: df$Time[2:n] <- time_vec where n = 10 in this case

Data:
df <- data.frame(
  ID = 1:10,
  Study = rep(2, 10),
  X = rep(3, 10),
  Y = rep(4, 10),
  Z = rep(5, 10),
  Time = rep(0, 10)
)

time_vec <- c(1, 1.3, 4, 5, 8, 24, 34, 55, 66)


text:
Q: My several Windows XP programs disappeared I have several programs disappeared from my computer ( Win XP ). They are :

*

*Notepad

*System Restore

*Windows Media Player ( It disappear. I can't find it everywhere but when I opened a song, the song is played with WMP. Weird ! )

*In Start Menu -> Accessories --> Entertaiment, It is empty. But there is no missing audio or sound.

*There is still other programs disappear. The conclusion is I found that several programs disappeared or lost from my start menu ( especially Accessories ).
Why ?
My command prompt can't recognized attrib /?. Why ?
My disk defragmenter is still there. But, when I opened, It appeared a windows " Open with.." . I can't do anything then.
Any solution for my those problems ? I am very stressed with them

A: I suggest downloading and running a utility called unhide, or they may be found in a folder named smtmp inside:
C:\Documents and Settings\Username\Local Settings\Temp
These will be there unless you have removed temp files / folders
There could be multiple numbered folders wich will be numbered 1,2 and 4.
All you have to do then is look in the 1 folder for a folder named "Programs" and copy/paste this to:
 C:\Documents and Settings\All Users\Start Menu
wich would probably already have that folder but it is safe to overwrite since windows will replace the subfolders as well.
Inside folder 2 you should select all of the quick launch items and paste them into:
 C:\Documents and Settings\Your User Name\Application Data\Microsoft\Internet Explorer\Quick Launch.
Inside the folder 4 there are desktop items that should be copied to C:\Documents and Settings\All Users\Desktop
If you can't find the smtp folder you might want to check C:\Windows\Temp, copy them into C:\Documents and Settings\Username\Local Settings\Temp


text:
Q: jQuery Toggle Div - how to leave div open on page load I have the following code which works fine:

$(document).ready(function () {
    $('.text').hide();
    $('.expander').click(function () {
        // .parent() selects the A tag, .next() selects the P tag
        $(this).parent().next().slideToggle(200);
    });
    $('.text').slideUp(200);
});

Click Here

Hidden Text

Click Here

Hidden Text

Click Here

Hidden Text

Click Here

Hidden Text

However - I wondered if there is a way to change the jQuery so that the content in the DIVs is visible when the page first loads, rather than hidden as currently happens.
I tried commenting out this line:
$('.text').hide();

But it made no difference.

A: You can do this.
Your jQuery will be cleaner this way.

$(document).ready(function () {
    $('.expander').click(function () {
        $(this).parent().next().slideToggle(200);
    });
});

Click Here

Hidden Text

Click Here

Hidden Text

Click Here

Hidden Text

Click Here

Hidden Text

A: Remove/comment out $('.text').slideUp(200); and $('.text').hide();.
These are the two lines  which are hiding the "Hidden text". They both does the same thing, hides the matched elements. .hide() hides the element as the name depicts. And .slideUp does the same by making he heigh zero of the matched element so hides the element

A: there are two function hiding $('.text')
commenting them out would work as expected.

$(document).ready(function () {
    // $('.text').hide();
    $('.expander').click(function () {
        // .parent() selects the A tag, .next() selects the P tag
        $(this).parent().next().slideToggle(200);
    });
    // $('.text').slideUp(200);
});

Click Here

Hidden Text

Click Here

Hidden Text

Click Here

Hidden Text

Click Here

Hidden Text


text:
Q: React native modal not swiping down to close I am using modal from react-native to display a bigger view of an image:
import {  Modal } from 'react-native'

<Modal
        animationType="slide"
        visible={this.state.modalOpen}
        presentationStyle="pageSheet"
        swipeDirection='down'
        swipeThreshold={50}
        onSwipeComplete={()=> this.closeImageModal()}
        onDismiss={() => this.closeImageModal()}>

        <View  style={{ flex: 1, backgroundColor: '#121212', justifyContent: 'center', alignItems: 'center'}}>
            <TouchableOpacity
                style={{padding: 15}}
                onPress = { () => this.closeImageModal() }>
                <Ionicons name="ios-close-circle" size={30} color="red" />
            </TouchableOpacity>

            <Image
                source={{ uri: this.state.image }}
                style={styles.fullScreenImage}
            />
        </View>
    </Modal>

Right now, I need to press the touchable opacity above the image to close the modal.
I have tried using react-native-modal, and it has been extremely glitchy and difficult to use in my application, so I decided to stick with the modal from react native. Is there any way I can implement swiping down to close with this modal, without having to use react-native-modal?