text:
Q: How to draw a line using a texture with Cocos2D How can I draw a line using a texture in Cocos2D? Specifically I'm looking to create an effect similar to: http://www.slickcar.com/products/purple-neon.jpg
Thanks!

A: Check out this repository https://github.com/hiepnd/cocos2d-ext/. CCNode+Ext.h has a function called (drawLineFrom:to:texture:baseLength:stretch:). Hope it helps :)


text:
Q: determine software installed in computer using php/javascript is there a way to detect what software is installed in computer using php/javascript or any plugin.
what i want to do is if a client open our site using firefox or ie and our web detected that chrome is installed, the chrome will open automatically directing to our site.

A: No you can't do that. That would be a huge security risk.

A: This is not possible, I'm sorry.

A: No, that is not possible, not unless you ask the user to install and run client-side software written using something other than JavaScript. To allow otherwise would be a large security and privacy risk.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to copy video files from gallery into internal storage? How can I copy a video opened by the gallery to my app's internal storage?
I'm using Android +10, so I am not able to see the absolute path of the video.
All I have is this URI: content://com.google.android.apps.photos.contentprovider/-1/2/content%3A%2F%2Fmedia%2Fexternal%2Fvideo%2Fmedia%2F29/ORIGINAL/NONE/1233865568


text:
Q: call ccTouchesBegan even when i touch a ccMenuItem I have a CCMenu with CCMenuItems that I add on a CCLayer. When I click on the CCMenuItems, my CCTouchesBegan doesn't fire up.
How can I call this method also when I touch my menu items?

A: CCMenu registers as targeted touch delegate and swallows touches on menu items. You can try to create your subclass of CCMenu and override it registerWithTouchDispatcher method like this
-(void) registerWithTouchDispatcher
{
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:kCCMenuTouchPriority swallowsTouches:NO];
}

This should work as you want, but maybe can cause other problems with menu behavior.


text:
Q: LogFactory ClassNotFoundException with Google AutoValue and spring-context-support A Spring boot project depends on auto-value 1.1 and spring-context-support 4.2.1. When I run it with mvn spring-boot:run, I see the following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'velocityConfigurer' defined in class path resource [org/springframework/boot/autoconfigure/velocity/VelocityAutoConfiguration$VelocityWebConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: autovalue/shaded/org/apache/commons/logging/LogFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at com.example.SampleApplication.main(SampleApplication.java:10)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.springframework.boot.maven.RunMojo$LaunchRunner.run(RunMojo.java:418)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoClassDefFoundError: autovalue/shaded/org/apache/commons/logging/LogFactory
    at org.apache.velocity.runtime.log.CommonsLogLogChute.init(CommonsLogLogChute.java:75)
    at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:81)
    at org.apache.velocity.runtime.log.LogManager.updateLog(LogManager.java:269)
    at org.apache.velocity.runtime.RuntimeInstance.initializeLog(RuntimeInstance.java:871)
    at org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:262)
    at org.apache.velocity.app.VelocityEngine.init(VelocityEngine.java:93)
    at org.springframework.ui.velocity.VelocityEngineFactory.createVelocityEngine(VelocityEngineFactory.java:249)
    at org.springframework.web.servlet.view.velocity.VelocityConfigurer.afterPropertiesSet(VelocityConfigurer.java:120)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
    ... 21 common frames omitted
Caused by: java.lang.ClassNotFoundException: autovalue.shaded.org.apache.commons.logging.LogFactory
    at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 31 common frames omitted

Looking at AutoValue's pom.xml. It seems Apache commons has been shaded, but why aren't the shaded classes loaded?
My application's pom.xml is on Github.

A: The problem is the VelocityAutoConfiguration class...
For some reason, AutoValue includes Velocity in its shaded jar but does not relocate the references.
When you include spring-context-support, some Velocity-related classes are loaded, which are picked up by VelocityAutoConfiguration, which then tries to load from the AutoValue included classes, crashing spectacularly.
My solution so far has been adding
@EnableAutoConfiguration(exclude = VelocityAutoConfiguration.class)

A: I resolved this issue by adding exclude to SpringBootApplicationclass as follows:
@SpringBootApplication(exclude = VelocityAutoConfiguration.class)


text:
Q: if there are two records for same id ,then get only one record based on below condition ![enter image description here][1]
if there are two records for same id ,then get only one record based on below condition.
e.g.

i) If I get 2 null data in a column for same id, then pass null.
ii) If I get 2 same not null data in a column for same id, then pass not null.
ii) If I get 1 null and 1 not null data in a column for same id, then pass not null.
ii) If I get 2 different not null data in a column for same id, then pass '?'.
Please find the data in source.
Thanks in advance.


text:
Q: How do I install these PHP extensions on Ubuntu?
*

*Ubuntu 16.04.

*nginx version: nginx/1.10.0 (Ubuntu)

*PHP 7.0.8-0ubuntu0.16.04.3

When I run composer install -v in Magento 2 directory I get this:
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Dependency resolution completed in 0.000 seconds
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested PHP extension ext-gd * is missing from your system. Install or enable PHP's gd extension.
  Problem 2
    - The requested PHP extension ext-dom * is missing from your system. Install or enable PHP's dom extension.
  Problem 3
    - The requested PHP extension ext-simplexml * is missing from your system. Install or enable PHP's simplexml extension.
  Problem 4
    - The requested PHP extension ext-mcrypt * is missing from your system. Install or enable PHP's mcrypt extension.
  Problem 5
    - The requested PHP extension ext-curl * is missing from your system. Install or enable PHP's curl extension.
  Problem 6
    - The requested PHP extension ext-intl * is missing from your system. Install or enable PHP's intl extension.
  Problem 7
    - The requested PHP extension ext-xsl * is missing from your system. Install or enable PHP's xsl extension.
  Problem 8
    - The requested PHP extension ext-mbstring * is missing from your system. Install or enable PHP's mbstring extension.
  Problem 9
    - The requested PHP extension ext-zip * is missing from your system. Install or enable PHP's zip extension.
  Problem 10
    - Installation request for braintree/braintree_php 3.7.0 -> satisfiable by braintree/braintree_php[3.7.0].
    - braintree/braintree_php 3.7.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
  Problem 11
    - Installation request for pelago/emogrifier v0.1.1 -> satisfiable by pelago/emogrifier[v0.1.1].
    - pelago/emogrifier v0.1.1 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
  Problem 12
    - Installation request for phpunit/phpunit 4.1.0 -> satisfiable by phpunit/phpunit[4.1.0].
    - phpunit/phpunit 4.1.0 requires ext-dom * -> the requested PHP extension dom is missing from your system.
  Problem 13
    - Installation request for theseer/fdomdocument 1.6.1 -> satisfiable by theseer/fdomdocument[1.6.1].
    - theseer/fdomdocument 1.6.1 requires ext-dom * -> the requested PHP extension dom is missing from your system.
  Problem 14
    - theseer/fdomdocument 1.6.1 requires ext-dom * -> the requested PHP extension dom is missing from your system.
    - sebastian/phpcpd 2.0.0 requires theseer/fdomdocument ~1.4 -> satisfiable by theseer/fdomdocument[1.6.1].
    - Installation request for sebastian/phpcpd 2.0.0 -> satisfiable by sebastian/phpcpd[2.0.0].

How do I install these extensions? I have LEMP stack installed.

A: You can most probably use your package manager to do this.
For the gd extension specifically you can run
sudo apt-get update && sudo apt-get install php7.0-gd

And there is probably a similar package for the rest of the extensions available.
with apt-cache search you can search for packages. for example
 apt-cache search php7.0

will find you all packages related to php7.0


text:
Q: Exception minimum y maximum progress bar Al realiza mi proceso de lectura, con este va avanzando el progress bar, o al menos asi debe ser,el problema es que todo mi proceso termina exitosamente y el progress bar no va al mismo ritmo, este termina un minuto despues, y despues de eso me manda una exception:

System.ArgumentOutOfRangeException: 'Value of '31' is not valid for
  'Value'. 'Value' should be between 'minimum' and 'maximum'. Parameter
  name: Value'

if (progressing_Files.InvokeRequired)
    {
     progressing_Files.Invoke(new MethodInvoker(() => { progressing_Files.Value++; })); //en esta marca la exception
    }

Tengo definidos mi minimo y maximo de la siguiente manera:
progressing_Files.Minimum = 0;
progressing_Files.Maximum = Files_Descompress.Length + Files1.Length + Files2.Length;

Que causa la exception?

A: Considerando:
progressing_Files.Minimum = 0;
progressing_Files.Maximum = Files_Descompress.Length + Files1.Length + Files2.Length;

Tenemos:
if (progressing_Files.InvokeRequired)
{
     progressing_Files.Invoke(new MethodInvoker(() => {
         // Preguntamos si es menor que el maximo
         if(progressing_Files.Value < progressing_Files.Maximum) {
             progressing_Files.Value++;
          }
     }));
}


text:
Q: Profit Maximization - Statement:

A manufacturer has been selling $1000$ television sets a week at $\$480 $ each. A market survey indicates that for each $\$11$ rebate offered to a buyer, the number of sets sold will increase by $110$ per week.

Questions :

a) Find the function representing the revenue $R(x)$, where $x$ is the number of $\$11$ rebates offered.

For this, I got $(110x+1000)(480-11x)$. Which is marked correct

