Are questions on large scale civil electrical engineering on-topic?

Question: I'd like to ask why it takes years to build a single large grid transformer. Is a question like that on-topic? If it's not on-topic here, would it be on-topic on a different stack?
Comment: This is the best fitted site for such questions within Stack Exchange. For example there's been the occasional high voltage guru posting here in the past.
Comment: Seem on topic to me. I don't know how custom  each large grid transformer is, but if each one is designed from the ground up and tooled specifically to build that one, I wouldn't be surprised if it took a few years after having seeing things designed then produced/machined.
Comment: related: https://electronics.meta.stackexchange.com/questions/3118/are-power-electrical-engineering-questions-on-topic-for-ee-se-if-so-should-thi
Answer: The question is not off topic but YMMV because there are few power\industrial engineers here. You may not get the best answers
Answer: I would think so; this stack is "Electrical Engineering", not "Electronics Engineering."
Like all aspects of electrical/electronics, large-scale-grid is its own separate "local cluster" in the "electricity galaxy." I've seen a few such questions answered. But the quality of the answers totally depends on which experts (if any) happen to see the question. The more obscure and field-specific the question, the less chance anybody else will know about it.
That said, folks here are quite intelligent. Very rarely is this stack totally clueless about anything ranging from "vacuum nanotubes" to beer...
Comment: It's electrical engineering but the topics are mostly about "a specific electronic design problem" https://electronics.stackexchange.com/help/on-topic That being said we do most any electrical design question, but most people are circuit designers so if you do post a question about power electronics or the grid, you may not get a timely answer or an answer at all.
Answer: I agree with others that it is on-topic here, though I suspect better answers might come from engineering.stackexchange.com since the issues involved are not so much about the electrical properties of substation transformers but about the process of specification, procurement, and manufacturing of large-scale unique-design equipment.
FWIW, I would also be interested in seeing more questions and answers within this realm of EE on this stack.  Although electronics is a hobby since adolescence, my profession is EE within environmental public infrastructure (i.e. water, wastewater, solid waste).


arcPy findAndReplaceWorkspacePath Won't Update Rasters

Question: I'm using ArcGIS 10.3. I have an MXD that contains symbolized global raster images. I have a GP tool that masks these rasters to a country or state and exports the images. I'm trying to update the source background layers and rasters each time a new country is chosen. The layer names are all generic, but the source files all have the country or state name tagged on.  findAndReplaceWorkspacePath works just fine with the background layers (shapefiles), but it won't update the rasters. I've confirmed the old and new sources with print statements, it's just not changing the source. The only time I get images is if I use the default state (Texas) set in the MXD. If I choose any other location, I just get a blank country or state outline image.
Here is my code snippet:
<code> layer_list = ["Precip","High_Temp","Temp_Departure"]
 for filename in layer_list:
   layer_name = filename
     for lyr in arcpy.mapping.ListLayers(mxd):
       if lyr.supports("DATASOURCE"):

          if layer_name == str(lyr.name):
            old_source = os.path.dirname(lyr.dataSource)

            new_source = country_temp_path

   lyr.findAndReplaceWorkspacePath(old_source, new_source, False)
</code>
return()
Answer: Here is the answer. Check to see if layer is a raster, then change data source.
<code>for lyr in arcpy.mapping.ListLayers(mxd):
            if lyr.supports("DATASOURCE"):
                new_source = country_temp_path
                if  lyr.isRasterLayer:
                    lyr.replaceDataSource(new_source, "RASTER_WORKSPACE",input_country + "_" + layer_name, False)
</code>


What types of testing is right for server OS upgrade

Question: My company is doing server OS upgrade, so as a tester I would want to know what types of testing is most helpful in this process?
Comment: server OS upgrade tests.
Seriously- you need to come with more context and ideas you thought about, at the moment the way your question is written we can fill books with answers
Answer: Please run through below check list and pick applicable ones for your environment

Regression Testing - Ensure Server, Features stable and running fine post upgrade
For browser upgrades - Compatibility testing
For specific machine upgrades (Not all machines upgraded) - If not all systems are upgraded then basic testing needs to ensure different versions of platforms do not have any impact. Connectivity of upstream and downstream system post upgrade is successful
Monitor resource usage (CPU / DB) and measure if there is any abnormal spike. There could be override / change in default system param. This may hurt performance aspects
In case of upgrade failure test the roll back strategy
All this upgrade need to be done from QA-UAT finally to prod
Managing downtime during the upgrade (Read only access / fail over systems ?)
Answer: Expecting you have a DTAP setup: Upgrade the Acceptance server OS and let any users depended on the services of the server accept that their applications are still working.
For operational testing have a look at what ITIL describes: http://wiki.en.it-processmaps.com/index.php/Service_Validation_and_Testing


How to maximize revenue by changing price?

Question: I run a SaaS and I have the following data from it:
Number of trials (A), number of subscribers (B), subscribe cost (C) and total revenue (D) for every type of service my SaaS provide.
If I increase (C) it can reduce (B) and in result I can get less (D).
So, is there a way to find balanced (C) to maximize (D)?
Also I think there is some dependency between (A) and (B) that shows subscribers solvency.
Answer: Your question does not provide enough information for me to walk you through the process step-by-step using your information, but hopefully I can point you in the right direction.
You question about Price Elasticity of Demand (usually just called Elasticity of Demand). Elasticity of Demand is used to show how responsive demand is to a change in price. For example, if a $1\%$ increase in price leads to a massive drop in the quantity demanded, say 75%, then we would say that the demand is relatively elastic. If an increase in price does not really cause a drop in the quantity demanded then demand is relatively inelastic. The concept of elasticity of demand translates to your question because $price\ multiplied\ by\ quantity\ equals\ revenue$.
You mention that if you increase $(C)$, you reduce $(B)$. Yes, this is (usually) correct because the relationship between price and quantity is negative-- the higher the price, the fewer items sold. As for reducing $(D)$, this depends on the elasticity of demand. For example,
Assume the price for each subscription is $\$2$. Assume that at a price of $\$2$, you sell $1,000$ subscriptions. This gives you a revenue of $\$2,000$: $$\$2( 1,000)=$2,000$$
Elasticity demand can be calculated a few ways, I'm going to use: $$Elascitity\ of\ Demand = {\frac  {{\mathrm  {Percent\ Change\ in\ }}Q}{{\mathrm  {Percent\ Change\ in\ }}P}}$$ Where $Q$ is quantity demanded and $P$ is price.
Lets consider the following two examples:
Scenario 1:
Assume that you increase the subscription price from $\$2$ to $\$3$. Now assume that an increase in price from $\$2$ to $\$3$ decreases the total number of subscriptions sold from $1,000$ to $960$. Notice that the number of subscriptions decreased, but revenue increased from $\$2,000$ to $\$2,880$: $$\$3(960)=$2,880$$ This happened because the demand for subscriptions is considered inelastic. Price by 50% [$(3-2)/2$], and your quantity decreased by 4% [$(960-1000)/1000$]. Since the percent of the price increase increased by more than the quantity demanded decreased, you increased your revenue. Your elasticity of demand in this scenario is, $$\frac {\mathrm -0.04}{\mathrm 0.50}=-0.08$$
Scenario 2:
Assume that you apply the same price increase from $\$2$ to $\$3$ per subscription, but this time the quantity sold drops from $1,000$ to $400$. Your revenue is now, $\$1,200$ $$\$3(400)=$1,200$$ In this case an increase in price caused your revenue to decrease. What happened? In this case subscriptions are considered elastic. The price increased by 50% [$(3-2)/2$], and your subscriptions demanded decreased by 60% [$(960-1000)/1000$].Your elasticity of demand in this scenario is, $$\frac {\mathrm -0.6}{\mathrm 0.50}=-1.5$$
To answer your question, you are looking for the place on your demand curve where the % change in price is the same as the percent change in quantity demanded. This is point is called Unit Elastic. In order to calculate this for yourself, you will need to know the relationship between the price of subscriptions and the quantity demanded.
Consider reading more about elasticity of demand as there are a couple of ways to calculate it. When you do the calculations you will get an elasticity of demand number that ranges from $0$ to $-∞$. (Some people will convert these numbers to absolute value... $0$ to $∞$, means the same thing.) The number you get from calculating your elasticity of demand will tell you what to do with your price. For example, if you get an elasticity of demand number that is greater than $-1$ (or less than $1$ if you use absolute value), then increase your price because revenue should increase. If you get back an elasticity of demand number less than $-1$ (or greater than $1$ if you use absolute value) then decrease your price and your revenue should increase. You want to adjust your price until your elasticity of demand number is $-1$ (or $1$ if you use absolute value). $-1$ is the point of unit elastic.
Answer: In Microsoft Excel there is a function named Solver that can give you a very accurate measurement of how to maximize profit with a change in price given the products/service price, number of consumers. You would have to input the these constraints in a changeable column and input the constraints of what you want to maximize, minimize in the solver constraints that are located inside the Solver Parameters option.


Calculate OTM premium from implied volatility?

Question: ThinkOrSwim, IBKR, and others reports the implied-volatility (IV) for a given expiration.  If I know the current underlying price and IV for that expiration, can I compute a rough estimate of the call or put premium at a given OTM strike (say 0.15 to 0.4 delta) options?  I think the black-scholes formula will give me that, but does anyone know of a Java library or script for computing it?
Comment: I found this website to calculate Black Scholes. I plugged in some numbers for various stocks and ETFs, seems to give a good estimate. https://goodcalculators.com/black-scholes-calculator/
Answer: I'm not sure why you would want to do such a calculation because if the option trades, the premium is available from the market.  Be that as it may, yes, you can use Black Scholes to generate a rough theoretical estimate of of any option's premium if you know the IV for that expiration.  However it will be rough because it won't account for variations like wide B/A spreads or volatility smile/smirk, etc.
I use IBKR's delta and IV numbers and at times, they are not that reliable, particularly for options expiring in a day or two.  I don't need precision but sometimes their numbers are just whacked out or not updating in a timely fashion.
Sorry, can't help you with a Java script.
Comment: Simply as a short-cut.  To pull the IV for a given expiration is a single query with IB's API.  To pull the bid and ask is two queries multiplied by how many strikes you want.  I've done that, it's just slower.  I'm interested in using this as a screener, most likely run after the market is closed to identify trade candidates and potential trades for the next day.  Tweaking will be needed of course, but I'm looking to calculate quick break-evens for mostly long-stock + short option trades expiring approximately 13 to 50 days out.
Answer: IV is not constant for a given expiration but you will have a smile. If you have all IVs for all available strikes, you can get an exact theoretical value because the iV itself was computed from that price.
Now in terms of delta, it will be unlikely that any given quoted strike will correspond exactly to the desired delta. However, since you have all IV values, you can compute the vol surface using techniques like SVI. Below is a Python example:
spot = 1.34
forward = 1.35
t = 30 / 365.0
vols = np.array([ 12, 10, 9.5, 9, 10.5, 8, 10.24, 9.6, 11.2, 9.4, 11.9, 9.7, 20, 23,  27]) / 100
strikes = np.array([1.21, 1.3, 1.4, 1.3, 1.3, 1.32, 1.38, 1.3,
                    1.4, 1.3, 1.45, 1.25, 1.5 , 1.6,  1.8])
