text:
Q: If potato chips come in contact with humid air, they become what? In my mother-tongue, there's a word for it. I'm wondering what the English word is.

If potato chips come in contact with humid air (as in rainy days), they lose their crispiness, and become _____________.

Fill in the blank. Note that the chips are eatable and won't cause food poisoning. But neither are they wet because of contact with liquid water. They are just not crispy. In other words, if you take a potato chip and break it, it won't produce any sound of 'cracking'. It'd rather bend :)
I'm not looking for something like 'uncrispy' because it'll serve an all different purpose in this context.

To avoid confusion of chips or fries, this is the picture of what I mean chips here.

A: Soggy fits the bill I believe.

Saturated or sodden with moisture; soaked: soggy clothes.

A: The answer IS stale:

Stale adjective (staler, stalest)

*

*(of food) no longer fresh and pleasant to eat; hard, musty, or dry:
'stale bread'

synonyms: dry, dried out, hard, hardened, old, past its best, past its sell-by date

Taken from the Oxford Dictionary of English and the Oxford Thesaurus of English.

A: Mushy would be a good description.  Merriam-Webster defines it as "soft and wet".
Soggy could also work, but I would say that it applies only when the chips are significantly saturated with water.  If the chips are merely no longer crispy due to exposure to low levels of moisture, mushy would be a better word.

A: This is a somewhat technical answer. Hey, I'm an amateur cooking geek :-)
For a starch or starch-oil food (which includes bread, chips, french fries, etc.), there are several ways they become less palatable:

*

*Soggy. This seems like what you're mainly describing. It's a change in the texture (how it feels) not so much how it tastes. If you dipped it in water, it'd become soggy. (Similarly, cereal left in milk too long becomes soggy).

*Stale. This is a change in both taste and texture, and is a change to the starch. The texture (for bread at least) is normally drier. Put some bread in the fridge for a few days, and it'll be stale. (Note this can be mostly reversed by heating). In bread at least, it occurs fastest around fridge temperatures.

*Rancid. This is the oil or fat oxidizing, so it can't happen without fat or oil. For things with a lot of oil, and once its well-progressed, you'll notice a very off odor that's normally described as "chemical" or even "paint thinner". This is also what, for example, limits the shelf life of whole wheat flour; the oils go rancid. This won't actually give you food poisoning, by the way.

*Spoiled. There is mold, bacteria, etc. growing on it. It's no longer safe to eat it. Also, especially in extreme cases, rotten.

A: They become damp.
damp

moisture diffused through the air or a solid substance or condensed on a surface, typically with detrimental or unpleasant effects.

This isn't unique.

A: From the Wikipedia entry on "Jaffa Cakes":

McVities defended its classification of Jaffa Cakes as cakes at a VAT tribunal in 1991, against the ruling that Jaffa Cakes were biscuits ... The product was assessed on the following criteria: ... The product hardens when stale, in the manner of a cake.

The implication here is that while some things (e.g. cakes) harden when stale (presumably by losing moisture) while other things soften (e.g. biscuits) when stale (presumably by gaining moisture).
If the chips got directly rained on, then that would be "soggy", but if you left the bag open on a humid day, causing them to get a bit damp, that would be "stale".

A: Given that it's come in contact with water, the word would not be "stale" which is when it becomes hard and dry but, as others have said, "soggy" or perhaps "sodden".
A stale chip will snap audibly, a soggy chip will bend and tear.

A: I recommend the simple contrast of soft if the environment is such that the chips lost their crispness much faster than normal.  (Or, for humor value, you could refer to them as flaccid.)
Stale is also quite appropriate, as many others have pointed out: it is kind of a middle state where the food is no longer fresh, has lost some of its appeal and has degraded in some way, but is not yet harmful or inedible.  Normally you would use this if the food has sat out for some extended period.
Soggy is a more drastic state that implies an excess of moisture, to the point that it may actually drip water, or at least will make your fingers damp if you hold it.

A: We've also got a word for that in my country's primary language. :D
From experience, I believe the English word you are looking for is "stale".
"Stale" seems to have the meaning "no longer pleasant to consume after being left in the open for too long". In which case, stale chips have lost their crispness, stale bread has become hard and dry, stale beer has lost its carbonation, stale coffee has oxidized and become sour and rancid.


text:
Q: Is there a shorter key combination than :cn to go to the next item in the quickfix list? I'm reading through a large C++ code base in Vim.
Within a single file, I can do
/foo
n
n
n

Now, if I want to search through more than one file, I have to do:
:vimgrep /foo/
:cn
:cn
:cn

Now, typing :cn is so much less convenient than n. Is there a way to search through vimgrep results with n (like searches with /) instead of :cn?

A: Use the Quickfix List. It will automatically be filled with found matches (no matter if you use :grep or :vimgrep). It can be navigated with the usual keys (so the key for "next" is j instead of n).
To open it use :copen.

A: This is what I have in my .vimrc exactly for this purpose:
nmap <F7> :cp^M
nmap <F8> :cn^M