b) How large rebate should the company offer to a buyer, in order to maximize its revenue?

For this I got $17.27$. Which was incorrect. I then tried $840999$, the sum total revenue at optimized levels

c) If it costs the manufacturer $\$160$ for each television set sold and there is a fixed cost of $\$80000$, how should the manufacturer set the size of the rebate to maximize its profit?

For this, I received an answer of $10$, which was incorrect.

A: For part b, the question is: for what $x$ is $R(x)=(110x+1000)(480-11x)$ maximized?
First, differentiate using the power rule and then set the derivative equal to zero:
$$R'(x)=110(480-11x)-11(110x+1000)=-2420x+41800$$
$$R'(x)=0 \Leftrightarrow -2420x+41800 \Leftrightarrow x\approx17.2$$
The rebate offered must therefore be $$\$17.2\cdot11=\$190\,\text{dollars}$$


text:
Q: Why is simple Processing code crashing the browser? In p5.js I wrote this simple linear loop that draws lines between random points on the screen.
If I loop 99 999 times the screen displays instantly.
999 999 times and it takes ten seconds
9 999 999 it hangs the browser.
Why is this happening for a linear loop with a basic operation?  Is there something about the Processing lifecycle that I am not understanding?  Like when exactly is the canvas updated (each line or in batches or what)? Do I need to put my code in an async loop?
function setup()
{
    createCanvas(1920, 965, P2D);
    colorMode(HSL, 100); // hue saturation lightness
    noLoop();
    background(100,100,100,255); //solid white background
    for (let i = 0; i < 9999999; i++)
        drawLines()
}

function drawLines()
{
    stroke(60, random(60,100), random(0,100), 255);
    const p1 = getRandomPoint();
    const p2 = getRandomPoint();
    line(p1.x, p1.y, p2.x, p2.y);
}

function getRandomPoint()
{
    return { x: random(0, width), y: random(0, height) };
}

A: 9999999 are just to many lines at once. Split drawing the lines:

function setup()
{
    createCanvas(1920, 965, P2D);
    colorMode(HSL, 100); // hue saturation lightness
    background(100,100,100,255); //solid white background
}

function draw()
{
    for (let i = 0; i < 1000; i++)
        drawLines()
    if (frameCount >= 9999)
        noLoop();
}

function drawLines()
{
    stroke(60, random(60,100), random(0,100), 255);
    const p1 = getRandomPoint();
    const p2 = getRandomPoint();
    line(p1.x, p1.y, p2.x, p2.y);
}

function getRandomPoint()
{
    return { x: random(0, width), y: random(0, height) };
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>


text:
Q: most efficient javascript method declaration While writing javascript, one can define a method in 3 different ways.
1] A function in global namespace
function doSomething();

2] A function that is member of a function
function Clazz() {}
Clazz.doSomething = function(){};

3] A function that is memeber of the instance of function
function Clazz() {}
Clazz.prototype.doSomething = function(){};

Depending upon the code organization, one can choose one of the above methods over others.
But purely from performance standpoint which is the most efficient one? (especially between 1 and 2)
Will your answer be different if doSomething has arguments?

A: From a pure performance POV, 1 should be the fastest. The reason being that it would require less work to setup the scope chain & execution context. Also if you access any global variables from within the function, the resolution will be fastest with 1, again simply because of the depth of scope chain.
As a general rule further up (near to the global) an object is in the scope, the faster it is. for the same reason accessing property a.b will be faster than accessing a.b.c
The performance gain might not be too much in case of a simple function call, however it can mount up if say you call the function n a loop.

A: None of those declarations do the same thing and aren't interchangeable, what kind of comparison do you expect? It's like asking if it's faster to instantiate 10 variables or an array with 10 items: one is fastest, but the result is not the same.

A: You cannot compare performance between the function declarations,
For example add(a,b) functions declared in all the 3 places give the same performance. performance matters by how you write your code, not by where you declare your functions...

A: you are missing the most optimized one:
var x = function(){}

When javascript sees the definition:
function x(){}

It then converts it into the former form. If you do it that way in the first place there is a negligable speed up. But for the sake of answering your question, this is the most optimal.


text:
Q: How to get what the user is typing and display it on a label in swift I'm making a form in Swift, and want to get what the user is typing to display it on the screen as they type.
I've tried to use the following code to get what the user is typing as they type but it is not showing:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
[enter image description here][1]
  [1]: https://i.stack.imgur.com/8xfdJ.png

A: UITextView will show what the user is typing, but if you need the actual text as the user is typing, the method you used is fine, you just need to perform the replacement since the method you used is asking for permission to change the current text depending on the new input, so you get the final text by:
if let text = textField.text, let range = Range(range, in: text) {
   let newText = text.replacingCharacters(in: range, with: string)
   print(newText) // <-- String of the new text, do what you want with it
}


text:
Q: jQuery AJAX call into MVC controller action never returns I've looked at the previously-posted jQuery/MVC questions and haven't found a workable answer.
I have the following JavaScript code:
appCode.runReports = function (e) {

    var reportList = '';

    $('.rptCheck:checked').each(function (index) {
        reportList += ($(this).attr('reportName') + ',');
    });

    $.ajax({
            url: '/Report/RunReports/?reports=' + reportList,
            error: appCode.reportAjaxFailure,
            success: appCode.listRunningReports,
            complete: appCode.ajaxComplete,
            dataType: 'json'
        });

    e.preventDefault();
}

$(document).ready(function () {
    $('#runReportsButton').click(appCode.runReports);
});

The URL it calls into uses the following controller:
namespace workflowDemoMVC.Controllers
{
    public class ReportController : Controller
    {

        public JsonResult RunReports(string reports = "")
        {
            try
            {
                var ret = reports.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                return Json(ret, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                ide.Trace.WriteLine(ex.ToString());
                return Json(null, JsonRequestBehavior.AllowGet);
            }
        }

    }
}

When I run the code in dev, the controller action executes as expected and returns, but none of the callbacks defined in the AJAX call (complete, error, or success) fire. Once, in an earlier code version, I saw an 500-coded exception (Internal Server Error,) but now I don't see anything at all.
Environment: MVC3, jQuery1.6 .net4

A: You should try and set the content type on the AJAX call.  I had a problem like this and that fixed it for me.  Basically you would do this.  I know I had a lot of problems with IE until I specified this.
$.ajax({
        url: '/Report/RunReports/?reports=' + reportList,
        error: appCode.reportAjaxFailure,
        success: appCode.listRunningReports,
        complete: appCode.ajaxComplete,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8'
    });


text:
Q: How to get an image displayed in second column when clicking a radio button?

<title>Project 1.6</title>

  <form>
   <input type= "radio" value = "Argentina" name = "places">Argentina

   <input type= "radio" value = "Australia" name = "places">Australia

   <input type= "radio" value = "Bolivia" name = "places">Bolivia

   <input type= "radio" value = "Cuba" name = "places">Cuba

   <input type= "radio" value = "Findland" name = "places">Findland

   <input type= "radio" value = "France" name = "places">France

   <input type= "radio" value = "Italy" name = "places">Italy

   <input type= "radio" value = "Peru" name = "places">Peru

   <input type= "radio" value = "Syria" name = "places">Syria

   <input type= "radio" value = "Tunisia" name = "places">Tunisia

