Q:

How to copy text from one file to another and then turning the first letters of the text string into uppercase

I am trying to build a program that copies text from one .txt file to another and then takes the first letter of each word in the text and switches it to an uppercase letter. So far, I have only managed to copy the text with no luck or idea on the uppercase part. Any tips or help would be greatly appreciated. This is what I have so far:
int main()
{
    std::ifstream fin("source.txt");
    std::ofstream fout("target.txt");
    fout<<fin.rdbuf(); //sends the text string to the file "target.txt"

    system("pause");
    return 0;
}

A:

Try this,  Take the file content to a string, then process it, and again write to the traget file.
int main()
{
  std::ifstream fin("source.txt");
  std::ofstream fout("target.txt");
  // get pointer to associated buffer object
  std::filebuf* pbuf = fin.rdbuf();
  // get file size using buffer's members
  std::size_t size = pbuf->pubseekoff (0,fin.end,fin.in);
  pbuf->pubseekpos (0,fin.in);
  // allocate memory to contain file data
  char* buffer=new char[size];
  // get file data
  pbuf->sgetn (buffer,size);
  fin.close();
  locale loc;
  string fileBuffer = buffer;
  stringstream ss;
  for (std::string::size_type i=0; i<fileBuffer.length(); ++i){
    if(i==0)
      ss << toupper(fileBuffer[i],loc);
    else if (isspace(c))
      ss << fileBuffer[i] << toupper(fileBuffer[++i],loc);
    else
      ss << fileBuffer[i];
  }

  string outString = ss.str();

  fout << outString;
  fout.close();

}


Q:

Filling input field with expression language issue

I have problem with filling input field with request attribute using expression language. It's work correct when i display this attribute using for example ${title}but when I trying fill input by this way <input name="bookTitle" type="text" value=${title} > it only fill one first word. What I doing wrong?
My code below:
editBook.jsp

                        Title
                        <input name="bookTitle" type="text"
                            value=${title} >

adminPanel.jsp
Edit
editBookServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String title = request.getParameter("bookTitle");
request.setAttribute("title", title);
request.getRequestDispatcher("/editBook.jsp").forward(request, response);
}

A:

try to wrap value=${title} in the quotes like this:
value="${title}"


Q:

SignalR Client Connection has been not established

I created a SignalR Selfhosted application but can not access via browsers or Windows Phone (which is my client). I followed several tutorials and they pretty much say the same thing, I believe that the error is on my network configuration also notice that when you run the project, the IIS does not fire (not sure if it is also required).
SignalRServer:
class Program : Hub
    {
        private static HubConnection Connection { get; set; }
        private static IHubProxy HubProxy { get; set; }

        const string Url = "http://*:8080";

        static void Main(string[] args)
        {
            // This will *ONLY* bind to localhost, if you want to bind to all addresses
            // use http://*:8080 to bind to all addresses.
            // See http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx
            // for more information.

            using (WebApp.Start(Url))
            {
                Console.WriteLine("Servidor rodando em {0}", Url);
                Console.ReadLine();
            }
        }

        private static void Connection_Closed()
        {
            Connection = null;
        }
    }

    class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);
            app.MapSignalR();
        }
    }

The error is:

The connection has not been established.

My Client class:
public class SignalRService : PhoneApplicationPage
    {
        public String UserName { get; set; }

        public IHubProxy HubProxy { get; set; }

        private const string ServerURI = "http://localhost:8080";

        public HubConnection Connection { get; set; }

        public SignalRService()
        {
            UserName = "Luizaooo";

            ConnectAsync();
        }

        public void ObterAtualizacoesProdutos()
        {
            ProdutoService produtoService = new ProdutoService();
            var dataHora = produtoService.ObterDataHoraUltimaAtualizacao();
            HubProxy.Invoke("ObterAtualizacoes", dataHora);
            MessageBox.Show("passou");
        }

        private async void ConnectAsync()
        {
            Connection = new HubConnection(ServerURI);
            Connection.Closed += Connection_Closed;
            HubProxy = Connection.CreateHubProxy("ProdutoHub");

            HubProxy.On<List<Produto>>("AtualizarProdutos", (ListaDeProdutos) =>
                this.Dispatcher.BeginInvoke(() =>
                {
                    var a = ListaDeProdutos;
                }));

            try
            {
                await Connection.Start();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return;
            }
        }

        private void Connection_Closed()
        {
            Connection = null;
        }
    }

A:

Getting the Startup class to be recognized correctly can be tricky, especially in self-host scenarios.
For your code, first check if the Configuration method is actually running. If it isn't, add
[assembly: OwinStartup(typeof(Program.Startup))]

above the namespace decleration as described here: Owin Startup Detection
You can bypass this problem entirely by using the overload of WebApp.Start that takes a predicate:
 WebApp.Start(url, new Action<IAppBuilder>((app) =>
 {
     app.UseCors(CorsOptions.AllowAll);
     app.MapSignalR();
 }));

Either way, test your connection by navigating to http://localhost:8080/signalr/hubs . If that shows you a signalR javascript file, you will know that your service is up and running


Q:

Benefits of using customer supplied tenant secret in Platform encryption

Shield Platform encryption provides 2 options for tenant secrets.Customer-supplied tenant secret upload(BYOK) and On-demand tenant secret generation. I am looking for advantages of BYOK over on-demand tenant secret generation. To me it seems like both are same. Either you upload a tenant secret to Salesforce or you let Salesforce generate a tenant secret. Does anyone have better ideas?

A:

Absolutely, I completely agree with you.
We are expanding our BYOK capabilities in multiple steps
1/ Bring your own entropy, which is what we offer today
2/ Bring your own key
3/ Cahe only key
With 2/, you would be able to provide us the actual AES key we would be using for encrypting/decrypting the data. But your key would still be stored encrypted in our database, the same way that we store your entropy today, and we would use our HSM only for wrapping/unwrapping your key
With 3/, your key will only stay in memory and would never touch any of our system of records. We would keep it in our cache for an amount of time under your control, forcing us to go back to your HSM to fetch it again on a regular basis.
Everything is of course under the usual safe harbor, but as an FYI we are starting working on 2/ and we are in the middle of a 2-releases entire refactor of our caching strategy in preparation for 3/


Q:

Was ist der Unterschied zwischen "parametrieren" und "parametrisieren"?

In dieser Frage kam der Begriff parametrierbare Motorleistung auf. Ich hatte parametrieren noch nie gehört, und kenne nur parametrisieren (also: mit (veränderbaren) Parametern versehen). Der Duden bestägt, dass es parametrieren gibt, und ergänzt "Gebrauch: besonders Elektrotechnik, Kfz-Technik".
Was ist also genau der Unterschied zwischen parametrieren und parametrisieren? Bedeuten sie vielleicht dasselbe, und unterscheiden sich nur im Sprachgebrauch des Anwendungsgebiets?
Wenn es so ist, wie ist dieser Unterschied entstanden? Möglicherweise ähnlich wie bei edieren und editieren? Gibt es weitere Beispiele für solche Paare?

A:

Parametrisieren: Versehen eines Objekts|Modells|etc. mit Parametern

So weit wie ich das verstehen bedeutet parametrisieren jetzt an dein Beispiel angelehnt, der Motorleistung Parameter hinzu zu fügen.

Parametrieren: Versehen dieser Parameter mit Werten

parametrieren jedoch bedeutet die Parameter anzupassen. Also die werte der Verschiedenen Parameter zu verändern.
EDIT:
Scheinbar werden die beiden Wörter je nach Fachgebiet unterschiedlich verwendet und haben manchmal auch die gleiche Bedeutung:

Unter einer Parameterdarstellung (auch Parametrisierung oder Parametrierung) versteht man in der Mathematik eine Darstellung, bei der die Punkte einer Kurve oder Fläche als Funktion einer oder mehrerer Variablen, der Parameter, durchlaufen werden. Für die Beschreibung einer Kurve in der Ebene oder im Raum wird ein Parameter benötigt, für die Beschreibung einer Fläche ein Satz von zwei Parametern.

Wikipedia
Wobei parametrieren bevorzugt in der Elektrotechnik und Kfz-Technick verwendet wird,

parametrieren
Wortart: schwaches Verb
Gebrauch: besonders Elektrotechnik, Kfz-Technik

Duden


Q:

Can I move my downloaded games from PS3 to PS4?

We have a large collection of downloaded games from the store, mainly PSX gen (Crash Bandicoot, Spyro, FF7 etc.) and I was wondering if we can move them/re-download them onto the PS4?

A:

You wouldn't be able to play any of them. PS4 doesn't support ps, ps2 or ps3 games. You can't re download them onto the console from the store for that reason. It is reasonable to assume that if Sony ever add support for, say, downloaded PS1 games then previously purchased titles will be available to you in the store.
You can't use a USB stick or similar to transfer them either as far as I'm aware, though since there's no point in doing so I haven't tried.

A:

You can't move them over.
It currently looks like the PlayStation Now system will be the only way to play PS1, PS2, and PS3 games on the PS4.
Having said that, the PlayStation TV and PS Vita can play PSX titles from PSN.


Q:

How do governments stop hyperinflation?

After reading this, I wonder "How can a government stop hyperinflation?"
What can other governments do to help?
And for completeness, How do governments keep currency stability?

A:

Runaway or hyperinflation occurs when there is a lot more money than there are goods at current prices.  In theory, you could fix this two ways.
First, you could flood the economy with goods, reducing the monetary pressures.  I don't know that anyone has really tried that against hyperinflation, as the amount of goods required would be tremendous.
Second and more commonly, you reduce the money supply or at least stop it from growing.  This often involves replacing the existing, near valueless, currency with a new currency.  So if it takes a thousand bills to make a reasonable purchase, you exchange one new bill for a thousand of the old.  The important part is that people and markets need to be confident that the new currency won't also be overprinted.
In practice, hyperinflation is generally triggered by a shortage of goods.  The shortage causes increasing prices.  The government attempts to overcome this by printing more currency, which is the exact wrong thing to do.  Because the shortage is still there, the government can never catch up.  They provide more bills.  People with more bills bid up prices.  Still a shortage.  The government provides more bills.  Prices increase.  Still a shortage.
The essential problem is that more money doesn't make more goods.  So printing money to fix a shortage in goods is much like a dog chasing its tail.  The faster it goes, the faster its target recedes.  Only worse, since the dog stays the same size.  Under hyperinflation, an economy shrinks.
Ideally, the first thing to fix is the shortage in goods.  Then a stable currency can be created.  If the government can't do that, then the problem gets worse before it gets better.  In the early stages of moving from hyperinflation to normal growth, already bad unemployment increases more.
The two things that external governments can do are to provide more goods to address the original shortage and to help restore confidence in the currency.  Possibly by accepting payment for the goods in the currency and then holding it.  Another alternative would be for more trusted foreign central banks to manage the money supply.  Of course, most countries don't want to surrender control of their money supply in that way.
To avoid hyperinflation from starting, countries need to limit their currency growth to match production growth.  And maintain an environment in which production is stable or growing.  If production does fall, the government has to allow a recession rather than trying to cover it up by overprinting currency.