A: Just another option: the vim-unimpaired plugin binds ]q to :cnext and [q to :cNext among many other useful keymappings.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JPA Persist Entity with Foreign key value but don't want to explicit FIND for Foreign key Entity I want to Persist an entity  Book  which has  ManyToOne  relationship with other entity  Author .
  @Entity
    @Table(name = "BOOK")
    public class Book {
        private int id;
        private Author author;

    @ManyToOne(cascade = CascadeType.ALL)
     @JoinColumn(name = "AUTHOR_ID")
     public Author getAuthor() {
        return author;
    }
}

So, When I want to save a Book entity, I need to FIND the Author entity using
Author aut = entityManager.find(Author.class, Id);
book.setAuthor(aut);
em.merge(book)

So, for finding of a Author I need to explicitly issue an SELECT query which I don't want to do. Is there any other way that, I can avoid explicit looking for foreign key but can persist the entity with Foreign key value?
Thanks

A: Is it option for you to use JPQL? You can just use simple query
UPDATE Book b SET b.author=(SELECT a FROM Author a WHERE a.id=:author_id) WHERE b.id=:book_id

Another way to do this is following:
Author reference = entityManager.getReference(Author.class,authorId);
book.setAuthor(reference);
entityManager.merge(book);

A bit more info about getReference method
This way select won't be issued.


text:
Q: How do I figure out what kind of distribution represents this data on ping response times? I've sampled a real world process, network ping times. The "round-trip-time" is measured in milliseconds. Results are plotted in a histogram:

Latency has a minimum value, but a long upper tail.
I want to know what statistical distribution this is, and how to estimate its parameters.
Even though the distribution is not a normal distribution, I can still show what I am trying to achieve.
The normal distribution uses the function:

with the two parameters

*

*μ (mean)

*σ2  (variance)

Parameter estimation
The formulas for estimating the two parameters are:

Applying these formulas against the data I have in Excel, I get:

*

*μ = 10.9558 (mean)

*σ2  = 67.4578 (variance)

With these parameters I can plot the "normal" distribution over top my sampled data:

Obviously it's not a normal distribution. A normal distribution has an infinite top and bottom tail, and is symmetrical. This distribution is not symmetrical.

*

*What principles would I apply; what
flowchart would I apply to determine
what kind of distribution this is?

*Given that the distribution has no negative tail, and long positive tail: what distributions match that?

*Is there a reference that matches distributions to the observations you're taking?

And cutting to the chase, what is the formula for this distribution, and what are the formulas to estimate its parameters?

I want to get the distribution so I can get the "average" value, as well as the "spread":

I am actually plotting the histogram in software, and I want to overlay the theoretical distribution:

Note: Cross-posted from math.stackexchange.com

Update: 160,000 samples:

Months and months, and countless sampling sessions, all give the same distribution. There must be a mathematical representation.

Harvey suggested putting the data on a log scale. Here's the probability density on a log scale:

Tags: sampling, statistics, parameter-estimation, normal-distribution

It's not an answer, but an addendum to the question. Here's the distribution buckets. I think the more adventurous person might like to paste them into Excel (or whatever program you know) and can discover the distribution.
The values are normalized
Time    Value
53.5    1.86885613545469E-5
54.5    0.00396197500716395
55.5    0.0299702228922418
56.5    0.0506460012708222
57.5    0.0625879919763777
58.5    0.069683415770654
59.5    0.0729476844872482
60.5    0.0508017392821101
61.5    0.032667605247748
62.5    0.025080049337802
63.5    0.0224138145845533
64.5    0.019703973188144
65.5    0.0183895443728742
66.5    0.0172059354870862
67.5    0.0162839664602619
68.5    0.0151688822994406
69.5    0.0142780608748739
70.5    0.0136924859524314
71.5    0.0132751080821798
72.5    0.0121849420031646
73.5    0.0119419907055555
74.5    0.0117114984488494
75.5    0.0105528076448675
76.5    0.0104219877153857
77.5    0.00964952717939773
78.5    0.00879608287754009
79.5    0.00836624596638551
80.5    0.00813575370967943
81.5    0.00760001495084908
82.5    0.00766853967581576
83.5    0.00722624372375815
84.5    0.00692099722163388
85.5    0.00679017729215205
86.5    0.00672788208763689
87.5    0.00667804592402477
88.5    0.00670919352628235
89.5    0.00683378393531266
90.5    0.00612361860383988
91.5    0.00630427469693383
92.5    0.00621706141061261
93.5    0.00596788059255199
94.5    0.00573115881539439
95.5    0.0052950923837883
96.5    0.00490886211579433
97.5    0.00505214108617919
98.5    0.0045413204091549
99.5    0.00467214033863673
100.5   0.00439181191831853
101.5   0.00439804143877004
102.5   0.00432951671380337
103.5   0.00419869678432154
104.5   0.00410525397754881
105.5   0.00440427095922156
106.5   0.00439804143877004
107.5   0.00408656541619426
108.5   0.0040616473343882
109.5   0.00389345028219728
110.5   0.00392459788445485
111.5   0.0038249255572306
112.5   0.00405541781393668
113.5   0.00393705692535789
114.5   0.00391213884355182
115.5   0.00401804069122759
116.5   0.0039432864458094
117.5   0.00365672850503968
118.5   0.00381869603677909
119.5   0.00365672850503968
120.5   0.00340131816652754
121.5   0.00328918679840026
122.5   0.00317082590982146
123.5   0.00344492480968815
124.5   0.00315213734846692
125.5   0.00324558015523965
126.5   0.00277213660092446
127.5   0.00298394029627599
128.5   0.00315213734846692
129.5   0.0030649240621457
130.5   0.00299639933717902
131.5   0.00308984214395176
132.5   0.00300885837808206
133.5   0.00301508789853357
134.5   0.00287803844860023
135.5   0.00277836612137598
136.5   0.00287803844860023
137.5   0.00265377571234566
138.5   0.00267246427370021
139.5   0.0027472185191184
140.5   0.0029465631735669
141.5   0.00247311961925171
142.5   0.00259148050783051
143.5   0.00258525098737899
144.5   0.00259148050783051
145.5   0.0023485292102214
146.5   0.00253541482376687
147.5   0.00226131592390018
148.5   0.00239213585338201
149.5   0.00250426722150929
150.5   0.0026288576305396
151.5   0.00248557866015474
152.5   0.00267869379415173
153.5   0.00247311961925171
154.5   0.00232984064886685
155.5   0.00243574249654262
156.5   0.00242328345563958
157.5   0.00231738160796382
158.5   0.00256656242602444
159.5   0.00221770928073957
160.5   0.00241705393518807
161.5   0.00228000448525473
162.5   0.00236098825112443
163.5   0.00216787311712744
164.5   0.00197475798313046
165.5   0.00203705318764562
166.5   0.00209311887170926
167.5   0.00193115133996985
168.5   0.00177541332868196
169.5   0.00165705244010316
170.5   0.00160098675603952
171.5   0.00154492107197588
172.5   0.0011150841608213
173.5   0.00115869080398191
174.5   0.00107770703811221
175.5   0.000946887108630378
176.5   0.000853444301857643
177.5   0.000822296699600065
178.5   0.00072885389282733
179.5   0.000753771974633393
180.5   0.000766231015536424
181.5   0.000566886361087923

Bonus Reading

*

*What Is the Expected Distribution of Website Response Times?

*What Do You Mean? - Revisiting Statistics for Web Response Time Measurements

*Modeling Network Latency

A: There is no reason to expect that any real world data set will fit a known distributional form...especially from such a known messy data source.
What you want to do with the answers will largely indicate an approach. For example, if you want to know when the ping times have changed significantly, then trending the empirical distribution may be a way to go. If you want to identify outliers, other techniques may be more appropriate.

A: A simpler approach might be to transform the data. After transforming, it might be close to Gaussian.
One common way to do so is by taking the logarithm of all values.
My guess is that in this case the distribution of the reciprocal of the round-trip times will be more symmetrical and perhaps close to Gaussian. By taking the reciprocal, you are essentially tabulating velocities instead of times, so it still is easy to interpret the results (unlike logarithms or many transforms).

A: Try the gamma distribution which is parametrized as $x \sim Gamma(k,\theta)$. If you see these pdf plots of the gamma from the wiki you will see that there are some plots that look similar to what you have.
Update- Estimation Process
The estimation via maximum likelihood is tricky but possible. I imagine you can start with the approximate solution given by the wiki for $\hat{\theta}$ and $\hat{k}$ and if the plots look ok and if needed you can estimate $\hat{k}$ more accurately using the details in the wiki.

A: Another approach, that is more justified by network considerations, is to try to fit a sum of independent exponentials with different parameters. A reasonable assumption would be that each node in the path of the ping the delay would be an independent exponential, with different parameters. A reference to the distributional form of the sum of independent exponentials with differing parameters is http://www.math.bme.hu/~balazs/sumexp.pdf.
You should probably also look at the ping times vs the number of hops.

A: Looking at it I would say a skew-normal or possibly a binormal distribution may fit it well.
In R you could use the sn library to deal with skew-normal distribution and use nls or mle to do a non-linear least square or a maximum likelihood extimation fit of your data.
===
EDIT: rereading your question/comments I would add something more
If what you're interested into is just drawing a pretty graph over the bars forget about distributions, who cares in the end if you're not doing anything with it. Just draw a B-spline over your data point and you're good.
Also, with this approach you avoid having to implement a MLE fit algorithm (or similar), and you're covered in the case of a distribution that is not skew-normal (or whatever you choose to draw)

A: Based on your comment "Really i want to draw the mathematical curve that follows the distribution. Granted it might not be a known distribution; but i can't imagine that this hasn't been investigated before." I am providing a function that sort of fits.
Take a look at ExtremeValueDistribution
I added an amplitude and made the two betas different. I figure your function's center is closer to 9.5 then 10.
New function:
a E^(-E^(((-x + alpha)/b1)) + (-x + alpha)/b2)/((b1 + b2)/2)
{alpha->9.5, b2 -> 0.899093, a -> 5822.2, b1 -> 0.381825}
Wolfram alpha:
plot 11193.8 E^(-E^(1.66667 (10 - x)) + 1.66667 (10 - x)) ,x 0..16, y from 0 to 4500
Some points around 10ms:
{{9, 390.254}, {10, 3979.59}, {11, 1680.73}, {12, 562.838}}
Tail does not fit perfectly though. The tail can be fit better if b2 is lower and the peak is chosen to be closer to 9.

A: Weibull is sometimes used for modelling ping time. try a weibull distribution. To fit one in R:
x<-rweibull(n=1000,shape=2,scale=100)
#generate a weibull (this should be your data).
hist(x)
#this is an histogram of your data.
library(survival)
a1<-survreg(Surv(x,rep(1,1000))~1,dist='weibull')
exp(a1$coef) #this is the ML estimate of the scale parameter
1/a1$scale     #this is the ML estimate of the shape parameter

If you're wondering for the goofy names (i.e. $scale to get the inverse of the shape)
it's because "survreg" uses another parametrization (i.e. it is parametrized in terms of the "inverse weibull" which is more comon in actuarial sciences).

A: Let me ask a more basic question:  what do you want to do with this distributional information?
The reason I ask is because it may well make more sense to approximate the distribution with some sort of kernel density estimator, rather than insist that it fit into one of the (possibly shifted) exponential family distributions.  You can answer almost all of the same sorts of questions that a standard distribution will let you answer, and you don't have to worry (as much) about whether you've selected the correct model.
But if there's a fixed minimum time, and you must have some sort of compactly parameterized distribution to go with it, then just eyeballing it I'd subtract off the minimum and fit a gamma, like others have suggested.

A: The distribution looks log-normal to me.
You can fit your data using two parameters: scale and location. These can be fitted in much the same way as a normal distribution using expectation maximisation.
http://en.wikipedia.org/wiki/Log-normal_distribution


text:
Q: How do I remap WASD to arrow keys? OK so, I saw this answer on another thread about how to remap keys:

Apple's Technical Note TN2450 describes how to remap keys. Running the
  following command will remap Right Alt to be Right Control.
hidutil property --set '{"UserKeyMapping":
    [{"HIDKeyboardModifierMappingSrc":0x7000000e6,
      "HIDKeyboardModifierMappingDst":0x7000000e4}]
}'

So I wrote this:
hidutil property --set '{"UserKeyMapping":
    [{"HIDKeyboardModifierMappingSrc":0x700000052,
      "HIDKeyboardModifierMappingDst":0x70000001A}
      "HIDKeyboardModifierMappingSrc":0x700000051,
      "HIDKeyboardModifierMappingDst":0x700000016}
      "HIDKeyboardModifierMappingSrc":0x700000050,
      "HIDKeyboardModifierMappingDst":0x700000004}
      "HIDKeyboardModifierMappingSrc":0x70000004F,
      "HIDKeyboardModifierMappingDst":0x700000007}]
}'

But when I run it I get this error:
2020-02-17 11:47:40.303 hidutil[2619:57497] NSJSONSerialization Error Domain=NSCocoaErrorDomain Code=3840

"Badly formed array around character 127."

UserInfo={NSDebugDescription=Badly formed array around character 127.}

ERROR!!!! Unable to create property object for
'{"UserKeyMapping":
    [{"HIDKeyboardModifierMappingSrc":0x700000052,
      "HIDKeyboardModifierMappingDst":0x70000001A}
      "HIDKeyboardModifierMappingSrc":0x700000051,
      "HIDKeyboardModifierMappingDst":0x700000016}
      "HIDKeyboardModifierMappingSrc":0x700000050,
      "HIDKeyboardModifierMappingDst":0x700000004}
      "HIDKeyboardModifierMappingSrc":0x70000004F,
      "HIDKeyboardModifierMappingDst":0x700000007}]
}'