  </form>

So, basically I want that whenever i click on a radio button in the first column, I get the image of the location's flag in the second column?
In HTML please.

A: You have to use JavaScript for this. Make an hidden div for each option in second column and make particular one visible with JavaScript on option select.

A: Some what ugly CSS solution, as I mentioned in my comment above this can't be done in pure HTML, this is as close as you'll get.

.flag
{
    position:absolute;
    top:0;
    left: 150px;
    display:none;
}

input[type="radio"]:checked + .flag {display: inline-block;}
<input type= "radio" value = "Argentina" name = "places">Argentina

<input type= "radio" value = "Australia" name = "places">Australia

<input type= "radio" value = "Bolivia" name = "places">Bolivia

<input type= "radio" value = "Cuba" name = "places">Cuba

<input type= "radio" value = "Findland" name = "places">Findland

This is dependant on the Adjacent Sibling selector so you can't move the image to a seperate table cell.
Or if you prefere cleaner HTML with slightly more complex CSS:

.flag
{
    position:absolute;
    top:0;
    left: 150px;
    display:none;
    width: 500px;
    height: 500px;
    background-repeat: no-repeat;
}

input[type="radio"]:checked ~ .flag {display: inline-block;}

input[value="Argentina"]:checked ~ .flag{
    background-image:url("https://www.cia.gov/library/publications/the-world-factbook/graphics/flags/large/ar-lgflag.gif");
}

input[value="Australia"]:checked ~ .flag{
    background-image:url("https://www.cia.gov/library/publications/the-world-factbook/graphics/flags/large/as-lgflag.gif");
}

input[value="Bolivia"]:checked ~ .flag{
    background-image:url("https://www.cia.gov/library/publications/the-world-factbook/graphics/flags/large/bl-lgflag.gif");
}

input[value="Cuba"]:checked ~ .flag {
    background-image:url("https://www.cia.gov/library/publications/the-world-factbook/graphics/flags/large/cu-lgflag.gif");
}

input[value="Findland"]:checked ~ .flag {
    background-image:url("https://www.cia.gov/library/publications/the-world-factbook/graphics/flags/large/fi-lgflag.gif");
}
<input type= "radio" value = "Argentina" name = "places">Argentina

<input type= "radio" value = "Australia" name = "places">Australia

<input type= "radio" value = "Bolivia" name = "places">Bolivia

<input type= "radio" value = "Cuba" name = "places">Cuba

<input type= "radio" value = "Findland" name = "places">Findland


text:
Q: How to set compiler correctly in build.sh for building VLC in iOS Whenever I tried to change CC and CPP in build.sh(ImportedSources/VLCKit/MobileVLCKit/ImportedSources/vlc/extras/package/ios)
This error comes
"Cannot pull with rebase: You have unstaged changes.
Please commit or stash them."

What is the right way to change CC and CPP path? I am trying to build VLC for iOS.
But "C compiler not working message" comes every time I build for device(for simulator it works fine). I found an answer from VLC forum that this might be due to xcrun points to wrong compiler (https://forum.videolan.org/viewtopic.php?f=36&t=117736).
But I can't change path in build.sh:( . Is there another way to deal with this error.
Where can I change the compiler path so that my C compiler works. I have searched a lot for this error, still no luck. Please provide some guidance.
Thanks,
Sibinesh M.C

A: Delete the existing and repull.
Next time just check that you are using zsh or iTerm2 (recommended by VLC). Also check the path expected by script file is same as yours. If not add by sudo.
I also faced the same issue, but setting the path by sudo does the job for me.


text:
Q: EC2 Instance connection to an RDS instance accessible only via VPN I have a Laravel application (API) that I am trying to move to AWS, however, the DB sits privately in AWS and is only accessible to me through a VPN.
The database is an RDS instance.
How can I provide my EC2 instance with access to the RDS Database?

A: You put the EC2 instance in the same AWS Account / VPC as the database.
If you don't have access to that VPC you create a new AWS account you may have to copy the database and create a new account, using a process something like this:

*

*Set up new AWS account / VPC / subnets / etc

*Set up new RDS instance

*Use AWS Database Migration Service to copy old database to new. You can also use the database native tools, e.g. mysqldump

*Set up EC2 in new VPC, configure application to point at new RDS

AWS is not a simple hosting environment, it's a complex enterprise environment and people really need training to understand it. A simple environment like Digital Ocean / Lightsail is better for simple needs.


text:
Q: Html.fromHtml() with custom ImageGetter inside ListView recycle issues I have to show some HTML with images from the internet in a ListView. The images are handled in a custom Html.ImageGetter. The problem is, I need the TextView available to download the images to inside. This leads to having to incorporate the HTML parsing inside the ArrayAdapter's getView method. But that method gets called very often by the Android system as it recycles and redraws elements.
How can I stop this recycling from happening? I assume I have to use a different flow. This is my current getView() method:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    TextView view = new TextView(context);
    CharSequence element = getItem(position);
    CharSequence html = Html.fromHtml(element.toString(), new MessageImageGetter(context, view), null);
    view.setText(html);

    view.setPadding(12, 4, 12, 4);

    return view;
}

Maybe a list-like behavior is possible without the use of ListView and ArrayAdapter, that doesn't recycle and redraw often.

A:
How can I stop this recycling from happening?

You don't. You create a richer model object. Rather than having what appears to be a ListAdapter<String>, have a ListAdapter<Thing>, where:

*

*Thing holds your existing string value (element)

*Thing caches the Html.fromHtml() result

*Your getView() gets the html CharSequence from the Thing and therefore can take advantage of caching

Feel free to substitute a more applicable noun than Thing, of course... :-)


text:
Q: Calling QueryAsync in Dapper throws a InvalidOperationException I was trying out the async support in dapper and when running a simple use case I ran into the follow issue. I have an ApiController that just triggers a log entries using dapper to create it in the database. My db connections are fine. When I run a synchronous version of the using the Query extension method from dapper, everything works fine. When I use the QueryAsync along with the async/await constructs, I get an InvalidOperationException. Here's what the code looks like
public class BackgroundController : ApiController
{
    [HttpGet]
    public async Task<HttpResponseMessage> Run(string op)
    {
        using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Backgrounder"].ConnectionString))
        {
            const string sql =
                "Insert Into SimpleLog (message, threadid, created) Values(@message, @threadid, @created); " +
                "SELECT CAST(SCOPE_IDENTITY() as int)";
            var results = await (connection.QueryAsync<int>(sql, new { message = "new log record", threadid = "1", created = DateTime.Now }));
            var id = results.SingleOrDefault();
            Debug.WriteLine("inserted log record id: " + id);
        }
        return this.Request.CreateResponse(HttpStatusCode.OK);
    }
}