Q:

Compute $\mathrm{Res}(\frac{1+2z+3z^2}{1+z+z^2-3z^3},1)$

I have to compute $\mathrm{Res}(\frac{1+2z+3z^2}{1+z+z^2-3z^3},1)$.

I know that $\mathrm{Res}(f,z_0)+a_{-1}= \int_{C_p} \frac{f(z)dz}{z-z_0}$, where $C_p$ is simply the circle at $z_0$ with radius of convergence $p$ ($0<p<r$) in positive direction.
Is anyone could give me some help how to proceed to compute it?

A:

Since the residue of $g$ at $a$ is $a_{-1}$ in the series
$$g(z) = \cdots + a_{-1}(z-a)^{-1}+a_0+a_1 (z-a) + \cdots$$
Then,
$$(z-a)g(z) = \cdots + a_{-1}+a_0(z-a)+a_1 (z-a)^2 + \cdots$$
Letting $z\to a$,
$$\lim_{z\to a} (z-a)g(z) = a_{-1} = \operatorname*{Res}_{z=a}g(z)$$

In your example, note
$$f(z) = -\frac{1+2z+3z^2}{(z-1) (3 z^2+2 z+1)}$$
So that
$$\operatorname*{Res}_{z\to1} f(z) = \lim_{z\to 1}-(z-1)\frac{1+2z+3z^2}{(z-1) (3 z^2+2 z+1)} = -\frac{1+2+3}{3+2+1} = -1$$


Q:

Invalid binary - missing 568h file

I am trying to submit my app to Apple Store but I am receiving the "invalid binary" message, informing that is missing the launch image for -568h modifier. But the file is in the package. I checked. Some details:

The launch image are localized but not for all languages. They are present for English and some other languages.
In the simulator and in the testing devices the launch image is displayed correctly.
I checked the sizes and are correct
I am using XCode 4.6.3
I recently installed XCode 5 preview but I am using 4.6.3 command line tools.
There is no UILaunchImageFile entry in the plist file (I am using the Default name).
The images do not appear in the Launch Images panel (after I localized them).

What is going on? I don't have any clue.

A:

Found the reason. If the launch image is localized it is necessary to provide the set of images for all languages the app supports. I tried that and Apple accepted my binary.


Q:

IPv6 Loopback Addresses (equivalent to 127.x.x.x)

I have a development environment set up where I have a separate loopback address for multiple websites.
For example, I have the following:
127.0.0.1 www.example.com
127.0.0.2 foo.example.com
127.0.0.3 bar.example.com
127.0.0.4 waffles.example.com

I'd like an equivalent solution for IPv6.
I already know that you can use ::1 as a loopback address, but ::2, ::3, etc don't seem to work.
Are there any other loopback addresses in IPv6?  Is there a way to have multiple unique loopback addresses?

A:

Technically ::2, ::3 etc. are part of ::0.0.0.0/96, the "ipv4 compatible ipv6 address" range. It's deprecated, but you probably don't want to use that range.
For a lab environment, use unique local addressing. Go to https://www.ultratools.com/tools/rangeGenerator and generate yourself a prefix. Then you can pick whatever addresses you want out of that prefix, and assign them to the loopback interface.

A:

Your loopback adress is ::1/128. Note the width of the subnet which restricts it to just one host.
change the subnetmask to something wider and check your routing table. Or use link-local adresses.

A:

I recommend using RFC 4193 addresses for this. RFC 4193 allows you to construct your own /48 for local use by taking the byte value fd followed by 5 random  bytes. You are allowed to put anything you see fit after the first 48 bits, so if you wanted a /64 you can take fd followed by 7 random bytes as in this example for Linux systems:
ip -6 route add to local fd66:29e9:f422:8dfe::/64 dev lo

Using RFC 4193 has the advantage compared to earlier answers that you are not violating any RFCs in doing so and the addresses can be used without an interface identifier.
Each of the ranges mentioned in earlier answers are either using ranges reserved for different purposes or link-local addresses which require an interface identifier whenever used.
There exists an expired draft suggesting that the range 1::/32 gets allocated for additional loopback addresses like you are asking for. However since that draft expired years ago and no such allocation was ever made you cannot use 1::/32 for this.


Q:

setuptools does not distribute my data files

I have the following in setup.py:
from setuptools import setup
# ...
setup(
    name='xml-boiler',
    version='0.0.1',
    url='https://github.com/vporton/xml-boiler',
    license='AGPLv3',
    author='Victor Porton',
    author_email='porton@narod.ru',
    description='Automatically transform between XML namespaces',

    packages=find_packages(),
    package_data={'': ['*.ttl', '*.xml']},
    scripts=['bin/boiler'],
    data_files = [
        ('/etc/xmlboiler', ['etc/config-cli.ttl'])
    ],
    test_suite="xmlboiler.tests",

    cmdclass={'build_py': MyBuild},
)

But after I run python setup.py build, the build directory does not contain any *.xml or *.ttl files.
What is my error?
I also want to distribute all files from xmlboiler/core/data/assets/ and
xmlboiler/core/data/assets/.

I don't understand how it works:
package_data={'': ['*/.xml', '*/.ttl', '*/.net', 'data/assets/*', 'data/scripts/*.xslt', 'xmlboiler/doc/*.html', 'xmlboiler/doc/*.css']},

included xmlboiler/core/data/scripts/section.xslt but not xmlboiler/tests/core/data/xml/simple.xml. Why?!

A:

package_data is a mapping of package names to files or file globs. This means that
package_data = {'', ['*.xml', '*.ttl']}

will include every file ending with .xml or .ttl located in any package directory, for example xmlboiler/file.xml, xmlboiler/core/file.ttl etc. It will, however, not include file xmlboiler/core/data/interpreters.ttl because it is located in data which is not a package dir (not containing an __init__.py file). To include that, you should use the correct file path:
package_data = {'xmlboiler.core', ['data/interpreters.ttl']}

To include every .ttl file under xmlboiler/core/data:
package_data = {'xmlboiler.core', ['data/*.ttl', 'data/**/*.ttl']}

This will include every .ttl file in data directory (glob data/*.ttl) and every .ttl file in every subdirectory of data (glob data/**/*.ttl).
To include every .ttl and .xml file in every package:
package_data = {'', ['*.xml', '**/*.xml', '*.ttl', '**/*.ttl']}

I also want to distribute all files from xmlboiler/core/data/assets/

Same approach for data/assets, but omit the file extension in globs:
package_data={
    'xmlboiler.core': ['data/assets/*', 'data/assets/**/*'],
}


Q:

Can others read my DNS entries?

Suppose I define an A record in my DNS for host foo.example.com. If nobody knows about the existence of foo.example.com, but do about example.com, could someone somehow query the DNS records of example.com to return that name foo.example.com?

A:

The answer is it depends.  If the user can guess the name, like www, then yes they can.  If you use more esoteric names the user would only be able to get arbitrary records if they were able to do what's called a zone transfer, which sends the entire domain's data.
Most nameservers disallow zone transfers by default.  You can test yours here:
https://tools.digitalpoint.com/zone-transfer?domain=example.com

A:

From end-user perspective of view, no. DNS will only return results for specific Hostname (or IP address for reverse-lookup).
Yet, many DNS servers support the feature known as Zone Transfer, that basically can dump all zone file data to another machine.
By doing so, the server can save some load by letting all other DNS servers have the full zone file instead of delegating the resolve request to it.
In reality, most DNS Administrators will not allow Zone Transfer for obvious (security) reasons.
If you want to try it yourself, use nslookup (in Windows):
//#requesting for google.com dns server
set q=ns
google.com

#response is: primary name server = ns1.google.com

server ns1.google.com
ls -d google.com //#this is the zone transfer request

More in Wikipedia


Q:

Synchronous buck using BJT's in stead of MOSFETS

Recently I came across a schematic of a synchronous buck converter using normal transistors in stead of MOSFETS, like this:

I was always under the impression that when the top switching device turns off, the inductor generates a large negative voltage because it wants to resist the change in flow of current. That's why the reverse biased freewheel diode is there in a asynchronous buck regulator, so the current can keep flowing.
How does the above circuit work then? The bottom PNP transistor, taking the place of the freewheel diode, cannot conduct current in that direction afaik. Current can flow emitter to ground but not from ground to emitter, can it ?
I built the circuit and it appears to work, measuring point before the inductor, where both emitters meet (excuse the poor quality):

Although I'm not sure what I'm seeing here. There appears to be a dip below ground on the negative cycle. At first I thought this was the inductor's negative voltage spike, somehow being cut off by the transistor. But the same is happening on the positive cycle, with a little 'bulge' above VCC.
Could anyone enlighten me about how this works and what is happening?

A:

Current can flow emitter to ground but not from ground to emitter, can
  it ?

Collector and emitter can work in reverse. It's an NPN or a PNP so junctions are somewhat interchangeable but you don't get great β but you do usually get quite low saturation voltages.
On the other hand, the circuit has poor efficiency because the top transistor (NPN) is an emitter follower and will always drop pretty much 0.7 volts or greater unless the base drive is lifted above the incoming power rail.
I would never sanction using this circuit - MOSFETs are far more suited to synchronous buck conversion (generalism alert!).


Q:

Wait for jQuery show() to finish before continuing function?

I can't make my div visible with the jquery show() until my function is over! It actually works in IE/FF but not in Chrome. How can I make sure my element is visible before continuing with my function?
Here's my code:
function doOperation(){
    $("#progressbar_area").show();
    (...)
}

A:

Add a callback to show:
$("#progressbar_area").show(speed, function() {});

The callback function will be called when the animation is complete.


Q:

Is "This question requires developer only knowledge" the same thing as developer intent?

The question I have in mind, in particular, is this one. There are arguments being made that this question is off topic because it requires developer insight in order to have a 100% authoritative answer. Does this fall under the category of developer intent or not?

A:

This is not developer intent.
As we have discussed before, answerability is a horrible metric for whether or not a question should be considered on-topic or not. In this case, without scouring the game code, there is no way to prove anything that those answering the question are saying, fair enough. However, this doesn't suddenly make it about developer intent. The question asks about a game mechanic, and how it works. It does not ask why it works, nor does it ask what the developer was thinking when implementing it.
Sure we can't prove anything beyond a reasonable doubt, but we can make a reasonable assessment based on experience, and the knowledge we can uncover. But that does not make it off-topic.