total_implied_variance = t * vols ** 2

def svi(k, param):
    a = param[0];
    b = param[1];
    m = param[2];
    rho = param[3];
    sigma = param[4];

    totalvariance = a + b * (rho * (k - m) + np.sqrt((k - m)** 2 + sigma**2));
    return totalvariance

def targetfunction(x):
    value=0
    for i in range(11):
        model_total_implied_variance = svi(np.log(strikes[i] / forward), x);
        value =value+(total_implied_variance[i]  - model_total_implied_variance) ** 2;
    return value**0.5

bound = [(1e-5, max(total_implied_variance)),(1e-3, 0.99),(min(strikes), max(strikes)),(-0.99, 0.99),(1e-3, 0.99)]
result = optimize.minimize(targetfunction, bound, tol=1e-8, method="BFGS")
x=result.x

K = np.linspace(-0.4, 0.4, 60)

newVols = [np.sqrt(svi(logmoneyness, x)/t) for logmoneyness in K]
plt.plot(np.log(strikes / forward), vols, marker='o', linestyle='none', label='market')
plt.plot(K, newVols, label='SVI')
plt.title("vol curve")

plt.grid()
plt.legend()
plt.show()

SABR is another possibility but it is more frequently used in fixed income. The calibration would involve fitting beta, alpha, rho and nu so that it resembles the shape of IV in the market. You can see details and the below illustration here.

Now you have a vol surface that you can use for any strike. Delta will depend on the market convention. Table 3 shows the math needed to get Delta neutral strikes in FX markets. P.a. stands for premium adjusted which is also explained in the paper.

It is a very good paper to read. To get strike for a premium adjusted Delta requires a root solver. If your delta is not premium adjusted you can use a closed form solution to solve for strike. Once you have your strike, you can fetch the IV from your vol surface
K = 1.4
np.sqrt(svi(np.log(K/spot), x)/t)

plug it into the Black Scholes formula and you are done.
from scipy.stats import norm

def BlackScholesCall(S,K,r,d,t, sigma):
    # get variables for formula
    d1 = ((np.log(S/K) + (r - d + 0.5 * sigma **2) * t) / (sigma * np.sqrt (t)))
    d2 = d1 - sigma * np.sqrt(t)
    # get BSM call & put values
    c = S * norm.cdf(d1) - K * exp(-r*t)  * norm.cdf(d2)
    # get Greeks
    return "Call price {}".format(c)

For simple requests like this, you do not need libraries because you can write it yourself with a few lines of code. Where libraries become useful is if you use this with actual market data, feed it into your tool to derive a vol surface and compute all sorts of details with it on a large scale. A wonderful tool is quantlib which is available in java as well.


Do you have to choose a target for a spell, or can you just cast it with no target and let it fizzle?

Question: Let's say I have Lightning Bolt and my one opponent has a Leyline of Sanctity and no creatures in play. I might still want to cast Lightning Bolt to delve it later or to buff up my Tarmogoyf or whatever. My question is...  can I cast Lightning Bolt without targeting anyone? Can I just decline to name a target and let the spell fizzle? Or if either I or my creatures are the only valid targets do I have to target myself?
Comment: You could always bolt yourself!
Comment: If a spell has no legal targets it cannot be cast.
Comment: If you're playing lightning bolt and your opponent opens with a Leyline of Sanctity, you might as well scoop anyway.
Comment: You could also just keep your hand full and when you get to 8 cards end your turn and discard it.
Answer: You cannot cast a spell without choosing all specified targets. In the process of casting a spell, we have these rules

601.2. To cast a spell is to take it from where it is (usually the hand), put it on the stack, and pay its costs, so that it will eventually resolve and have its effect. Casting a spell follows the steps listed below, in order. If, at any point during the casting of a spell, a player is unable to comply with any of the steps listed below, the casting of the spell is illegal; the game returns to the moment before that spell started to be cast (see rule 717, "Handling Illegal Actions"). Announcements and payments can't be altered after they've been made.

601.2c The player announces his or her choice of an appropriate player, object, or zone for each target the spell requires. A spell may require some targets only if an alternative or additional cost (such as a buyback or kicker cost), or a particular mode, was chosen for it; otherwise, the spell is cast as though it did not require those targets. If the spell has a variable number of targets, the player announces how many targets he or she will choose before he or she announces those targets. The same target can't be chosen multiple times for any one instance of the word "target" on the spell. However, if the spell uses the word "target" in multiple places, the same object, player, or zone can be chosen once for each instance of the word "target" (as long as it fits the targeting criteria). If any effects say that an object or player must be chosen as a target, the player chooses targets so that he or she obeys the maximum possible number of such effects without violating any rules or effects that say that an object or player can't be chosen as a target. The chosen players, objects, and/or zones each become a target of that spell. (Any abilities that trigger when those players, objects, and/or zones become the target of a spell trigger at this point; they'll wait to be put on the stack until the spell has finished being cast.)

So, when you cast a spell, you have to choose legal targets to legally cast the spell.
Comment: Note that you do not have to specify targets for activated and triggered abilities on the spells you cast. You can for example cast Hypothesizzle with no creatures on the battlefield (and discard a nonland card, if you wish). Hypothesizzle is anomalous though: previous cards solved optional targeting by saying "up to one target".


Best way to update item perms for multiple users with SP REST API?

Question: Using SharePoint REST API I can add and remove user permissions for a list item. If I need to add permissions for multiple users to a specific item, is there a way to do this other than looping the post for each one or creating a SP group?
Answer: I am afraid that there is no way other than looping the post for each one or creating a SharePoint group.
By REST API, it only can add permission for one user by one REST API post.
Answer: I usually do this with a workflow that is started on editing items. I modify a field specifically for this purpose per REST to trigger the workflow and let it set the permissions. Might not fit your scenario with a dynamic list of users, but perhaps the idea can help nevertheless.
Answer: I don't know if is it the best way, but I have created a Flow, with HTTP Trigger and input parameters:
siteurl, listName, itemId, and an array of user-permisison objects like:
<code>{
  "siteUrl": "https://xxxx.sharepoint.com/site",
  "listName": "Documents",
  "itemId": "1",
  "permissions": [
    {
      "userId": 8,
      "roleDefinitionId": "@{variables('RoleEdit')}"
    },
      "userId": 10,
      "roleDefinitionId": "@{variables('RoleEdit')}"
    },
    {
      "userId": 11,
      "roleDefinitionId": "@{variables('RoleFull')}"
    }
  ]
}
</code>
It is easy to reuse in any list with one REST call,
but inside the flow I am looping trough the users and set the permissions one by one, because there is no other way with SharePoint REST API.
Hope it helps.


History of Magnetism before the Hubbard model

Question: I'm interested in models used before the Hubbard model (free electron model, band model, etc, both itinerant and localized models). What were their strengths and weaknesses? Which model is currently the main topic of modern research? Did the Hubbard model overcome any obstacles that other models didn't?
Comment: Why Hubbard model if you ask about history of magnetism? Isn't Hubbard model a model for electric conductivity?
Comment: @nasu  The Hubbard model has traditionally been associated with magnetism, but if it also has been used to investigate electric conductivity I would gladly take a look at the sources.
Answer: I'm certainly no expert on the history of these models, and can only answer from my working knowledge about the topic. (In particular, I'm not quite the right person to give a detailed comparison with the Hubbard model.) Nevertheless, the text below is too long for a comment, and it might still be of some help. I do not claim completeness, but think that these are the bare minimum one should know about in this context. I'd be interested to see more detailed answers by people who know more about this than I do!

The Hubbard model is from the 1960s. Thus the Ising model (Lenz, 1920) is certainly older, as is the Heisenberg model (Heisenberg, 1928) for (anti)ferromagnetism. See e.g. "Magnetism" at Wikipedia, "Ferromagnetism" at Wikipedia and references there for more.
The Ising model is a classical-physical model, in the sense that the "spins" are discrete, and as such can be thought of as describing the limit of highly anisotropic interactions between the magnetic dipoles of the atoms. The Ising model in 1d was already solved by Ising in his PhD thesis; the 2d Ising model (on a square lattice) was famously tackled by Onsager (1944); while in 3d and up it is still topic of active research -- see e.g. references at "Ising model" at Wikipedia.
The Heisenberg model is already interesting in 1d (spatial), and shows up in current research, ranging from topics such as "quantum integrability", to "quench dynamics", to mathematically rigorous probabilistic approaches.


How should i report performance issues without performance requirements?

Question: We don't currently have any performance requirements for application.
However, during manual testing I am noticing several performance issues with slow pages.
How should i report these apparent performance issues when I don't have any specific performance specifications that I can refer to?
Comment: Updated question to make it a more answerable one.
Answer: If you have no requirements identified, but you consider it to be a significant issue then you report the issue and indicate that fact.  This is quite common in Agile environments where requirements are a discovery process from using the application.
The organization will then need to decide:

Should they address the issue without a typical upfront specification?
Should they take some time to document and specify performance requirements?
What performance requirements should the company add?
What customer experience is acceptable for users on low bandwidth connections?