Also, here is what the stacktrace look like:
at System.Data.SqlClient.SqlCommand.b_24(Task1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
   --- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
   at Dapper.SqlMapper.<QueryAsync>d__691.MoveNext() in c:\Dev\Dapper\Dapper NET45\SqlMapperAsync.cs:line 21
   --- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at WebApiBackgrounder.Controllers.BackgroundController.d_0.MoveNext()
It seems to be failing when dapper makes a call to ExecuteReaderAsync. Does anyone how to address this?
EDIT
Here's the connection string
 <add name="Backgrounder" providerName="System.Data.SqlClient" connectionString="Data Source=LPW7X6530;Initial Catalog=Sandbox;Integrated Security=SSPI;" />

A: Based on the error message, it sounds like the connection is not open. As it happens, dapper normally tries to do this for you - so it is not unreasonable that you didn't call Open() first - I guess we missed that. For now: call Open() on the connection.


text:
Q: Not able to run Emulator using the Android studio for my Flutter app, getting NO CONNECTED DEVICES error Please Note: I tried several available solutions but none worked for me since yesterday hence posting this. I have also mentioned below what are things I have tried so far.
I am new to Android Studio and Flutter application and I am trying to build a simple Flutter app using the Android Studio.

*

*I have downloaded and kept my flutter files in C:\src\flutter. Also added to Environment variables.

*I have installed the Android Studio and also installed the Flutter plugin with the Dart.

*I created the Virtual Emulator Device using the Tools->AVD Manager and choose the Nexus 6 with the Android 8.1

*Created a simple project using the File->New Flutter Project->Flutter Application.

*When I try to run this application I get the following error:

As you can see in the screenshot it shows that the No Devices in the emulator section not sure how to run it.
Things I have tried so far:

*

*If I run flutter doctor then I get a tick for all the things except Connect Devices. My guess is that it is obvious because I have not connected any external device but using the emulators.

*I tried to create the emulators using the command flutter emulators --create Nexus_6 and tried to launch it using the command flutter emulator launch.

*I tried running the Android studio as an Administrator.

*Restarted the system several times.

*My adb.exe was crashing so updated the windows and replaced it with the new adb.exe as mentioned in one of the solutions.

*My flutter emulators show following list in the command prompt:

*I tried checking the folder in Appdata -> Local seems to be fine as per other mentioned answers.

*When I run the Emulator using the AVD Manager from Android Studio I see that it is firing up the Android Emulator but it is not responding. In addition to this, I also observe in my task manager that process adb.exe(32 bit) is running whereas my WINDOW 8.1 is 64 bit. Is this expected?
I am not sure If I missed something here. Please help me on how to solve the issue.

A: Using below command on Flutter worked for me:
flutter config --android-sdk [android-sdk-path]

The path is usually C:\Users<username>\AppData\Local\Android\sdk
this path can be found from android studio - SDK manager also.


text:
Q: Getting select list id and value in jquery from array of select lists I have a HTML structure like following:
<?php foreach($active_brand as $brand) { ?>
 <select name="selector" id="selector">
    <?php foreach($options as $option) { ?>
        <option <?php if($brand['State'] == $option) { ?>selected="selected"<?php } ?> value="<?=$brand['id']?>"><?php echo $option; ?></option>
    <?php } ?>
</select>
<?php } ?>

This basically gives me lets say 10 select lists... Now I need to fetch the each value from the selected item in select list...
I have tried the following:
   $('#selector').text();
    $('#selector').change(function() {
        alert($(this).val());
    });

But whenever I select anything from any of the select lists, nothing  happens... Can someone help me out ?

A: Add class to select list;
<?php foreach($active_brand as $brand) { ?>
 <select class="my-select" name="selector" id="selector">
    <?php foreach($options as $option) { ?>
        <option <?php if($brand['State'] == $option) { ?>selected="selected"<?php } ?> value="<?=$brand['id']?>"><?php echo $option; ?></option>
    <?php } ?>
 </select>
<?php } ?>

Create change event from class name:
 $('.my-select').change(function() {
        alert($(this).val());
        alert($(this).find("option:selected").text()); // to get text of selected option
 });


text:
Q: mkdir inside sh, won't work I am trying to create directory using mkdir inside sh file, when I do that the directory is created, but then when trying to do something to it, I get the message "rm: cannot remove '/testFolder': No such file or directory", but it is there...
What am i doing wrong?
this is my sh file
#!/bin/sh
mkdir -p /testFolder
wget https://launcher.mojang.com/v1/objects/bb2b6b1aefcd70dfd1892149ac3a215f6c636b07/server.jar -O /testFolder/server.jar
echo "cd /testFolder\njava -Xmx1024M -Xms1024M -jar server.jar nogui" >> /testFolder/startMc.sh

then i call the file sudo sh test.sh

A: The new line \n is not being interpreted by the echo command try adding the -e argument to echo:
#!/bin/sh
mkdir -p /testFolder
wget https://launcher.mojang.com/v1/objects/bb2b6b1aefcd70dfd1892149ac3a215f6c636b07/server.jar -O /testFolder/server.jar
echo -e "cd /testFolder\njava -Xmx1024M -Xms1024M -jar server.jar nogui" >> /testFolder/startMc.shenter code here


text:
Q: Using the Avant Garde BK BT Font on Webpages? If I download and use this font on my web page, will it be able to render correctly on all browsers? I have checked on Google Chrome and it is not on the list of default fonts installed.
If not, is there an alternative that can be used so my web page will be able to render properly on all the browsers and operating systems?

A: You need to include a web-font in order to ensure your page renders the same on all browsers. A good repository of web-fonts can be found here:
http://www.google.com/fonts/
https://edgewebfonts.adobe.com/
If you own a licence which permits you to use the font on a website, you can use the following converter to change your font into a web format
http://www.fontsquirrel.com/tools/webfont-generator
An example of including and using a web-font :
HTML
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>

CSS
body {
    font-family: 'Open Sans', sans-serif;
}


text:
Q: Read .tar.gz file in spark socket dataset Reading .tar.gz file as file stream in spark streaming is well and good enough.
but my requirement is, can we read .tar.gz file that is coming from socketserver in spark-streaming?
when is post tar file in socket like
nc -l 9990 < input.tar.gz

i can read it in spark like
Dataset<org.apache.spark.sql.Row> dataset = ss.readStream()
                     .option("host", "localhost")
                     .option("port", "9990")
                     .format("socket")
                     .load();

if i try to store the result in csv format
dataset
               .coalesce(1)
               .writeStream()
               .format("csv")
               .outputMode(OutputMode.Append())
               .option("checkpointLocation", "/tmp/checkpoint")
               .option("path", "hdfs://10.15.xxx.xxx:8020/user/admin/sftp/tar_output4")
               .start()
               .awaitTermination();

i am getting output like binary format in output csv
0000000:    22 ef bf bd 08 00 00 00 00 00 00 00 ef bf bd ef   "...............
0000010:    bf bd 3b 0e ef bf bd 40 0c ef bf bd e1 ad 91 ef   ..;....@........
0000020:    bf bd 03 07 ef bf bd 18 ef bf bd 65 09 c7 a1 ef   ...........e....
0000030:    bf bd 41 01 ef bf bd 3a 7f 5c 22 ef bf bd 24 5b   ..A....:.\"...$[
0000040:    21 ef bf bd 2a ef bf bd ef bf bd 35 1e ef bf bd   !...*......5....
0000050:    ef bf bd ef bf bd 56 5b 1b 1e 6d ef bf bd ef bf   ......V[..m.....
0000060:    bd ef bf bd ca a5 21 ef bf bd ef bf bd ef bf bd   ......!.........
0000070:    ef bf bd 0e d1 ac ef bf bd 77 47 36 0b ef bf bd   .........wG6....
0000080:    77 ef bf bd 12 ef bf bd ef bf bd ef bf bd 2d 6b   w.............-k
0000090:    37 3b ef bf bd 1f ef bf bd d7 95 3b ef bf bd 73   7;.........;...s
00000a0:    37 ef bf bd 4b 6d 59 ef bf bd 72 ef bf bd 3c ef   7...KmY...r...<.
00000b0:    bf bd 04 ef bf bd ca b3 7f 17 02 00 00 00 00 00   ................
00000c0:    00 00 00 00 00 00 00 00 ef bf bd ef bf bd 06 59   ...............Y
00000d0:    e9 a9 85 00 28 22 0d 0a   ....("..

anyone please help me with this..
thanks

A: You reading binary files (archives) and writing output to csv files without any transformation. That's why your output csv contain binary information, it is still archive, but written to csv file.
As far as I know there is no out-of-the-box solution for binary files for structured streaming.
Check structured streaming programming guide for all input and output modes.

A: I wrote a TGZ codec and registered it. I use it for reading TGZ files as text/csv files.
Maybe that helps:
final class DecompressTgzCodec extends CompressionCodec {
  override def getDefaultExtension: String = ".tgz"

  override def createOutputStream(out: OutputStream): CompressionOutputStream = ???

  override def createOutputStream(out: OutputStream, compressor: Compressor): CompressionOutputStream = ???

  override def createCompressor(): Compressor = ???

  override def getCompressorType: Class[_ <: Compressor] = ???

  override def createInputStream(in: InputStream): CompressionInputStream = {
    new TarDecompressorStream(new TarArchiveInputStream(new GzipCompressorInputStream(in)))
  }

  override def createInputStream(in: InputStream, decompressor: Decompressor): CompressionInputStream = createInputStream(in)

  // we do not create any decompressor
  override def createDecompressor(): Decompressor = null

  // we do not create any decompressor
  override def getDecompressorType: Class[_ <: Decompressor] = null

  // see https://www.conductor.com/nightlight/how-to-build-a-speedy-custom-compression-codec-for-hadoop/
  final class TarDecompressorStream(in: TarArchiveInputStream) extends DecompressorStream(in) {
    def updateStream(): Unit = {
      // still have data in stream -> done
      if (in.available() <= 0) {
        // create stream content from following tar elements one by one
        in.getNextTarEntry
      }
    }

    override def read: Int = {
      checkStream()
      updateStream()
      in.read()
    }

    override def read(b: Array[Byte], off: Int, len: Int): Int = {
      checkStream()
      updateStream()
      in.read(b, off, len)
    }

    override def resetState(): Unit = {
    }
  }
}
...
// register the new codec:
    val conf = new SparkConf()
    conf.set("spark.hadoop.io.compression.codecs", classOf[DecompressTgzCodec].getName)

    val spark = SparkSession
      .builder()
      .master(...)
      .config(conf)
      .appName("Test")
      .getOrCreate()


text:
Q: Using Lexical Filtering of Azure Table on range of RowKey values Problem: no results are returned.
I'm using the following code to get a range of objects from a partition with only 100 or so rows:
var rangeQuery = new TableQuery<StorageEntity>().Where(
                TableQuery.CombineFilters(
                    TableQuery.CombineFilters(
                        TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey),
                        TableOperators.And,
                        TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.GreaterThanOrEqual, from)
                    ),
                    TableOperators.And,
                    TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.LessThanOrEqual, to)
                )
            );

            var results = table.ExecuteQuery(rangeQuery);
foreach (StorageEntity entity in results)
            {
                storageEntities.Add(entity);
            }

NOTE: it doesn't seem to matter how I combine the 3 terms, no results are returned.  An example of one that I am expecting is this (partitionKey, rowKey):
"10005678", "PL7NR_201503170900"
The ranged filter code generates this expression:

((PartitionKey eq '10005678') and (RowKey ge 'PL7NR_201503150000'))
  and (RowKey lt 'PL7NR_201504082359')

But I have also tried this (which is my preferred approach for performance reasons, i.e. partition scan):

(PartitionKey eq '10005678') and ((RowKey ge 'PL7NR_201503150000') and
  (RowKey lt 'PL7NR_201504082359'))

My understanding is that the Table storage performs a lexical search and that these row keys should therefore encompass a range that includes a row with the following keys:
"10005678", "PL7NR_201503170900"
Is there something fundamentally wrong with my understanding?
Thanks for looking at this.
UPDATE: question updated thanks to Gaurav's answer.  The code above implicitly handles continuation tokens (i.e. the foreach loop) and there are only 100 or so items in the partition, so I do not see the continuation tokens as being an issue.
I have tried removing the underscores ('_') from the key and even tried moving the prefix from the rowKey and adding it as a suffix to the partitionKey.

NOTE: This is all running on my local machine using storage emulation.

A: From Query Timeout and Pagination:

A query against the Table service may return a maximum of 1,000 items
  at one time and may execute for a maximum of five seconds. If the
  result set contains more than 1,000 items, if the query did not
  complete within five seconds, or if the query crosses the partition
  boundary, the response includes headers which provide the developer
  with continuation tokens to use in order to resume the query at the
  next item in the result set. Continuation token headers may be
  returned for a Query Tables operation or a Query Entities operation.

Please check if you're getting back Continuation Token in response.
Now coming on to your filter expressions:

((PartitionKey eq '10005678') and (RowKey ge 'PL7NR_201503150000'))
  and (RowKey lt 'PL7NR_201504082359')

This one is definitely doing a Full Table Scan because (RowKey lt 'PL7NR_201504082359') is a clause in itself. For executing of this particular piece, it basically starts from top of the table and find out entities where RowKey < 'PL7NR_201504082359' without taking PartitionKey into consideration.

(PartitionKey eq '10005678') and ((RowKey ge 'PL7NR_201503150000') and
  (RowKey lt 'PL7NR_201504082359'))

This one is doing a Partition Scan and you may not get result back if you have too much data in the specified partition or the query takes more than 5 seconds to execute as mentioned above.
So, check if your query is returning any continuation tokens and make use of them to get the next set of entities if no entities are returned.
A few resources that you may find useful:

*

*How to get most out of Windows Azure Tables: http://blogs.msdn.com/b/windowsazurestorage/archive/2010/11/06/how-to-get-most-out-of-windows-azure-tables.aspx

*Azure Storage Table Design Guide: Designing Scalable and Performant Tables: http://azure.microsoft.com/en-us/documentation/articles/storage-table-design-guide/