Q:

Unable to get CDI working in Weblogic 12c, hibernate 5.2.4, hibernate-validator/cdi 5.3.1

My env:
weblogic 12c
with jpa2.1 patch that sets: SET PRE_CLASSPATH=%MW_HOME%\oracle_common\modules\javax.persistence_2.1.jar;%MW_HOME%\wlserver\modules\com.oracle.weblogic.jpa21support_1.0.0.0_2-1.jar
my-ear/APP-INF/lib contains:
hibernate-release-5.2.4.Final/lib/required/*.jar
hibernate-validator-5.3.1/dist/*.jar and hibernate-validator-5.3.1/dist/lib/required/*

my persistence.xml:
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
  http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
  version="2.1">
<persistence-unit name="myPersistenceUnit" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>myDataSource</jta-data-source>

I am able to use persistence.xml and entityManager gets injected into my session bean without any issues. However when I add beans.xml (to use CDI) in one of the ejb-jar/META-INF I get:
org.jboss.weld.exceptions.UnproxyableResolutionException: WELD-001435 Normal scoped bean class org.hibernate.validator.internal.engine.ValidatorImpl is not proxyable because it has no no-args constructor - ValidatorBean [id=org.hibernate.validator.internal.cdi.ValidatorBean_default].

My weblogic-application.xml contains:
<prefer-application-packages>
 <package-name>antlr.*</package-name>
 <package-name>org.hibernate.*</package-name>
 <package-name>org.hibernate.validator.*</package-name>
 <package-name>org.hibernate.validator.internal.cdi.*</package-name>
 <package-name>javax.validation.*</package-name>
 <package-name>javax.validation.spi.*</package-name>
<package-name>javax.validation.bootstrap.*</package-name>

Complete stacktrace:
Exception 0 :
org.jboss.weld.exceptions.UnproxyableResolutionException: WELD-001435 Normal scoped bean class org.hibernate.validator.internal.engine.ValidatorImpl is not proxyable because it has no no-args constructor - ValidatorBean [id=org.hibernate.validator.internal.cdi.ValidatorBean_default].
    at org.jboss.weld.util.Proxies.getUnproxyableClassException(Proxies.java:214)
    at org.jboss.weld.util.Proxies.getUnproxyableTypeException(Proxies.java:180)
    at org.jboss.weld.util.Proxies.getUnproxyableTypesExceptionInt(Proxies.java:195)
    at org.jboss.weld.util.Proxies.getUnproxyableTypesException(Proxies.java:169)
    at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:151)
    at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:388)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:371)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:379)
    at com.oracle.injection.provider.weld.WeldInjectionContainer.start(WeldInjectionContainer.java:110)
    at com.oracle.injection.integration.CDIAppDeploymentExtension.initCdi(CDIAppDeploymentExtension.java:76)
    at com.oracle.injection.integration.CDIAppDeploymentExtension.activate(CDIAppDeploymentExtension.java:49)
    at weblogic.application.internal.flow.AppDeploymentExtensionFlow.activate(AppDeploymentExtensionFlow.java:37)
    at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:729)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
    at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:258)
    at weblogic.application.internal.EarDeployment.activate(EarDeployment.java:61)
    at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:165)
    at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:80)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.activate(AbstractOperation.java:587)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.activateDeployment(ActivateOperation.java:150)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doCommit(ActivateOperation.java:116)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.commit(AbstractOperation.java:339)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentCommit(DeploymentManager.java:846)
    at weblogic.deploy.internal.targetserver.DeploymentManager.activateDeploymentList(DeploymentManager.java:1275)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handleCommit(DeploymentManager.java:442)
    at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.commit(DeploymentServiceDispatcher.java:176)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doCommitCallback(DeploymentReceiverCallbackDeliverer.java:195)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$100(DeploymentReceiverCallbackDeliverer.java:13)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$2.run(DeploymentReceiverCallbackDeliverer.java:68)
    at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:548)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)

    at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:398)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:371)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:379)
    at com.oracle.injection.provider.weld.WeldInjectionContainer.start(WeldInjectionContainer.java:110)
    at com.oracle.injection.integration.CDIAppDeploymentExtension.initCdi(CDIAppDeploymentExtension.java:76)
    at com.oracle.injection.integration.CDIAppDeploymentExtension.activate(CDIAppDeploymentExtension.java:49)
    at weblogic.application.internal.flow.AppDeploymentExtensionFlow.activate(AppDeploymentExtensionFlow.java:37)
    at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:729)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
    at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:258)
    at weblogic.application.internal.EarDeployment.activate(EarDeployment.java:61)
    at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:165)
    at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:80)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.activate(AbstractOperation.java:587)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.activateDeployment(ActivateOperation.java:150)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doCommit(ActivateOperation.java:116)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.commit(AbstractOperation.java:339)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentCommit(DeploymentManager.java:846)
    at weblogic.deploy.internal.targetserver.DeploymentManager.activateDeploymentList(DeploymentManager.java:1275)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handleCommit(DeploymentManager.java:442)
    at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.commit(DeploymentServiceDispatcher.java:176)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doCommitCallback(DeploymentReceiverCallbackDeliverer.java:195)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$100(DeploymentReceiverCallbackDeliverer.java:13)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$2.run(DeploymentReceiverCallbackDeliverer.java:68)
    at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:548)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)

What am I missing? How do I get beans.xml/CDI working in this environment?

A:

I installed Weblogic patches 17754607 and 23744018 (Weblogic Server 12.1.3.0.161018).
and removed:
hibernate-validator-5.3.1/dist/*.jar from my-ear/APP-INF/lib.
The Oracle provided validation jars worked fine - and I am now able to use CDI.


Q:

How do I apply the Settings.settings values at design time?

I have a panel in my Form like this:

and a Panel_BackColor in project's Settings.setting file:

I can change panel back color in the Form constructor:
public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            panel1.BackColor = UI_Settings.Default.Panel_BackColor;
        }
    }

All things work at runtime:

But nothing change at Design Time. How can I apply these settings at Design mode too?

A:

I asked "not edited version" of this question on MSDN forum and got an answer within an hour.
Questions like Convert int to string? is a good questions but mine is not!
I think stackoverflow should keep a watch on it's editors and policy.
The answer:
Select your control in Form Designer (for example a button), go to Properties, (ApplicationSettings),(PropertyBinding), then bind BackColor or other property to Button_BackColor or other settings. Afterward by changing settings in Settings.settings file, all binded controls would be affected.


Q:

Smooth finish on large parts

I would like to print a vase that has a width/length/height footprint of 100x100x200 mm, and the surface finish is of particular interest to me. Ideally, I would like to do a minimum of sanding/XTC-3D coating after printing, if any.
What would be the best material to work with?

A:

From the printer...
Non-post-processed surface smoothness of a print is mainly a function of the Layer height during print: it is smoother if one reduces the height of the steps taken between the layers. A very good FDM machine can achieve down to 0.05 mm layer height, but 0.1 mm is what most hobbyist machines can achieve if well dialed in. SLA printers cure resin in layers down to 25 micron reliably and some can get down to 12.5 micron - a quarter of the best achievable FDM.
Reducing the layer height in FDM comes at the cost of mainly three factors:

Print time increases roughly antiproportional to the layer height. 0.1 mm is about double the print time of 0.2 mm and so on.
The prints tensile strength gets reduced by increasing the number of layers increases, creating additional possible weakpoints.
The thinner the layer, the more susceptible the print is to errors like clogged nozzles or variations of the filament thickness.

SLA printers are not affected by the print strength loss and the errors from clogged nozzles and can print entirely clear material without air inclusions. They are affected by the print time increase though. Usually, SLA prints come out of the vat covered in residual resin and curing them in the proper post-processing method results in this resin smoothing over the surface perfectly.
Simple Postprocessing...
Many prints can easily be post-processed.
Sanding
PLA and ABS can be easily sanded down to somewhat smooth, but you'll need to spend time and muscle grease or go electric. A sander with 300+ grit can help a lot. If you have a rotational body, you could sand the vase on a lathe.
Putty
A plastic putty could be smeared over the stepped surface to smooth it and then sanded smooth. I personally like Valejo plastic putty, as it doesn't shrink, but Tamya putty also is a good alternative, bonding strong.
Primer-Filler
Independent of the base material, using a spray coating can easily fill in the notches and crannies left behind during printing. Printing in 0.15 mm and giving it a short spray coat of primer-filler twice, sanding over rough spots between did a good job of smoothing prints for me.
Vapor Smoothing
If you chose ABS, you could use Acetone vapor to smooth over the surface of a print in almost an instant. This can achieve Super smooth results with tall layer heights, as you practically melt the plastic over, but it comes at the loss of small surface details.
Exposure time is the limiting factor here: the longer the exposure to the acetone vapor, the more the surface is smoothed and the less details remain. Think of exposure time like running the smooth filter in blender once or twice each second.

Similarly, ethylacetate or propylene carbonate could be used for PLA prints, though timing might differ from the well established "a couple of seconds" for acetone vapor. Note that these two chemicals are much more expensive.
Costs
Checking prices, I was quoted about 90 €/l for (chemical grade) Ethyl Acetate and 130 €/l for (chemical grade) Propylene Carbonate via a laboratory supply. Useable Acetone (not chemical grade) comes about 3.70 €/l in home depot. For comparison: chemical-grade Acetone comes with a price tag of about 50 €/l.
Considering that ABS filaments and PLA filaments typically price similarily,  ABS+Acetone Vapor is the least costly chemical Vapor smoothing.


Q:

PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following: := . ( % ;

Can not run following SQL from ant's sql task:
BEGIN
   DBMS_AQADM.CREATE_QUEUE_TABLE(
   queue_table => 'MY_QUEUE',
   queue_payload_type => 'sys.aq$_jms_map_message');

   DBMS_AQADM.CREATE_QUEUE(
   queue_name => 'MY_QUEUE',
   queue_table => 'MY_QUEUE');

   DBMS_AQADM.START_QUEUE (
   queue_name => 'MY_QUEUE');

END;
/

There are following errror:
CreateMyQueue:
      [sql] Executing resource: /u1/bin/sql/createMyQueue.sql
      [sql] Failed to execute:   BEGIN DBMS_AQADM.CREATE_QUEUE_TABLE( queue_table => 'MY_QUEUE', queue_payload_type => 'sys.aq\$_jms_map_message')

BUILD FAILED
/u1/bin/.tools/build.xml:194: java.sql.SQLException: ORA-06550: line 1, column 118:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
   := . ( % ;

What is wrong with SQL?

A:

Here is the solution!
http://www.javaddicts.net/blog/index.php/2005/06/13/executing-oracle-plsql-from-ant/
Following parameters should be used
delimiter="/"
delimitertype="row"
<project name="SWPDEPLOYMENT" basedir="." default="all">
   <target name="createMyQueue">
      <sql driver="oracle.jdbc.driver.OracleDriver"
           url="${sqlurl}"
           userid="${userid}"
           password="${pwd}"
           print="yes"
           delimiter="/"
           delimitertype="row"
           >
        <fileset dir=".">
           <include name="createMyQueue.sql"/>
        </fileset>
      </sql>
   </target>


Q:

How a C# GUI class receive periodic updates from a worker class?

I am trying to separate my worker code from my GUI code into an entirely different class, but I want to be able to report back to my GUI for progress update and file output.  For example, I want to have my GUI say to the worker class, "Read ten lines from the serial port, but report to me each thing you read as you receive it".  Currently my best way to do it is to have the GUI loop ten times and in each loop send a command to the worker class to read one thing and return it.
I would really prefer to keep all of the looping on the side of my worker class, since it will have more information of what is available (the actual amount of data will be variable, and the worker class already has access to the amount of data available, and I would prefer not to send this back to the GUI class to run the loop itself.
I have looked into backgroundworker but that seems to only report percentage done during a lengthy operation, and nothing else, so that would not help me much here.  Does anybody have a good idea how I can accomplish this?
Below is a shell of a program to try to (hopefully) better illustrate what I want to do.  How would you edit the code to do what I require?
The GUI's main class:
class Main_Class
{
    ...
    /*  Assume in the area we have instantiated these items and placed them on the form:
    *   Button  DoSomething:  A button to do something
    *   TextBox ShowInfo:  A text box to report something from the worker class
    */

    Worker_Class timewaster = new Worker_Class();

    private void buttonDoSomething_Click(object sender, EventArgs e)
    {
        timewaster.a_lengthy_task();
    }
}