It will also depend on whether you noticed this anecdotally when running tests vs. specific performance testing.  If found anecdotally you should file the bug and let your organization know that there are performance issues not covered by requirements.  If found through specific performance testing then your organization should create a process (e.g. write a ticket) when the performance testing finds an issue.
Answer: You can check with your SME or senior architect available regarding below points.
What are the acceptable level of benchmarks in the current feature?
Can we compare these test results with that system?
If not can we have a measurement criteria for benchmarking our current system or application?
Hopefully your query will be resolved. If you are not getting a satisfactory answer for that you need to find out a generic benchmarking level for the same.
Answer: Depending on where and how your application is going to be used performance can be not that critical, i.e. internal portal with information about your company performance is not that critical as for e-commerce shop during the black friday.
However I believe as a test engineer you should report everything which seems incorrect to you. Analyze page loading process as deep as possible using Developer Tools which come with your browser or more advanced solutions like YSlow.
If you have enough capacity to investigate the issue on your own you can quickly create a simple load test using one of free and open source load testing tools, normally all of them provide record-and-replay functionality and try to correlate increasing number of users concurrently accessing the application with other metrics like response time, transactions per second, etc.


anonymous User broken

Question: I just migrated the site from sqlite to Postgres, using the drush portabledb-import module
I'm getting a error page only when no user is logged in to the site.
I can get logged in using the login-link generated running
drush user-login
and everything works great, all the content is there and accessible, views all work, etc...
however log out and I get this message at the home page again
The website encountered an unexpected error. Please try again later.
and The watchdog-show reports this

 ID         :  8
 Date       :  12/Mar 13:07
 Type       :  php
 Severity   :  error
 Message    :  PDOException: SQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for integer: "not yet assigned"
               LINE 4: WHERE  (base.uid IN  ('not yet assigned'))
                                             ^: SELECT base.uid AS uid, base.name AS name, base.pass AS pass, base.mail AS mail, base.theme AS theme, base.signature AS signature, base.signature_format AS signature_format, base.created AS created, base.access AS access, base.login AS login, base.status AS status, base.timezone AS timezone, base.language AS language, base.picture AS picture, base.init AS init, base.data AS data, base.uuid AS uuid
               FROM
               {users} base
               WHERE  (base.uid IN  (:db_condition_placeholder_0)) ; Array
               (
                   [:db_condition_placeholder_0] => not yet assigned
               )
                in DrupalDefaultEntityController->load() (line 191 of/usr/local/www/main/includes/entity.inc).

I've checked the DB and the 0 uid looks fine
but just in case I followed the "Restore the anonymous (user ID 0) user record docs located here
https://drupal.org/node/1029506
any ideas or suggestions would be greatly appreciated.
Comment: Something in the code is doing that query with the value "not yet assigned" in place of the user id. If you can find that text string, you'll find the source of the problem.
Answer: I don't think you can migrate like that.  I am pretty sure the database creation during installation process is different if you're using postgres.

anonymous User broken


Is there any way to store my data into blockchain without smart contract