text:
Q: Intersection observer API scroll aware navigation I am trying to use the intersection observer to create something like the website link below, the whole aim is to recreate that the sticky boxes that serve as a navigation to each section, my thought process for this relates to the navigation bar on changing the active section when it comes in, a link to my codepen is attached an image also showing what I'm trying to achieve on the main site I got the idea from with a link to the site,
Codepen: https://codepen.io/thatfemicode/pen/JjWRNoZ
Sitelink: https://olaolu.dev/
Javascript
 const changeNav = (entries, observer) => {
      entries.forEach((entry) => {
        // verify the element is intersecting
        if (entry.isIntersecting && entry.intersectionRatio >= 0.55) {
          // remove old active class
          document.querySelector(".active").classList.remove("active");
          // get id of the intersecting section
          var id = entry.target.getAttribute("id");
          // find matching link & add appropriate class
          var newLink = document
            .querySelector(`[href="#${id}"]`)
            .classList.add("active");
        }
      });
    };

    // init the observer
    const options = {
      threshold: 0.55,
    };

    const observer = new IntersectionObserver(changeNav, options);

    // target the elements to be observed
    const sections = document.querySelectorAll("section");
    sections.forEach((section) => {
      observer.observe(section);
    });

A: change in that script the newLink line to:
var newLink = document.querySelector('[href="#'+id+'"]').classList.add('active');


text:
Q: Flutter ScrollPhysics change on Keyboard up / or other ideas? I want to navigate through my ListView only with two buttons, not with the fingers and scroll so:  physics: const NeverScrollableScrollPhysics(),.
here is a picture, the problem is below:

when I open the keyboard, it looks like this:
So my Input Fields are obscured behind the keyboard. With an active scroll physics, this wouldn't happen because it resizes the screen so that it fit. Is there a way to move the End of my scaffold to the end of the keyboard, e.g.? Or a workaround like to activate the scrolls physics only when the keyboard appears?
I also have a
    ScrollConfiguration(
                  behavior: MyBehavior(),

class MyBehavior extends ScrollBehavior {
  @override
  Widget buildOverscrollIndicator(
      BuildContext context, Widget child, ScrollableDetails details) {
    return child;
  }
}

but I think this is not important for my problem

A: You can check if keyboard is opened like this:
//use flutter_keyboard_visibility plugin for detection
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'dart:async';

late StreamSubscription<bool> keyboardSubscription;
bool isKeyboardVisible = false;

@override
void initState() {
  super.initState();

  var keyboardVisibilityController = KeyboardVisibilityController();
  // Query
  print('Keyboard visibility direct query: ${keyboardVisibilityController.isVisible}');

  // Subscribe
  keyboardSubscription = keyboardVisibilityController.onChange.listen((bool visible) {
    print('Keyboard visibility update. Is visible: $visible');
    isKeyboardVisible = visible;
  });
}

@override
void dispose() {
  keyboardSubscription.cancel();
  super.dispose();
}

For listview :
physics: !isKeyboardVisible?const NeverScrollableScrollPhysics():ClampingScrollPhysics(),

A: Wrap your listview in SingleChildScrollView like below,
SingleChildScrollView(
          child: ListView....


text:
Q: Find all the childs who have the same parents than the element hovered in jquery I have a list of subject. Inside each subject, i have items.
When i hover an item, i try to change the color of each item of this subject.

hello

hello2

hello3

hello

hello2

hello3

I if do like that, it change all the .items of the whole page :
$(".item").hover(function () {
    $(".item").addClass("hovering");
}, function () {
    $(".item").removeClass("hovering");
});

I can't find how to say "All the child who have the same parent than the item i'm hovering"...
Thanks !

A: change your JS to this:
$(".item").hover(function () {
    $(this).addClass("hovering");
}, function () {
    $(".item").removeClass("hovering");
});

here is the JSFiddle: http://jsfiddle.net/hZ9zb/

A: Use:
$(".item").hover(function () {
    $(this).parent().find('.item').addClass("hovering");
}, function () {
    $(this).parent().find('.item').removeClass("hovering");
});

jsFiddle example

A: $(".item").hover(function () {
   $(this).siblings().addClass("hovering");
 }, function () {
   $(this).siblings().removeClass("hovering");
});

Fiddle

A: i have created a jsfiddle please go through this.
$(document).ready(function()
                  {
  $(".item").hover(function () {

    $(this).addClass("hovering");
   }, function () {
    $(this).removeClass("hovering");
  });
});

http://jsfiddle.net/S8qep/49/
thanks


text:
Q: How do I change the desktop wallpaper to a dual screen image I found many articles that were similar to mine, but none with my specific problem.
I have a dual screen setup and I am using Ubuntu 11.10- I changed my wallpaper from one dual screen image (1600X600) to another (2560X1024) using the System Settings > Appearance > Wallpapers menu.
It worked fine. Then (being an idiot) I decided I wanted to try some different ones that Ubuntu provided.
I chose one that came packaged (The Grass Ain't Greener 2000X1250) then I decided to go back to the original. This is where the problem started. Using the Wallpaper menu, I could no longer select any images that have previously been used as wallpapers. What Gives?

A: It's looking only in specific locations for the wallpapers.  In order to use your own, you will need to either locate the pictures you used, by pressing the "+" button below the thumbnails, and browsing for the picture.  I believe it defaults to looking in the "Pictures" folder in your home directory, but you can browse any folder.
Don't forget to set the option above the theme name to "Span" if you want it to span both monitors instead of repeating.


text:
Q: Why OOP languages use the syntax "object.function()" to send a message? In C++ and Java and many other OOP languages, in order to send a message to an object, you have to use the object.function() syntax, for example:
myCar.start();    // send the start() message to the myCar object

But why was this syntax chosen to send a message? why for example wasn't the function(object) syntax chosen instead? and are all OOP languages use the object.function() syntax to send a message?

A:
In C++ and Java and many other OOP languages, in order to send a message to an object, you have to use the object.function() syntax […]

First, an important correction: they use the syntax object.message(), not object.function(). Messages and functions are fundamentally different.

But why was this syntax chosen to send a message? why for example wasn't the function(object) syntax chosen instead?

Frame challenge
I want to challenge the premise of your question because there are object-oriented programming languages that use or at least alternatively allow this syntax.
For example in Lark
list.length

is simply syntactic sugar for
length list

Also, interestingly in Python, methods are defined as functions taking the receiver as an argument:
class Foo:
  def bar(baz, qux):
    # within the method body, `baz` is the receiver
    pass

but they are called with the receiver as a special argument using the dot-message-sending syntax:
foo = Foo()

foo.bar(42)
# within the method body, `baz` is now `foo`.

Conventionally, this first parameter is named self, but that is only a convention.
Simula
This is the syntax used by Simula (1962), considered to be the first object-oriented programming language. Unfortunately, both designers of Simula, Kristen Nygaard and Ole-Johan Dahl, died in 2002, so we can't ask them why they chose it. However, you might find that they have documented their rationale in one of their papers.
However, there is a very good reason to distinguish the "special" zeroth argument from the other arguments, and that reason is that the "special" argument is … well special.
A method has privileged access to the internal representation and the private API of the receiver. Therefore, the receiver is different, and it makes sense to distinguish it from the rest of the arguments. If you have
message(object, arg1, arg2)

then there is no indication that object is treated different from arg1 and arg2. But they are different: the method can access the internal representation and the private API of object but only the public API of arg1 and arg2. Whereas with
object.message(arg1, arg2)

you can clearly see that object is different from arg1 and arg2.
Additionally, Simula was designed to be a fairly faithful superset of ALGOL and function(object) already has a meaning in ALGOL (subroutine call) that is different from message send, so that might also have been a reason not to overload it with two different meanings. It gets especially confusing when you have a subroutine named foo in scope and object also has a foo method, then what does foo(object) mean?

and are all OOP languages use the object.function() syntax to send a message?

No, of course not. There are thousands of languages, it would be a miracle if they all used the same syntax.
Smalltalk, Self, Newspeak, Objective-C, Objective-C++, Objective Modula-2, Fancy, Finch, Nu
The other extremely influential OO language next to Simula, Smalltalk, uses the so-called "Smalltalk keyword selector syntax". The message sending operator is simply the space, and the message is a "keyword selector" with the arguments written between the keywords. A "sentence" is ended with a period.
anArray ← Array new.

anArray append: 23.
anArray append: 42.

anArray at: 2 put: 4711.
"anArray will now contain the elements (23 4711)."

"If you want to send multiple messages to the same receiver, you can use a cascade:"

anArray
  append: 23;
  append: 42;
  at: 2 put: 4711.

Note: The name of the method in the last line is at:put:.
This syntax is also used by many of Smalltalk's descendants, successors, and derivatives, including Self (one of the influences on ECMAScript) and Newspeak as well as Fancy, Finch, Nu, and countless others. The most well-known language that inherited it from Smalltalk is Objective-C, which was until recently the primary language for macOS, iOS, iPadOS, tvOS, and watchOS development, and still plays an important role there.
Objective-C++ is interesting. Objective-C was created by taking the Smalltalk object model and Smalltalk message sending syntax and adding it to C as an orthogonal language extension. ("Extension" meaning that every legal C program is also a legal Objective-C program with identical semantics, and "orthogonal" meaning that the C part and the Objective part mostly don't interact.) Because Objective-C was designed as an orthogonal extension, it was actually possible to take the "Objective" part and apply it to other languages. (For example, Objective Modula-2.)
So, what do you get when you orthogonally extend C++ with "Objective"? You get a language with two separate object models and two different message sending syntaxes!
PLASMA
Carl Hewitt's PLASMA uses
message ⇒ object
object ⇐ message

interchangeably, depending on which one reads better in a certain context.
Note that in PLASMA, the message is not just a "message name" as it is in Simula or Smalltalk, but an object itself. For example, to add some numbers together, you would send the message [1 2 3 4] (an array of numbers) to the object + like this:
[1 2 3 4] ⇒ +
+ ⇐ [1 2 3 4]

On the receiver side, you define a receiver pattern, which uses a triple-shafted arrow:
⇛ pattern
  body

Io, Ioke, Seph, Atomo, Scala
In Io, Ioke, Seph and other languages based on similar ideas (e.g. Atomo), whitespace is used as the message sending operator as in Smalltalk, but arguments are passed in a parenthesized argument list like in ALGOL-style subroutine calls:
object message(arg1, arg2)

If there is only one argument, it is allowed to omit the parentheses, so you are allowed to write
2 + 3

instead of having to write
2 +(3)

Scala uses object.message() by default, but it allows to leave out the ., and if there is only a single argument, it also allows to leave out the parentheses.
Lisps (e.g. Clojure, Hy)
Lisps that support object-orientation typically keep the Lisp-style syntax. In Clojure and Hy, a method call looks like this:
(.message object arg1 arg2)

Grace
Grace uses a mixture of Simula-style and Smalltalk-style:
"abcdefghi".substringFrom(3)to(6)
"abcdefghi".substringFrom(3) to(6)
"abcdefghi".substringFrom 3 to 6

sends the message substringFrom(_)to(_) passing arguments 3 and 6.
Ruby, CoffeeScript, CokeScript, Coco
Ruby, CoffeeScript, Coco, and many others use Simula-style but allow to leave out the parentheses:
object.message arg1, arg2

Lua
Lua does not have OOP as part of its language semantics, but it does have some syntactic features that make it possible to implement OOP as a library while still looking like it is part of the language. This is quite interesting because it makes it possible to have multiple competing object systems in the same language, and choose the best one for the job.
In Lua,
object:message(arg1, arg2)

desugars into
object.message(object, arg1, arg2)

but it guarantees that object will only be evaluated once.
Erlang
Whether or not you consider Erlang object-oriented is a matter of opinion, but it definitely supports message sending:
object ! message

"Interesting" syntax sugar
Scala has right-associative operators. Any operator that ends with a colon : is right-associative and has the argument on the left and the receiver on the right:
a + b
// is syntactic sugar for
a.+(b)

// but

a +: b
// is syntactic sugar for
b.+:(a)

Languages in which everything is a message send
In some languages, really absolutely everything is a message send. For example, in Ioke, Seph, and Monte, list or array literals are message sends, even number literals can be.
For example, in Ioke
[1, 2, 3]

is actually the message send
[](1, 2, 3)

and even
42

is actually the message send
internal:createNumber("""42"""")

[Note: """42""" is not actually legal Ioke syntax. These methods take a so-called "strange object" as an argument, which is an object that belongs to the underlying platform and cannot be represented in Ioke. I am using this syntax here to mean "the strange object representing 42".]
and
"Hello World"

is actually the message send
internal:createText("""Hello World""")

so, this is sending the message internal:createText to what Ioke calls the "current ground", and the argument is a so-called "strange object" which is an object that is not actually an Ioke object but an object of the host platform. (We have to start the bootstrapping process somewhere.) So, in the JVM implementation of Ioke, this would be a java.lang.String and in the CLI implementation, it would be a System.String.
By overloading these methods, I can overload the meaning of literals. This is used in Ioke's parser generator library, where "a" for example does not mean "the string containing the character a" but "a parser that recognizes the character a".
Others …
Of course, until now, we have only looked at single-dispatch classical and prototype-based OO. There is a whole slew of other approaches such as multiple-dispatch OO that by necessity have different syntax.

A: This was likely a design decision by the original authors of some of those older languages. As others have pointed out in comments other syntaxes exist in languages that just didn't catch on. C and C++ caught on, and their challenges inspired a new generation of language authors. The newer generations were comfortable with the syntax, so they copied into their new language. My assumption is the syntax worked good enough and did not warrant a redesign.
That isn't to say object.method() is the best. It just turned out to be tradition.
As to why those original language authors choose that syntax? You'll need to ask those authors.

A: I can give one suggestion of why object.function() is used rather than function(object).
If the function took an extra parameter, then we'd be comparing object.function(foo) with function(object, foo). As OOP languages generally provide some form of polymorphism, often with single dynamic dispatch, it's useful to clearly distinguish between the parameter which is used to look up the function to call (object), and the parameter which is not involved in that process.
This is made clearer by having the parameter used for function lookup syntactically separated from the parameter which is not.

A: Last question: Not all. In objective-c you write [object method]. And Smalltalk is similar.

A:
But why was this syntax chosen to send a message?

It really comes down to this: those languages (starting from C++ and extending onward) do not consider this syntax to be "sending a message to an object" at all. They consider it to be "calling a function which is a member of the object." The syntax in C for getting a member of a struct is to use object.member_name. In C, if that member_name just so happens to be a function pointer, then you get to do object.member_name(parameters).
That's the basic idea. These languages are not built in terms of "sending messages". They're built in terms of "calling functions". You can conceptually consider "calling a function" to be a form of "sending a message", but those languages don't really agree.

why for example wasn't the function(object) syntax chosen instead?

There are many different reasons why this wasn't done, usually down to the specifics of the different languages.
In C, function(object) already has a well-understood meaning; there is a global function named function, which takes an argument of a type equivalent to that of object. That's what the compiler does with that code, and it gives you an error if none of those conditions are satisfied.
C++ was designed to be backwards-compatible with C (mostly), so it inherited this meaning. Also, C++ wanted to have non-member functions too, so it was always going to inherit this meaning.
Allowing function(object) to look up function declarations within the scope of object's type would be... weird. It could be very confusing as to which function would be called in any given scenario, especially since people can write non-member functions anywhere that could conflict with such a call.
The ISO C++ committee tried for many years to attempt to reconcile this weirdness so as to allow object.function and function(object) to mean the same thing. Nothing came from these efforts, and they've more-or-less given up on the idea of making one automatically map to the other.
Remember again that we're not talking about "messages"; we're talking about static constructs. object has some type, and function must be a function declared within object's type. This is what allows the compiler to resolve object.function down to a specific piece of code.
Scripting languages like Python or Lua use similar object.function() notation as well, for somewhat separate reasons. In languages like those, functions are first-class objects. As such, "member functions" are a convention, not a distinct idea. A "member function" is just a regular function whose value happens to be stored in that object, just like any other value. So object.function() means "retrieve the function member of object and call it with object as one of its parameters." This is functionally no different from object.value used to retrieve or set the value member of object.
Since these languages also have non-member functions, they also have the issue of having function(object) already having a well-defined meaning: find the function with the name function that is accessible from this scope and call it with the object parameter. Trying to make it mean something else as well could get really confusing.


text:
Q: How to show a notification even app is not running i'm beginner in android.i create a service to show a notification when onCreat on mainActivity called
    public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent a = new Intent(this,myService.class);
        startService(a);
    }

}

here is my service class
public class myService extends Service{
  private NotificationManager mManager;

 @Override
    public void onCreate() {

     mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
       Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);

       Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
       intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

       PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
       notification.flags |= Notification.FLAG_AUTO_CANCEL;
       notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);

       mManager.notify(0, notification);
 }

but i want if my app is not running i can show this service for example if my phone time is bigger than 9 i show this notification only one time in a day.any ideas ? thanks in advance

A: Notifications are running on background and application running is not needed. While application is not running, notifications also work and this is the main mission of them. I suggest you Vogella's tutorial and documentation:
http://www.vogella.com/tutorials/AndroidNotifications/article.html
http://developer.android.com/guide/topics/ui/notifiers/notifications.html

A: *

*You don't want to show notifications while your app is running. That is just annoying and has (usually) no point. There are of course exceptions.

*If you want to show a notification at a specific time, you should consider to use the AlarmManager.

*If you want to trigger the notification from a server or wherever else, use Google Cloud Messaging.


text:
Q: How can I install a newer Perl without damaging the system install? I have seen plenty of people mention some of the cool new features in Perl >= 5.12 but my preferred flavor of Linux Ubuntu only comes with 5.10.1.
I have no fear of PPAs and I know how to google (unless someone finds me something, then I'll feel sheepish). I cannot find someone that provides a Perl PPA; I thought there was a PPA for everything!
My further fear is that since linux-based OSes use perl as part of their packaging and other systems I don't necessarily want to venture out on my own to compile/install it for fear of breaking my OS.
Can someone give me some guidance on the easiest while still safest way to upgrade/parallel-install the newest Perl versions?

*

*Can I specify multiple binaries in a good way to not affect system utilities?

*How do the Modules work if multiple versions of Perl are installed?

A: I'd recommend taking a look at the excellent perlbrew, available from CPAN, which allows you to locally install and manage multiple perl versions.

A: You sound more like your trying to replace the dist perl, you don't want to do that. You want to install a separate perl. Because of all the baggage associated with the perls, I usually install them as a separate user in their home and then export out like a /opt or what not.

A: What I do is, compile my own perl and install it in /opt/perl. Then, I add export PATH=/opt/perl/bin:$PATH to my .bashrc. Thus the system perl remains intact and I have the latest perl to play with. :-)


text:
Q: How to Create sticky session in haproxy My Configurations are:-
frontend http-8081
    bind *:8081
    mode http
    acl is_keycloak hdr(X-TARGET) keycloak
    use_backend keycloak if is_keycloak
backend keycloak
    mode http
    balance roundrobin
    option forwardfor
    option httpchk HEAD / HTTP/1.1\r\nHost:localhost
    server 192.168.99.100:32768 192.168.99.101:32766 check inter 5000
I am new to this and I need a Sticky session. Can anyone tell me using this configuration that how to create a Sticky session?

A: I believe using cookies will help you here.
I would also say have your servers on seperate lines for each one
cookie SERVERID insert
server s1 192.168.99.100:32768 check inter 5000 check cookie s1
server s2 192.168.99.101:32766 check inter 5000 check cookie s2


text:
Q: Firebase Functions deploy fails 'There was an error deploying Functions' with Easypost Hello fellow world peace and Moonbase-36 residents, Deploying this firebase function Fails because I've added EASYPOST into the file. Do I need to create another functions file and deploy that to make this work?
// require('babel-polyfill');
const functions = require("firebase-functions");
const cors = require("cors");
const express = require("express");
const EasyPost = require('@easypost/api');
const EPapi = new EasyPost('YOURAPIKEY');

const app = express();
const stripe = require("stripe")("APIKEY");

As soon as I comment out the const EasyPost and const EPapi, the deploy works fine. But we need Easypost to work.
firebase functions:log Detailed stack trace: Error: Cannot find module '@easypost/api'

A: OP resolved the issue by installing Easypost using npm install Easypost into the Functions folder to have it as dependency in firebase functions. The functions were deployed without errors.


text:
Q: FileSystemWatcher works in the PowerShell ISE but not when run I want to monitor a folder and move files that match certain criteria, so I'm trying to use the FileSystemWatcher.
I have a function that will be called with each new file:
function ProcessFile()
{
    param ([string]$filename)
    Write-Host "Processing file '$filename' to $destination"
}

And then I set up a FSW:
Write-Host "Watching $source for new files..."
$fsw = New-Object IO.FileSystemWatcher $source, $filter -Property @{IncludeSubdirectories = $false; NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action
{
    ProcessFile $Event.SourceEventArgs.FullPath
}

That works fine when I run it from the ISE, and any files I drop into the watched folder are correctly tracked, but if I start a PowerShell window and run the script with .\FileWatch.ps1 then nothing happens.
I see the "watching ..." message, but never see a "processing..." message
Here's the full script that works in the ISE but not in a shell...
$source = 'D:\Dev\PowerShell\FileWatch\Test\Source'
$filter = '*.*'
$destination = 'D:\Dev\PowerShell\FileWatch\Test\Found\'

function ProcessFile()
{
    param ([string]$filename)
    Write-Host "Processing file '$filename' to $destination"
}

Write-Host "Watching $source for new files..."
$fsw = New-Object IO.FileSystemWatcher $source, $filter -Property @{IncludeSubdirectories = $false; NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
    ProcessFile $Event.SourceEventArgs.FullPath
}

A: The problem is that your function ProcessFile isn't loaded in powershell session.
Try loading you script in this way:
. .\myscript.ps1

In this way your code in my system works!
Read about Dot Sourcing a script in powershell.


text:
Q: Vue - hidden file input - listen for cancel I am using an hidden file input that I am triggering using Vue
    <input
        ref="uploader"
        class="d-none"
        type="file"
        @change="onFileChanged"
        @cancel="closeWizard"
    >

this section of code is triggered by this method:
  window.addEventListener('focus', () => {
    this.isSelecting = false;
  }, { once: true });

  // Trigger click on the FileInput
  this.$refs.uploader.click();

It works almost perfect, I can access the file in the onFileChanged method. However, I would like to catch a cancel event so that I can close the wizard in which the file dialog resides. Unfortunately,
@cancel="closeWizard"
does not work, any ideas how to catch the cancel?

A: I fixed it by adapting some of my own code:
handleFileImport() {
  console.log('handleFileImport');
  this.isSelecting = true;

  // After obtaining the focus when closing the FilePicker, return the button state to normal
  window.addEventListener('focus', () => {
    this.isSelecting = false;

    setTimeout(() => {
      console.log('selected file', this.selectedFile);
      if (this.selectedFile == null) {
        this.$emit('close_wizard', true);
      }
    }, 500);
  }, { once: true });

  // Trigger click on the FileInput
  this.$refs.uploader.click();
},

and the hidden input
    <!-- Create a File Input that will be hidden but triggered with JavaScript -->
    <input
        ref="uploader"
        class="d-none"
        type="file"
        @change="onFileChanged"
    >

If no selected file is set, an emit is generated using this line:             this.$emit('close_wizard', true);
and the wizard that holds the file input is closed


text:
Q: Android: What is transport and jsonFactory in GoogleIdTokenVerifier.Builder? in the blow code, whats is transport and jsonFactory ? (I do not understand)
https://developers.google.com/identity/sign-in/android/backend-auth#using-a-google-api-client-library
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;

...

GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport /**Here**/, jsonFactory /**Here**/)
.setAudience(Arrays.asList(CLIENT_ID))
// If you retrieved the token on Android using the Play Services 8.3 API or newer, set
// the issuer to "https://accounts.google.com". Otherwise, set the issuer to
// "accounts.google.com". If you need to verify tokens from multiple sources, build
// a GoogleIdTokenVerifier for each issuer and try them both.
.setIssuer("https://accounts.google.com")
.build();

// (Receive idTokenString by HTTPS POST)

GoogleIdToken idToken = verifier.verify(idTokenString);
if (idToken != null) {
  Payload payload = idToken.getPayload();

  // Print user identifier
  String userId = payload.getSubject();
  System.out.println("User ID: " + userId);

  // Get profile information from payload
  String email = payload.getEmail();
  boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());
  String name = (String) payload.get("name");
  String pictureUrl = (String) payload.get("picture");
  String locale = (String) payload.get("locale");
  String familyName = (String) payload.get("family_name");
  String givenName = (String) payload.get("given_name");

  // Use or store profile information
  // ...

} else {
  System.out.println("Invalid ID token.");
}

A: Since all the other answers are blah blah blah, here's a short answer:
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;

GoogleIdTokenVerifier verifier =
    new GoogleIdTokenVerifier.Builder(new NetHttpTransport(), new GsonFactory());

A: You need to select transport according to the platform on which you are running the code.
Quoting from the documentation
Implementation is thread-safe, and sub-classes must be thread-safe. For maximum efficiency, applications should use a single globally-shared instance of the HTTP transport.

The recommended concrete implementation HTTP transport library to use depends on what environment you are running in:

Google App Engine: use com.google.api.client.extensions.appengine.http.UrlFetchTransport.
com.google.api.client.apache.ApacheHttpTransport doesn't work on App Engine because the Apache HTTP Client opens its own sockets (though in theory there are ways to hack it to work on App Engine that might work).
com.google.api.client.javanet.NetHttpTransport is discouraged due to a bug in the App Engine SDK itself in how it parses HTTP headers in the response.
Android:
For maximum backwards compatibility with older SDK's use newCompatibleTransport from com.google.api.client.extensions.android.http.AndroidHttp (read its JavaDoc for details).
If your application is targeting Gingerbread (SDK 2.3) or higher, simply use com.google.api.client.javanet.NetHttpTransport.
Other Java environments
com.google.api.client.javanet.NetHttpTransport is based on the HttpURLConnection built into the Java SDK, so it is normally the preferred choice.
com.google.api.client.apache.ApacheHttpTransport is a good choice for users of the Apache HTTP Client, especially if you need some of the configuration options available in that library.

Documentation Link: https://developers.google.com/api-client-library/java/google-http-java-client/reference/1.19.0/com/google/api/client/http/HttpTransport?is-external=true
If you blindly follow the 2nd answer to the question, you will get the exception Caused by: java.lang.ClassNotFoundException: com.google.appengine.api.urlfetch.HTTPMethod

A: The GoogleIdTokenVerifier.Builder returns a GoogleIdTokenVerifier that will make a request to the tokeninfo endpoint with the transport you give it and use the JSONFactory to create a parser to parse the response.
Here is an example of an authenticator for a Cloud Endpoints project that uses the GoogleIdTokenVerifier.Builder
public class GoogleAuthenticator implements Authenticator {

    private static final Logger log = Logger.getLogger(GoogleAuthenticator.class.getName());
    private static final JacksonFactory jacksonFactory = new JacksonFactory();

    // From: https://developers.google.com/identity/sign-in/android/backend-auth#using-a-google-api-client-library
    // If you retrieved the token on Android using the Play Services 8.3 API or newer, set
    // the issuer to "https://accounts.google.com". Otherwise, set the issuer to
    // "accounts.google.com". If you need to verify tokens from multiple sources, build
    // a GoogleIdTokenVerifier for each issuer and try them both.

    GoogleIdTokenVerifier verifierForNewAndroidClients = new GoogleIdTokenVerifier.Builder(UrlFetchTransport.getDefaultInstance(), jacksonFactory)
            .setAudience(Arrays.asList(CRLConstants.IOS_CLIENT_ID, CRLConstants.ANDROID_CLIENT_ID_RELEASE, CRLConstants.ANDROID_CLIENT_ID_DEBUG))
            .setIssuer("https://accounts.google.com")
            .build();

    GoogleIdTokenVerifier verifierForOtherClients = new GoogleIdTokenVerifier.Builder(UrlFetchTransport.getDefaultInstance(), jacksonFactory)
            .setAudience(Arrays.asList(CRLConstants.IOS_CLIENT_ID, CRLConstants.ANDROID_CLIENT_ID_RELEASE, CRLConstants.ANDROID_CLIENT_ID_DEBUG))
            .setIssuer("accounts.google.com")
            .build();

    // Custom Authenticator class for authenticating google accounts
    @Override
    public User authenticate(HttpServletRequest request) {

        String token = request.getHeader("google_id_token");
        if (token != null) {

            GoogleIdToken idToken = null;
            try {
                idToken = verifierForNewAndroidClients.verify(token);
                if(idToken == null) idToken = verifierForOtherClients.verify(token);

                if (idToken != null) {

                    GoogleIdToken.Payload payload = idToken.getPayload();

                    // Get profile information from payload
                    String userId = payload.getSubject();
                    String email = payload.getEmail();

                    return new GoogleUser(userId, email);

                } else {
                    log.warning("Invalid Google ID token.");
                }

            } catch (GeneralSecurityException e) {
                log.warning(e.getLocalizedMessage());
            } catch (IOException e) {
                log.warning(e.getLocalizedMessage());
            }

        }

        return null;
    }

}

A: JacksonFactory is deprecated. So this works.
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;

GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(new NetHttpTransport(), new GsonFactory())
.setAudience(Arrays.asList(CRLConstants.IOS_CLIENT_ID, CRLConstants.ANDROID_CLIENT_ID_RELEASE, CRLConstants.ANDROID_CLIENT_ID_DEBUG))
            .setIssuer("accounts.google.com")
            .build();


text:
Q: Mirroring Odd Bits of an Register Does anyone know how to mirror bits in NASM/8086?
Here is an example:
10100001 after mirroring => 10000101
The problem is more complicated, because I should mirror ONLY the odd bits of a register:
That means:
       10100001 => 00001011
       76543210 => 76543210

i.e. 1 <=> 7 and 3 <=> 5

A: The obvious algorithm would appear to be:

*

*create mask of even bits (mask = 01010101...01010101)

*extract even bits into a temporary (temp = src AND mask)

*mask out even bits from source register (src = src AND NOT mask)

*reverse bits in source register (plenty of existing algos for this)

*shift reverse bits left by 1 so that they are still in odd locations (src = src SHL 1)

*re-insert even bits (src = src OR temp)

Of course if this is just for 8 bit values then you could just use a pre-computed 256 element LUT.

A: I finally find out another way to solve the problem. Your Answer was very good, but the algorithm that you linked me yesterday it´s hard to implement, when you have only few minutes to solve the problem. I have not specified, but this homework was in fact an exam problem, with limited amount of time.
I think that the algorithm from Stanford University it´s more optimized but a little difficult to implement, or am I wrong?!
So, here is my Ideea:
MOV EAX,2862962005  ; Register where the odd bits must be mirrored
                    ; Initialised with an random Number as example
                    ; Result should be putted again in EAX

ODD_MIRRORED:
PUSH EBX            ;put the values of the other registers on to the Stack
PUSH ECX            ;probably this registers hold valuable datas inside
PUSH EDX

MOV EDX,0           ;EDX is counter, form 0 to 31
MOV EBX,0           ;EBX holds the inverted odd bits during the process
                    ;For Auxiliary use only

iteration:
ROR EAX,1           ;EVEN VALUE? JUMP: EAX rotated to the right
ROL EBX,1           ;                  EBX rotated to the left (for mirroring)
INC EDX             ;                  counter incremented

MOV ECX,0x00000001  ;ODD VALUE? USE mask and extract only one odd value
                    ;from EAX at a given time
AND ECX,EAX
OR EBX,ECX          ;put the value in EBX
ROR EAX,1           ;EAX rotated to the right
ROL EBX,1           ;EBX rotated to the left (for mirroring)
INC EDX             ;counter incremented again

CMP EDX,31
JGE end             ;if counter is greater or equal 31 jump at the end of the program

JMP iteration

end:
                    ;now EAX was rotated to the initial position
AND EAX,0x55555555  ;we want only just to get away from old odd values with
                    ;the mask 0x55555555 (0101), which is deleting the odd values
OR EAX,EBX          ;finally we transfer the mirrored odd bits into EAX from the
                    ;auxiliary variable EBX

POP EDX             ;restore EBX,ECX,EDX
POP ECX
POP EBX
RET

I verified this solution in NASM/8086 Assembler with various numbers and it works! :P


text:
Q: underfined reference to CLSID_FileOpenDialog - Mingw64 I have a whole project that I had to move from one machine to another and since moving the code, it has been coming up with an error of undefined reference to 'CLSID_FileOpenDialog'.
I'm using the x64 8.1.0 Posix SEH release though I have tried a couple of other versions, such as 7.3.0. I need to use the posix version as I have mutexes in my code and these do no work in the win32 versions.
Is there some library of similar that I need to add to the linker to stop this from happening?
I was using Mingw64 on the old machine so cannot understand why this is happening.
Thanks for any help!

A: Literally after posting this, I noticed that my project settings didn't include the "ole32", "comctl32", "oleaut32" and "uuid" libraries.
Adding these fixes the issue.


text:
Q: streamwriter does not save unicode files correctly I'm opening a text file and removing the first line to prepare it for importing in a database using bulk insert. Here is my code:
string tempFile = Path.GetTempFileName();
using (var sr = new StreamReader("F:\\Upload\\File.txt", System.Text.Encoding.UTF8))
{
    using (var sw = new StreamWriter(tempFile,true, System.Text.Encoding.UTF8))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            if (line.Substring(0, 8) != "Nr. Crt.")
                sw.WriteLine(line);
        }
    }
}