The separate worker class:
class Worker_Class
{
    ...//Various Setup stuff up here

    void a_lengthy task()
    {
        int iteration = 0;

        while(iteration < 10)
        {
            Datetime saveNOW = Datetime.Now;        //lets say I report this back to the the GUI to write in that ShowInfo box
            Thread.sleep(10000);                    //To waste time and make this lengthy

            //Your code here to facilitate sending saveNOW back to the the Main_Class and display it on the ShowInfo textbox.

            iteration++
        }
    }
}

A:

What you need is events.  If you can't work around what's built into the BackgroundWorker class to get it to work for you, you can at least model your solution after what it does.
The worker class should have a public event IterationComplete or whatever you want to call it.  You can give it an EventArgs object (or an object that extends EventArgs) that contains the information relevant to that iteration that the UI will need.  The event can be fired after each iteration is complete (or whenever the UI modifications should take place).
The UI can then subscribe to the event for all UI tasks related to that iteration.
Code sample:
Main class:
public class MainClass
{
    Worker_Class timewaster = new Worker_Class();

    private void buttonDoSomething_Click(object sender, EventArgs e)
    {
        timewaster.IterationComplete += new EventHandler<Worker_Class.IterationEventArgs>(timewaster_IterationComplete);
        timewaster.LengthyTask();
    }

    void timewaster_IterationComplete(object sender, Worker_Class.IterationEventArgs e)
    {
        string infoFromWorker = e.iterationNumber;
    }
}

Worker class:
public class Worker_Class
{
    //Various Setup stuff up here

    public class IterationEventArgs : EventArgs
    {
        public string iterationNumber { get; set; }
    }

    public event EventHandler<IterationEventArgs> IterationComplete;

    public void LengthyTask()
    {
        int iteration = 0;

        while (iteration < 10)
        {
            DateTime saveNOW = DateTime.Now;        //lets say I report this back to the the GUI to write in that ShowInfo box
            Thread.Sleep(10000);                    //To waste time and make this lengthy

            //Your code here to facilitate sending saveNOW back to the the Main_Class and display it on the ShowInfo textbox.

            if (IterationComplete != null)
            {
                IterationEventArgs args = new IterationEventArgs();
                args.iterationNumber = iteration.ToString();
                IterationComplete(this, args);
            }

            iteration++;
        }
    }
}


Q:

Dojo scope question for store.query with ItemFileWriteStore

I am writing a method to grab the lowest unique id in an ItemFileWriteStore. I have a boolean to tell me when I reach my condition, but I can't get the scope correct.
The function call works as I expect, apart from when newIdOkay is set to true, it is not recognised in the while loop.
Please can you explain why and what I have to do to get this right?
Many thanks
Here is my code:
function checkNewId( size ) {
    if( size == 0 ) {
        console.log('found new ID!');
        newIdOkay = true;
    }
 }

function addContentItem( store ) {
    // New ID
    var newIdOkay = false;
    var newId = 0;

    while( newIdOkay == false && newId < 8 ) {
        newId++;
        store.fetch({ query: {id:newId}, onBegin: dojo.hitch(this, "checkNewId"),
                      start:0, count:0, sync:true });
    }
}

A:

To understand the reason, you need to have basic understanding of identifier resolution and scope chain in JavaScript. I recommend you to read this article: http://jibbering.com/faq/notes/closures/
Regarding you question, in the function addContentItem, the check in the while loop is tested against the identifier newIdOkay which is in the of the activation object corresponding to this function execution context. In the function checkNewId, the identifier newIdOkay you set is in the global object. So these two are not the same one. An easy fix is to move the newIdOkay in addContentItem function to the global scope.
var newIdOkay = false;

function checkNewId( size ) {
    if( size == 0 ) {
        console.log('found new ID!');
        newIdOkay = true;
    }
 }

function addContentItem( store ) {
    // New ID

    var newId = 0;

    while( newIdOkay == false && newId < 8 ) {
        newId++;
        store.fetch({ query: {id:newId}, onBegin: dojo.hitch(this, "checkNewId"),
                  start:0, count:0, sync:true });
    }
}


Q:

JET and ODBC driver missing, can not get data from MDBs

These are MY symptoms:  (XP Pro, 32bit)
-Programs that access .mdb databases (aside from Access 2007 itself) can not get any data.
-Using the Data Sources in Visual Studio 2008 to connect to an MDB shows tables, but you can not query. you receive "Unknown Error" from the Microsoft JET Database Engine
-ArcCatalog can not read a personal geodatabase (mdb), after opening the database it has no feature classes within it
-Trying to bring up the properties of a User DSN "MS Access Database" in the ODBC Data Source Administrator returns error
"The setup routines for the Microsoft Access Driver (*.mdb, *.accdb) ODBC driver could not be found. Please reinstall the driver."
I attempted to reinstall latest MDAC (by setting it to compatibility mode of windows 2000) and latest JET driver. Reinstalled XP SP3.
Also tried a lot of regsvr32 gymnastics with the dao350.dll and dao360.dll, uninstalled the dao350, etc, etc. Nothing worked.

A:

(Yes, I'm answering my own question, to record my solution)
I should also note, in addition to above, I couldn't use the SQL Native Client driver either.
In the registry, under HKLM\SOFTWARE\ODBC the \ODBC.INI branch contains any defined connections, and the \ODBCINST.INI contains records for the installed drivers.
I checked a similar development machine, and my ODBCINST.INI was missing A LOT of entries. I blame the ccleaner application that was recently used to clean up my system of junk.
After exporting the registry branch from the other computer, and importing over my existing keys, everything worked again.
Below are some of the core records, to generate a .reg script. You should get the full list from a similar machine to yours.
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI]

[HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\Microsoft Access Driver (*.mdb)]
"UsageCount"=dword:00000002
"Driver"="C:\\WINDOWS\\system32\\odbcjt32.dll"
"Setup"="C:\\WINDOWS\\system32\\odbcjt32.dll"
"APILevel"="1"
"ConnectFunctions"="YYN"
"DriverODBCVer"="02.50"
"FileUsage"="2"
"FileExtns"="*.mdb"
"SQLLevel"="0"

[HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\Microsoft Access Driver (*.mdb, *.accdb)]
"UsageCount"=dword:00000003
"Driver"="C:\\PROGRA~1\\COMMON~1\\MICROS~1\\OFFICE12\\ACEODBC.DLL"
"Setup"="C:\\PROGRA~1\\COMMON~1\\MICROS~1\\OFFICE12\\ACEODBC.DLL"
"APILevel"="1"
"ConnectFunctions"="YYN"
"DriverODBCVer"="02.50"
"FileUsage"="2"
"FileExtns"="*.mdb,*.accdb"
"SQLLevel"="0"

[HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\Microsoft Excel Driver (*.xls)]
"UsageCount"=dword:00000002
"Driver"="C:\\WINDOWS\\system32\\odbcjt32.dll"
"Setup"="C:\\WINDOWS\\system32\\odexl32.dll"
"APILevel"="1"
"ConnectFunctions"="YYN"
"DriverODBCVer"="02.50"
"FileUsage"="1"
"FileExtns"="*.xls"
"SQLLevel"="0"

[HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)]
"UsageCount"=dword:00000003
"Driver"="C:\\PROGRA~1\\COMMON~1\\MICROS~1\\OFFICE12\\ACEODBC.DLL"
"Setup"="C:\\PROGRA~1\\COMMON~1\\MICROS~1\\OFFICE12\\ACEODEXL.DLL"
"APILevel"="1"
"ConnectFunctions"="YYN"
"DriverODBCVer"="02.50"
"FileUsage"="2"
"FileExtns"="*.xls,*.xlsx, *.xlsb"
"SQLLevel"="0"

[HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\SQL Native Client]
"UsageCount"=dword:00000001
"Driver"="c:\\WINDOWS\\system32\\sqlncli.dll"
"Setup"="c:\\WINDOWS\\system32\\sqlncli.dll"
"APILevel"="2"
"ConnectFunctions"="YYY"
"CPTimeout"="60"
"DriverODBCVer"="09.00"
"FileUsage"="0"
"SQLLevel"="1"

[HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\SQL Server]
"UsageCount"=dword:00000002
"Driver"="C:\\WINDOWS\\system32\\SQLSRV32.dll"
"Setup"="C:\\WINDOWS\\system32\\sqlsrv32.dll"
"SQLLevel"="1"
"FileUsage"="0"
"DriverODBCVer"="03.50"
"ConnectFunctions"="YYY"
"APILevel"="2"
"CPTimeout"="60"


Q:

Regex con rango de 1 a 20 que acepte 2 decimales

hola, estoy usando una mascara de RegEx en un control TextEdit de DevExpress y quiero que tenga un rango de 1 a 20 y que acepte dos decimales, la mascara que tengo actualmente acepta de 1 a 99 con dos decimales
\d{0,2}(\.\d{1,2})?