What's the problem?
(I'm a total noob just trying to remap a key for a game (EU:4), I'm not an expert programmer or anything, so please be gentle and explain things in layman's terms for my noob ass to understand! xD)
Thanks, R69NiX

A: As you are not a programmer and want a very simple way, then I recommend using Karabiner to remap keys.

A powerful and stable keyboard customizer for OS X.

This page will give you step by step guidelines. You can achieve your setup as per my following screenshot:


text:
Q: how to add the existed iOS DocSet to xcode? I have already downloaded the iOS 6.1 DocSet, as shown here in Finder when I navigate to /Applications/Xcode.app/Contents/Developer/Documentation/DocSets/:

But, when in Xcode preferences it prompts me to Install it again, even though it's already been downloaded:

How can I make Xcode read the already installed DocSet?


text:
Q: Обрезка картинок в папке средствами php Есть папка с 6000+ картинками. Они все разного размера, их нужно порезать под квадрат. Квадрат вырезать из центра, со стороной, равной меньшей стороне исходного прямоугольника.
Как вырезать квадрат средствами PHP, я знаю.
А вот как перебрать все картинки по одной в папке? И сколько времени займёт работа такого скрипта (перебор + обрезание)? Размер исходной картинки не более 100 кб.
Поделитесь, пожалуйста, у кого опыт есть? Спасибо.

A: Получаешь список файлов в дирректории
$files = scandir( '/home/username/images );

Потом проходишься foreach'ем по этому списку и пробуешь открывать их при помощи imagick или gd. Кто выкинул исключение, того пропускаем, остальных режем. Или можно ещё имя файла проверять на расширение. Как-то так.


text:
Q: Github pages for Github project I am new to Github pages. I followed their instructions for User, Organization, and Project Pages and Creating Project Pages manually,
so I have something up at oresoftware.github.io, which is my Github "user site".
Now I am looking to put something up at oresoftware.github.io/suman, a "project site".
The problem, and this might be telling, is that
oresoftware.github.io/suman/index.html is available
but I get a 404 when going to
oresoftware.github.io/suman
there is probably a good reason for that, but I am not that knowledgeable with the www.
Why would this be? The project structure for my github repo (gh-pages branch) might give info about why - https://github.com/ORESoftware/suman/tree/gh-pages

A: As of today's date, your repo https://github.com/ORESoftware/suman has no gh-pages branch
a gh-pages branch is required for Github Pages


text:
Q: Phonegap How to open Spotify url in Spotify app I need to know How to open Spotify url in Spotify native app in Android and iOS. The example for opening facebook is
if(device.platform == "Android"){
    scheme = "com.facebook.katana";
}else if(device.platform == "iOS"){
    scheme = "fb://";
}
window.open(url, "_system");

A: RTFM
Use inAppBrowser
http://docs.phonegap.com/en/3.3.0/cordova_inappbrowser_inappbrowser.md.html#InAppBrowser
Stackexchange wants more words in my message.


text:
Q: I need to create Bullets in XNA, C# but an error in the Bullets class tells me that "texture" doesnt have a value public class Bullet
    {
        public Rectangle boundingBox;
        public Texture2D texture;
        public Vector2 origin;
        public Vector2 position;
        public bool isVisible;
        public float speed;

        public Bullet (Texture2D newTexture)
        {
            speed = 10;
            texture = newTexture;
            isVisible = false;
        }
        public void Draw(SpriteBatch spritebatch)
        {
            spritebatch.Draw(texture, position, Color.White);
        }
    }

public class ClasePersonaje : Microsoft.Xna.Framework.Game
    {
        public Texture2D PersonajePrincipalClase { get; set; }
        public int Filas { get; set; }
        public int Columnas { get; set; }
        public int marcoMax { get; set; }
        public int marcoMin { get; set; }
        public int marcoActual { get; set; }
        private int marcosTotales;
        private double contadorFrames;
        public static int posPersonajePrincipalX = 30;
        public static int posPersonajePrincipalY = 30;

        public Texture2D bulletTexture;
        public float bulletDelay;
        public List<Bullet> bulletList;

        public ClasePersonaje(Texture2D texturaPersonajePrincipal, int filas, int columnas)
        {
            PersonajePrincipalClase = texturaPersonajePrincipal;
            Filas = filas;
            Columnas = columnas;
            marcoActual = marcoMin;
            marcosTotales = filas * columnas;

            bulletList = new List<Bullet>();
            bulletDelay = 20;
        }
        public void Draw(SpriteBatch spriteBatch, Vector2 location, float size)
        {
            int ancho = PersonajePrincipalClase.Width / Columnas;
            int altura = PersonajePrincipalClase.Height / Filas;
            int fila = (int)((float)marcoActual / (float)Columnas);
            int columna = marcoActual % Columnas;

            Rectangle rectanguloOrigen = new Rectangle(ancho * columna, altura * fila, ancho, altura);
            Rectangle rectanguloDestino = new Rectangle((int)location.X, (int)location.Y, (int)(ancho * size), (int)(altura * size));

            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null);
            spriteBatch.Draw(PersonajePrincipalClase, rectanguloDestino, rectanguloOrigen, Color.White);
            spriteBatch.End();

            foreach (Bullet b in bulletList)
            {
                b.Draw(spriteBatch);
            }
        }
        public void Update()
        {
            if (Game1.disparo)
            {
                Shoot();
            }
            UpdateBullets();
            if (contadorFrames >= 100)
            {
                if (marcoActual < marcoMin || marcoMax <= marcoActual)
                {
                    marcoActual = marcoMin;
                }
                else
                {
                    marcoActual++;
                }
                if (Game1.derPersonaje)
                {
                    if (Game1.derDisparo)
                    {
                        marcoMin = 0;
                        marcoMax = 3;
                    }
                    else if (Game1.izqDisparo)
                    {
                        marcoMin = 4;
                        marcoMax = 7;
                    }
                    else if (Game1.arDisparo)
                    {
                        marcoMin = 8;
                        marcoMax = 11;
                    }
                    else if (Game1.abDisparo)
                    {
                        marcoMin = 12;
                        marcoMax = 15;
                    }
                    if (!Game1.arDisparo && !Game1.abDisparo && !Game1.derDisparo && !Game1.izqDisparo)
                    {
                        marcoMin = 0;
                        marcoMax = 3;
                    }
                    posPersonajePrincipalX += 10;
                }
                else if (Game1.izqPersonaje)
                {
                    if (Game1.derDisparo)
                    {
                        marcoMin = 0;
                        marcoMax = 3;
                    }
                    else if (Game1.izqDisparo)
                    {
                        marcoMin = 4;
                        marcoMax = 7;
                    }
                    else if (Game1.arDisparo)
                    {
                        marcoMin = 8;
                        marcoMax = 11;
                    }
                    else if (Game1.abDisparo)
                    {
                        marcoMin = 12;
                        marcoMax = 15;
                    }
                    if (!Game1.arDisparo && !Game1.abDisparo && !Game1.derDisparo && !Game1.izqDisparo)
                    {
                        marcoMin = 4;
                        marcoMax = 7;
                    }
                    posPersonajePrincipalX -= 10;
                }
                else if (Game1.arPersonaje)
                {
                    if (Game1.derDisparo)
                    {
                        marcoMin = 0;
                        marcoMax = 3;
                    }
                    else if (Game1.izqDisparo)
                    {
                        marcoMin = 4;
                        marcoMax = 7;
                    }
                    else if (Game1.arDisparo)
                    {
                        marcoMin = 8;
                        marcoMax = 11;
                    }
                    else if (Game1.abDisparo)
                    {
                        marcoMin = 12;
                        marcoMax = 15;
                    }
                    if (!Game1.arDisparo && !Game1.abDisparo && !Game1.derDisparo && !Game1.izqDisparo)
                    {
                        marcoMin = 8;
                        marcoMax = 11;
                    }
                    posPersonajePrincipalY -= 10;
                }
                else if (Game1.abPersonaje)
                {
                    if (Game1.derDisparo)
                    {
                        marcoMin = 0;
                        marcoMax = 3;
                    }
                    else if (Game1.izqDisparo)
                    {
                        marcoMin = 4;
                        marcoMax = 7;
                    }
                    else if (Game1.arDisparo)
                    {
                        marcoMin = 8;
                        marcoMax = 11;
                    }
                    else if (Game1.abDisparo)
                    {
                        marcoMin = 12;
                        marcoMax = 15;
                    }
                    if (!Game1.arDisparo && !Game1.abDisparo && !Game1.derDisparo && !Game1.izqDisparo)
                    {
                        marcoMin = 12;
                        marcoMax = 15;
                    }
                    posPersonajePrincipalY += 10;
                }
                if (!Game1.abPersonaje && !Game1.arPersonaje && !Game1.derPersonaje && !Game1.izqPersonaje)
                {
                    marcoActual = 12;
                }
                contadorFrames = 0;
            }
            else
            {
                contadorFrames += Game1.ElapsedTime;
            }
        }
        public void Shoot()
        {
            if (bulletDelay >= 0)
            {
                bulletDelay--;
            }
            if (bulletDelay <= 0)
            {
                Bullet b = new Bullet(bulletTexture);
                b.position = new Vector2(posPersonajePrincipalX, posPersonajePrincipalY);
                b.isVisible = true;
                if (bulletList.Count() < 20)
                {
                    bulletList.Add(b);
                }
            }
            if (bulletDelay == 0)
            {
                bulletDelay = 20;
            }
        }
        public void UpdateBullets()
        {
            foreach (Bullet b in bulletList)
            {
                b.position.Y -= 10;
                if(b.position.Y <= 0)
                {
                    b.isVisible = false;
                }
            }
            for (int i = 0; i < bulletList.Count(); i++)
            {
                if(!bulletList[i].isVisible)
                {
                    bulletList.RemoveAt(i);
                    i--;
                }
            }
        }
    }

The error is in the texture inside the Draw Method of the Bullet Class (it says that it is null). I've been trying to solve this for 5 days and I still couldn't find a solution. And i know it's not that difficult but I'm new to programming and XNA (I started this in March)


text:
Q: Serving image from external resource Using a webservice we are retrieving data and displaying it in our SalesForce Environment using lightning components. This webservice is password protected and we are passing the credentials along with our webservice requests.
This webservice can also serve images, but these are also password protected, so I can not add this URL in an  tag. I have now solved it by making an httpconnection and base64 encoding the result data. Then let aura place the value in the src attr.
Is this the best way of solving this or would there be another recommended SalesForce way of doing this?

A: To solve this issue I have done the following, download the image using apex with an httpconnection and base64 encoding the result data and add the String data:image;base64,. Then let aura place the value in the src attr.
Then start a job to store the downloaded image as an attachment in the Salesforce database. The next time the image is requested, it can serve the image using the following URL: /servlet/servlet.FileDownload?file=<some_image_id>


text:
Q: How to get OTG files via Storage Access Framework So, I want to read a very specific file from any connected USB OTG drive. It's a text file that should be stored on a USB stick and I need to read that file, which has a specific name, say myFile.txt. While I understand this kind of getting user input is dumb and not user-friendly, it's what I'm told to implement.
But my problem is, that there are many mount points for USB Drives. on my phone it's /storage/USBStorage1, while on my friend's it's /storage/[HEX_ID]. I tried to get all of them, but it's not possible. in Nexus phones it mounts on /mnt/media_rw/[HEX_ID] which requires root access.
I searched around a little and found SAF, but I didn't find anything on how to use it to open any file without user's direct selection. I don't want the picker to show up. I just want to check if [USB_OTG_PATH]/myFile.txt exists or not, and if it exists I want to read it.
And on a sidenote, do I need to have root acces to read /mnt folders (except media_rw)?

A:
I didn't find anything on how to use it to open any file without user's direct selection

That is because there is no option for this.

I just want to check if [USB_OTG_PATH]/myFile.txt exists or not, and if it exists I want to read it.

That is not supported.
If your file is located in one of the directories returned by getExternalFilesDirs(), getExternalCacheDirs(), and getExternalMediaDirs(), then you can access it directly using normal Java file I/O. However, AFAIK, that directory needs to be created as part of running your app — another developer ran into problems trying to create the directories ahead of time. So, for your use case, this approach is unlikely to be practical, though with luck I am wrong and it proves useful to you.

do I need to have root acces to read /mnt folders (except media_rw)?

In general, yes, though in practice the answer varies by device, Android OS version, etc.


text:
Q: Is there any benchmark tool for FUSE file systems? I was searching for a benchmark tool for some FUSE file system implementation, I found a file system benchmark tool in general which is called iozone, but it seems that it has problems specifically with FUSE, it actually didn't work for me...

A: If iozone gives poor results with a FUSE filesystem, I'd say that just means the filesystem or FUSE has problems in general, which will cause you to see poor performance in actual use of the filesystem. That's certainly been my experience: I have yet to see a FUSE based filesystem that performs anywhere near what you get with an in-kernel filesystem.
Personally, I find Bonnie++ easier to use and its results easier to interpret. But, I don't expect it to give qualitatively different results than you'd get from IOzone.

A: I wrote a little script called fs-performance to evaluate the performance of my own fuse file system. The script itself is very alpha. It only supports measurement of ls operations right now.


text:
Q: How to add filetype to meta value when using wp_upload_bits? I've set up a custom post type and would like to have the ability to attach files to those posts. I've got the CPT and metabox set up, and the upload function as well.
When I display the CPT on the front end, I'd like there to be a download link for the file. To simplify things, I'd like to use the included MIME type icons (wp-includes/images/crystal/document.png for example). Using wp_upload_bits() there's no MIME in the meta array.
Is it possible to add the MIME type to the function? Or should I be looking at another function/method of identifying the MIME?
Here's my upload code:
 $upload = wp_upload_bits($_FILES['resources_attachment']['name'], null, file_get_contents($_FILES['resources_attachment']['tmp_name']));

 if(isset($upload['error']) && $upload['error'] != 0) {
   wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
 } else {
 add_post_meta($id, 'resources_attachment', $upload);
 update_post_meta($id, 'resources_attachment', $upload);
 }

A: Ended up using wp_handle_upload(), which puts MIME type into the DB automatically. See http://codex.wordpress.org/Function_Reference/wp_handle_upload
One thing to note, this function enters the file in the DB as post meta and not as an attachment. wp_insert_attachment() would do the latter.


text:
Q: Why does my image stacking code cause color banding and overflow in the result? I made a simple program to stack images with opencv. What it does is simply take two same pixels in two images and average the colours. Code works great except for brighter areas in the image.
Before using the program with different images I tested it with one image. Result should be the same as I use the same image. But after saving the image the darker areas of the image have not changed. But brighter areas have changed to different coloures.
This is the original image.

Image after stacking.

This is the code I used. Written in python.
import cv2
import os
import numpy as np

np.seterr(over ="ignore") # hide numpy errors

# image folder
folder = "sample/"

# list all the images in folder
img_lst = [folder + i for i in os.listdir(folder)]

# get number of row and columns in an image
img = cv2.imread(img_lst[0] , -1)
print("processing image 1: " + img_lst[0], ", rows: " + str(img.shape[0]) + ", columns: " + str(img.shape[1]))

rows = img.shape[0]
columns = img.shape[1]

# output image
final_img = np.asarray(img)
final_img.setflags(write=True)

# stacking
img_num = 1; row = 0; column = 0; color = 0

while img_num< len(img_lst): # read all the images int he list

    img = np.asarray(cv2.imread(img_lst[img_num] , -1))
    print("processing image " + str(img_num + 1))

    # read all the pixels
    while row< rows:
        while column< columns:
            while color<3:
                # average the color of image
                final_img[row][column][color] = int((final_img[row][column][color] + img[row][column][color])/2)
                color += 1

            color =0
            column += 1

        column = 0
        row += 1

    row = 0
    img_num += 1

print("finished...")
cv2.imwrite(folder + "final.jpg", final_img) # write the final image

So what could be the problem. I thought this is because of RGB to BGR conversion in opencv. But seems like it's not.


text:
Q: Why is JdbcTemplate null in my JUnit test? I have a test сlass with a method where I add some data to the database and then retrieve it and check if the data is the same:
public class QueryImplTest {
    @Autowired
    Jdbc jdbcTemplate;

    QueryImpl queryImpl = new QueryImpl(jdbcTemplate);

    @Test
    public void someTest() {
    SomeObject someExpectedObject = new SomeObject(//object
    queryImpl.saveSomeObject(someExpectedObject)
    SomeObject someRealObject = jdbcTemplate.queryForObject(SELECT_OBJECT_QUERY, SomeObject.Class)
    //all of the Assertions

}

And I get a Cannot invoke JdbcTemplate.update()(from saveSomeObject method) because this.jdbcTemplate is null
The QueryImpl class:
@Repository
public class QueryImpl {

    private JdbcTemplate jdbcTemplate;
    @Autowired
    public QueryImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    //methods and query strings

}

A: I can see you are Autowiring Jdbc class in the test case. That is incorrect. Please use JdbcTemplate class. Here is the fixed version of your test case.
@JdbcTest
public class QueryImplTest {

    @Autowired
    JdbcTemplate jdbcTemplate;

    QueryImpl queryImpl = new QueryImpl();

    @Test
    public void someTest() {
    SomeObject someExpectedObject = new SomeObject(//object
    queryImpl.saveSomeObject(someExpectedObject)
    SomeObject someRealObject = jdbcTemplate.queryForObject(SELECT_OBJECT_QUERY, SomeObject.Class)
    //all of the Assertions

}

If you need more details please read this article.
https://www.baeldung.com/spring-jdbctemplate-testing


text:
Q: Isomorphism of circulant graphs Can circulant graphs be isomorphic to any non-circulant regular graph?
I am trying to show uniqueness of a graph for a given independence polynomial and the graph I obtained is a circulant graph on 9 vertices.
My question is..
Does there exists any non circulant graph which is isomorphic to circulant graphs?


text:
Q: ERROR: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress I have a WordPress site. Suddenly, it stopped working everything that was working in the previous day. The next day I am unable to login. It gives the following error:

ERROR: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress.

I don't think there is any problem with its plugins. I have a similar website with the same theme and plugins, and the site is working fine.
My WordPress was automatically updated two days ago from 3.7 to 3.8, but it worked fine for two days. How can it cause a problem after two days?

A: There could be the following issues in your site.
Coding Error
Unnecessary Spaces in Code
Caching & Security Plugin

Check more here: https://www.scratchcode.io/cookies-are-blocked-or-not-supported-by-your-browser/


text:
Q: How to make "this" in nested function refer to parent object or what is the best practice to this problem? From example code below
I'm trying to add a method inside an object where it generates new name based on object properties
but "this" in this context is referring global object  but not the parent one
It's ok using arrow function but the functions won't be hoisted and I need to express the function before using it. I prefer knowing what it does before seeing the code.
using arrow function expression it does work but is not hoisted
using function declaration it doesn't work but is hoisted
Is there any best practice approach to this kind of problem?
const agent = {
  firsName: "John",
  lastName: "Depp",
  born: 12/04/1987,
  secretName: function() {

      return newFirstName() + newLastName()

    function newFirstName() {

      // complex codes here

      return "Agent " + this.firstName // for simplicity
      }

    function newLastName() {

      // complex codes here

      return "Agent " + this.LastName // for simplicity
    }
  },
};

console.log(agent.secretName()) // logs  "Agent undefinedAgent undefined"

A: It's probably due to the lexical scope of your functions. You can read more about it here and here.
So if you move your helper functions one level up, it solves the problem:
const agent = {
  firstName: 'John',
  lastName: 'Depp',
  born: 12 / 04 / 1987,
  newFirstName: function () {
    // complex codes here

    return 'Agent ' + this.firstName; // for simplicity
  },
  newLastName: function () {
    // complex codes here

    return 'Agent ' + this.lastName; // for simplicity
  },
  secretName: function () {
    return this.newFirstName() + this.newLastName();
  },
};

console.log(agent.secretName()); // logs  "Agent undefinedAgent undefined"

A: you should use arrow function so they can target their parent scope.
const agent = {
  firstName: "John",
  lastName: "Depp",
  born: 12/04/1987,
  secretName: function() {
        const  newFirstName = () => {
      return "Agent " + this.firstName;
      }
    const newLastName = ()  => {
      return " Agent " + this.lastName;
      }

    return newFirstName() + newLastName();
  },
};
console.log(agent.secretName())

A: Ok I have found the answer from this thread How to access the correct `this` inside a callback?
In short: just define the outer scope
let self = this
Example
const agent = {
  firstName: "John",
  lastName: "Depp",
  born: 12/04/1987,
  secretName: function() {
    const self = this;

      return newFirstName() + newLastName()

    function newFirstName() {
      return "Agent " + self.firstName
      }
    function newLastName() {
      return "Agent " + self.lastName
   }
  }
}

console.log(agent.secretName()) // logs JohnJohn it works!!


text:
Q: Use Electron with Bootstrap 5 doesn't work I am creating my first electron app and wanted some styling with bootstrap 5.
So I:
(1) installed via npm i --save bootstrap jquery popper.js the necessary modules
(2) created a main.scss including @import '~bootstrap/scss/bootstrap';
(3) put into the head of my index.html:
   <link rel="stylesheet" href="./contents/bootstrap/5.0.2/css/bootstrap.min.css" />
    <script>let $ = require('jquery');</script>
    <script>require('popper.js');</script>
    <script>const bootstrap = require('bootstrap');</script>

After that I copy+paste a nav bar out of the bootstrap documentation. I dont know what is wrong and I didnt find any answer. Thanks for helping.

A: Bootstrap 5 doesn't use jQuery any longer.
Just do:
npm i --save bootstrap@latest


text:
Q: Redirect based on symlink using htaccess I'm using Capistrano to deploy Git repos and currently, I'm having an issue with redirection using .htaccess and the symlink setup.
Here's the run-down:

*

*I have dev.example.com as a sub-domain on MediaTemple GS.

*Under the dev.example.com folder, I have client folders e.g. dev.example.com/client

*Under dev.example.com/client Capistrano has /releases, /shared, /tmp and a symlink of /current pointing to the /releases folder (so any visits to /current always show the curren version of the site)

Ideally, I would like anyone visiting dev.example.com/client to be redirected to that /current folder in order for it to continue following the symlink path.
I put the following in an .htaccess in the /client folder:
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^client.*$ /current [L]

But, it fails miserably :(
Normally, there would be an /html folder and it's as simple as using a symlink of: ln -s ./current ./html but given this is a sub-directory the /html has no meaning. (I guess I could create an /html directory and figure out how to make visits to /client go to /html but that seems crazy).
Any help would be greatly appreciated!

A: If you've put the rules in the /client folder, then you don't need to match against client as it's automatically stripped off. Try just:
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^$ /current/ [L]

Or if you want requests for /client/whatever to also go to /current/whatever:
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)$ /current/$1 [L]


text:
Q: USB bootable drive preventing me to access BIOS I have a Thomson-branded netbook that has a microSD card as unique storage area. The SD shows 58.xx GB of disposable space.
There was a Windows 10 instance I wanted to wipe in order to restaure my own windows10 acronis true image backup, however even though it was few MB less than the maximum, it couldn't manage to restaure. I acccessed the bios through 'Esc' key.
So I used a PopOS live-try bootable to use gparted and wipe the SD card (tried to format it "empty", MSDOS, and FAT32). However after that, I was only able to boot on EFI shell and type exit to access the BIOS, that did not show my Win10 bootable plugged in before the boot.
After  that I decided to fresh install Kubuntu, which suggested me to install an EFI "system partition" alongside the remainder for / the root partition. It went all good and I am able to boot on Kubuntu.
However now I'm only able to access the BIOS through spamming Esc when the win10bootable isn't plugged. Whenever I try to boot with it plugged in, I'm stuck on the manufacturer (Thomson red logo) screen, and no BIOS shows up for me to choose the USB stick to boot on.
Here is a pic of the win10bootable content, I believe it's not corrupted since it shows up flawlessly on an ubuntu16.04 system. + Another picture of what looks like my BIOS when I access it without a bootable plugged, and after having flashed kubuntu :

https://imgur.com/a/chkET4t
What to do please? Regards
[edit] to answer @Madhubala,

*

*the win10 bootable works on another dualboot HP machine (its BIOS recognizes it)

*gparted isn't able to format partitions to gpt

*but I tried keeping the 100MiB partition dev/mmcblk0p1 in fat32 (gparted flags are "boot, esp") and format dev/mmcblk0p1 (gparted flag "msftdata") in ntfs : BIOS still not accessible and stuck on OEM screen.

*when formating the whole eMMC to ntfs, same freeze.

Would you have other hints ? regards

A: Maybe try something like Ventoy (https://www.ventoy.net/en/index.html)
to install the OS. It does not care about BIOS and is always seen by
system during boot menu.


text:
Q: Nashorn--Only one class is used to get its bytecode Nashorn,"Java.extend function returns a type object for a subclass of the specified Java class (or implementation of the specified interface) that acts as a script-to-Java adapter for it."
I passed Java.extend(xxx,{xxx: function(){}}).class get a class object,and I want to write its bytecode on a file.
What should I do?

A: Nashorn doesn't support this directly, however you can do something yourself using the Java instrumentation API, and implementing a ClassFileTransformer.


text:
Q: Booksleeve - Setting multiple Hash Values and retrieve them at once I'm trying to set multiple fields of a hash independently and retrieve them all at once later on. Is the code below supposed to work or am doing something wrong here? When I run it locally against redis-2.0.0-x64 on Windows downloaded from the Service Stack site, the result of task3 will always just contains field2.
var con = RedisConnectionManager.Instance.GetConnection();
var key = "somekey1";

// set the field value and expiration
var task = con.Hashes.Set(1, key, "field1", token.ToByteArray())
    .ContinueWith((x)=> con.Keys.Expire(1, key, 7200));
task.Wait();

var task2 = con.Hashes.Set(1, key, "field2", "fooobar");
task2.Wait();

var task3 = con.Hashes.GetAll(1, key);
task3.Wait();

A: Cannot reproduce this on a reasonably current version of redis - looks fine here:
using (var con = Config.GetUnsecuredConnection())
{
    var key = "somekey1";

    // set the field value and expiration
    var task = con.Hashes.Set(1, key, "field1", Encoding.UTF8.GetBytes("hello world"))
        .ContinueWith((x) => con.Keys.Expire(1, key, 7200));
    task.Wait();

    var task2 = con.Hashes.Set(1, key, "field2", "fooobar");
    task2.Wait();

    var task3 = con.Hashes.GetAll(1, key);
    task3.Wait();

    Assert.AreEqual(2, task3.Result.Count);
    Assert.AreEqual("hello world", Encoding.UTF8.GetString(task3.Result["field1"]));
    Assert.AreEqual("fooobar", Encoding.UTF8.GetString(task3.Result["field2"]));
}

or, more efficiently (uses pipelining, by not waiting):
using (var con = Config.GetUnsecuredConnection())
{
    var key = "somekey1";

    // set the field value and expiration
    con.Hashes.Set(1, key, "field1", Encoding.UTF8.GetBytes("hello world"));
    con.Keys.Expire(1, key, 7200);
    con.Hashes.Set(1, key, "field2", "fooobar");
    var task = con.Hashes.GetAll(1, key);
    con.Wait(task);

    Assert.AreEqual(2, task.Result.Count);
    Assert.AreEqual("hello world", Encoding.UTF8.GetString(task.Result["field1"]));
    Assert.AreEqual("fooobar", Encoding.UTF8.GetString(task.Result["field2"]));
}

So yes: should work, and seems to work. Note I'm using 2.4.5 locally; 2.0 is very old now, and has a number of important bugs. It is entirely possible that there was a bug relating to HSET plus EXPIRE at the server - in which case there isn't much the client library can do to compensate.
I strongly suggest using a more "current" build of redis-server than 2.0. If one isn't available, you might want to try the dmajkic binaries (goes to 2.4.5), or the [MSOpenTech]*https://github.com/MSOpenTech/redis) source. However!!! This is just for local debugging. For production work at the current time (i.e. until the MSOpenTech code is happy-happy), I would recommend using a linux server to host redis. Ubuntu Server works well.


text:
Q: loop javascript function for each row after add new row I have a row in a table that can be duplicated by javascript. In the first row I have a javascript code that makes a calculation.
After duplicating a new row the calc javascript is not working for the new row..
What i do wrong?
table row:

    <form action="ProjectParameterNewRecord.php" method="post">

                <input type="text" id="Parameters" name="TypeOfOut" />

                <?php include "ExchangeRates.php"?>

                <input id="Cost" type="number" value="" class="ee105" name="Cost" onchange="changeCost()">

                <input id="Amount" type="number" value="" class="ee105" name="Amount" onchange="changeAmount()">

                <input type="hidden" id="ParameterID" name="ParameterID"></input>

                <input type="hidden" id="ProjectID" name="ProjectID" value="3"></input>

                <input type="submit" value="Submit">

    </form>

code to create a new row:

javascript code to calculate:
function CalcUnitValue() {
    var U = document.getElementById("Unit").value;
    var SUM = -1 * ((((($('#Amount').val())) * (((($('#Cost').val())) * (($('#Unit').val())))))));
    document.getElementById("minisum").innerHTML = SUM;
    document.getElementById("minisum").readOnly = true;
}

function changeCost() {
    var C = document.getElementById("Cost").value;
    var SUM = -1 * ((((($('#Amount').val())) * (((($('#Cost').val())) * (($('#Unit').val())))))));
    document.getElementById("minisum").innerHTML = SUM;
    document.getElementById("minisum").readOnly = true;
}

function changeAmount() {
    var C = document.getElementById("Amount").value;
    var SUM = -1 * ((((($('#Amount').val())) * (((($('#Cost').val())) * (($('#Unit').val())))))));
    document.getElementById("minisum").innerHTML = SUM;
    document.getElementById("minisum").readOnly = true;

}

function changeUnit() {
    var C = document.getElementById("Amount").value;
    var SUM = -1 * ((((($('#Amount').val())) * (((($('#Cost').val())) * (($('#Unit').val())))))));
    document.getElementById("minisum").innerHTML = SUM;
    document.getElementById("minisum").readOnly = true;

}

function minisum() {
    var SUM = -1 * ((((($('#Amount').val())) * (((($('#Cost').val())) * (($('#Unit').val())))))));
    return alert(document.getElementById('minisuminput').innerHTML);

thank you :)

A: *

*Your HTML is invalid. You have an extra closing 	 in the middle. You also need to put the form outside the table.

*You can't have duplicate IDs in a HTML page and expect to reference anything except the first one. Use classes instead.

*Don't use inline event handlers with jQuery. Use delegated jQuery handlers if you have dynamically added elements.

*Use an element hidden in the page to hold your template. If you store it in the HTML, and not code, you would have noticed your </select> was missing and replaced by an extra 	.

*You mix JavaScript selectors with jQuery. Just stick to jQuery selectors. They are shorter.

*None of the extra parenthesis are required for a * b * c * d equations.

*inputs and img elements are meant to be self-closing, not have end tags.

*All your calculations are exactly the same, so reuse the code.

*Get into the habit on using consistent case (upper/lower/mixed) for variables and classes.

Use delegated event handlers like this:
$(document).on('change', '.cost,.amount,.unit,.parameters', function() {
    var $tr = $(this).closest('tr');
    var sum = -1 * $('.Amount', $tr).val() * $('.cost', $tr).val() * $('.Unit', $tr).val();
    $(".minisum", $tr).html(sum);
}

Re templating: you can store your template row in a dummy script block, with unknown type (I use text/template) and it will be ignored by the browser.
e.g.

You will note a {counter} placeholder where you wanted to insert a new value. Use it as the HTML source to create new rows.
e.g.
$('table.Parameter#new').append($('#template').html().replace('{counter}', counter));

JSFiddle to play with ( most of this functional): https://jsfiddle.net/TrueBlueAussie/33e9ptgu/

A: It looks like your problem is coming from having duplicate ids.  When there are duplicate ids, the behavior of document.getElementById() is undefined.  Each browser will try to do something reasonable, but there's no way to know which element will be returned (though it's usually the first element).
One option is to change the duplicated ids to class, and then when creating a new row, give the row it's own unique id using your counter:
var newRow = jQuery('
.....
 ');
This will allow you to access whichever row you want for calculation, as well as it's children using jquery:
Instead of $('#Cost') or document.getElementById("minisum"), use $('#' + [number of rowid]).find('.Cost'); or $('#' + [number of rowid]).find('.minisum');
A couple of other tips:

*

*To get the value of an <input> into your functions, simply pass it as a parameter like so: onchange="changeCost(value)".  Now you can delete 3 of your 4 identical functions as well as remove the first line of the remaining one.

*You don't need closing </input> tags (see here)

*There are two 	 tags on your second column

*Make sure you have correct tag nesting on your
 and </form> tags


text:
Q: Post request body incorrectly parsed i'm trying to make a $http.post like this:
$http({
   method: 'POST',
   url: '//192.168.2.1:3000/auth/signup',
   data: $scope.credentials,
   headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
   }
})

when:
$scope.credentials = {email: 'some_email', password: 'some_password'}

and in Node, I'm logging:
console.log(req.body)
and I get:
{ '{"email":"some_email","password":"some_password"}': '' }

i don't understand why this is happening.

A: You're assuming angularjs is automatically serializing form data for you.
You need to serialize your form data yourself when dealing with content types that are not json.
For instance, when the Content-Type equals 'application/x-www-form-urlencoded' , given an object {foo:"bar",bar:"baz"} , it needs to be serialized as foo=bar&bar=baz


text:
Q: wrapper for a function with variable arguments in C Recently I wanted to implement a printf wrapper. After some search I found the vprintf is good for this need:
void my_printf(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    vprintf(fmt, args);
    va_end(args);
}

But is it possible to implement such a wrapper for printf or any other similar functions with variable arguments instead of va_list?
(I mean, what if they don't provide a v version?)

Since some commenter didn't fully capture my idea, I'd better elaborate it.
Suppose you have a plain printf function as in the C library.
Some one gives you a fmt string "%d %u %f", and corresponding inputs.
Now you want to write a function similar to printf, but with all %f replaced by %.2f.
Of course you can use two statements to finish the task:
replace(fmt, "%f", "%.2f");
printf(fmt, inputs);

But if you use this function many times, probably you want to have a wrapper to save some time.
A macro can finish this task, of course. But is it possible without a macro, like:
void myprintf(fmt, ...)
{
    replace(fmt, "%f", "%.2f");
    printf(fmt, inputs);
}

The problem here is that you don't know how to feed the inner printf with the arguments ... of myprintf.
Hope this clarifies.

A: If you just want to use this to prepend an string to the output or so, you could use a variadic macro.
#define MYPRINT(...) printf("toto has: " __VA_ARGS__)

in that simple example this suppposes that format that you pass in is a string literal, so this is a bit restricted. But I hope you see the pattern how to use such simple macro wrappers.

A: There is no portable way to construct a call to a variadic function when the API don't offer you functions with va_list parameter.
However, you could [ab]use the libffi for that purpose, by constructing the variadic call and doing it.


text:
Q: How to switch accounts in react native I'm trying to build react native app in which user will have option to switch multiple accounts, similar to Instagram. My problem is, How to change user data on when user switches account.

A: You can use react-native-keychain to store the Active User and User List. This will store the data in Device.
const StoreData = async () => {
   let activeUser = 'User1'
   let userList = [
      { ID: 'User1' },
      { ID: 'User2' }
   ]
   userList = JSON.stringify(userList)
   await Keychain.setGenericPassword(activeUser, userList); // Note: activeUser and userList should be string.
}

const RetrieveData = async () => {
   try {
      const credentials = await Keychain.getGenericPassword();
      if (!credentials)
         return console.log('No credentials stored')

      let { username: activeUser, password: userList } = credentials
      userList = JSON.parse(userList)
      return console.log({ activeUser, userList })
    } catch (error) {
        return console.log("Keychain couldn't be accessed!", error);
    }
}

If you are using library similar to Redux, MobX, ... You can use them to refresh the APP with the selected user.

A: One way you could do this is by having the token of the other users and then retrieve all the user data everytime you switch users.


text:
Q: Docker API not accessible from within a container I can make cUrl calls to Docker API but if I run the same script from a container (docker-compose), I can't reach any API endpoint.
My requests looks like :
$ curl --unix-socket /var/run/docker.sock -X POST http:/localhost/containers/json

The reason could be the use of localhost but I can't find the solution for now. Any suggestions?
EDIT : Here's a brief summary of the stack i'm using (Api-Platform https://api-platform.com/). Every container is attached to an "api_default" bridge network :

*

*php = Symfony based application

*nginx = NGINX web server

*psql = Hosts the main database

*mssql = Used to sync datas

*...

I do have a shell script in my "php" container which is meant to reach the Docker API. To summarize, I request the "mssql" container to sync with an external service and then I ask to "psql" container to copy those datas (export/import done with csv files through shared volumes).
The problem is :

*

*If I do docker-compose exec php bin/console app:sync (Symfony command which runs the script), everything works fine : the containers communicate through docker.sock with the Docker API and I can sync my databases.

*But if I run the same script with an api endpoint (localhost:8080/api/sync) or via a VueJS app (Axios), the Docker API never return any response.

Below is a part of my script :
curl -XPOST -H 'Content-Type: application/json' \
      --unix-socket /var/run/docker.sock http:/localhost/containers/mssql/exec \
      -d '{
        "AttachStdout":true,
        "Tty":true,
        "Cmd":["/opt/mssql-tools/bin/sqlcmd", ...]
      }'

And here is the way I call my Symfony command in the api endpoint Controller :
 /**
  * @Route("/api/sync", name="sync", methods={"GET"})
  */
  public function sync(KernelInterface $kernel)
  {
    $application = new Application($kernel);
    $application->setAutoExit(false);

    $input = new ArrayInput(array(
        'command' => 'app:sync'
    ));

    $output = new BufferedOutput();
    $application->run($input, $output);
    $content = $output->fetch();

    return new Response($content);
  }

Maybe should I replace "localhost" with "api_default" to reach the good network, but that doesn't work ... ?

A: the localhost you try to connnect is the localhost in the container you run curl
you should find and replace with its host ip

A: Yep. If you want to communicate between one docker container and another docker container, at the very least, you need to use the service name instead of localhost because, as @BMW said, localhost is relative to the machine you are on, and from the container's point of view, localhost is the container itself.
I had a similar situation recently where it wasn't enough to use the service name. I also had to create a network and add each service to that network. Like this:
my_service:
    ...
    ...
    ...
    networks:
      - backend

networks:
  backend:
    driver: bridge


text:
Q: iOS SWIFT - JSON object nil after NSJSONSerialization hello I am trying to read JSON as an array from the server not the dictionary. If  I do this
let json: NSArray?
do {
    json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSArray
    print("json is \(json)")
}

json object comes nil through this code and also I can't access the variable like this json["code"] I have tried this too
NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as! NSArray

But If I don't specify any type and let the variable as AnyObject
do {
    let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
    print("json is \(json["code"]!)")
}

It works But 1st problem here is it prints Optional in the debugger but its least of my worries compared to that I can't do something like this
if json["code"] == 200 {

}

If I do this it says
Binary operator '==' cannot by applied to operands of type Anyobject? and Int
what I want is to get the data in NSArray. I don't want the json variable to be set as AnyObject. Inshort I want this code to work
let json: NSArray?
do {
    json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSArray
    print("json is \(json)")
}

if its possible. I don't know what I am doing wrong here
json:
 {"code":200,"msg":"login success"}

A: If printing json["code"] works, then json is doubtless a dictionary.
JSONObjectWithData returns AnyObject that is
 "I-have-no-idea-what-it-is-but-it-is-some-kind-of-object-and-not-a-value" (thanks to gnasher729 for the more accurate paraphrase of AnyObject)
Since you know the object is [String:AnyObject] cast the type
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! [String:AnyObject]

Then get the code – which is an Int – with
if json["code"] as! Int == 200 {

}

or with optional binding if the key is optional
if let code = json["code"] as? Int {
   if code == 200 {

   }
}


text:
Q: What does "orientation" of a platonic solid really mean? Is there any rigorous definition of "orientation" of a platonic solid?
Lots of books mention that the whole group of symmetries of platonic solids consists of rotations composed with reflections, but I'm not sure how we know that the reflections produce only two possible orientations. Furthermore, rotations are said to preserve orientation whereas reflections are said to "invert" the orientation.
Firstly, by "reflection" I assume they mean reflection about a plane?
Secondly, how do we know that there are only 2 possible "orientations" of a platonic solid and not any more or any less than that?
Some supporting visuals/diagrams would be great as well!

A: Rotations of platonic solids are subgroups of rotations in general. So let's talk why rotations in general preserve orientation. If you take three base vectors $\hat\imath$, $\hat\jmath$, $\hat k$, then the mixed product $(\hat\imath\times\hat\jmath, \hat k)=1 > 0$. If a transformation keeps this product positive, than we say that the transformation preserves orientation. For example, if rotation around $(1,1,1)$ by 120° cyclically swaps base vectors, so we end up with product
$$(\hat\imath_1\times\hat\jmath_1, \hat k_1)=(\hat\jmath\times\hat k, \hat\imath)=1>0$$
and we say that this rotation preserves orientation. If instead, we take a reflection around plane $xy$, then
$$(\hat\imath_1\times\hat\jmath_1, \hat k_1)=(\hat\imath\times\hat\jmath, -\hat k)=-1 < 0$$
and we say that reflection switches orientation.
One can show that distance preserving transformations (rotations and reflections) can make this mixed product either $1$ or $-1$. So there are only two possible orientations.

A: There are two ways of orienting a polygon, which we could think of as clockwise and counterclockwise.
A polyhedron is said to be oriented if each of its faces has been oriented in a consistent way, so that, if an edge is shared by two faces, then the order of its vertices given by one face is the opposite that given by the other face.
$\hspace{2 cm}$
If the (connected) polyhedron is orientable at all, an orientation of one face determines the orientations of all the other faces. So there are precisely two orientations, because any given face has precisely two orientations. This is true for any orientable polyhedron, not just Platonic solids.
A symmetry of the polyhedron can therefore either preserve or reverse / invert the orientation. If we think of the polyhedron as situated in three-dimensional space, and its symmetries as arising from isometries of space with an invariant point (the "origin"), then this conception coincides with the one described by Vasily Mitch, though there's quite a bit to unpack there.
By "reflection," your sources most likely mean reflection across a plane, although reflection across a point is also orientation-reversing, and is the product of the reflections across three mutually perpendicular planes. The point could be any point, of course, and the plane could be any plane. But if the transformations are symmetries of a Platonic solid, the point will be the center of the solid (the "origin"), and the planes will pass through this point.
The fact that the dodecahedron has two orientations is illustrated very prettily by the fact that it contains two compounds of five tetrahedra, a "right-handed" one and a "left-handed" one. Half its symmetries preserve these two compounds, and half reverse them.
$\hspace{1 cm}$
Each orientation-preserving symmetry of the dodecahedron permutes the set of five tetrahedra in a given compound, and in this way the symmetry group is seen to be isomorphic to the alternating group $A_5$. Reflection across the center commutes with all symmetries, so the total group is seen to be isomorphic to $A_5 \times \mathbb{Z}_2$.
Chapter 3 of Coxeter's Regular Polytopes is highly recommended.


text:
Q: ScaNN weight features for similary search I am using ScaNN to perform similarity searches and would like to place more emphasis on some features than others when performing a similarity search.
for example, if I have the following data
name  | age | country | income
John     29     US        $47k
Susan    28     US        $44k
Bill     26     US        $39k
Sarah    35     UK        $100k
Jack     34     UK        $90k
Maggie   37     UK        $95k

and income has more importance, then given the following query:
George, 28, US, $100k

it would return
Sarah, Jack, Maggie

adding more weight to the income feature.
Training data values are normalized before building the similarity index
df_np = preprocessing.normalize(df[features])

and likewise the query values are normalized before performing a search
np_q = preprocessing.normalize([list(query.values())])


text:
Q: Getting java.lang.IncompatibleClassChangeError while running a test Getting error as

java.lang.IncompatibleClassChangeError: class
  org.glassfish.jersey.server.internal.scanning.AnnotationAcceptingListener$AnnotatedClassVisitor can not implement org.objectweb.asm.ClassVisitor, because it is not an interface (org.objectweb.asm.ClassVisitor is in unnamed module of loader 'app')

package com.configuration;

import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.container.*;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import java.io.IOException;

public class EndpointLoggingListenerTest extends JerseyTest {

    private static final String APPLICATION_NAME = "EndpointApplication";
    private static EndpointLoggingListener applicationEventListener;

    @Override
    protected Application configure() {
        applicationEventListener = new EndpointLoggingListener("abc");
        final ResourceConfig resourceConfig = new ResourceConfig(MyResource.class);
        resourceConfig.register(applicationEventListener);
        resourceConfig.register(RequestFilter.class);
        resourceConfig.register(PreMatchingRequestFilter.class);
        resourceConfig.register(ResponseFilter.class);
        // resourceConfig.register(MyExceptionMapper.class);
        resourceConfig.setApplicationName(APPLICATION_NAME);
        return resourceConfig;
    }

    @Test
    public void testMatchedMethod() {
        final Response response = target().path("resource").request().get();
        assertEquals(200, response.getStatus());
        assertEquals("get", response.readEntity(String.class));
    }

    public static class RequestFilter implements ContainerRequestFilter {

        @Override
        public void filter(ContainerRequestContext requestContext) throws IOException {
        }
    }

    @PreMatching
    public static class PreMatchingRequestFilter implements ContainerRequestFilter {

        @Override
        public void filter(ContainerRequestContext requestContext) throws IOException {
        }
    }

    public static class ResponseFilter implements ContainerResponseFilter {

        @Override
        public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        }
    }

    @Path("resource")
    public static class MyResource {

        @GET
        public String getMethod() {
            return "get";
        }

        @POST
        public void post(String entity) {
        }

        @Path("locator")
        public SubResource locator() {
            return new SubResource();
        }
    }

    public static class SubResource {
        @GET
        public String get() {
            return "sub";
        }
    }
}

A: Net, the class AnnotationAcceptingListener was implemented using a version of ClassVisitor, but a new implementation of ClassVisitor has been provided with changes which are not compatible with the Listener implementation.
This is because ASM changed the ClassVisitor implementation when introducing version 4.0.  Before version 4.0, ClassVisitor was implemented as an interface.  Starting with version 4.0, ClassVisitor became an abstract class. See: https://asm.ow2.io/versions.html, and in particular, this text:

11 September 2011: ASM 4.0 RC2 (tag ASM_4_0_RC2) ClassVisitor,
  MethodVisitor, etc interfaces replaced with abstract classes, in order
  to ensure backward binary compatibility in future ASM versions.

Either, you'll need to link in an earlier version of the ASM jar, or you'll need a new implementation of AnnotationAcceptingListener which is compatible with the new ASM APIs.
(Generally, an IncompatibleClassChange error will be reported based on the dependency of a particular class on another class, where the initial, dependent, class is expecting a particular characteristic of the other, dependency, class.  For example, the dependent class might have been compiled while the dependent class was an interface, but the implementation of the dependent class was changed to be a concrete class.  A load of the dependent class made against the initial version of the dependency class works fine.  A load of the dependent class against the updated version of the dependency class fails with an exception.)


text:
Q: How to Mount Western My Book Live Duo I have been reading everything I can to do this and have come to the conclusion that there are too many things I don't understand to make sense of it so finally asking a question.
Goal: I want to mount a folder on WD My Book Live Duo (mbld) so I can use it from application file/folder Open dialogs. Most urgently I need to do a directory comparison using Meld.
I can mount and bookmark it via Files, but it does not appear in a file open dialog.
I have read about 'mounting' it but have not been able to figure it out.
I can get to it from Ubuntu via a Windows workgroup.
Looking in the windows workgroup I see the location as smb://yudmtry/
First question: I don't know how to find the IP address. I have seen recommendations to use a Windows or Mac machine but I don't have one.
Second question: I have read that samba is the easiest way to mount it. Is this the case for Ubuntu GNOME 16.04 which I am using?

A: Answer to first question: Run hostname -I <--- CaSe SeNsItIvE
Answer to your second question: Samba is a network mount. Are you trying to mount it locally, or over the LAN?


text:
Q: Regularization of linear regression problem Consider a vector $a \in R^n$. I want to know how I can find analytically the solution of the following optimization problem: $x^* = argmin_{x \in R^n} f(x)$, where $f(x) = ||x-a||_{2}^2 + \lambda ||x||_1$, $\lambda > 0$ and $||.||_p$ is the p-norm in $R^n$.
Thanks in advance.


text:
Q: window.setInterval('string;', 1); I have seen the following working! setinterval call.
window.setInterval('checkhash();', 1);

Any idea why this is working?
normaly it is like this:
setInterval(function(){
      do something
},1000);

function checkhash(){ };

A: You have several options:
1) hand over a string which is then evaluated (bad - never do this!)
window.setInterval('checkhash()', 4);

This basically runs an evaluation on the string like eval('checkhash()').
Important to know, is that it is evaluated in the global context, so the following will fail:
(function(){
    function test(){alert("foo")};
    function test2(){alert("bar")};

    // will fail
    setTimeout("test()",1000);

    // will work
    setTimeout(test2,1000);

})();

The first timeout will produce an Uncaught ReferenceError: test is not defined, because test() is only known in the context of your anonymous function, but not in the global space:
See example
2) hand over a function reference (the preferred way)
window.setInterval(checkhash, 4);

3) hand over an anonymous function (used, when you need to hand over parameters)
setInterval(function(){
      checkhash(param1,param2);
},4);

Doing the following (common beginners mistake) is possible too:
window.setInterval(checkhash(), 4);

This will call the function immediately and hand over the return value to the timeout to be executed after the specified amount of time.
Important notes:

*

*the execution is asynchronous - the javscript engine will continue with the execution of the rest of your js code.

*The minimal timeout is 4 ms as per spec, so basically 0-3 will give you an interval of at least 4ms (depending on the scheduler of course).

*You have no guarantee that the timeout will trigger in exactly that amount of time. It might even be completely discarded in some very rare circumstances.

A very good reading is John Resig's article about timers.
MDN setTimeout documentation

A: this should be like,
window.setInterval(checkhash, 1);

remove your quotes, and do like this.

A: This is one of the all the JavaScript eval situations, which is not a good practice, if you use string as the first parameter, it automatically get converted to a anonymous function like this:
Function('checkhash();')

So why not passing the first parameter as a function, which is the other alternative and more reasonable one.
window.setInterval(function(){
    checkhash();
}, 1);

or simply:
window.setInterval(checkhash, 1);

the only problem this way is sometimes you need to use JavaScript closures to keep you your variable values stable.


text:
Q: What kind of bats live in the Batcave in Christopher Nolan's Batman? Near the start of Batman Begins young Bruce Wayne falls down a well and gets attacked by bats. Later we meet the bats again when he first discovers the bat cave and in one scene Batman uses the bats to destroy a Swat team. Is there any evidence of what type of bat they are in-universe. Does the habitat or extremely strong swarming and mobbing response to humans suggest what species they might be?

A: American Brown Bats

The vast caverns had once been used to shelter runaway slaves escaping
  to the North. Damp limestone walls glistened beneath the subdued
  interior lighting that Bruce had installed years ago. A shallow,
  slow-moving river was all that remained of the underground waterway
  that had carved out the caverns in ages past. Massive wooden arches,
  high overhead, helped to support the mansion's foundations.
Scores of North American brown bats roosted amidst the jagged
  stalactites hanging from the ceiling. Towering calcite columns rose
  hundreds of feet in height. The bats squeaked and rustled overhead.
The Dark Knight Rises: Official Novelisation

This tallies nicely with what we know from other sources, notably the DC Visual Dictionary

"though the scores of American Brown Bats (Myotis lucifugus) perched high above the Batcave floor were a nuisance to Alfred's fastidious
  cleaning...""


text:
Q: AngularJS not displaying scope data I'm having issues with a dynamically placed template.
My HTML for index.html looks something like this:

<data-ng-include id="outside" src="dynamicTemplate()"></data-ng-include>

The index.html page displays a template based on a certain condition.
Here is the code for my home.html, which is the default template for index.html.

<form data-ng-controller="FormController" data-ng-submit="processForm()">
other form stuff goes here
</form>

My FormController looks something like this:
  app.controller("FormController", ['$scope', '$http', '$window', function($scope, $http, $window) {
    $scope.message = "";

    $scope.processForm = function() {
      $scope.message = "Processing form";
      $scope.messageStyle = {
        "color": "green"
      };
      // Ajax Logic to process form
      .success(function(data) {
        $scope.message = data.msg; /* Message never gets updated in the view */

      });

    };

  }]);

The issue here is that the $scope.message never displays any data in the data-ng-bind="message" after the FormController gets called. I think the issue lies with the scope not knowing which controller it belongs to. How can I fix this?


text:
Q: Questions about minor page fault From Stephen's reply and comment at https://unix.stackexchange.com/a/289446/674:

in some cases, data which has been marked for paging out but hasn't
yet been paged out.
paging out would indeed involve accessing the disk, but that's another
operation which doesn't have anything to do with the page fault:
there's a marking operation, a separate paging out operation (which
hasn't happened yet), and the page fault which causes the memory to
be retrieved (so the page-out probably won't happen at all). Even in
(3), servicing the page fault doesn't involve touching the disk
(the data isn't there yet), so it's a minor page fault.

*

*What does "the page fault which causes the memory to be retrieved (so the page-out probably won't happen at all)" mean?
Why won't the page-out probably happen at all?

*Why "servicing the page fault doesn't involve touching the disk"?
Is the reason for not paging-out yet in "data which has been marked for paging out but hasn't yet been paged out" that the data needed isn't on the disk yet?
Thanks.

A: Regarding your first question, a page-out involves a page of memory which (for whatever reason) doesn't need to be kept in physical memory; but the removal of a page isn't necessarily instantaneous. If, between the time the page is determined to be unnecessary and the time it's actually paged out, a page fault causes the page to be "pulled in" again, then the page fault can be serviced immediately without a page-in (so it's minor), and because the page in question is now needed in main memory again, it shouldn't be paged out.
An analogy which may help is the returns cart in a library. When you return a book, it's placed on the cart, and at some point the whole cart is taken and the books it holds are placed in the shelves. Between the time you return the book and the time it is returned to the shelf, someone else may request the book and retrieve it from the cart, which is faster than retrieving it from the shelf...
Regarding your second question, it's simply the definition of a minor page fault: if a page fault doesn't involve touching the disk, it's minor, otherwise it's major. In the example, servicing the page fault doesn't involve touching the disk, because the page was "caught" before it was discarded from memory — and this remains true even if the page has actually been written out to disk ("touching the disk" then was related to the page-out, not the page fault).
Hopefully that clarifies things!


text:
Q: How can I create a static String in Rust? Is there a way I can create a static String in Rust?
I tried this:
static somestring: String = String::new();

but I got this error:
error: `std::string::String::new` is not yet stable as a const fn
 --> src/main.rs:2:29
  |
2 | static somestring: String = String::new();
  |

How to create a static string at compile time does not solve my problem because it's about &'static str, not String. I need the String to be globally addressable.

A: Don't confuse the String type with the str type.
What are the differences between Rust's `String` and `str`?
A String is mutable and always heap-allocated.
A str, usually presented as &str is not mutable and is simply a view into a string.
Your question seems to confuse the idea of static and globally adressable. You may refer to (&'static str) as a string with a 'static lifetime. Strings with  'static lifetimes are common because they (mostly) represent hardcoded strings in the program. A 'static lifetime means the object (in this case, a string) will live until the end of the program. Most 'static objects are known at compile time. This should be natural to think about, because hardcoded strings are known at compile time. These strings can not mutate.
Strings on the other hand, are mutable. And you can make a String from a &'static str.
Given the lack of context in the question, if what you want is a String that is globally adressable and want to define it static I may suggest the macro lazy-static:
https://crates.io/crates/lazy_static
As sugested by mcarton, this question seems to boil down to the singleton pattern. You can learn more about its implementation in Rust here: How do I create a global, mutable singleton?


text:
Q: Socket.IO Best way to send messages between two users? I want to know what is the best way to send messages between two users? I know you can do rooms and join them but you have to "create" them first. Think of it like chat messenger. You only show the messages you recieve between those two users.
I can do one big object but eventually that would be a big object.
What are your suggestions on handling this?

A: Every socket in Socket.io has its own ID. You can send messages directly to a socket, once you know that ID. Example from https://socket.io/docs/v3/rooms/index.html#Default-room
    io.on('connection', socket => {
        socket.on('private message', (anotherSocketId, msg) => {
            socket.to(anotherSocketId).emit('private message', socket.id, msg);
        });
    });


text:
Q: Sublime Text 3 Ruler I tried to add a ruler through View>Ruler but it adds to the current file only.
How to make a specific ruler with the size of 79 characters in sublime and make it appear in every file?

A: If you want to make a ruler appear in every file, then go to Preferences: Settings from the command palette and add the setting "rulers": [79] to your user preferences. This will make the ruler appear at column 79 for every file.
The reason why View -> Ruler -> <Some value> applies only for the current file is because, behind the scenes, it uses a command called set_setting, which sets the given setting (here it's rulers) and it's value only for the current view (Just try to apply a ruler value to a file using View -> Ruler, close the file, open it again and see that it doesn't persist. It's just temporary). Hence, the rulers value is not applied to any other file


text:
Q: Suggest a way to find and replace values in xml file I would like to find a parameter and update its corresponding value in a xml file.
Example:
Original file
"DefaultSecure" enable="true" in some.xml

Updated file
"DefaultSecure" enable="false" in some.xml

A: Depends on the structure of your XML file, it might be accomplished with regex search and replace, for which I prefer Notepad++.
You can find tutorials here: http://markantoniou.blogspot.com/2008/06/notepad-how-to-use-regular-expressions.html


text:
Q: How to find product of arithmetic progression? I need to write a function to find a product of arithmetic progression elements (using recursion). I have only vague idea how to do it – something like this:
public static int product(int n)
{
   if (n == 0)
      return 0;
   else
      return <some code> * product(n-1);
}

Could you at least give me a hint?

A: you need to write a function which take 3 arguments first Term(f) , common difference(d) , and total number of term (n) in AP.
     int fun(int f,int d,int n){
      if(n==0) return 1;
else (f+(n-1)*d) * fun(f,d,n--);
    }

A: The following code should do the trick:
public static int Product(int arithInitial, int arithDifference, int n)
{
   if (n == 1)
      return GetArithmeticSeriesTerm(arithInitial,arithDifference,1);
   else
      return GetArithmeticSeriesTerm(arithInitial,arithDifference,n) * Product(arithInitial, arithDifference, n-1);
}

public static int GetArithmeticSeriesTerm(int initial, int difference, int position)
{
    return initial+difference*(position-1);
}

I have created a new method to get the elements of the arithmetic progression. I've also changed the base case of the recursion to be n==1 and then put the call to the arithmetic series term.
It should hopefully be pretty self explanatory as to what it does.
For the first four terms of the series 1,3,5,7,... you would call it as
int result = Product(1,2,4)`

Note: You don't need two methods for this but I feel that introducing the second method makes it clearer what the code is doing. You could of course just inline the expression and of course your base case can in fact be simplified to just initial if you wanted to make it a bit cleaner. Using the full method though makes it very intuitive of why we are doing that.


text:
Q: Desining a system for mutiple input/multiple output Background
I'm sketching on an application that needs to perform something like this
database a >--|                          |--> fileformat 1
database b >--+--> custom application >--+--> fileformat 2
...           |                          |    ...
database n >--|                          |--> fileformat n

The databases in question are all of the same type but with different tables and structure. The objects that are to be loaded are all products of some type. The files have similar structure but not necessarily the same, some are xml, some are csv etc.
The custom application is here to ensure a consistent interface for manipulating the objects retrieved from the relational data. It is a simple web application with a few options on each product and a paginated display of the products. It adds additional data to each record that is persisted through the means of an ORM.
Only one database will be active in each instance of the application, however many fileformats can be active. The writing of these files are simultaneous.
Question
I've been struggling with finding the best approach for designing the conversion steps.
Is there a pattern that somehow manages to combine the different schemas into one single Model? There is the assumption here that only the fields that are present in all of the databases are supposed to end up in the model.
And what about the reverse? When the product objects are to be written to file?
I've looked at different patterns such as the Strategy pattern, but i'm still not having that moment where all the bits and pieces seem to fall into place.
For what it's worth the application itself will most likely be written in PHP.

A: This would be my approach:
Each DB would have a view on it that would present the needed data to your app.
Your app would have a layer that would read the data and reformulate it into a (fairly standard) data structure.
Then you would have a layer that would read those standard data structures and write out to the requested files.


text:
Q: Incorporating error and exception handling into my python script I'm attempting to incorporate error handling into my python script.
prod.py searches the kernel config file for a module and returns it's branch.
example:
comp@able~$ python prod.py CRYPTO_DEV
# Random Number Generation
import sys

module = sys.argv[1]

def probe(module):
  with open('/usr/src/linux/.config', 'r') as module_list:
    modlist = module_list.read()
    blocks = modlist.split('\n\n')
    block = filter (lambda search:module in search, blocks)

    for line in block:
      head = line.split('\n')
      print head[1]
      break

probe(module)

I'd like to capture typos and print "Are you sure that is a module?" in return.
End Question
The errors  below were thrown by shell, and not python. Apologies.
but I would also like to handle errors like;
comp@able~$ ./prod.py CRYPTO_DEV;[
# Random Number Generation
bash:[:missing `]
comp@able~$ ./prod.py CRYPTO_DEV(
# Random Number Generation
bash:syntax error near unexpected token `('
---
I attempted some variations of 'try:' and 'except', but either broke the script, returned no value, or returned a value regardless of error.
Any help is greatly appreciated.


text:
Q: Как найти первый встречный по оси Z объект? Есть наклейка, которую могу переместить по оси X, Y, зажимая кнопку мыши и таская эту наклейку. Мне нужно, чтобы после того, как я отпустил кнопку мыши, она прилепилась к ближайшему объекту по оси Z, а этих объектов на этой оси может быть несколько (z = 1, z = 2 и т.д). Пока что я использую вот такой костыль, но он мне дико не нравится:
public void OnMouseDrag () {
        Vector2 p = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y));
        gameObject.transform.position = new Vector3 (p.x, p.y, -1);
        gameObject.GetComponent<BoxCollider>().center = new Vector3(
            gameObject.GetComponent<BoxCollider>().center.x,
            gameObject.GetComponent<BoxCollider>().center.y, -7);
    }
void OnTriggerEnter(Collider other) {
        if (other.CompareTag ("Tag"))
            // делаю что-то
        }
void Update () {
        // если не перетаскивается, то постоянно "проходит" по z-координате
        if (gameObject.GetComponent<BoxCollider> ().center.z < 5) {
            gameObject.GetComponent<BoxCollider> ().center = new Vector3 (
                gameObject.GetComponent<BoxCollider> ().center.x,
                gameObject.GetComponent<BoxCollider> ().center.y,
                gameObject.GetComponent<BoxCollider> ().center.z + 5 * Time.deltaTime);
}
}

Тут BoxCollider постоянно проходит некоторое расстояние по оси Z. Как только я перетаскиваю наклейку, BoxCollider по оси Z становится равен -7, как только я отпускаю наклейку, BoxCollider по оси Z перемещается на 5 * Time.deltaTime. И все это для того, чтобы OnTriggerEnter() случился только с ближайшим объектом по оси Z, а не со всеми (или несколькими) по этой же оси. Есть какое-нибудь решение без сложных расчетов и вычислений (для производительности)?

A: Есть Vector3.Distance, который возвращает расстояние между объектом а и b.
Соответственно сравни расположение объекта с точками и выбери ту, с чем имеется минимальная дистанция.

A: насколько я понял, ты хочешь реализовать drag and drop.
если у тебя 2d объект, то ты можешь посмотреть маленький туториал по drag'n'drop:
https://www.youtube.com/watch?v=c47QYgsJrWc (eng)
конечно не оптимальное решение, но для начала сойдет.
удачи!

A: Найти ответ помог Xumera_hZ, если он его напишет (даже просто комментарий свой скопирует), отмечу его как правильный))
В скрипте наклейки:
    RaycastHit hit;
    Ray ray;

    public bool canHit;
    public int someInt;

void Start () {
        canHit = false;
        ray = new Ray (transform.position, Vector3.forward);
    }

public void OnMouseDrag () {
        Vector2 p = Camera.main.ScreenToWorldPoint (new Vector2 (Input.mousePosition.x, Input.mousePosition.y));
        gameObject.transform.position = new Vector3 (p.x, p.y, -1);
        }

    void OnMouseDown(){
        canHit = false;
    }
    void OnMouseUp(){
        canHit = true;
    }

void Update () {

        if (canHit)
        {
            ray.origin = transform.position;
            ray.direction = Vector3.forward;
            Debug.DrawRay (transform.position, Vector3.forward * 10);

            if (Physics.Raycast (ray, out hit, 11)) {
if (hit.collider.gameObject.CompareTag ("Tag")) {

// делаю что-нибудь с объектом, на который попал луч
hit.collider.gameObject.GetComponen<SomeoneScript> ().someInt = someInt;
// делаю что-нибудь еще

canHit = false;
                }
            }
else // если рэйкаст не встречает объекты
{
// делаю что-нибудь
}
        }

    }