System.IO.File.Delete("F:\\Upload\\File.txt");
System.IO.File.Move(tempFile, "F:\\Upload\\File.txt");

After this if I open the resulting file, Unicode characters are replaced with other characters. For example strings containing non-breaking space (unicode U+00A0): Value  (note the unicode char ) are transformed in Value� .
How can I avoid this?
Edit:
Notepad++ is set to 'Encode in UTF-8'
Here is a picture of how it looks :

A:
are transformed in Value�

The byte values for those 3 odd characters are 0xef 0xbd 0xbf.  Which is the utf8 encoding for codepoint \ufffd, the replacement character �.  Which is used when reading utf encoded text and the text contains an invalid encoding byte sequence.
Pointing squarely at an issue with File.txt, it was probably not encoded in utf-8.  If you have no idea what encoding was used for that file then the first guess is to pass Encoding.Default to the StreamReader constructor.

A: It looks to me like it is writing fine, but the tool you are reading with is not expecting UTF-8. In many cases, you need to explicitly tell the tool what encoding to expect. However, a common approach is to prepend a BOM ("byte order mark"). This is simple - just use new UTF8Encoding(true) as the encoding and it will happen automatically. In tools that don't expect a BOM this will display as a few mangled chars at the start - but most modern tools will know what it means, and will switch to UTF-8 automatically. The point is: the BOM for UTF-8, UTF-16 LE and UTF-16 BE etc are all slightly different, but recognisable. A more complete list is on wikipedia.