Agradezco su ayuda.

A:

Usa el siguiente Regex
^((20\.00)|20|((1\d|[1-9])(\.\d{1,2})?))$

A diferencia los comentarios este regex no hace match con 0 u otros números entre 20 y 21 y a diferencia del comentario de @gbianchi sí hace match con 20(al igual que con 20.0 y 20.00)


Q:

jQuery AJAX Load Content Problem

I have a XHTML Strict Website 'main.php' with a normal Header where jQuery and other Scripts are loaded - also there's a menu:

On Click the URL is loaded via jQuery.load(); into the #content div. Everything works fine and also the CSS defined in the main.php for the feed.php is added to
the #content div.
Now the Problem: in the loaded File e.g. feed.php there's an Image

i have added my own jQuery.mouseover, mouseout function - and it does not work! Also i have a  input Box in the main.php
and in the feed.php which is loaded via AJAX there's a link e.g.

It does also not work, why? I thought the AJAX loaded page is integrated to the main.php? But all my JS/jQuery Stuff does not work?
Hope you understand and hope you can help?

A:

Use the live event handlers:

Binds a handler to an event (like
  click) for all current - and future -
  matched element. Can also bind custom
  events.

Such as:
$('#myImage').live("mouseover", function() {
    // do stuff
}).live("mouseout", function() {
    // do stuff
});

$('#myLink').live("click", function() {
    // do stuff
});


Q:

Bootstrap - after clicking link, switch to tab and move to anchor

What i'm trying to achieve: After clicking on a link (inside a tab), switch to another tab and move to a specific part of the page (like a anchor).
What i got working is switching to the tab after clicking on the link, but it won't scroll down to the anchor point.
Help is really appreciated!
Code:

        Bag-in-Box

        ...

Bag-in-Box

A:

The other tab that is holding the anchor tag, remove class "fade" and add class "active" to it like this.


Q:

Intercepting JavaScript array accessor

I would like to associate some side effect with every array accessor like a[i]. For example, if the side effect is writing a message to the console, the following program:

var array = [1, 2, 3]
var total = 0;
for (var i in array) {
  total += array[i]
}
console.log(total);

should return the output like:

1 // access a[0]
2 // access a[1]
3 // access a[2]
6 // print original total

In case I was interested in intercepting an array method push, I'd use the technique from this blog post and provided an interceptor:

var _push = Array.prototype.push;
Array.prototype.push = function( item ) {
    console.log( 'pushing ', item, ' into ', this );
    _push.apply( this, arguments );
}

Is it possible apply the same trick to an array accessor? Or what would be a better solution for this problem? One important note is that I don't want to modify the original code of the program. Therefore, using JS proxies to intercept getters and setters doesn't seem te be a valid option for my problem.
One particular side effect, I want to introduce is raising an exception in case the accessed value is undefined (some variation of the index out of bounds exception for JS arrays.) I would check if the currently accessing value is equal to undefined, and throw an exception, in that case, otherwise just return the original value.

A:

You can't override that accessor of Arrays.
Here an example:

Object.defineProperty(Array.prototype, 0, {
  get: function () { return "my get on 0"; }
});
var a = [1,2,3];
console.log(a[0]); // output: 1

But if you try to do the same with a property which doesn't really exist in the array, you will achieve it:

Object.defineProperty(Array.prototype, 5, {
  get: function () { return "my get on 5"; }
});
var a = [1,2,3];
console.log(a[5]); // output: my get on 5

What you can do is a little workaround accessing the elements through the get method of Arrays.

Array.prototype.get = function(i) {
  console.log('my print');
  console.log(this[i]);
  return "this is!";
};
var a = [1,2,3];
console.log(a.get(0)); // output: my print 1 this is!

So, coming back to your question you could do something like you did for push but with the get, avoiding proxies:

Array.prototype.get = function (i) {
  console.log('Accessing element: ' + this[i]);
  console.log(this);
  return this[i];
};
var array = [1, 2, 3];
var total = 0;
// be careful that now you cannot do anymore
// for (var i in array), because inside the array there is also the property get defined and it will cycle also on that
// if you want to cycle again in that way, you need the check through hasOwnProperty method
/*
for(var i in array) {
  if (array.hasOwnProperty(i)){
    console.log(i);
    total += array.get(i);
  }
}
*/
for(var i = 0; i < array.length; i++) {
  total += array.get(i);
}
console.log(total);

Just for completing the answer, what you are trying to do can be done in one line with reduce method of Arrays:

var array = [1, 2, 3];
var result = array.reduce(function (accumulator, actual) {
  return accumulator + actual;
}, 0);
console.log(result);

I strongly recommend you to avoid the override of these accessors. You will change the basis of the code so it will be impossible for third party people to understand what's going on without reading all the code. Moreover you will lose a lot of built-in useful methods.
I hope this helps
p.s. following to your edit, for checking undefined values and raise exceptions you can add the check inside the override of the get method.
But my suggestion is just to filter the array, detect the undefined values and get rid of them.
Note that I am using the double equal. because undefined == null but undefined !== null.
In this way you will remove both undefined and null values. If you want to remove only undefined, change it to if (typeof element === 'undefined').
So something like this, using just one loop with arrays filter method:

var data = [1, 2, undefined, 3, 4, undefined, 5];

data = data.filter(function( element, index ) {
   // note that I am using the double equal. because undefined == null but undefined !== null.
   // in this way you will remove both undefined and null values
   // if you want to remove only undefined, change it to if (typeof element === 'undefined')
   if (element == null) {
     console.log('found and undefined null value at index: ' + index);
   }
   return element != null;
});
console.log(data); // array without undefined and null values


Q:

How to filter pandas DataFrame based on SQL conditions in Python?

I would like to convert my SQL code into a Python (pandas) filter function, but it is giving me a hard time. Any idea how I can filter my data based on the SQL conditions without looping through the records? The Value check for Desc = 'Bla1' makes the difference.

if joe_doe: keep records with Hello = 1; else: keep records with
  Hello = 0

SQL
Hello =
        CASE
            WHEN
            (
                Desc = 'Bla1'
                AND Value = 'True'
            )
            OR
            (
                Desc IN('Bla2', 'Bla3')
                AND Active = 'True'
            )
            AND Enabled = 'True'
            THEN 1
            ELSE 0

Python (incl. pandas)
def get_it(john_doe, df):

    sentences = {
            'Bla1': 'Value',
            'Bla2': 'Active',
            'Bla3': 'Active'
        }

    if john_doe:
        df = df[HOW TO KEEP ALL RECORDS THAT HAVE Hello = 1?]
    else:
        df = df[HOW TO KEEP ALL RECORDS THAT HAVE Hello = 0?]
    return df

DataFrame input
id | Desc | Active | Enabled | Value | [A LOT OF OTHER COLUMNS]
1  | Bla2 | 1      | 0       | 1     | [A LOT OF OTHER COLUMNS]
2  | Bla3 | 1      | 1       | 1     | [A LOT OF OTHER COLUMNS]
3  | Bla3 | 1      | 1       | 0     | [A LOT OF OTHER COLUMNS]
4  | Bla4 | 1      | 1       | 1     | [A LOT OF OTHER COLUMNS]
5  | Bla6 | 1      | 1       | 0     | [A LOT OF OTHER COLUMNS]
6  | Bla7 | 0      | 0       | 1     | [A LOT OF OTHER COLUMNS]
7  | Bla1 | 0      | 1       | 1     | [A LOT OF OTHER COLUMNS]
8  | Bla1 | 1      | 1       | 0     | [A LOT OF OTHER COLUMNS]

DataFrame needed ouput for IF JOE_DOE
id | Desc | Active | Enabled | Value | [A LOT OF OTHER COLUMNS]
2  | Bla3 | 1      | 1       | 1     | [A LOT OF OTHER COLUMNS]
3  | Bla3 | 1      | 1       | 0     | [A LOT OF OTHER COLUMNS]
7  | Bla1 | 0      | 1       | 1     | [A LOT OF OTHER COLUMNS]

DataFrame needed ouput for ELSE
id | Desc | Active | Enabled | Value | [A LOT OF OTHER COLUMNS]
1  | Bla2 | 1      | 0       | 1     | [A LOT OF OTHER COLUMNS]
4  | Bla4 | 1      | 1       | 1     | [A LOT OF OTHER COLUMNS]
5  | Bla6 | 1      | 1       | 0     | [A LOT OF OTHER COLUMNS]
6  | Bla7 | 0      | 0       | 1     | [A LOT OF OTHER COLUMNS]
8  | Bla1 | 1      | 1       | 0     | [A LOT OF OTHER COLUMNS]

A:

Something like this should work. Pandas can take any number of logical arguments to filter a dataframe. & and | are used to separate arguments, and ~ is used to negate an argument. I don't understand the need for the dict you built, and I don't think it's necessary in this case.
logic1 = (df.Desc=='Bla11') & (df.Value==1) & (df.Enabled==1)
logic2 = (df.Desc=='Bla12') & (df.Active==1) & (df.Enabled==1)
logic3 = (df.Desc=='Bla13') & (df.Active==1) & (df.Enabled==1)

if joe_doe:
     df = df[logic1 | logic2 | logic3]
else:
     df = df[~logic1 & ~logic2 & ~logic3]
return df


Q:

What's a good web system for sharing photos amongst co-workers?

I work for a company where we quite often are doing internal events, seminars, and party's. This offen ends up with quite a lot of pictures, from both the company dSLR but also coworkers that bring their cameras.
I am looking for a good way to share these amongst the company, essencally a online photodatabase.
The requirements that this must meet is:
Events Based Photo Sharing
We want to be able to share photos of events, so there has to be a grouping feature.
Private
Only company members can see the uploaded pictures.
Downloadale images
Easy download of uploaded pictures.
Comments/Description
Not the most important thing, but it would be nice.
Easy upload
Everyone can upload pictures to a event, as all members are trusted workers.
Self-hosted would be a nice thing, as nobody else would have the pictures, and all rights are ours.
Active Directory login would be nice.
Do you know any services or applications that can do this? It would not hurt if it was open source as we like to add new features ect.

A:

With a current round of updates to Media functionality in the last few months, I am finding that WordPress (self-hosted) is becoming my go-to solution for photo sharing. Here is how using WordPress can meet your requirements:
Events Based Photo Sharing
How you define an 'event' and 'grouping' is certainly up to interpretation, but if you were to create a post type of 'Event', a gallery of photos can be attached to each event post to keep a logical hierarchy. Filtering that grouping with metadata like Categories or Tags (supported out-of-box in WordPress) allows for free-form taxonomy across all media and posts. Additionally, if you need WordPress to handle more event management beyond grouping events, there are plugins available for that level of detailed event management: Events
Private
WordPress by default provides an authentication and authorization system, but if you have another service (Google, Facebook, Twitter, LDAP, Active Directory, etc etc etc) that you prefer to use for one or both of those purposes, the plugins are available, and most are battled-tested. Again, this is personal preference as to what is the most unifying way to provide people access without having to necessarily create 'yet another another password'.
Downloadable Images
The simplest way I can imagine doing this with WordPress is attaching a gallery of images to a post, with a .zip attached containing all the images uploaded and a link provided. Latitude to be creative with this requirement is pretty wide.
Comments/Description
Two different things, in most contexts. Again, especially with recent updates, WordPress Media functionality is very robust, and all levels of image description (written description down to metadata/RDF) data fields are provided for each photo. Commenting, by default, is available in WordPress at the Post level.
Easy Upload
Ease of access to the upload system depends on your authentication/authorization provider, but the newest iterations of WordPress allow drag-and-dropping of images right into the Media library.
WordPress is open-source and self-hosted, with less than a five minute install in most cases.


Q:

Fill in-between entries in an ID vector

Looking for a quick-and-easy solution to a problem which I have only been able to solve inelegantly, by looping. I have an ID vector which looks something like this:
id<-c(NA,NA,1,1,1,NA,1,NA,2,2,2,NA,3,NA,3,3,3)

The NA's that fall in-between a sequence of a single number (id[6], id[14]) need to be replaced by that number. However, the NA's that don't meet this condition (those between sequences of two different numbers) need to be left alone (i.e., id[1],id[2],id[8],id[12]). The target vector is therefore:
id.target<-c(NA,NA,1,1,1,1,1,NA,2,2,2,NA,3,3,3,3,3)

This is not difficult to do by looping through each value, but I am looking to do this to many very long vectors, and was hoping for a neater solution. Thanks for any suggestions.

A:

This seem to work. The idea is to use zoo::na.locf in order to fill the NAs correctly and then insert NAs when they are between different numbers
id.target <- zoo::na.locf(id, na.rm = FALSE)
id.target[(c(diff(id.target), 1L) > 0L) & is.na(id)] <- NA
id.target
## [1] NA NA  1  1  1  1  1 NA  2  2  2 NA  3  3  3  3  3


Q:

What is the alternate command of grep -A for Solaris?

I am trying to grep few exception details from a server log file.
I have tried this:
cat server.log | grep -A10 exception

so that i can get exception details.
But server response is:
grep: illegal option -- A

Is there any alternate  in Solaris for above command ? Please help.

A:

The same behavior as grep -A can be achieved with awk:
awk -v A=10 '/exception/{f=A+1} f{print;f--}' server.log

The above prints the match and the ten lines following it, just like grep -A10 exception server.log.  The value of A can be changed as you like.
Example
Consider this sample file:
$ cat server.log
a
b
c
exception
1
2
3
4
5

With A set to 3, the following is the output:
$ awk -v A=3 '/exception/{f=A+1} f{print;f--}' server.log
exception
1
2
3

Special note for SunOS/Solaris
The native awk on Sun/Solaris is notoriously bug-filled.  In its place, use nawk or
better yet /usr/xpg4/bin/awk  or /usr/xpg6/bin/awk.  For example:
/usr/xpg4/bin/awk -v A=10 '/exception/{f=A+1} f{print;f--}' server.log

Simulating grep's behavior with multiple files
When given multiple file names, grep's output changes to:
$ grep -A3 exception server.log server.log
server.log:exception
server.log-1
server.log-2
server.log-3
--
server.log:exception
server.log-1
server.log-2
server.log-3

We can emulate this with awk as well (this may required GNU awk):
$ awk -v A=3 '/exception/{f=A+1;if(x)print"---";x=1} f{print FILENAME (f==A+1?":":"-") $0;f--}' server.log server.log
server.log:exception
server.log-1
server.log-2
server.log-3
---
server.log:exception
server.log-1
server.log-2
server.log-3


Q:

React UseState - using previous state vs not using previous state

I was wondering what the difference is between both examples below.
In one example I use the previous state and in the other example I directly use the current value.
They both give me the same results.
In which cases should I use one way over the other?
Thanks in advance.
import React,{useState} from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [count, setCount] = useState(0);
  const [count2, setCount2] = useState(0);
  return (

      Count: {count}
      <button onClick={() => setCount(0)}>Reset</button>
      <button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>

      Count: {count2}
      <button onClick={() => setCount2(0)}>Reset</button>
      <button onClick={() => setCount2(count2 - 1)}>-</button>
      <button onClick={() => setCount2(count2 + 1)}>+</button>

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

A:

Because those calls to the state setter are in click handlers, your component is guaranteed to be re-rendered before another click is processed. For that reason, in most cases you don't have to use the callback version of the setter, you can directly use your existing state. (Even in concurrent mode.) (Note that if you handle the same click in more than one place [an element and a descendant of it, for instance], and you want both of those handlers to update the value, that's a different matter — see skyboyer's answer for an example of that.)
This is not true for all events (mousemove, for instance, does not have this guarantee), but it's true for click.
I got this information from Dan Abramov on twitter in this thread. At the time, events like click that had this guarantee were called "interactive" events. The name has since changed to "discrete" events. You can find a list in this source file in the React code.
Of course, not all state changes come directly from events. Suppose you have a click handler in your code that does a couple of ajax calls in series and, it happens, updates your value in response to completing each of them. The direct update version will be incorrect even if you've tried to be really thorough with useCallback; the callback version will be correct:

const {useState, useCallback} = React;

function ajaxGet() {
    return new Promise(resolve => setTimeout(resolve, 10));
}

function Example() {
    const [directValue, setDirectValue] = useState(0);
    const [callbackValue, setCallbackValue] = useState(0);

    const doThis = useCallback(() => {
        setDirectValue(directValue + 1);
        setCallbackValue(callbackValue => callbackValue + 1);
    }, [directValue, callbackValue]);

    const doThat = useCallback(() => {
        setDirectValue(directValue + 1);
        setCallbackValue(callbackValue => callbackValue + 1);
    }, [directValue, callbackValue]);

    const handleFirstFulfilled = useCallback(() => {
        // ...
        doThis();
        // ...
        return ajaxGet("something else");
    }, [doThis]);

    const handleSecondFulfilled = useCallback(() => {
        // ...
        doThat();
        // ...
    }, [doThat]);

    const handleClick = useCallback(() => {
        ajaxGet("something")
        .then(handleFirstFulfilled)
        .then(handleSecondFulfilled)
        .catch(error => {
            // ...handle/report error...
        });
    }, [handleFirstFulfilled, handleSecondFulfilled]);

    const cls = directValue !== callbackValue ? "diff" : "";

    return (

          <input type="button" onClick={handleClick} value="Click Me" />

          Direct: {directValue}

          Callback: {callbackValue}

    );
}

ReactDOM.render(<Example />, document.getElementById("root"));
.diff {
    color: #d00;
}

(Disclaimer: That code may be utter rubbish. The point is to see the effect despite having tried to memoize everything. :-) )
For that reason, any time I'm setting a new value that's based on the previous value, I use the callback version unless it's a dedicated click handler or similar, in which case I may go direct.

Getting back to events, concurrent mode makes non-"discrete" events easier to stack up. In the current version of React on cdnjs.com (v16.10.2), I cannot get the following to have different numbers for directValue, callbackValue, and manualValue:

const {useState} = React;

// Obviously this is a hack that only works when `Example` is used only once on a page
let manualValue = 0;
const manualDisplay = document.getElementById("manualDisplay");
function Example() {
    const [directValue, setDirectValue] = useState(0);
    const [callbackValue, setCallbackValue] = useState(0);

    const handleMouseMove = () => {
        setDirectValue(directValue + 1);
        setCallbackValue(callbackValue => callbackValue + 1);
        manualDisplay.textContent = ++manualValue;
    };

    const different = directValue !== callbackValue || directValue !== manualValue;
    document.body.className = different ? "diff" : "";

    return (

          Move the mouse rapidly over this element.

          Direct: {directValue}

          Callback: {callbackValue}

    );
}

const ex = <Example />;
if (ReactDOM.createRoot) {
    document.body.insertAdjacentHTML("beforeend", "
Concurrent
");
    ReactDOM.createRoot(document.getElementById("root")).render(ex);
} else {
    ReactDOM.render(ex, document.getElementById("root"));
    document.body.insertAdjacentHTML("beforeend", "
Legacy
");
}
.diff {
    color: #d00;
}

Manual: 0

Maybe that's just me not testing on enough platforms, but I can't get them to diverge in React's "legacy mode." But, using that same code with the experimental release with concurrent mode, it's fairly easy to get the directValue to lag behind the callbackValue and manualValue by waggling the mouse quickly over it, indicating that the event handler is running more than once between renders.

A:

For your example there is no difference. But there are cases when that matters.
const [val, setVal] = useState(0);

return (
 setVal(val + 1)}>
  setVal(val + 1)}>{val}

);

will increment value only by 1 per click(0 -> 1 -> 2 -> 3). Live Example:

const {useState} = React;

function Example() {
  const [val, setVal] = useState(0);

  return (
 setVal(val + 1)}>
    setVal(val + 1)}>{val}

);
}

ReactDOM.render(<Example/>, document.getElementById("root"));

const [val, setVal] = useState(0);

return (
 setVal(oldVal => oldVal + 1)}>
  setVal(oldVal => oldVal + 1)}>{val}

);

will increment value by 2 per click(0 -> 2 -> 4 -> 6). Live Example:

const {useState} = React;

function Example() {
  const [val, setVal] = useState(0);

  return (
 setVal(oldVal => oldVal + 1)}>
    setVal(oldVal => oldVal + 1)}>{val}

);
}

ReactDOM.render(<Example/>, document.getElementById("root"));


Q:

What is the recommended way to append to NSString

I am performing some string concatenation to create a database query.
As part of this, I need to assign and re-assign NSString variable in order to append to it.
I am currently using this code:
NSString *retVal = [[NSString alloc]init];
NSString *concat = @"";
retVal = [NSString stringWithFormat:@"%@%@ myfield= 'myvalue'", retVal, concat];

Note that whenever retVal and concat hold "" (empty string), I get empty string back in retVal. This is definitely not expected as I should get " myfield= 'myvalue'".
What am I missing?
Update:
Here is last I tried:
NSMutableString * retVal =  [[NSMutableString alloc] init];
NSString * concat = @"";

[retVal appendString:@"appendstring"];

NSLog(@"%@", retVal); // prints <object returned empty description>

[retVal appendString:concat];
[retVal appendString:@"appendstring1"];