Question: I am trying to store customer data (name,address,dob,age etc) into blockchain. Is there any way of storing these values without smart contract ?
Answer: If you ever intend to retrieve the data from the blockchain, then no. The smart contract provides the storage you would later need to query to retrieve the data. A regular 'external' account has no storage, and the only type of account other than a smart contract is a regular external account.
You could send a data payload in a transaction's input data field (you can send anything in the input data field as I describe in this article: https://medium.com/@tjayrush/knowing-the-future-and-proving-you-know-it-3add7a69d54c), but the data wouldn't be stored on chain (other than in the record of the transaction).
If there was a way to later retrieve the history of those transactions (there is--it's called the RPC interface), you could rebuild the data from there, but you wouldn't be able to query the data from the blockchain the way you can query public variable values from a smart contract.


How to extract machine code from a file(especially executable) in C

Question: How to get machine code of a file(mainly executables) in C?
I have written a C program to convert machine code to assembly. But how to get machine code of a file? How would I go about programming a c program to convert a file to machine code?
Comment: Can you please write more about your understanding of what a file is, and why you need a program to "convert a file to machine code"? Like, why couldn't a file already contain machine code? Then we can better understand where you are coming from and answer, including clearing up any misconceptions if needed.
Answer: You can make a program that interprets machine code using an engine like Capstone-engine, this is the easiest way to do something that gives you good results in an optimized way easily, keep in mind that this is not an easy task, it is much better to use a ready-made tool, we have many free and very good options and constantly updated like Ghidra, but if you still want to write your own enjoy and also read the manual IA-32 Intel manual.
Comment: Read the Capstone-Engine documentation and its implementation in C language here:
http://www.capstone-engine.org/lang_c.html
Comment: Thank you so much. This cleared my doubt. I have upvoted and accepted. Thanks for sharing your knowledge.
Answer: <code>from binascii import *
from pefile import *
from capstone import *

if(sys.argv[1]):
    pe      = PE(sys.argv[1])
    entry   = pe.OPTIONAL_HEADER.AddressOfEntryPoint
    base    = pe.OPTIONAL_HEADER.ImageBase
    OEP = base+entry
    bytes   = pe.get_data(entry,17)
    print(hexlify(bytes))
    for i in (Cs(CS_ARCH_X86,CS_MODE_64).disasm(bytes,OEP)):
        print("0x%x:\t%s\t%s" %(i.address, i.mnemonic, i.op_str))

</code>
result and confirmation
<code>:\>python getbytatent.py c:\Windows\System32\calc.exe
b'e84bfdffff6a5868e82e0101e8eb99ffff'
0x1012d6c:      call    0x1012abc
0x1012d71:      push    0x58
0x1012d73:      push    0x1012ee8
0x1012d78:      call    0x100c768

:\>cdb -c "u @$exentry l4;q" c:\Windows\System32\calc.exe | awk "/Reading/,/quit/"
0:000> cdb: Reading initial command 'u @$exentry l4;q'
calc!WinMainCRTStartup:
00a92d6c e84bfdffff      call    calc!__security_init_cookie (00a92abc)
00a92d71 6a58            push    58h
00a92d73 68e82ea900      push    offset calc!_CT??_R0?AV_com_error+0xdc (00a92ee8)
00a92d78 e8eb99ffff      call    calc!_SEH_prolog4 (00a8c768)
quit:
</code>
i hate putting this here after that comment BY OP
it takes less than a minute to convert that into winapi
(i should state that winapi is not c )
and a pure c does not have the PE format structures defined
one can obviously do fopen(),fseek(),fread() but well that is beyond compare exercise in futility
<code>:\>type mcc.cpp
#include <windows.h>
#include <dbghelp.h>
#include <stdio.h>
int main (int argc ,char * argv[]) {
    if(argc == 2) {
        HMODULE hMod = LoadLibraryA(argv[1]);
        if(hMod){
            DWORD AEP = ((PIMAGE_NT_HEADERS32)ImageNtHeader(hMod))->OptionalHeader.AddressOfEntryPoint;
            DWORD OEP = (DWORD)hMod + AEP;
            for (int i =0; i< 17 ; i++) {
                printf("%02x ",*(BYTE *)(OEP+i));
            }
        }
    }
}
:\>cl /Zi /W4 /analyze /Od mcc.cpp /nologo /link /release dbghelp.lib
mcc.cpp

:\>mcc.exe c:\Windows\System32\calc.exe
e8 4b fd ff ff 6a 58 68 e8 2e 82 00 e8 eb 99 ff ff
:\>
</code>
and just to complete the circle a fragile non productive c hack
for a specific application
in a specific os
with specific dos, nt headers,
aep in .code section starting at 0x400
file alignment of 0x200 and page alignment of 0x1000
<code>:\>type futilemcc.cpp
//assume = ass u and me a beyond compare exercise in futility
#include <stdio.h>
int main (int argc ,char *argv[] ){
    if(argc ==2){
        FILE *fp = NULL;
        unsigned long nth = NULL;
        unsigned char mcc[17] ={0};
        errno_t err= fopen_s(&fp,argv[1],"rb");
        if(err == 0 && fp != NULL) {
            if ( fseek(fp,0x3c,SEEK_SET) == 0) {
                fread_s(&nth,sizeof(unsigned long),sizeof(unsigned long),1,fp);
                if ( fseek(fp,nth+0x28,SEEK_SET) == 0) {
                    fread_s(&nth,sizeof(unsigned long),sizeof(unsigned long),1,fp);
                    if ( fseek(fp,nth-(0x1000-0x400),SEEK_SET) == 0) {
                        fread_s(&mcc,sizeof(mcc),sizeof(unsigned char),sizeof(mcc),fp);
                        for(int i =0;i<17;i++){
                            printf("%02x ",mcc[i]);
                        }
                    }
                }
            }
        }
    }
}
:\>complink.bat futilemcc

:\>cl /Zi /W4 /analyze /nologo /Od /EHsc futilemcc.cpp /link /release
futilemcc.cpp

:\>futilemcc.exe c:\Windows\System32\calc.exe
e8 4b fd ff ff 6a 58 68 e8 2e 01 01 e8 eb 99 ff ff
:\>
</code>
Comment: I had specifically mentioned "C" in the title! I also tagged this question as "C"! Why did you paste python code here?
Comment: its just an python exampel for windows exe (PE) loading - here is the wine-pe loader in your prefered language, Sir! : https://github.com/wine-mirror/wine/blob/master/libs/wine/loader.c
Answer: its very hard to understand what you want

How to get machine code of a file(mainly executables) in C?

so you want a C program that loads an executable file (for example dos,windows,linux exucutable) and showing you the whole or parts of the image (that normaly contains machine code and data)?
so there are several documented file formats that can contain machine code

dos exe (legacy exe format: https://en.wikibooks.org/wiki/X86_Disassembly/Windows_Executable_Files)
windows exe (pe format: https://en.wikipedia.org/wiki/Portable_Executable)
linux (elf
format: https://de.wikipedia.org/wiki/Executable_and_Linking_Format),
dynamic libraries
object files from several compilers in
omf, coff format
pure/properitary binary files with no documented
layout

for example see IDAs supported files types: https://www.hex-rays.com/products/ida/file_formats/

I have written a C program to convert machine code to assembly.

so you've already got some sort of disassembler?

But how to get machine code of a file?

read the spec of your operating system file format and write a small loader/parser, there are serveral C,C++,go,python ... example on github/google...

How would I go about programming a c program to convert a file to machine code?

and now you revert you question completely - before - you ask how to load a file with machine-code and now you ask how to convert "a file" to machine-code
what format is "a file" in your example - some sort of source-code or object file format?
Normaly this is the way: C/C++/Assembler/whatever-Source --> Compiler --> Objectfiles --> OS-related-Executable-Format[Machine-Code+Data]
try to ask more precise - its easy to help you when its clear what your exact target is


Engine failure due to turbocharger replaced

Question: My logan car has a faulty turbocharger when i was go to repair engine that time engine sound was a smooth but when mecanic  replace turbocharger with fitting chines turbo cor then after few km engine run with abnormal sound  . Mecanic then remove oil span he saw no3 big end bearing worn out why these happen please give me a factory manual of logan dls1.5
Comment: Turbo AND bearings : probably due to poor oil , not changed often, too low and blocked filter...
Comment: I appreciate English may not be your first language but please rewrite your question with some proper spelling and words that make sense. What on earth does 'with fitting chines turbo cor' mean?
Comment: Probably just a coincidence.
Answer: Turbocharger bearings are very sensitive to poor lubrication.  Engine journal bearings are similar in that they are journal bearings, but they are much more robust in that there is splash oiling, in addition to pumped oil.
Given your description, I would expect that the car was run on low oil which caused lubrication starvation of the turbo.  Usually that failure is very evident, and because it may mess up the mixture and fueling, it gets attention right away.
The number three crank bearing is a little more robust and will still function even after gross lubrication starvation.  One reason for this is that the bearing does not have the rotational speed that the turbocharger bearing has.
My most likely estimate of what happened is that the engine had oil starvation, probably on several occurences. This frequently happens when the engine burns or leaks a little oil, and due to inattention, and then operation with low oil.
Dirty oil over a long time could also cause similar symptoms, however most frequently failures of the turbo and the main bearings is associated with under-lubrication or operation for a period of time with no lubrication.
Comment: As I mentioned above - any thoughts about the filter?
Comment: I discount the filter, as filters have bypasses, both internal to the filter, and on the block.  I have seen several cars with similar symptoms, and in the end, it appears (or the owner confessed) that it was run with no oil (forgot to fill after a change) or low oil (put off checking with an engine which consumed some oil). In the end, we are really looking at most probable cause, because without more detailed history, we will not know many relevant details.


Business register in Austria

Question: I've tried to search for company register with API for registered businesses (including companies and self-employed people) in Austria, but with no luck. Does anybody know, if is there any?
Comment: please self answer if any of those on this question are useful: https://opendata.stackexchange.com/q/3495/1511
Comment: Thank you @philshen, but the databases from the linked thread are not for Austria, but Germany. Also these databases don't contain ALL companies, just some of them, but I'd need to search among all businesses in the country (like in central register which exists in Czech Republic, Poland, Slovakia and many more countries).
Answer: There is a Firmenbuch in Austria which officially registers all businesses. Unfortunately, retrieving data from that register is not for free. Take a look here, and you will see a price list after your search query. (If you know German, there are more information about the Firmenbuch here at the Republic of Austria's Unternehmensserviceportal.)
If you are fine with aggregated data about the Austrian landscape of businesses, then you could take a look at the relevant page of Statistics Austria. You might also find something at Austria's Open Data Portal.

Business register in Austria


Deadline for printing concert tickets in Japan

Question: So I'm travelling to Japan for Download Festival. I want to buy tickets but I am unsure if there is a deadline for printing them out (at 7 Eleven). We'll get there less than a week before the event. Is there a deadline for printing tickets?
Comment: Which booking system did you use?
Comment: @alamar That is not how "printing the ticket" works in Japan. In Japan, they give you a barcode which they scan at a convenience store, and the store prints the ticket on special paper. There are no PDFs or anything like that.
Comment: Did you receive an email with the tickets in attachments?
Comment: Not related to travel, but why don't you print them to PDF, and then print out this one physically as you please?
Comment: Now I remember having such system 10 years ago.
Answer: You should be fine.
While I cannot say 100% that this will be the case since I haven't used Ticket Pia in a while, I'm pretty sure it's the same as the other ticket sites. I was unable to find any warnings on printing deadlines on neither the concert site nor Ticket Pia's site, so they probably don't have one.
I've been to many concerts in Japan, but I have never seen a case where there is a deadline to print the tickets (to pay, yes). You will be able to print the tickets on the day of the concerts if you wanted to. Heck, it's common practice to actually set the limit to the day after, though I assume that's to make sure any procrastinators will be able to print last-minute.
Just make sure you note down the voucher number to claim the ticket, and bring some cash (change), as there will be a fee to print, and they don't take card or electronic money for this particular transaction.
Answer: All the major ticketing systems (Pia, eplus, Lawson Ticket, Y! Ticket, Rakuten Ticket) almost always allow you to claim your ticket up until the day after the concert (in case you missed the show but are eligible for a refund), so you should be fine.
7-11 doesn't use their electronic portal for ticketing services like Lawson or FamilyMart do, so you'd show your barcode to the cashier directly. BTW, the ticket pickup charge (店頭発券手数料) is usually set to 110 yen or 220 yen. Make sure you bring some change.


Reaper auto panning based on conditions

Question: I am currently evaluating Reaper v6.08 and I wonder if it's possible to pan based on certain conditions.
Detailed explanation:

I have two tracks, A and B.
A is panned 100% Left
B is panned 100% Right

When both tracks have a certain amount of silence, in this short period of silence I want to flip Left and Right smoothly.
This means that track A must be panned from 100% Left to 100% right and track B vice versa.
The 'flipping' should take as much time as there is silence on both tracks.
Is something like this possible?
Please see screenshot that I created to explain...

Thanks in advance,
Mike
Answer: Fairly confident this is possible through the scripting interface of Reaper.

Reaper auto panning based on conditions


Why is there such low current produced when discharging a Van de Graaff Generator, even though voltage is very high?

Question: E.g. putting your finger close to the Generator and seeing a spark between it and your finger. Obviously this does not kill you, but why is there such low current produced when the potential difference is so great?
Answer: The statement "Obviously this does not kill you" is not true in all cases and certainly not true for larger Van de Graaff machines.
The charge on a VdG is stored on the dome whose capacitance is approximately given by $C = 4 \pi \epsilon_o R$ where $R$ is the radius of the dome which for a dome of radius 20 cm is approximately 20 pF.
The charge stored is $Q= CV$ where $Q$ is the charge on the dome and $V$ the potential difference between the dome and earth so for a potential difference of 100 kV this represents a charge of 2 $\mu$C. The charge transferred by a current of 2 $\mu$A in one second.
Increasing the voltage brings problems of leakage of charge down the supports which hold up the dome and the air around the dome where there will be corona discharge.  You can often hear this above the noise of the motor driving the belt. Large VdG machines are usually housed in a vessel which contains gas under high pressure to reduce corona discharge or even spark loss.  You will also have noted that high voltage devices tend not to have any sharp edges.
Then you have the belt having a limited capacity as to the amount of charge it can transfer from the bottom of the VdG machine to the top. It also will suffer leakage.  You may have noticed that on a small VdG the motor slows down as the charge (and hence potential difference) builds up because the motor has to do more work lifting the charges against a potential gradient.
Comment: Those large Van de Graaff machines use (intentional) corona current as part of the voltage stabilization on the terminal, allowing fast feedback. If you are hearing it though, something is wrong.
Comment: I've just asked [How much current can be produced by Van de Graaff generators or Pelletrons?](https://physics.stackexchange.com/q/473488/83380)
Answer: Current and voltage are different things. Any source of voltage be it a battery, solar cell, wall-wart power supply, your wall outlet, some overhead transmission lines or lightening has a limit on how much current it can supply.This is obvious when you think about it, if there was no limit you could do spot welding of heavy steel plates with a few AAA cells. Why is there a limit ? Because the number of electrons stored (or available) in the power source has a finite limit based upon how many have been "stuffed" in there AND the current is also limited by the resistance of the circuit.
In the case of the Vann De Graaff we are stuffing electrons up into the top dome as we wind the handle. It is really a capacitor you are charging up and the more electrons on the top plate the higher the voltage. The capacitance is low though (maybe a few pF ?) so there is a low (relative, still millions) limit to how many electrons are up there before the voltage breaks down.
Wind the V de G up to the max, just before breakdown, and you have it fully charged and can make a nice spark, it will last for a tiny tiny fraction of a second and the current will be low because there are just not enough electrons flowing to make it higher because there are not enough electrons there in the first place.Current is a measure of flow rate of electrons.
If you could find, or make, a more substantial capacitor with a voltage rating higher than the V de G you could (if your arm doesn't tire) charge that too and get a higher current when it is discharged. From this we can see that the higher the voltage on a capacitor and the higher the capacitance the more dangerous it might be if you discharge it through a low resistance (or yourself). People have been killed & injured from capacitor discharges on so called "dead" i.e. disconnected/isolated electrical equipment.
W=1/2 CV^2 Try googling some more capacitor equations to understand the relationships between Capacitance, Voltage, Energy Stored, Discharge Times, Etc.
Answer: Ohm's Law sets the intensity of current (I) directly proportional to potential difference (V) and indirectly proportional to resistance (R).  Current is expressed in amperes, potential difference in volts, and resistance in ohms:
I = V / R
Current will be higher as resistance is lower.  While Van de Graaf generators can produce a large potential difference (high voltage), they do this in an environment of high resistance, which is necessary to allow charge to accumulate in the generator.
Smaller Van de Graaf generators with limited storage capacity generally discharge before accumulating a potential difference great enough to kill you.  Just as static electricity builds up in your clothing as you shuffle across a carpet and discharges with an impressive spark when a sharp edge of your body comes near a ground, but doesn't seriously injure you, a small Van de Graaf generator doesn't have great enough storage capacity to do more than produce an impressive spark.
Also, as Farcher points out in his answer, power demand of the moving belt mechanism used in small Van de Graaf generators to deposit charge in the storage dome, becomes greater as charge accumulates, which limits the ability of the mechanism to deposit charge in the dome.  Van de Graaf generators are dependent on high R to operate, and run into diminishing returns when building up high V.  So it's difficult to raise V/R to achieve a high current relative to the power consumption of the mechanism.


Oyster and Railcard purchase at Gatwick Airport

Question: Can I purchase a Railcard at Gatwick Airport and if so, where?  Also, can I purchase an Oyster Card at Gatwick Airport.  Skybreak told me that they would charge me 18 pounds.  I thought it was free with a 5 pound deposit afterwhich you added money to the card.  Also, any advice on getting from Gatwick Airport to Euston Station?
Comment: By "rail card" do you mean a train ticket, or a card for buying discount rail tickets with (http://www.railcard.co.uk/)
Comment: Oyster card yes. http://www.visitlondon.com/traveller-information/getting-around-london/oyster. From Gatwick take the Thameslink to St Pancras International, walk over to Kings Cross tube station and take the tube to Euston.
Comment: Many contactless credit cards now work on the Oyster readers, you can save time by trying your credit card instead
Comment: @dumbcoder If you're taking the Thameslink all the way to St Pancras, you may as well walk to Euston - probably faster than going down to the tube and back up again! Thameslink to London Bridge and tube from there would be quicker overall, I think.
Comment: @Andrew It is not easy to walk when you carry many luggage and it is easy to get loss when you leave st Pancras the first time.
Answer: Railcards
Assuming you actually mean a railcard as in the discount card, according to the how to buy page for railcards (in this case the 16-25, but you can switch to the others from the menu), they can be bought online or by phone with a UK driving license or passport (which I assume you don't have) or at any station with a manned ticket office.
You can see what facilities a station has from this page on the National Rail Enquiries site. According to that, there is a 24 hour(!) ticket office at Gatwick. Be prepared to queue however.
I'd also reccomend checking that a non-UK resident is actually allowed a railcard.
Oyster Card
This page on visit london (thanks DumbCoder) specifically mentions Gatwick as a location to buy oyster cards. Transport For London's site however only mentions visitor cards being available through the post and various international agents. It may be safeest to buy one in advance. The £18 you have been quoted is probably £3 for the card itself, and £15 for the minimum balance you can load on to it.
I didn't mean a Rail discount card, I meant a ticket/pass
Train tickets can be bought from any station with a ticket office or machine. See the above NRE link to check if a station has these facilities. If you are boarding at a station without a way of buyng tickets, you can board the train, then immediatley seek out a conductor and ask to buy a ticket.
If you want a broader "pass" for Rail travel in the UK, then EU residents should look towards single country passes from Interrail, while non-eligible nations can look at Britrail. (Request for help here - it's not clear to me which of britrail.com and britrail.net are the offical site)
Answer: You can purchase vistor oyster card in gatwick airport train station. It cost £3 plus at least £10 credit. You can receive discount fare when using oyster card
Oyster card can be used in:
Tube, DLR, TfL Rail and London Overground:All services in Zones 1-9 and to Watford Junction and Shenfield.
National Rail:All suburban trains stopping in Zones 1-9 and on journeys to:Chafford Hundred, Grays, Ockendon, Purfleet , Watford Junction , Broxbourne
But not on:Heathrow Express, Heathrow Connect services between Hayes & Harlington and Heathrow,  Southeastern high speed services between St Pancras International and Stratford International,  Any journey starting or finishing outside Zones 1-9 or beyond Watford Junction, Broxbourne, Shenfield or Grays
I dont sure what railcard mean. If you mean rail ticket, you can buy it in ticket machine/counter, or purchase online and get it in ticket machine with your debit/credit card and reserve code. Like flight ticket, purchase early usually costs less.
There are 3 types of rail ticket
Anytime: most expensive but you can travel anytime
Off-peak/super off-peak:less expensive but travel time is limited
Advanced: Fixed traveltime, limited availability, cheapest
If you mean the seperate dicount card which offer 1/3 fare off, you can purchase it online/train station counter. It cost £30 except £20 for disables annual. Most rail card has requirements on cardholder, except network railcard but it covers smaller area. You need a passport photo for some of the rail card and you have to show both railcard and ticket when staff is checking ticket on train.
The fastest way from Gatwick airport to Euston station is going to Victoria station first and interchange Victoria line to Euston station. The trip takes not more than an hour. The train between Gatwick to Victoria station is served by Gatwick Express and Southern, the latter trip is longer but cheaper.
Finally you can search these website for more information.
https://www.tfl.gov.uk/plan-a-journey/
http://www.nationalrail.co.uk
PS1: Gatwick train ticket office opens 24hours, London Victoria ticket office opens 4am-1am except 6am-1am on sunday
PS2: The queue in gatwick ticket office is not long, but in Lonlon Victoria you have to wait 5mins
Comment: Not all railcards need passport photos, the Network Railcard for one doesn't


When to use и or а as "and"?

Question: What is the difference between the forms of "and"  "и" and "a"?
Comment: Far too broad. These are not "forms" of _and_. Both conjunctions serve for too many purposes to list it here. Try to start from a comprehensive dictionary and then narrow your question.
Comment: The first one  "и" is for a logical and, whereas the second one "a" is for a temporal and.
Answer: I could not really recall any example when Russian a can be translated as and in English. Usually it is but in English. But then I looked into a dictionary and there was such a meaning.
and

1) и (сочинительный союз, реализующий различные логические отношения
  между соединяемыми частями)
boys and girls — мальчики и девочки
2) а, но (противительный союз)
I shall go and you stay here. — Я пойду, а ты оставайся здесь.
  There are books and books. — Есть книги и книги.

The difference is that the former is a coordinative one and the latter is an adversative conjunction. The first connects some words, which are not opposing each other in a particular context. And the second is something like an opposite, it connects words, parts of a sentence which do oppose to each other.
So boys and girls do not oppose, you are sort of enumerating the options.
With the I shall go and you stay here example there are two parts of the sentence which do oppose.
And There are books and books even in the dictionary was translated as и which also has the same meaning in Russian.
And if I encountered such examples in English I would not use the a conjunction, really. I would simply translate it as и in every example of the provided ones, as it was done with the third one.
Comment: "Yet" is a descent translation of "а" in most cases.
Comment: @VCH250 yes, exactly, thanks
Answer: I believe one good way to conceptualize 'a' in Russian and how to differentiate it from 'и' is the conjunction 'whereas.' In most cases I believe it is a good approximation, noting that 'whereas' generally means 'compared with the fact that; but.' When there is a clear, easily divisible contrast between the first and the second clauses of a sentence, it sets you down the right path to using it properly yourself when found in other contexts.
Certainly it doesn't cover all cases. In English, when it comes to bringing two clauses together there are a lot of subordinating conjunctions (after, although, as, as if, because, before, even if, even though, if, if only, rather than, since, that, though, unless, until, when, where, whereas, wherever, whether, which, while). As an English speaker you've internalized how to use these words largely unwittingly. If you wanted to explain when you use any of these and how one differs from the others, I think it would require a concerted mental effort to do so. Think analogously that Russian speakers have the same concepts, but some of which are wrapped up in 'а' but cannot be consistently translated as the same word in the English. It requires context to see its variety of meaning and you'll gain that with exposure, like you did with English.
I'll give you a couple examples to see how it varies, even when among sentences where it seems to follow the same structure:

Звонок брякнул слабо, как будто был сделан из жести, а не из меди.

The bell rang weakly, as if it was made out of tin and not out of copper. (/as though it were made not of copper but of tin.)

На ее тонкой и длинной шее, похожей на куриную ногу, было наверчено
  какое-то фланелевое тряпье, а на плечах, несмотря на жару, болталась
  вся истрепанная и пожелтелая меховая кацавейка.

On her thin and long (we would say 'long, thin' in English) neck, which resembled a chicken's leg, was wrapped in some kind of flannel rag, whereas on (from) [her] shoulders, despite the heat, dangled an all (entirely) worn-out and yellowed fur katsaveyka (jacket).

When to use и or а as "and"?


Is there any connection between visual processing ability and social skills?

Question: I suspect there is a connection because visual processing ability is necessary in noticing important subtle social cues.
Comment: **Yes.** Can you access this paper? http://greenlab.npih.ucla.edu/Publications/Sergi%20et%20al_SocCog_AJP.pdf Read the introduction which summarizes findings. Also try https://scholar.google.com/scholar?q="social+skills"+"visual+processing"
Comment: Are you interested in individual differences in "visual processing ability" or are you more generally interested in the link between visual perception and social perception?  I suspect (warning:  pure conjecture) that visually-driven impairments in social skills will stem more from deficits in attention and gaze orientation, so these terms might help you in your search for literature.
Comment: Not directly, it's more related to learning ability which then can be affected by visual processing ability. However, if some person is not able to spot small differences in the pictures, it doesn't mean he/she has learning difficulties, but and vice-versa. It would just require more focus.
Answer: Reading facial expressions is very important to understand others' intentions (Heise, 1985).

Recent research indicates that (1) the human face is a highly sophisticated signaling system for communicating affect, and (2) affect plays a key role in the experience of social organization and in the day-by-day production of culture. This essay suggests that emotional displays—on the face especially—are a primary means of socialization, allowing a neophyte to attain knowledge of the sociocultural system rapidly and efficiently.

Having a visual impairment may yield difficulties in socializing (at least in child in the Autism Spectrum Disorder) (Hellendoorn, et al, 2013):

This study suggests that visual perception may be a mechanism in the development of interpersonal relationships in ASD, which is in accordance with an embodied approach to social cognition.

...and in schizophrenia cases, as per @what comment (Sergi et al, 2006):

Social cognition appears to be a key determinant of functional status in schizophrenia. Using a very basic measure of visual perception, the present study found that social perception mediates the influence of early visual processing on functional status in schizophrenia.

Other indirect consequences may happen due to behavior related to some visual disorder. Vision problems and social skills (note: not a peer-reviewed article):

Vision problems also affect social interaction. Your child might appear awkward, clumsy, or other children may complain that he is invading their personal space, because he has trouble with spatial and body awareness and depth perception. The other children might treat him differently because he has developed coping habits, such as constantly rubbing his eyes, squinting, or tilting his head, or because he often complains of headaches or nausea. He may become distracted while talking or ignore the rhythm of a conversation and other social cues. Children or other parents might unfairly judge this behavior as unmannerly or inconsiderate.
Dealing with difficulty in school, awkwardness in social settings, poor performance in physical activities, and strained relationships with parents is a lot for a child to handle. While children with other learning disabilities may excel in sports or sociability, vision problems interfere more often beyond the classroom. Falling behind academically and being treated differently by peers and adults can lead to low self-esteem and withdrawal.
Answer: Yes there is relation, but currently there is no research evidences. its theoretical.
As you can observe we at according to situation and its demands. with passage of time our social skills improved and we also learn new skills in such way.
Comment: Welcome to cogsci.SE!  Can you cite sources for more information on this theoretical link?


Does the Paxos algorithm use failure detectors?

Question: Does the Paxos algorithm use failure detectors? If not, how can it solve consensus, given the impossibility result?
Answer: In short, the "plain" Paxos algorithm does not use failure detectors, but it can be augmented with failure detectors. Furthermore, the "plain" Paxos algorithm does not fully solve the problem of consensus.
To answer this question more in detail, we first define "the consensus problem". An algorithm "solves" the problem of consensus if it guarantees that the following properties are satisfied:

Termination (or liveness, or progress): all non-faulty processes eventually decide on a value
Agreement (or consistency, or safety): all processes that decide do so on the same value
Validity (or non-triviality): the value that has been decided must have proposed by some process

The "plain" Paxos guarantees that agreement and validity are always satisfied, that is, if you use Paxos to solve consensus, then you will never get as a result processes that decide on different values or that decide on values that have never been proposed.
However, "plain" Paxos does not guarantee termination, that is, if you use "plain" Paxos, then it is possible that processes will never decide on a value. This problem can be (partially) circumvented by using using "leader election", that is, you elect a leader (which must be a proposer in the "plain" Paxos algorithm) which coordinates the proposals. However, the leader can also fail. This failure of the leader can e.g. be detected using failure detectors (which, in practice, may be implemented as "timeouts"). Therefore, Paxos can use failure detectors. But I won't dwell more on this topic.
In conclusion, "plain" Paxos does not fully solve the problem of consensus, because it does not guarantee "progress".
Comment: Note that the FLP impossibility result says that _no_ protocol can solve the consensus problem in an asynchronous environment, even in the presence of just one crash-fault.


Random Island Name

Question: I know about several random island generators. What I would like is a table or program to generate names of islands randomly.  I found a Greek island version but would like something for English names.
Answer: The Agon island generator generates islands complete with names.
Other than that, I think any random place name generator would work, if you stick "Isle of" on the front or "Island" on the back of it.
Comment: Unfortunately it uses greek style island names. I am looking more for english style.
Answer: Just by googling a bit, I found this one. Hope it's useful to you. On the other hand, this variation seems to work better for english names.

Random Island Name


Why do you need excess LAH to reduce esters?

Question: I am little confused on this question. On one hand, I remember my teacher saying that $\ce{LiAlH4}$ is like $\ce{BH3}$ of hydroboration oxidation of alkene, where you one mole of $\ce{BH3}$ can oxidize 3 mole of alkene molecule. but on the other hand my textbook keeps on mentioning excess LAH when reducing ester? Can't one mole of LAH reduce four mole of ester molecules as well? Thanks.
Comment: LAH is a bit more fickle than borane. Some of the hydrides might not add. Depends on the binding of the reduced components to the central aluminum. They form an oxide, and the oxide can reduce the nucleophiliticity of the hydrides and increase steric crowding.
Comment: A single reduction of a single gives a aldehyde, which is a more reactive carbonyl than an ester is.
Comment: I know that. I am asking why can't one mole of LAH reduce ester twice since it havs 4 hydrogens attacked to Aluminum.
Answer: Lithium aluminium hydride or LAH is the more everyday form of $\ce{LiAlH4}$. When originally produced, most of it is indeed $\ce{LiAlH4}$ but that quickly partially hydrolyses giving the grey powder you may or may not know from the lab. As such, $\ce{LiAlH4}$ is practically never entered into reactions in pure form. Since it is impure, excess reagent is added to make sure the reduction job is performed as desired.
Also, remember to consider the reaction meachnism:
$$\ce{R-COOR' ->[LAH][- HOR'] R-CHO ->[LAH] R-CH2OH}\tag{1}$$
Note that the second step, the reduction of an aldehyde, is more rapid than the first as aldehydes are more reactive towards nucleophiles than esters. Thus, if you attempted to bargain, hoping to arrive at the aldehyde selectively, you would end up with under half of your reactant reduced to the alcohol and half of it still as an ester. Another reason to always add excess just to be sure.
Answer:
For one, the action of $\ce{BH3}$ (or a borane in general) on an alkene in the course of a hydroboration is not an oxidation, rather than an reduction.  The second step, the action of hydrogenperoxide on the product of this addition (an alkane) is an oxidation.
For the reduction of an ester by LAH, there are two things to retain:

general rule: LAH reacts with a carbonyl compound, initially forming a lithium alcoholate and $\ce{AlH3}$, and subsequently they form the lithium alanate (decomposed during mildly acidic aqueous workup)
The first H of $\ce{LiAlH4}$ leads only to the aldehyde, and the second one to the alcohol you are able to isolate.


What is the easiest color to see on black and white?

Question: Not exactly photography but somewhat related due to picture editing..  What is the easiest color to see whether it's on black or white?
Comment: In high key photographs: it's white. In low key photographs - it's white. Otherwise: It's grey. ;)
Comment: I would think that something like that "ugly green color" that they make firetrucks now-a-days would be the easiest to see on any background--is that not the case?
Comment: Use a pattern of white and black and fill the area. That is the easy to see on any color.
Comment: Do you mean the easiest color to see, or the easiest color to read? A very bright color like yellow would be easy to see, but hard to read.
Comment: To clarify Guffa, the best colour to pop will be orange. By what I read this colour can be seen in most bad circumstances
Comment: I've provided an answer with a bit of photographic slant as appropriate for this site. However, it may be that you really wanted to ask this on [Graphic Design Stack Exchange](http://graphicdesign.stackexchange.com)
Comment: I didn't see that exchange site and it probably would have been more appropriate but your answer is more than adequate for what I asked, thanks ^_^.
Answer: This isn't necessarily just of interest in photo editing — it can be useful in making strong color compositions as well. In general, yellow is the most visible and first-noticed color (random citation, but there are plenty of others) and yellow on black is widely regarded as providing the most visibile contrast. You'll often see it used for warning signs for this reason.
On a white, any dark color will do, and it's more a matter of whether you want to convey urgency (red) or calm and stability (green and blue), or go with the matter-of-factness of black.
Now, if you're looking for the color that works best to contrast with both black and white, something in the middle is logically most appropriate. Avoid yellow or purple, which are inherently bright and dark — see the great answer to my question for why Why are there no dark yellows, or bright violets?. Red, blue, or green would probably all work (and, generally, be more apparent than neutral gray.) Of course, if you're composing something where the color has semantic meaning, be aware of colorblindness, and make sure your selected hue is relatively high-contrast to those with differing vision.
Another option may be to outline your object, either in the object itself or through backlighting or rim lighting. That way, there's a line delineating your object as separate from the background.


How to convert a uint to bytes in Solidity?

Question: Is there an easy way to convert a uint to bytes in Solidity?
Answer: The alternative to @eth's answer is to use assembly:
function toBytes(uint256 x) returns (bytes b) {
    b = new bytes(32);
    assembly { mstore(add(b, 32), x) }
}

This is significantly more gas-efficient, but depends on the internal memory layout used by the Solidity compiler. In theory, this can change in future, but in practice it should be fairly stable.
Comment: Would you mind explaining what each line does? What is the purpose of this add(b, 32). Couldn't we simply do mstore(b, x)?
Comment: @ppoliani the `bytes` type in Solidity is stored in memory as: 1) first 32 bytes = length of the `bytes` value, 2) then the `bytes` value itself. The `mstore` opcode stores 32 bytes, starting from a certain offset (in the bytes value to grab) to a specified location in memory. So the instruction `mstore(add(b, 32), x)` can be translated in plain words as _"stores 32 bytes at position x in memory, starting from the 32nd bytes offset in the `b`"_ (so to skip the length, and just store `b` itself).
Comment: @ppoliani did you get an answer to your question? I am also curious why we add 32 to b. (when b should be at the start of memory address anyway).
Comment: Actually it is explained here:
https://ethereum.stackexchange.com/questions/98750/what-does-addsource-32-do-in-solidity
Answer: It seems there now is, since solidity version 0.4.24 you can use abi.encodePacked
E.G:
uint i = 0;
i_bytes = abi.encodePacked(i);

Answer: Here's a comparison of the gas used in the three methods by @NickJohnson, @Eth and @k26dr. I've added a constant to the function modifiers as these functions do not alter the blockchain:
pragma solidity ^0.4.2;

contract Test {
    function toBytesNickJohnson(uint256 x) constant returns (bytes b) {
        b = new bytes(32);
        assembly { mstore(add(b, 32), x) }
    }

    function toBytesEth(uint256 x) constant returns (bytes b) {
        b = new bytes(32);
        for (uint i = 0; i < 32; i++) {
            b[i] = byte(uint8(x / (2**(8*(31 - i)))));
        }
    }

    function toBytesNicolasMassart(uint256 x) constant returns (bytes c) {
        bytes32 b = bytes32(x);
        c = new bytes(32);
        for (uint i=0; i < 32; i++) {
            c[i] = b[i];
        }
    }
}

You can see the gas cost of running these functions in Remix (Solidity Browser):
Answer: There are no easy ways to convert anything to bytes. Here's a function:
function toBytes(uint256 x) returns (bytes b) {
    b = new bytes(32);
    for (uint i = 0; i < 32; i++) {
        b[i] = byte(uint8(x / (2**(8*(31 - i)))));
    }
}

Based on Solidity Gitter chat.
Answer: If you're overly concerned about gas we can improve on @NickJohnson answer too.
function toBytes(uint _num) returns (bytes _ret) {
    assembly {
        _ret := mload(0x10)
        mstore(_ret, 0x20)
        mstore(add(_ret, 0x20), _num)
    }
}

This will shave approximately a further 15% off the gas cost, just be careful that you're not using that memory for something else as 0x10 is a direct reference to memory.
Also, if you want to copy an 8bit int to byte here's an alternative which only uses half the gas cost:
function toByte(uint8 _num) returns (byte _ret) {
    assembly {
        mstore8(0x20, _num)
        _ret := mload(0x20)
    }
}

Again, be mindful that 0x20 is another direct memory reference and in all honesty with this one I would stick with
function toByte(uint8 _num) returns (byte _ret) {
    return byte(_num);
}

The gas price between the two was almost identical, but the functional ASM was undercutting it by about 70 wei
Edit: If you're concerned about overwriting memory you could use:
let m_alloc := add(msize(),0x1)

Instead of referencing memory yourself
Comment: I didn't know msize() can be used to increase the memory allocation by adding to it. The solidity assembly document (https://solidity.readthedocs.io/en/v0.4.24/assembly.html?highlight=calldatacopy) is very brief. Is there a better reference document out there?
Comment: msize doesn't, it returns the highest point in memory and you simply state that you want to write to msize() plus 1. Here's another stack page where I explain it in more detail https://ethereum.stackexchange.com/questions/9537/how-to-return-dynamic-sized-arrays-original-address-on-the-memory-of-solidity
Answer: You can convert to bytes32 then convert to bytes:
uint u = 200;
bytes32 b = bytes32(u);
bytes memory c = new bytes(32);
for (uint i=0; i < 32; i++) {
    c[i] = b[i];
}

Answer: You can avoid padding the bytes array with 0's with the toBytes implementations by determining the scriptNumSize
function scriptNumSize(uint256 i) public view returns (uint256) {
    if      (i > 0x7fffffff) { return 5; }
    else if (i > 0x7fffff  ) { return 4; }
    else if (i > 0x7fff    ) { return 3; }
    else if (i > 0x7f      ) { return 2; }
    else if (i > 0x00      ) { return 1; }
    else                     { return 0; }
}

function toBytes(uint256 x) public view returns (bytes memory b) {
    uint a = scriptNumSize(x);
    b = new bytes(a);
    for (uint i = 0; i < a; i++) {
        b[i] = byte(uint8(x / (2**(8*(a - 1 - i)))));
    }
}

For example uint 1563384765 would return 0x5d2f5bbd not 0x000000000000000000000000000000000000000000000000000000005d2f5bbd
This was written specifically for timestamps. If you want larger numbers you can add more if cases.


VB.NET Write yields #ERROR 448#

Question: I have a bit of ported code. It was automatically converted from VB6 to VB.NET. Now when if finally compiles, it produces output files with some values replaced with literal #ERROR 448#.
I will eventually find out what's the problem, but I just wonder, if anyone knows what does this error mean. VB's Write function is used.
Comment: Ha-ha, I couldn't find it yet. Lurking for the right piece now.
Answer: I guess it as simple as trying to write a variable set to Nothing makes #ERROR 448# written to the file. Strange that msdn is not telling you this.
Answer: You are tryng to WRITE a null value or other unacceptable value to a file. Earlier versions of BASIC just ignored the WRITE request. MSDN should be telling you about this.

VB.NET Write yields #ERROR 448#


Game Programming Resources for Programmers

Question: I am a self-taught high school programmer (have an internship at local university), and understand the fundamentals of C++ and other related languages. I am looking to expand into game development, and have found a good DirectX book from which I will study. However, what are some good resources (online tutorials/books/etc) for C++ game programming which are tailored towards someone who is already experienced with C++? Most of the resources I have found attempt to teach basic programming, then get into game development.
Comment: Where to get started questions are off topic. See the [FAQ](http://gamedev.stackexchange.com/faq) about what kind of questions to ask here.
Comment: Game design is the non-technical side of game development - is that really what you mean to ask about? Or are you asking about game-specific programming tasks?
Comment: Sorry, I meant game programming. Thanks for correcting me.
Answer: There is a clear distinction between design and development. A game designer may have no programming skills, even though it would definitely be helpful.
Concerning game development, which I presume you're interested in, unfortunately there is no silver bullet. It's an issue that has been bothering me for a lot of time. It definitely depends on what you need to do, what you like and how much time you're prepared to invest in gamedev.
What I know is that the best way to learn how to code games is to actually code! There are two wonderful ways to achieve this:

Start small, and try to build even simple types of games. Brickout and Pacman may sound trivial but they are an awful lot of work!
Participate in a Libre/FOSS game project. Start studying the code, use paper to write down the basic architecture, and then delve in whatever part interests you most!

In addition, try not to re-invent the wheel and use popular/easy tools and algorithms, don't build everything from scratch, don't over-engineer, don't focus on performance or optimal design.
I'm sure you can find a lot of useful books here in Gamedev.SE and you can easily find interesting resources online.
You must also decide if you want to start with 2D or 3D game development. Of course, you can focus on tools or other parts of the game so graphics won't be an issue.
If you want to try something practical really fast, take a peek here: http://www.lazyfoo.net/SDL_tutorials/
Why don't you check some projects here?

freegamer.blogspot.com
planetrev.freegamedev.net

Fit in a big community in order to learn by studying and improving GOOD, WORKING CODE. Simply studying resources and algorithms won't get you too far, as you will soon lose interest.
Answer: For game design, i recommend one of my favourite books: The Art of Game Design: A book of lenses, a extremely enjoable reading.
For game programming i have spent some time with Game Coding Complete, Fourth Edition, and i think it is worth reading because t explores all the major subsystems of modern game engines.
Answer: I found Game Programming AI by Example to be a great reference for fundamental game development concepts. It covers game math, flocking, state machines, lua scripting, advanced data structures, and path finding.
Comment: I have this book and have not yet gotten around going through most of it. Glad to see someone else liked it!


Dealership Says I need all New Rotors

Question: I need new brakes, and yes I have one warped rotor on the right front wheel. I understand replacing both front rotors but the dealership says all 4 rotors need replacement even though NONE of them have grooves. 2018 Platinum Ford Explorer is this true?
Comment: Welcome to Motor Vehicle Maintenance & Repair! It really depends on the wear on the rotors. You have to measure their thickness to see if they are within specs. If you doubt the dealership's voracity, you can always check with a mechanic you trust.
Comment: Did you ask the dealer why they recommend replacing all the rotors? On late-model vehicles the rotors are pretty thin right fromt he factory and there ofen isn't enough metal left after machining, so they replace them. If the dealer has measured them with a micrometer and determined they need to be replaced, it doresn't really matter what they look like to you.
Comment: If you aren't convinced by what the dealer says, you can always have another independent workshop take a look.  As the dealer what thickness the rotors are and ask Ford themselves what the minimum thickness is.  Ask an independent to measure the thickness and use these three pieces of information to work out if the dealership is being honest with you.
Comment: If it is warped it needs replaced, they are just upselling on the rear rotors i think, that is what they do, upsell.
Answer: Brakes work by creating friction: hydraulic calipers squeeze pads into rotors, which removes material from both the pads and the rotors. Too much heat can cause rotors to warp, which causes a vibration when braking. Rotors should be replaced when they get too thin, which they measure using a specific tool, or are too warped to correct, which also is measured using a tool. Sometimes warped rotors can be resurfaced if they have enough remaining material and it's not too severe.
Brake rotors should generally be replaced in pairs, both fronts or both rears, in order to have even braking. If you had one thin and one thick rotor you may get more braking action from one side than the other, which isn't good.
This is a relatively new car, unless you are driving a heck of a lot I wouldn't expect your rotors to need replacing yet, so the dealer telling you all 4 need replacing is a bit dubious. The front 2 I can believe, the back 2 not so much.
Answer: Grooves are NOT the determining factor for rotor replacement.  The two main concerns are runout (i.e. is the thing warped or not) and thickness (i.e. is the rotor worn to the manufacturer's service limit, or will it be too thin after being turned to remove any problem areas).
You cannot tell this by looking but you can measure the thickness with calipers or a micrometer and check the runout with a runout gauge.
Both figures, runout and thickness, are specified in the vehicle's service manual.
If you have these tools, do the measurements yourself.  If not, then you're at the shop's mercy.  If you don't trust the dealership, I can't imagine why you took it there to begin with.
In my experience, however, vehicle manufacturers today leave very little "meat" on the rotors to begin with.  I'm sure this is to cut costs to some degree but more so to cut weight as every gram matters when figuring fuel economy numbers.  Making the rotors a few 10th of an inch thinner may will a bit of weight.  So I've noticed that the rotors almost always need to be replaced when the pads are worn.  Having a warped rotor is a sign of hard use, so I'm not at all surprised that your rotors need to be replaced.

Dealership Says I need all New Rotors


Piano 5-finger exercises in Bb and Eb

Question: It seems to me 5-finger exercises are usually presented in the key C major, but I thought it might be good to practice them in all keys. Bb and Eb major are difficult for me, because my third fingers get stuck between the black keys when hitting the white keys. If I angle my forearms a bit it seems to help, because my fingertips have a bit more room to fit between the keys. In Bb the problem is finger 5 L.H. and finger 1 R.H. have trouble reaching Bb. Forearm and wrist adjustments seem to help. Hoewever, both of these keys feel awkward. Can anyone offer any other advice? Does anyone recommend to not do 5-finger exercises in all keys?
Answer: You certainly should practise 5-finger exercises in all keys.
If your fingers are getting tangled in the black keys, practice slower, try bending your fingers more, and try moving your hand (and arm) forwards and backwards when your thumb needs to reach a black key.
All this will feel awkward, in the sense that if you wanted to play the notes in a piece of music you would normally use the same fingering as a Bb or Eb major scale. But one day, that won't be a practical option and you will need to play a 4-note chord like Eb - Gb - A natural - Eb without getting tied in knots - and maybe add a C natural as well, or a 5-note dominant 7th chord like D# - F# - A - B - D#.
Comment: I don't see that in a piece you'd use the same fingering as you would in a scale of the same key. Sometimes, but not often.
Comment: I think this answer addresses my concern which is more about optional fingering when the standard Eb/Bb fingering isn't practical rather than preparation for full scales.
Answer: Unless your fingers are very wide, and the middle one is actually squeezing betweed Db and Eb, you should be able to play using all five. Thumb will start on Bb (for the Bb exercise), and your hand ought to be in a straight line with your forearm. Moving so that the angle from above changes probably won't help much. In fact, normally, you should be able to place all five digits on all five keys, and lift each separately.
All the above presumes that your fingers will fit without getting jammed - something I've never seen! If that's the case, you'll have to press the white keys just where the black keys ends are. Of course, your fingers are nicely bent, so the tips press them down. Aren't they?!
To prepare for full scales, though, it's a good idea to start with middle finger on Bb, then thumb under onto C. Thus, it's only a four finger exercise, but thumb on a black key is often something to avoid. Not always possible, obviously, but given the option to play a black key with anything but thumb - take it.

Piano 5-finger exercises in Bb and Eb


Connect SSD with USB, install new Windows/Mac OS, and then replace hard drive; is that possible?

Question: I just get my fist ssd and I wonder if I can install it in an easy way. So I want to connect the new SSD via USB to my computer, and install Windows or Mac OS first (so the SSD here is not the primary boot drive, just connected externally). And then I would replace my present hard drive with the SSD. Is that even possible?
Answer: No it is not possible to install an OS onto an external drive.
You must swap the drives first then run off the installation disk.
Or you can use 3rd party software or DOS to copy your old hard drive to your new SSD so that you still have the same OS. Though that would take more time but it's still possible if you want to keep all your stuff.
Answer: Yes it is possible. I do this all of the time.
http://www.wikihow.com/Install-Osx-Lion-on-an-External-Drive


How can I migrate photos from Microsoft OneDrive to Google Photos?

Question: How can I migrate photos from Microsoft OneDrive to Google Photos? Can I do it without having to download all the photos from OneDrive to my desktop and then uploading them to Google Photos?
Answer: There are several ways including free and paid, but I will show you the free way.

Google has announced new Google Photos that works with Google Drive, so you need to make sure that there is a Google Photos folder in your Google Drive.
Head to www.multcloud.com and register an account.
Confirm the accounts and start linking your cloud services
Click Transfer on the header of the website and select the folders you want to transfer. Your destination folder should be Google Photos.
Boom! You're done!

Let me know if you caught any issue.
Comment: Amazing solution. But When I select google drive, it shows the drive (with folders and files). I cant see google photos as destination. How can I get that?
Comment: The Google Photos folder is added automatically. Can you go to drive.google.com and check if there is any wizard to create it?
Comment: I found an issue with this solution, you need enough free space in your Google Drive Account to hold all the pictures in their original (high res) form. Using the app and copying from your PC has an option for a lower res but free unlimited space. So looks like I am back to uploading from my PC
Answer: Actually you can select the individual file by dropdown eliminating having to use the entire folder unless that is what you are after.


Is there a way to change the pmount mount point?

Question: Based on this answer for automounting USB...
Running Stretch Lite on a Pi3, running Openbox window manager, no desktop or session manager.
Is there a way to change the name of the mount point created by pmount?
For example, by default it will mount to "/media" but I need it to mount to "/media/username".  I'd like to do this just by modifying some setup file, or running a CLI; no graphical interface.
If not possible with pmount, is there any other way of automounting to an alternate mount point?
Answer: Mounting drives into /media/user/* is usually done by your file manager. Try running one in daemon mode, e.g.
pcmanfm -d &

Make sure the relevant options in "Volume Management" are checked:

You may need to install a session manager. Otherwise, if two users are simultaneously logged into the system, how do you want the automount to decide which user gets access to removable drives? Automount scripts which work without a session manager (such as usbmount)  mount everything into a common /mnt exactly for this reason.
The purpose of pmount is to let you mount drives manually without sudo, it's strange to transform it into an automount solution using custom scripts.
Answer: From the pmount man pages:

pmount device [ label ]
This will mount device to a directory below /media if policy is met (see below). If label is given, the mount point will be /media/label, otherwise it will be /media/device.

So, if you run pmount /dev/sda1 /media/this_is_my_personalised_mounting_point then you will get /media/this_is_my_personalised_mounting_point in stead of /media/usb1 which would be chosen by default (if /media/usb1 is not already occupied, of course...)
Comment: Thanks.  To clarify, the goal is for things to mount to /media/username/usb1...2...3... etc.  In other words, I want the base to be /media/username/ then the mount points under that.  I'm looking for a more elegant solution than just brute-forcing username/usb1.  I was hoping there was some undocumented config file somewhere that specifies the base mount point.  My current solution just creates a symbolic link in the udev script.


Is there any reason to keep original drive-train components together until they can all be replaced?

Question: I broke the master link in my chain a while ago and my LSB told me it was because I wasn't cleaning/lubricating my chain often enough. The chain had experienced more wear than it should have as a result. I asked about replacing the chain and was told that you typically don't want to replace individual parts of the drive-train, that mixing and matching new chain and old chain-rings is a bad idea. Is there any truth to this? Why would a new chain on an old (we're talking less than 4 months) be a bad thing?
Answer:
Breaking a master link, as already said, is not so common, and is usually not related to the chain wear. It can be related to loss of lubrication, for example when the chain RUSTS and gets some hard links that cause the chain to get entangled with the derailer while pedaling, for example. But only because it is worn, supposing it is clean and lubed, I'd say no.
Installing a new chain with an used cassette might be divided in two kinds of situations:

You install and the chain doesn't skip. This is the ideal situation, meaning you replaced the chain at the right time, and your cassette will last much longer (note: this is the recommended thing to do - use lots of chains with the same cassette, replacing them often as soon as they get some wearing);
You install the chain AND IT SKIPS over the cogs when you pedal. That means you waited too much to replace the chain. It might be very difficult or almost impossible to use the new chain and make the cassete wear "back to normal". In this case, it MIGH BE a better idea to keep riding with that chain for a bit more and replace it together with the cassette later (waiting too much can be dangerous, since the chainrings might get damaged in the process). Even when the chain skips, though, if it skips only while pedaling hard, and/or only on specific gears, it is usually possible to ride slowly in the beginning, and the skipping starts to disappear as the cogs wear, and everything might come back to normal.

So, the shop guy may or may not have told you the truth, depending on how much your cassette is worn. This is not an easy thing to do if he didn't measure the chain with a gauge, so it is possible that is obvously worn, or he has a very good eye, or he actually wants to sell you the whole kit. Besides, the need to change everything together is surely NOT true, since the expected is to change the chain often, so as to preserve the gears, which can last MUCH longer.
I would do the following: buy a new chain and try. If it works, it works. If it skips, I put back the old chain and keep the new one at home. When the time arrives, I change the cassette and then install the new chain.
(Finally, some crafty people are able to remanufacture the shape of the cassette teeth by disassembling the cassette and correcting the teeth shape with a round file, one by one. I did it successfully a lot of times, but it takes some skill and a lot of time and hand labor, sort of a masochistic hobby, but anyway it works and can save you some money or at least the trip to the shop.)
Comment: (A Dremel tool will make the cog dentistry go much faster.)
Comment: @DanielRHicks I had tried this with the Dremel, and didn't like it. It tends to climb over the tooth, and requires an uncomfortable force from the wrist. As with many other things I planned to do with the Dremel when I bought it, this is one more job where manual tools end up being easier, not to say the round file gives more "bite" to the teeth, so that they grab the chain much better.
Comment: (side note: Dremel is the brand name of a very nice hi-speed rotary tool. It is ideal, for example, to rectify the shape of cable housings after cutting them with a common plier, or to remove eventual sharp edges from the inner side of rims).
Comment: Sound advice. Will pick up a new chain next week, thanks.
Comment: Yeah, a Dremel is definitely hard to control.  You need the sprocket to be firmly fixed (not twisting), and you need to arrange a way to brace the Dremel, then grind very carefully.
Comment: (PS: I agree he should just buy a new chain and try it.)
Comment: Bought a new chain and tried it - no issues so far, and no skipping even under extreme load.
Comment: @meagar That's nice! The best thing you can do, now, is to clean the chain regularly, lube it after cleaning, and not waiting TOOO long to replace it.
Answer: How many miles do you have on the bike?  How worn was the chain, when the bike shop guy used a gauge on it (which he should have done)?  (Note that usually shifting problems and chain skipping are the first signs of a badly worn chain.  A failed master link is not usually the first sign of wear.)
Generally a chain should be replaced about every 2000 miles (when chain stretch measures about 0.75%, and certainly no more than 1%).  If you wait longer than that the sprockets "take a set" to the worn chain and a new chain will not fit as well.  But if you replace the chain before it's that badly worn then you can get 5000 miles or better from a rear cluster and 10K miles from your front rings.
The "replace everything together" "rule" is stated for two reasons:  1) It makes the bike shops money, and 2) most people don't replace their chains until they're too worn.
But even then, the rear cluster is usually the seriously worn piece and the front rings are often not bad enough to need replacing.  And, in any event, a competent bike shop should have a gauge for measuring sprocket wear, vs just using "the rule".
Comment: The bike is about 4 months old, and has been getting between 150 and 200km/week of usage. He did use a gauge, and told me the chain had *much* more wear than it should for a bike only ~4 months old. I'm trying to drag this out of memory, but the thing read "twice" what it should, give or take. They chalked it up to insufficient cleaning/oiling of the chain. When I asked if the chain should just be replaced, he told me the above about not mixing and matching old/new components in the drive train.
Comment: More wear than it "should" for a 4-month-old bike (which in "normal" circumstances would have about 500 miles on it), or more wear than the "allowable" amount (which is about 0.75% to 1%)?  (You can buy an inexpensive "go/no-go" chain stretch gauge to measure this yourself.)
Comment: 200km a week is a lot. In 4 x 4 = 16 weeks you get 3200km. Even if you clean and lube, this is enough to make most chains go beyond end of life. Since most people usually don't ride this much, I think that's what the shop guy meant with "more than it should for a bike with 4 months". Twice that it should probably mean 2% "elongation", considering 1% as the reference that prompts for a new chain.