text:
Q: Flux with dynamic reactjs page I have a problem with flux implementation on my app.
Heres the scenario:
We're a site builder plataform, we have pages where we don't know what will be rendering. Its completely dynamic, varying from user to user.
We have a lot of different components that may ou may not be loaded on the page and each component can have multiple instances.
What we need:
We need a FLUX structure that allows us to load only what we need from store and avoid unnecessary payload.
I have tried using Redux but the problems were:
Firstly we couldn't load all reducers at once but after a few research I built an interface capable of loading reducers on demand. But then I couldn't solve the problem with multiple instances from a component because the store file needs all states pre-refferenced :/
So, here's the question: How can I architect my app to use flux with dynamic pages and multiple instances from a component? Thanks in advance.

A: I think what you are trying to do is called "lazy loading". So you will just load components and pieces of javascript when they are needed.
Here you can find more information about (you need to generate more bundles of code with webpack):
https://blog.risingstack.com/react-js-best-practices-for-2016/
I will need this in a project in few months, but right now in our MVP we just need to make things run :)

A: Well, after a few (a lot) more research and attempts I'll implement a solution using React + Flux.Dispatcher + Backbone as suggested here:
https://www.toptal.com/front-end/simple-data-flow-in-react-applications-using-flux-and-backbone
===========================
Hope anyone has used that tip above. Worked nice for simple screens, got shit and slowly with complex pages.
Best way is to implement simple flux architecture as described in:
https://scotch.io/tutorials/getting-to-know-flux-the-react-js-architecture
https://blog.risingstack.com/the-react-js-way-flux-architecture-with-immutable-js/
Connect your components with a store via decorator and go for it, works simple majestic.
Hope it's usefull for someone.