NSLog(@"%@", retVal);  // prints %@

A:

Either use an NSMutableString with appendString:, use stringByAppendingString:, or construct the full string with a single stringWithFormat:, plugging in the values you need all at once.


Q:

Array max length not working

When I click on an image it should be adding it to an array, however the max lenght of the array is 6, therefore if there are already 6 objects in the array it should alert and stop letting the user click on any new image.
When I run the following I can keep adding images and the alert never happens.
      jQuery('body').on('change', '.masonry .item :checkbox', function () {
        var urls = [];
        urls.length = 6;
        if (jQuery(urls.length > 6)) {
          alert("Puoi aggiungere un massimo di 6 immagini");
        } else {
          jQuery('.masonry .item :checkbox:checked').each(function () {
            urls.push(jQuery(this).next('label').find('img').attr('src'));
          });
        }
      });

A:

You'll have to check the length of the checked items, not an empty array.
jQuery('body').on('change', '.masonry .item :checkbox', function () {
    var urls = [];
    var checkedItems = jQuery('.masonry .item :checkbox:checked'); // get the checked items
    if (checkedItems.length > 6) {                                 // if the checked items are more than 6, ...
        alert("No! No! No! Only 6!");
        jQuery(this).prop("checked", false);  //<<< UNCHECK THE ELEMENT JUST CHECKED SO THE COUNT REMAINS 6
    } else {
        checkedItems.each(function () {
            urls.push(jQuery(this).next('label').find('img').attr('src'));
        });
    }
});


Q:

Using link_to make an image the link

I need to link this image to profile_path(thing.user)
<%= image_tag thing.user.photo.url(:small), { :class=>"rounded_square" ,
    style: "margin-left:8px; text-align:center; vertical-align:middle;" } %>

A:

link_to should take a block if nothing helps:
<%= link_to profile_path(thing.user) do %>
    <%= image_tag thing.user.photo.url(:small), { :class=>"rounded_square" ,
style: "margin-left:8px; text-align:center; vertical-align:middle;" } %>
<% end %>


Q:

Android : 5.0 : WebChromeClient.FileChooserParams cannot be resolved to a type

I am trying to make my webview compatible with android 5.0 for the upload file purposes.My build target is API19 4.4.2 . I have download 5.0 sdk and it dependencies.  I am getting an error WebChromeClient.FileChooserParams cannot be resolved to a type
I found this code on Stackoverflow.
  webView = (WebView) findViewById(R.id.webView1);

            webView.setWebChromeClient(new WebChromeClient() {
                public boolean onShowFileChooser(
                        WebView webView, ValueCallback<Uri[]> filePathCallback,
                        WebChromeClient.FileChooserParams fileChooserParams) {

                    // Double check that we don't have any existing callbacks
                    if(mFilePathCallback != null) {
                        mFilePathCallback.onReceiveValue(null);
                    }
                    mFilePathCallback = filePathCallback;

                    // Set up the take picture intent
                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
                        // Create the File where the photo should go
                        File photoFile = null;
                        try {
                            photoFile = createImageFile();
                            takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                        } catch (IOException ex) {
                            // Error occurred while creating the File
                            Log.e(TAG, "Unable to create Image File", ex);
                        }

                        // Continue only if the File was successfully created
                        if (photoFile != null) {
                            mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(photoFile));
                        } else {
                            takePictureIntent = null;
                        }
                    }

                    // Set up the intent to get an existing image
                    Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                    contentSelectionIntent.setType("image/*");

                    // Set up the intents for the Intent chooser
                    Intent[] intentArray;
                    if(takePictureIntent != null) {
                        intentArray = new Intent[]{takePictureIntent};
                    } else {
                        intentArray = new Intent[0];
                    }

                    Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                    chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                    chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

                    startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

                    return true;
                }
        });

Issue

A:

WebChromeClient.FileChooserParams is new to API Level 21, as is the onShowFileChooser() method.
So, you need to set your compileSdkVersion (a.k.a., "build target" in Eclipse) to 21, otherwise those symbols will not be recognized.


Q:

Anyone Have MediaRecorder Working with ParcelFileDescriptor and createPipe()?

I am trying to work out an example of recording audio, with the data storage being handled by the app, not MediaRecorder. Use cases include storing the recording on internal storage or encrypting the recording.
In principle, this should work using a pipe created by createPipe() on ParcelFileDescriptor, but I am getting malformed output.
First, here is a sample project that records "naturally" using MediaRecorder, with MediaRecorder writing directly to an output file on external storage. This app works just fine, and the output can be played either by the Android device the recorded it or VLC on my Linux box.
Here is my createPipe() variation of this project. From the standpoint of general MediaRecorder configuration (e.g., setOutputFormat()), it is the same as the first, so that code is presumably correct.
However, I am supplying the output via:
  recorder.setOutputFile(getStreamFd());

Where getStreamFd() uses createPipe(), spawns a background thread to read from the pipe, and returns the writing end for use by MediaRecorder:
  private FileDescriptor getStreamFd() {
    ParcelFileDescriptor[] pipe=null;

    try {
      pipe=ParcelFileDescriptor.createPipe();

      new TransferThread(new AutoCloseInputStream(pipe[0]),
                       new FileOutputStream(getOutputFile())).start();
    }
    catch (IOException e) {
      Log.e(getClass().getSimpleName(), "Exception opening pipe", e);
    }

    return(pipe[1].getFileDescriptor());
  }

TransferThread is a classic java.io stream-to-stream copy routine, augmented with smarts to flush and sync the output file:
  static class TransferThread extends Thread {
    InputStream in;
    FileOutputStream out;

    TransferThread(InputStream in, FileOutputStream out) {
      this.in=in;
      this.out=out;
    }

    @Override
    public void run() {
      byte[] buf=new byte[8192];
      int len;

      try {
        while ((len=in.read(buf)) > 0) {
          out.write(buf, 0, len);
        }

        in.close();

        out.flush();
        out.getFD().sync();
        out.close();
      }
      catch (IOException e) {
        Log.e(getClass().getSimpleName(),
              "Exception transferring file", e);
      }
    }
  }

When I run the second app, I get an output file that, by crude inspection via a hex editor, seems basically OK. IOW, it's not like it's a zero-byte file, or is filled with unrecognizable gibberish. It is filled with a similar sort of gibberish as is the output from the first app. However, neither Android nor VLC can play it.
If I had to guess, I would presume that I am screwing up something in reading from the pipe, but I am not sure where specifically I am going wrong.
Any suggestions?
Thanks in advance!

A:

I would guess this is related to my answer to your other question.
Anyone Have MediaPlayer Working with ParcelFileDescriptor and createPipe()?
Probably when the MediaRecorder will seek to write the Header information, the pipe is closed.
If you use:
recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

The record works fine, because it will not have a header information, only raw audio.


Q:

Unable to mirror AVCaptureVideoPreviewLayer on macOS

I'm using AVCaptureVideoPreviewLayer (macOS, not iOS) to capture video input from an attached camera. I've setup a capture session and created a UIView to display the image:
self.captureLayer = AVCaptureVideoPreviewLayer(session: self.captureSession);
self.playerView.layer = self.captureLayer;

Everything is working fine, and I see the image from the camera, but now I want to mirror the image (vertically). I'm using a CATransform3DMakeScale:
self.captureLayer.transform = CATransform3DMakeScale(-1.0, 1.0, 1.0);
Instead of mirroring the image however, the layer just goes blank (background of the parent view).
I've tried other transforms (e.g. resizes) and they work fine. I've also tried mirroring the superlayer:
self.captureLayer.superLayer?.transform = CATransform3DMakeScale(-1.0, 1.0, 1.0);
And this works (although it mirrors the entire window including the title bar!).
Any help appreciated. I believe the transform is correct, but for some reason it's not applying to a AVCaptureVideoPreviewLayer.

A:

You can make use of avcaptureconnection properties to do this.
self.cameraLayer = AVCaptureVideoPreviewLayer(session: frontVideoSession)
self.cameraLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill

    if (self.cameraLayer!.connection.isVideoMirroringSupported)
    {
        self.cameraLayer!.connection.automaticallyAdjustsVideoMirroring = false
        self.cameraLayer!.connection.isVideoMirrored = true
    }

You can read more about this at https://developer.apple.com/reference/avfoundation/avcaptureconnection/1389172-isvideomirrored

The isVideoMirrored flag allows you to choose whether you want to mirror the video or not. If it is set to true, it will mirror the video, if it set to false, it will not mirror. In order for you to use this flag, you must set automaticallyAdjustsVideoMirroring flag to false.

Wrote an example code for you https://github.com/manishganvir/mac-camera-mirror-example. Please check the same. Snippet below
do {
         let input = try AVCaptureDeviceInput(device: camDevice)

          VideoSession.addInput(input)

          self.cameraLayer = AVCaptureVideoPreviewLayer(session: VideoSession)
          print(" connection " , self.cameraLayer!.connection.isVideoMirroringSupported , self.cameraLayer!.connection.automaticallyAdjustsVideoMirroring);

          if (self.cameraLayer!.connection.isVideoMirroringSupported)
          {
                 self.cameraLayer!.connection.automaticallyAdjustsVideoMirroring = false
                 self.cameraLayer!.connection.isVideoMirrored = true
          }
          self.cameraLayer!.frame = self.view.bounds

          self.view.layer = self.cameraLayer!
          self.view.wantsLayer = true

          VideoSession.startRunning()
   }


Q:

Retrofit call in Kotlin Coroutines viewModelScope

Recently I've updated my ViewModel to use new viewModelScope. From its' implementation, I see that Dispatchers.Main.immediate is set as the default CoroutineDispatcher for viewModelScope.
So when printing the current Thread in viewModelScope.launch it gives Thread[main,5,main]
But here is my question. Although this runs in Main Thread, the following code works for me which performs a network call.
viewModelScope.launch {
    userRepo.login(email, password)
}

Here userRepo.login(email, password) is suspend function, which calls Retrofit suspend function.
So how this works, if my Current Thread is Main Thread?

A:

It works because Retrofit's suspend implementation delegates to Call<T>.enqueue. This means it already executes on its own background executor by default instead of using the caller's Dispatcher.


Q:

Is there any way to get the xpath of element stored following page object model from a separate file?

Suppose I have stored WebElment in LoginPage.java class as shown below.
@FindBy(xpath="//input[@name='user_name']") WebElement username;

Now from my test file say VerifyLogin.java I want to access xpath of username which is stored in above LoginPage.java file something like this
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
loginPage.username;//then it should return the xpath //input[@name='user_name']

I know the above approach is wrong, but is there any way to get only the xpath that was stored in LoginPage file that I can use in VerifyLogin file?

A:

If you need it outside of the page object then your design is not that good .
Anyhow if you really want it the following should do the job
@FindBy(xpath="//input[@name='user_name']")
public WebElement username;

new YourPageObject().username;


Q:

Python List into Django model

I want to add an ip list (ex. ['192.168.0.1','...',]) into Django Model TextField.
I don't know the serializer and validator well, so I keep getting the error 'not a valid string'.
How can I change it?

A:

you are most probably trying to save list in text field, which will not be possible, you can use array fields
https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#arrayfield
class ChessBoard(models.Model):
    board = ArrayField(
        ArrayField(
            models.CharField(max_length=10, blank=True),
            size=8,
        ),
        size=8,
    )


Q:

Get the duration of fling in Android

The getDuration method in the Scroller class gets the duration of scroll.
Can we use this method to get the duration of fling as well? Or is there any other way to do that?
public final int getDuration ()

Returns how long the scroll event will take, in milliseconds.

Returns
The duration of the scroll in milliseconds.

A:

Can we use this method to get the duration of fling as well? Or is
  there any other way to do that?

Since the duration will be calculated at the start of a fling, the duration we get by using that method during a fling is no doubt the fling's duration.
BTW, this duration depend the initial velocity of the fling. Here is the code snippet of the Scroller, and you can see how it is calculated:
    /**
     * Returns how long the scroll event will take, in milliseconds.
     *
     * @return The duration of the scroll in milliseconds.
     */
    public final int getDuration() {
        return mDuration;
    }

   // Code in the fling() method which will be called based on a fling gesture
   mDuration = getSplineFlingDuration(velocity);

    // The essential method.
    private int getSplineFlingDuration(float velocity) {
        final double l = getSplineDeceleration(velocity);
        final double decelMinusOne = DECELERATION_RATE - 1.0;
        return (int) (1000.0 * Math.exp(l / decelMinusOne));
    }
    private double getSplineDeceleration(float velocity) {
        return Math.log(INFLEXION * Math.abs(velocity) / (mFlingFriction * mPhysicalCoeff));
    }

Update:

How can the duration be calculated at the start of a fling?

"At the start of a fling" means at the time when the user of the Scroller detect  a fling gesture.Then he should call the following method with proper parameters if he want to use the fling function of a Scroller:
  public void fling(int startX, int startY, int velocityX, int velocityY,
            int minX, int maxX, int minY, int maxY)

The duration is calculated inside the upper method. It calculate the total velocity with velocityX and velocityY at first and then pass the velocity to getSplineFlingDuration() method to get a fling duration.I'v paste the code of that method initially and I think it's not difficult for you to understand.


Q:

How can I get messages from Services Bus in a specific time?

I have this method that works great to get all the messages from my subscription in Azure Service Bus. But I want the messages that have been in there for the last 60 minutes. Is there a way to do that?
public void GetMessages()
    {
        var connectionString = ConfigurationManager.ConnectionStrings["ServiceBus.EndPoint"].ConnectionString;
        var topic = ConfigurationManager.AppSettings["ServiceBus.Topic"];
        var subscription = ConfigurationManager.AppSettings["ServiceBus.Subscription"];
        var client = SubscriptionClient.CreateFromConnectionString(connectionString, topic, subscription, ReceiveMode.PeekLock);

        client.RetryPolicy = new RetryExponential(TimeSpan.FromSeconds(0.1), TimeSpan.FromSeconds(5), 5);

        var messages = client.PeekBatch(100);

        foreach (var msg in messages)
        {
            string body = msg.GetBody<String>();
        }
    }

A:

I want the messages that have been in there for the last 60 minutes

The short answer is "why?". You can peek at the messages, but when you'll try to get them, you're not promised to have the same messages. Or any messages at all.
It's been said by many multiple times that a happy queue is an empty queue. If a message is sitting on a queue for 60 minutes, then something feels off. Almost as if a queue is used as a storage. Either your processors where all offline, and once they get online they should process regardless of how long the message was on the queue, or you're looking for some functionality that probably should be implemented via additional service/in a different way.


Q:

Can I pass image form data to a PHP function for upload?

I'm trying to use jquery and PHP to upload an image like so:
HTML
<form id="form-photo" enctype="multipart/form-data"><

    Add Photo
    <input type="file" name="photo-img" id="photo-img">

</form>

Current jquery framework looks like this:
$('#photo-img').change(function(){
    var file = this.files[0];

    //console.log(file);
    name = file.name;
    size = file.size;
    type = file.type;

    // I'll do some validation here before proceeding

    var formData = new FormData($('#form-photo'));

    console.log(formData);

   // How do I pass the image form data to a PHP function via jquery?

});

Can I just pass the formData to a PHP function via jquery post?

A:

Tested and working on Goolge Chrome, Opera, Firefox, Safari.
doesn't work with IE8 or lower
Javascript
Create a FormData object and append the file with index photo-img and POST it to your server with the help of XMLHttpRequest
$(function() {
  $('#photo-img').change(function(){
    var file  = this.files[0];

    // do your validation here

    var formData  = new FormData();
    formData.append( 'photo-img', file ); // append the file to form data

    var xhr = false;
    if ( typeof XMLHttpRequest !== 'undefined' ) {
      xhr = new XMLHttpRequest();
    }
    else {
      var versions  = [ "MSXML2.XmlHttp.5.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.2.0", "Microsoft.XmlHttp" ];
      for( var i = 0, len = versions.length; i < len; i++ ) {
        try {
          xhr = new ActiveXObject( versions[i] );
          break;
        }
        catch(e) {}
      }
    }
    if ( xhr ) {
      // replace test.php with your own upload script url
      xhr.open( "POST", "test.php", true );
      xhr.onreadystatechange  = function() {
        if ( this.readyState === 4 && this.status == 200 ) {
          var response  = this.response || this.responseText;

          /** Do Something with the reponse **/
          response  = $.parseJSON( response );
          if ( response && response.message ) {
            window.alert( response.message );
          }

        }
      }
      // now send the formData to server
      xhr.send( formData );
    }
  });
});

PHP
A better image upload handling on server side and return a JSON object as response
<?php
  if ( isset( $_FILES["photo-img"] ) ) {
    $error  = false;
    $image  = $_FILES["photo-img"];
    $code   = (int)$image["error"];
    $valid  = array( IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF );
    $folder = dirname( __FILE__ )."/upload/"; // path to folder to where you want to move uploaded file
    $target = $folder.$image["name"];

    if ( !file_exists( $folder ) ) {
      @mkdir( $folder, 0755, true ) ;
    }

    if ( $code !== UPLOAD_ERR_OK ) {
      switch( $code ) {
        case UPLOAD_ERR_INI_SIZE:
          $error  = 'Error '.$code.': The uploaded file exceeds the upload_max_filesize directive in php.ini';
        break;
        case UPLOAD_ERR_FORM_SIZE:
          $error  = 'Error '.$code.': The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
        break;
        case UPLOAD_ERR_PARTIAL:
          $error  = 'Error '.$code.': The uploaded file was only partially uploaded';
        break;
        case UPLOAD_ERR_NO_FILE:
          $error  = 'Error '.$code.': No file was uploaded';
        break;
        case UPLOAD_ERR_NO_TMP_DIR:
          $error  = 'Error '.$code.': Missing a temporary folder';
        break;
        case UPLOAD_ERR_CANT_WRITE:
          $error  = 'Error '.$code.': Failed to write file to disk';
        break;
        case UPLOAD_ERR_EXTENSION:
          $error  = 'Error '.$code.': A PHP extension stopped the file upload';
        break;
        default:
          $error  = 'Error '.$code.': Unknown upload error';
        break;
      }
    }
    else {
      $iminfo = @getimagesize( $image["tmp_name"] );
      if ( $iminfo && is_array( $iminfo ) ) {
        if ( isset( $iminfo[2] ) && in_array( $iminfo[2], $valid ) && is_readable( $image["tmp_name"] ) ) {
          if ( !move_uploaded_file( $image["tmp_name"], $target ) ) {
            $error  = "Error while moving uploaded file";
          }
        }
        else {
          $error  = "Invalid format or image is not readable";
        }
      }
      else {
        $error  = "Only image files are allowed (jpg, gif, png)";
      }
    }
    if ( empty( $error ) ) {
      echo json_encode( array( "error" => 0, "message" => "Upload success!" ) );
    }
    else {
      echo json_encode( array( "error" => 1, "message" => $error ) );
    }
    exit();
  }
?>


Q:

AngularJs Data Manipulation before display

I have a simple table in which there are 2 columns: a) Name b) Country. Currently it works fine and displays name of the user and country.
Now I want to add a condition so that if the country is Germany then instead of Germany it should print Europe and if country is Argentina or Brazil it should print South America, for other countries it will remain same, for example UK, Sweden or any other country will be printed as it is.
My angular code is this ::
<!DOCTYPE html>

    {{ x.Name }}
    {{ x.Country }}

And json data in my user-data.php file is this::
{
    "records":[
    {"Name":"Alfreds Futterkiste","City":"Berlin","Country":"Germany"},
    {"Name":"Ana Trujillo Emparedados","City":"México D.F.","Country":"Mexico"},
    {"Name":"Antonio Moreno Taquería","City":"México D.F.","Country":"Mexico"},
    {"Name":"Around the Horn","City":"London","Country":"UK"},
    {"Name":"B's Beverages","City":"London","Country":"UK"},
    {"Name":"Berglunds snabbköp","City":"Luleå","Country":"Sweden"},
    {"Name":"Blauer See Delikatessen","City":"Mannheim","Country":"Germany"},
    {"Name":"Blondel père et fils","City":"Strasbourg","Country":"France"},
    {"Name":"Bólido Comidas preparadas","City":"Madrid","Country":"Spain"},
    {"Name":"Bon app'","City":"Marseille","Country":"France"},
    {"Name":"Bottom-Dollar Marketse","City":"Tsawassen","Country":"Canada"},
    {"Name":"Cactus Comidas para llevar","City":"Buenos Aires","Country":"Argentina"},
    {"Name":"Centro comercial Moctezuma","City":"México D.F.","Country":"Mexico"},
    {"Name":"Chop-suey Chinese","City":"Bern","Country":"Switzerland"},
    {"Name":"Comércio Mineiro","City":"São Paulo","Country":"Brazil"}
    ]
}

A:

There are numerous ways to achieve this in angular. (directives, functions, services, ng-if...etc.)
The cleanest in your case would be a custom filter:
.filter('countryFormat', function() {
    return function(input) {
        if (input != undefined) {
           //Your switch case here
           return 'South America'; // for example
        }
    }
});

And in the html:
{{ x.Country | countryFormat }}