text:
Q: Vision: eyes vs cameras I think this is related to physics, and light waves.
Is there some materials that can be seen by human eyes and can't be seen by cameras? (Imagine a special writing) Is that even possible therotically?

A: Short answer: In the simplest physical sense, no (see bolded item below).
But it depends on what you mean by "seeing".
Note that human vision blurs the line between Physics and Biology - the brain is responsible for a lot of what we think of as "seeing".
Longer answer:
Since you tagged this with visible-light, I'll take the liberty of assuming those are the wavelengths you care about.  (As the commenters pointed out, cameras can be built to be sensitive to other wavelengths outside the visible range, but to me this seems outside the spirit of the question.  It's definitely not a 'fair' comparison to the human eye.)
Ultimately "seeing" has two components:

*

*Translating a spectrum visible wavelengths into a single (or in the case of color, three) brightness or intensity values

*Image processing the brightness/intensity to understand what was sensed in #1.

#2 is no longer purely physics - a 'brain' is now involved.
For #1, there is little difference between a human eye and a camera for visible wavelengths.  (Yes, some cameras can sense other wavelengths, but we will ignore that for now, per above.)  Both are sensitive to visible wavelengths, and both translate them down to one brightness or intensity value (three for color).  You can web search for 'wavelength sensitivity of cameras' to prove this to yourself, if you want.
Perhaps the biggest relevant difference is dynamic range - the human eye has much better dynamic range control than a typical camera.  (See this question from photo.stackexchange.com for info.) Cameras are fast approaching the eye's resolution (think pixel count) as well.
With wavelength filtering, apertures, ND filtering (etc), a camera could be created with almost identical wavelength and brightness response to a human eye. For all intents and purposes, the signal measured by such a camera is the same as measured by the human eye.  In that case, it doesn't matter what the material is - the human eye sensor or the camera sensor would register an equivalent measurement under the same conditions.  Even a typical camera without these extra properties responds similarly enough to a human eye; that's the point of the camera, after all.  :)
If you just wanted the answer to #1 (this being Physics), you can stop here.
For #2, now that we have established that input devices (human eye or image sensor) have basically equivalent responses, we now shift focus from the input devices to the processors that evaluate the data (brain or software algorithm).  Here is where we leave pure Physics.  That said, the brain is controlling the inputs that are relevant to #1. For example, a brain will dynamically adjusting aperture size based on signal input.  (Even eyes can overexpose.)
If there is some software trying to "see" your proposed material, it's probably trying to distinguish things inside its field of view from either a 'background', or from other things.  You could in principle design a material to confuse this algorithm, if you knew how the algorithm worked.
That said, human brains are highly adaptable - they can learn new algorithms.  If you allowed the brain of your camera to do this as well, then the answer is still no, as the same logic a human brain learned to identify a material could be encoded into an algorithm for the camera.
It's up to you how far you want to take this thought experiment, such as what limits you want to set up for the human (eye + brain) and/or the camera (sensor + software).  To me, the comparison should be 'pure' and 'fair', where the non-human system has similar specifications (resolution, dynamic range, even a brain system that can learn), so I would still answer "no".


text:
Q: Why can't I disable landscape view in Xcode 6 project? When I click the Landscape checkboxes below to remove them, Xcode (version 6.1.1) just turns them back on. If I go to the Info tab and remove the landscape displays from the arrays there, it just puts them back. The project file is not write protected.

A: Check if the info.plist file is writable.
Open your app's info.plist file.
Find the "Supported interface orientations" entry.
Click the minus button on the entry for the orientation you want to remove.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Eclipse / PyDev running a pyramid development.ini issue "pkg_resources.DistributionNotFound:" I'm starting out with the Pyramid framework and trying to run this inside of Eclipse.
My run configuration is:
Main Module: /home/ben/env/bin/paster
Program Arguments: serve /home/ben/dev/python/pyramid/firstPyramid/first/development.ini
This virtualenv paster will serve development.ini fine from the command line. However, running this in eclipse gives:
[Invalid file specified for console output: ]
Traceback (most recent call last):
  File "/home/ben/env/bin/paster", line 8, in <module>
    load_entry_point('PasteScript==1.7.3', 'console_scripts', 'paster')()
  File "/home/ben/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/command.py", line 84, in run
    invoke(command, command_name, options, args[1:])
  File "/home/ben/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/command.py", line 123, in invoke
    exit_code = runner.run(args)
  File "/home/ben/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/command.py", line 218, in run
    result = self.command()
  File "/home/ben/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/serve.py", line 276, in command
    relative_to=base, global_conf=vars)
  File "/home/ben/env/lib/python2.6/site-packages/PasteScript-1.7.3-py2.6.egg/paste/script/serve.py", line 313, in loadapp
    **kw)
  File "/home/ben/env/lib/python2.6/site-packages/PasteDeploy-1.3.4-py2.6.egg/paste/deploy/loadwsgi.py", line 203, in loadapp
    return loadobj(APP, uri, name=name, **kw)
  File "/home/ben/env/lib/python2.6/site-packages/PasteDeploy-1.3.4-py2.6.egg/paste/deploy/loadwsgi.py", line 223, in loadobj
    global_conf=global_conf)
  File "/home/ben/env/lib/python2.6/site-packages/PasteDeploy-1.3.4-py2.6.egg/paste/deploy/loadwsgi.py", line 247, in loadcontext
    global_conf=global_conf)
  File "/home/ben/env/lib/python2.6/site-packages/PasteDeploy-1.3.4-py2.6.egg/paste/deploy/loadwsgi.py", line 270, in _loadconfig
    return loader.get_context(object_type, name, global_conf)
  File "/home/ben/env/lib/python2.6/site-packages/PasteDeploy-1.3.4-py2.6.egg/paste/deploy/loadwsgi.py", line 397, in get_context
    global_additions=global_additions)
  File "/home/ben/env/lib/python2.6/site-packages/PasteDeploy-1.3.4-py2.6.egg/paste/deploy/loadwsgi.py", line 492, in _pipeline_app_context
    APP, pipeline[-1], global_conf)
  File "/home/ben/env/lib/python2.6/site-packages/PasteDeploy-1.3.4-py2.6.egg/paste/deploy/loadwsgi.py", line 401, in get_context
    section)
  File "/home/ben/env/lib/python2.6/site-packages/PasteDeploy-1.3.4-py2.6.egg/paste/deploy/loadwsgi.py", line 423, in _context_from_use
    object_type, name=use, global_conf=global_conf)
  File "/home/ben/env/lib/python2.6/site-packages/PasteDeploy-1.3.4-py2.6.egg/paste/deploy/loadwsgi.py", line 353, in get_context
    global_conf=global_conf)
  File "/home/ben/env/lib/python2.6/site-packages/PasteDeploy-1.3.4-py2.6.egg/paste/deploy/loadwsgi.py", line 247, in loadcontext
    global_conf=global_conf)
  File "/home/ben/env/lib/python2.6/site-packages/PasteDeploy-1.3.4-py2.6.egg/paste/deploy/loadwsgi.py", line 277, in _loadegg
    return loader.get_context(object_type, name, global_conf)
  File "/home/ben/env/lib/python2.6/site-packages/PasteDeploy-1.3.4-py2.6.egg/paste/deploy/loadwsgi.py", line 553, in get_context
    object_type, name=name)
  File "/home/ben/env/lib/python2.6/site-packages/PasteDeploy-1.3.4-py2.6.egg/paste/deploy/loadwsgi.py", line 573, in find_egg_entry_point
    pkg_resources.require(self.spec)
  File "/home/ben/env/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg/pkg_resources.py", line 666, in require
  File "/home/ben/env/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg/pkg_resources.py", line 565, in resolve
pkg_resources.DistributionNotFound: MyProject

I also have PyDev using the python interpreter of the virtualenv setup.
Any ideas what may be the issue?
Here is a screenshot:

A: I fixed this by changing the PYHTONPATH property in pydev to also use env/bin.


text:
Q: Associative arrays python soap client I am new to python coding .I have done a soap client program in php but now i want to convert it in python
I am stuck at this point
$result = $client->GetLastData(array('Id' => array($id)));

How can i convert this set of code from php to python.
Can any one please tell me is there an way to pass an  associative arrays in python
Thanks in advance

A: There is nothing special you really have to do. If you have an associative array like this (In Python called a dictionary):
a = {
    "id": [1234567, 55555, 4444444]
}

And you want to pass your dictionary (associative array) the way you are trying to do in your example, you just need to do this:
GetLastData(a)

If you are looking to pass specific data from your associative array / dictionary, then you can do this:
GetLastData(a.get("id"))

or
GetLastData(a["id"])

I would suggest using get as the default return will be None if the "id" key is not found. If you access with the "square brackets", it would throw a key error, and you would have to handle accordingly.


text:
Q: Spring SOAP merging .xsd files I have two .xsd files in my web service, I will write them down here, my goal is to have instead of two, one xsd file and still have the same functionality(so that I can have only one wsdl), I have tried to search here and in goolge for similar problems but could not find any, maybe i am writing the problem wrong :/
File 1 and 2:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:tns="http://www.org.com/action"
    targetNamespace="http://www.org.com/action" elementFormDefault="qualified">

    <xs:element name="getActionRequest">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Username" type="xs:string"/>
                <xs:element name="Password" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:element name="getActionResponse">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Code" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

</xs:schema>

    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:tns="http://www.org.com/validate"
        targetNamespace="http://www.org.com/validate" elementFormDefault="qualified">

        <xs:element name="getValidateRequest">
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="Username" type="xs:string"/>
                    <xs:element name="Password" type="xs:string"/>
                    <xs:element name="Value" type="xs:int"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>

        <xs:element name="getValidateResponse">
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="Code" type="xs:string"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>

    </xs:schema>

A: That should work:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:tns="http://www.org.com/action"
    targetNamespace="http://www.org.com/action"
    elementFormDefault="qualified">

<xs:element name="getActionRequest">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="Username" type="xs:string"/>
            <xs:element name="Password" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

<xs:element name="getActionResponse">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="Code" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>
<xs:element name="getValidateRequest">
    <xs:complexType>
        <xs:sequence>
           <xs:element name="Username" type="xs:string"/>
           <xs:element name="Password" type="xs:string"/>
           <xs:element name="Value" type="xs:int"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

<xs:element name="getValidateResponse">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="Code" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>
</xs:schema>


text:
Q: Specifying object property in dot notation with a variable Is it possible to access a property/method on a Python object with a variable and how?
Example:
handler.request.GET.add()

I'd like to replace the 'GET' part by capturing the method beforehand into a variable and then using it in the dot notation.
method = handler.method
handler.request.{method}.add()

I just can't see where/how to do that.

A: Use the getattr() function to access dynamic attributes:
method = 'GET'
getattr(handler.request, method).add()

which would do exactly the same thing as handler.request.GET.add().

A: You are looking for getattr:
getattr(handler.request, 'GET') is the same as handler.request.GET.
So you can do
method = "GET"
getattr(handler.request, method).add()

A: You could do something like getattr
getattr(handler.request, "GET").add()

Then just do
method = "GET" # or "POST"
getattr(handler.request, method).add()


text:
Q: How do I identify out the global Rails settings in a custom COP? My cop:
# lib/rubocop/cop/myproject/my_cop.rb

require 'rubocop'

module RuboCop
  module Cop
    module MyProject
      class MyCop < RuboCop::Cop::Cop
        # ...
      end
    end
  end
end

This cop needs to know some global settings Rails. For example, Rails.logger.log_level
But I get errors:
1) undefined method 'logger' for RuboCop::Cop::Rails:Module - when I call Rails.logger.log_level
2) uninitialized constant Rails - when I call ::Rails.logger.log_level
Can this be done or is it a stupid idea?

A: Rubocop is a static code analyzer. Which means when you run rubocop command, it does not load any ruby environments, including Rails. It just reads ruby files and analyses those as text files.
So the short answer is: no, it can not be achieved with Rubocop.

A: As an option you can do:
# lib/rubocop/cop/myproject/my_cop.rb

require 'rubocop'
require_relative '../../../../../config/environment'

module RuboCop
  module Cop
    module MyProject
      class MyCop < RuboCop::Cop::Cop
        # ...
      end
    end
  end
end

And call ::Rails.logger.level


text:
Q: not getting success when using retryWhen I want to receive success after successful retry. Here's my minimal working example:
        var i = 0

        Observable.just(i)
            .flatMapSingle {
                println(i)
                i++
                when {
                    it < 3 -> Single.error(Exception())
                    else -> Single.just(it)
                }
            }
            .retryWhen { errorObservable -> errorObservable
                .take(4)
            }
            .subscribe { println("subscribe $i") }

this will subscribe and print 0, subscribe 1. If I uncomment commented lines, I'll get only 0, 1, 2, 3
How do I get successful value in subscribe in given example?


text:
Q: Django 1.9.5 and easy_thumbnails late loading and south I have some problems using django easy thumbnails.
First: Thumbnails doesn't load in first time. This looks like easy_thumbnails doesn't generate thumbnail in a first time. And then all OK.
Second error is

There is no South database module 'south.db.mysql' for your database.
  Please either choose a supported database, check for
  SOUTH_DATABASE_ADAPTER[S] settings, or remove South from
  INSTALLED_APPS.

A: Problem with south was in south in my environment. But removing south doesn't give me some results. Just error:
ImportError: No module named south.db

Then I've reinstall easy_thumbnails and migrations was rewrited on Django migrations:
pip uninstall South
pip uninstall easy_thumbnails
pip install easy_thumbnails


text:
Q: Trouble with having my password fields in phpmyadmin database to be in asterisk How do I set my password field in phpmyadmin database to be in asterisk/hash it?
I've tried MD5 & SHA1 function for the password field but it generate a new password instead of sticking with the password the employee have created. Does anyone have any idea or advice on this?


text:
Q: Unable to scroll video divs in opentok cordova application I am using bootstrap 3.0.2, and have used the example application for the cordova opentok plugin as the beginings of this page...  I have added the 2.2 version of the opentok API for the desktop version, and the same version for the cordova application.
My issue is that if I have four windows of video, connected to the same session, my desktop application, using the 2.2 JS API works by creating the correct divs and I append them to the container div.  All of that works.
But, the Android Cordova app creates the video, and attaches the divs to the page, but if there is more than two screams, then I am unable to see more than two divs, as the underlying divs scroll with the page, but the video itself remains in the same location, one on top of each other, each pushed father down the screen.  In fact, if I attempt to scroll the page, I am watching the "video" background scroll away from the live video.  I thought that if I appended the video container to the "mySubDiv" div tag, then it would scroll based on its container object.  But, apparently it doesn't work like the desktop version.
Some code below.  It is pretty simple, and I will add more if it is needed, but this should be enough for someone who has played with this object in cordova.  If not, just say so.  Thanks.

// JS FILE
function onDeviceReady ()
{

var apiKey    = "MY_KEY";
var sessionId = "MY_SESSION";
var token     = "T1==MY_REALLY_LONG_TOKEN_STRING";

// Very simple OpenTok Code for group video chat
var publisherOptions = {name:"WorkAdvisor", publishVideo: true, insertMode: "after"};
var publisher = TB.initPublisher(apiKey,'myPublisherDiv',publisherOptions,);

videoSession = TB.initSession( apiKey, sessionId );

videoSession.on({
  'streamCreated': function( event ){
      var div = document.createElement('div');
      div.setAttribute('id', 'stream' + event.stream.streamId);
      var oldDiv = document.getElementById('mySubDiv');
      oldDiv.appendChild(div);
      videoSession.subscribe( event.stream, div.id, {subscribeToAudio: false} );
  }
});
    videoSession.connect(token, function(){
    videoSession.publish( publisher );
});

}

A: This is happening because the actual video streams are not actually web elements. Cordova plugin creates a fake div that is a place holder for the video, passes the div position and size into native code, and the native code draws out a video at that position ontop of cordova. During scroll, you can fix this by calling TB.updateViews() to update the native video elements to the position of the web element's new location.


text:
Q: Retrofit, Live Data adapter, make response class wrapper generic? I use the LiveData call adapter for retrofit, adapted from the google sample
public interface ApiService {
    @GET("?schema=1.2&form=cjson&byCategories=liveChannels&range=1-500&count=true")
    LiveData<ApiResponse<Page<Media>>> getChannels();
}

I have to use different endpoints so I want to make the ApiResponse generic.
ApiResponse would be interface or abstract and have different variants from it for all those endpoints;
I dont want to write different LiveData extentions for every class that extends ApiResponse.
I want to do something like:
RetrofitLiveData<R, E extends ApiResponse<R>> extends LiveData<E<R>>

(I know the previous code its not compilable, its just an example for what I want)
and then in retrofit interface I can:
LiveData<Endpoint1ApiResponse<Endpoint1Data>>
LiveData<Endpoint2ApiResponse<Endpoint2Data>>
LiveData<Endpoint3ApiResponse<Endpoint3Data>>

public class LiveDataCallAdapterFactory extends CallAdapter.Factory {

    @Override
    public CallAdapter<?, ?> get(@NonNull Type returnType, @NonNull Annotation[] annotations,
                                 @NonNull Retrofit retrofit) {
        if (getRawType(returnType) != LiveData.class) {
            return null;
        }
        Type observableType = getParameterUpperBound(0, (ParameterizedType) returnType);
        Class<?> rawObservableType = getRawType(observableType);
        if (rawObservableType != ApiResponse.class) {
            throw new IllegalArgumentException("type must be a resource");
        }
        if (! (observableType instanceof ParameterizedType)) {
            throw new IllegalArgumentException("resource must be parameterized");
        }
        Type bodyType = getParameterUpperBound(0, (ParameterizedType) observableType);
        return new LiveDataCallAdapter<>(bodyType);
    }
}

public class LiveDataCallAdapter<R> implements CallAdapter<R, LiveData<ApiResponse<R>>> {
    private final Type responseType;

    public LiveDataCallAdapter(Type responseType) {
        this.responseType = responseType;
    }

    @Override
    public Type responseType() {
        return responseType;
    }

    @Override
    public LiveData<ApiResponse<R>> adapt(@NonNull Call<R> call) {
        return new RetrofitLiveData<R>(call);
    }
}

public class RetrofitLiveData<R> extends LiveData<ApiResponse<R>> {
    private final Call<R> call;

    public RetrofitLiveData(Call<R> call) {
        this.call = call;
    }

    @Override
    protected void onActive() {
        if (!call.isCanceled() && !call.isExecuted()) {
            call.enqueue(callback);
        }
    }

    private final Callback<R> callback = new Callback<R>() {
        @Override
        public void onResponse(@NonNull Call<R> call, @NonNull Response<R> response) {
            postValue(new ApiResponse<>(response));
        }

        @Override
        public void onFailure(@NonNull Call<R> call, @NonNull Throwable t) {
            postValue(new ApiResponse<>(t));
        }
    };

    public void cancel() {
        if (!call.isCanceled()) {
            call.cancel();
        }
    }
}

public class ApiResponse<T> {
    public final int code;
    @Nullable
    public final T body;
    @Nullable
    public final String errorMessage;

    public ApiResponse(Throwable error) {
        code = 500;
        body = null;
        errorMessage = error.getMessage();
    }

    public ApiResponse(Response<T> response) {
        // .......... not important here
    }

    public boolean isSuccessful() {
        return code >= 200 && code < 300;
    }
}

A: You can use these classes for reaching your goal.
1- You need a liveDataWrapper for using it in CallAdapterFactory.if you need other types of events you can add it in NetworkData sealed class and use it in your required section
import android.os.Handler
import android.os.Looper
import androidx.lifecycle.MutableLiveData
import retrofit2.HttpException

    class NetworkLiveData<T> : MutableLiveData<NetworkLiveData.NetworkData<T?>>() {

        private lateinit var observer: NetworkData<T?>.() -> Unit

        internal fun onSuccessResponse(body: T?) {
            val result = NetworkData.Success(body)
            postValue(result)
        }

        fun observeForever(f: NetworkData<T?>.() -> Unit) {
            observer = f
            super.observeForever(f)
        }

        internal fun onResponseHttpException(httpException: HttpException) {
            val result = NetworkData.ErrorResponse<T?>(httpException)
            postValue(result)
        }

        internal fun onFailedRequest(t: Throwable) {
            val result = NetworkData.ErrorRequest<T?>(t)
            postValue(result)
        }

        fun onFinish() {
            Handler(Looper.getMainLooper()).post {
                this.removeObserver(observer)
            }
        }

        sealed class NetworkData<T> {
            data class Success<T>(val value: T) : NetworkData<T>()
            data class ErrorResponse<T>(val httpException: HttpException) : NetworkData<T>()
            data class ErrorRequest<T>(val t: Throwable) : NetworkData<T>()

            fun onSuccess(f: (responseBody: T) -> Unit) {
                if (this is Success) {
                    f.invoke(value)
                }
            }

            fun onHttpException(f: (code: Int, message: String) -> Unit) {
                if (this is ErrorResponse) {
                    f.invoke(httpException.code(), httpException.message())
                }
            }

            fun onConnectionFailed(f: (t: Throwable) -> Unit) {
                if (this is ErrorRequest) {
                    f.invoke(t)
                }
            }
        }
    }

2-You should create a CallAdapterFactory for LiveData
import retrofit2.*
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

class LiveDataCallAdapterFactory private constructor() : CallAdapter.Factory() {
    companion object {
        operator fun invoke() = LiveDataCallAdapterFactory()
    }

    override fun get(
        returnType: Type, annotations: Array<out Annotation>, retrofit: Retrofit
    ): CallAdapter<*, *>? {

        if (getRawType(returnType) != NetworkLiveData::class.java) {
            return null
        }

        if (returnType !is ParameterizedType) {
            throw IllegalStateException(
                "must be parameterized"
            )
        }
        val responseType = getParameterUpperBound(0, returnType)
        return BodyCallAdapter<Any>(responseType)
    }

    private class BodyCallAdapter<T>(
        private val responseType: Type
    ) : CallAdapter<T, NetworkLiveData<T>> {

        override fun responseType() = responseType

        override fun adapt(call: Call<T>): NetworkLiveData<T> {
            val liveData = NetworkLiveData<T>()

            call.enqueue(object : Callback<T> {
                override fun onFailure(call: Call<T>, t: Throwable) {
                    liveData.onFailedRequest(t)
                    liveData.onFinish()
                }

                override fun onResponse(call: Call<T>, response: Response<T>) {
                    if (response.isSuccessful) {
                        liveData.onSuccessResponse(response.body())
                    } else {
                        liveData.onResponseHttpException(HttpException(response))
                    }
                    liveData.onFinish()
                }
            })
            return liveData
        }
    }
}

You can find the complete code with sample in this github repository.


text:
Q: Know if all posts are loaded - tumblr infinite scrolling In a custom Tumblr theme, I'm trying to add a scroll to top link that needs to appear only when all the posts have been loaded(, right after them).
{block:IndexPage}
{block:IfInfinitescrolling}

⤒

{/block:IfInfinitescrolling}
{/block:IndexPage}

If I simply add a nav with the link, it appears on all pages until all posts are loaded - itself getting loaded numerous times.
How can I tell if all the pages have been loaded and then append or show it?
(Using the standard Cody Sherman/ Proto.jp script from http://codysherman.tumblr.com/tools/infinite-scrolling/code.)


text:
Q: Regular expression to check if a string contains certain value in a range of characters I need verify if string contains + in a interval of single quotes.
Example: string str = "'Name + R405'".
But, it may happen that this string has more than one range with these values.
Example: string str = "'Name + R405' + '(Name)'". In this case, the second + has a particular function in my code (it is out of single quotes).
In other words, I need identify only + that are within the single quotes. If have a other way for this, please explain for me.
Update:
Within single quotes (where is the text I need) may contain other single quotes. Therefore, I can not simply do checks to observe the beginning and end of a pair of single quotes.
Update 2:
I have a problem that might be a little complicated. My system has functions that take certain strings, and those strings are manipulated according to certain parameter:

Text in single quotes are not altered / manipulated;
To separate one text from another, is used +;
My string must accept any character (this is a problem, I know).

For example: "'Name' + On + 'Sector'". Strings like this, only have the part "On" manipulated by these methods. However, I have strings like "'Name + Code' + On + 'Sector'" or "'Name'+Code '+ On +'Sector'". The "Name + Code"/"Name'+Code" will not be manipulated. Thus, the methods are "confused" with this kind of text and using the + and single quotes that are within parts of the text should that not be changed. But I can not change the methods, must perform a treatment in the string before calling the methods for them.

A: You can do this by iterating through the characters and keeping track of the single quotes you have seen.
public static bool HasPlusBetweenSingleQuotes(string str)
{
    bool inSingleQuotes = false;
    foreach (char c in str)
    {
        if (c == '\'')
        {
            inSingleQuotes = !inSingleQuotes;
        }
        else if (c == '+' && inSingleQuotes)
        {
            return true;
        }
    }

    return false;
}

If you need the indexes of the plus signs within single quotes you can do the following.
public static IEnumerable<int> PlusBetweenSingleQuotesIndexes(string str)
{
    bool inSingleQuotes = false;
    for(int i=0;i<str.Length;i++)
    {
        if (str[i] == '\'')
        {
            inSingleQuotes = !inSingleQuotes;
        }
        else if (str[i] == '+' && inSingleQuotes)
        {
            yield return i;
        }
    }
}

Note that these methods do not verify that every opening single quote has a closing single quote.
EDIT
If you have delimited quotes you just check if the previous character is the delimiter like \.
public static bool HasPlusBetweenSingleQuotes(string str)
{
    bool inSingleQuotes = false;
    char previous = ' '; // just defaulting to a space.
    foreach (char c in str)
    {
        if (c == '\'' && previous != '\\')
        {
            inSingleQuotes = !inSingleQuotes;
        }
        else if (c == '+' && inSingleQuotes)
        {
            return true;
        }

        previous = c;
    }

    return false;
}

A: I'm not sure if this can be done with a regular expression (It might be possible?). It would be easier just to do this with a loop of characters and track if you are in or outside of quotes.
bool inBlock = false;

foreach(var aChar in string mySentence) {
    //Testing with ascii codes + == +, ' == '
    inBlock = (aChar == "'") ? !inBlock : inBlock;
    if(inBlock && aChar == "+")
         // do stuff here
}

As a note, the code might not work, I didn't test it.

A: Why not invert the logic here and use the "concatenation sequences" as the structure for the pattern? These can be described as a sequence of + or +On+ (with optional spaces) that are in between single quoted (possibly non-balanced) strings. Match the "glue" sequence bookended by a lookbehind for a ' and a lookahead for a ', and you can parse the string into "single quoted strings" and "glue" tokens:
 var strings = new string[]
            {"'Name'+Code '+ On +'Sector'",
             "'Name + R405' + '(Name)'",
             "'Name + Code' + On + 'Sector'",
             "'Name''+'Sector'"
            };

            const string pattern = @"(?<=')(\s*\+\s*|\s*\+\s*On\s*\+\s*)(?=')";

            foreach (string s in strings)
            {
                Console.WriteLine("input:"+s);
                string[] tokens = Regex.Split(s, pattern);
                foreach (string token in tokens)
                {
                    Console.WriteLine("token:->{0}<-", token);
                }
                //tokens.Where((x, i) => i % 2 == 0)  //single quoted strings
                //tokens.Where((x, i) => i % 2 != 0) //glue sequences
            }


text:
Q: How to obtain proper React key for Marker component? When using react-leaflet and rendering e.g. several Marker components from array of latlons, one ends up with e.g.:
latlons.map((lat, lon, i) => <Marker key={i} position={L.latLng(lat, lon)} />

however the key={i} is not a good practice as explained here.
It does not seems react-leaflet provides tools to generate some unique key for a component. In some cases one may use key={lat.toString() + lon.toString()}, however this approach will not work when the Marker should be draggable.

A: Just make a unique string of your choosing.  If you're saving your markers to a database, a good option would be to create a string that includes the primary key value of your marker.  If you need to generate something on the fly you could use the uuid package to generate a unique id.


text:
Q: How do I look for the highest value of something in a txt file using Batch and set it as a value? I downloaded a file using curl and I am tyring to make batch find the highest value "paper-1.19.2-x" of x.
I wrote this code
`
@ECHO off
curl "https://api.papermc.io/v2/projects/paper/versions/1.19.2/builds/" --output builds.txt
setlocal enabledelayedexpansion
For /f %%i in (builds.txt) do (
    for %%x in (paper-1.19.2-*.jar) do (
         set "line=%%~nx"
         set "line=!FN:paper-1.19.2-=!"
         if !line! GTR !max! set max=!line!
))
Echo paper-1.19.2-%max%.jar

I download the file and name it builds.txt then I try to read the file and look for the highest x value. but the output of this is simply
paper-1.19.2-.jar
I think what I am doing incorrectly is not reading the file correctly.
Any help?
edit
the builds.txt that is downloaded by curl is just a json file that i convert into txt, so it basically converts to 1 line txt file
and part of the code from it looks like this
`
{"project_id":"paper","project_name":"Paper","version":"1.19.2","builds":[{"build":112,"time":"2022-08-05T23:08:28.926Z","channel":"default","promoted":false,"changes":[{"commit":"bef2c9d005bdd039f188ee53094a928e76bd8e59","summary":"1.19.2 (#8250)","message":"1.19.2 (#8250)\n\n"}],"downloads":{"application":{"name":"paper-1.19.2-112.jar","sha256":"59e5b07dbffcbceeef15ebbe77ffcc8a56f58fdfcb2d3092be256c32a5c9588d"},"mojang-mappings":{"name":"paper-mojmap-1.19.2-112.jar","sha256":"f743f109522b2a21b290e9e9e8015e2e630ec74d6e7496a6bc31e5af34f2a4bd"}}},{"build":113,"time":"2022-08-06T23:30:43.315Z","channel":"default","promoted":false,"changes":[{"commit":"a15152e96a0c1f8b8f6792f4308e8077e01614d2"

the new batch code is
`
@ECHO off

setlocal EnableExtensions
setlocal EnableDelayedExpansion
curl "https://api.papermc.io/v2/projects/paper/versions/1.19.2/builds/" --output builds.txt
set "MaxNumber=0"
if exist "builds.txt" for /F "tokens=5 delims=-." %%I in ('%SystemRoot%\System32\findstr.exe /R "paper-.*\.jar" "builds.txt"') do if %%I GTR !MaxNumber! set "MaxNumber=%%I"
Echo %MaxNumber%

and it just out puts this
`
05T23:08:28

A: There is a much simpler way to get the same result for your data:
@echo off
setlocal EnableDelayedExpansion

curl "https://api.papermc.io/v2/projects/paper/versions/1.19.2/builds/" --output builds.txt
call :readFile < builds.txt
for /F "delims=." %%a in ("!last:*paper-1.19.2-=!") do echo paper-1.19.2-%%a.jar
goto :EOF

:readFile
set "last=%line%"
set /P "line="
if not errorlevel 1 goto readFile
exit /B

Output:
paper-1.19.2-256.jar

A: Your build.txt doesn't contain any line endings, so it's too big to be processed by a pure batch script.
You need a way to search the file (at best with REGEX). Powershell may provide an elegant solution, but if you are stuck with cmd/batch, you can download jrepl.bat (written by dbenham, a highly reputable member of this community), which is able to use full REGEX in batch:
for /f "delims=" %a in ('^<build.txt jrepl "paper-1.19.2-\d*" "" /match') do set "lastMatch=%%a"
echo %lastMatch%.jar

The REGEX pattern "paper-1.19.2-\d*" looks for any string "paper-1.19.2- followed by any number of digits (the parameter "" ("replacement") is not used, but has to be present for syntax reasons)


text:
Q: Boxplot and plot point side by side in R ggspot2 So I have a dataset (output below), and my goal is to have boxplot and plots side by side.  (see diagram below)
library(tidyverse)
DataSet <- read.csv("filelocation")
ggplot(data = DataSet,
   aes(x = id,
       y = result)) +
geom_boxplot(aes(color = live)) +
facet_wrap( ~ resource, scales = "free_y")

For example with this dataset, c3 would have a boxplot for True, but to the right of it, plot points for False.

dput output:
structure(list(id = c(101L, 101L, 101L, 101L, 102L, 102L, 102L,
102L, 103L, 103L, 103L, 103L, 103L, 103L, 103L, 104L, 104L, 104L,
104L, 104L, 105L, 106L, 106L, 106L, 106L, 106L, 107L, 107L, 107L,
107L, 108L, 108L, 109L, 109L, 109L, 109L, 109L, 109L, 109L, 109L,
109L, 109L), resource = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L), .Label = c("a", "b"), class = "factor"), result = c(2.12,
4.72, 4.17, 5.53, 3.6, 3.31, 3.64, 5.33, 4.32, 5.48, 5.93, 3.4,
3.09, 5.91, 2.93, 1.81, 3.93, 2.22, 4.77, 3.92, 4.08, 3.65, 5.23,
3.74, 4.03, 3.54, 4.29, 4.3, 2.82, 2.89, 5.41, 4.61, 4, 5.92,
1.66, 1.65, 1.91, 2.69, 5.28, 2.24, 3.64, 4.77), live = structure(c(2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L), .Label = c("f", "t"), class = "factor")), class = "data.frame", row.names = c(NA,
-42L))

I'd also ideally like to be able to separate the groups with a dividing line, like in the diagram. I've read some R resources but haven't seen any hint that it can be done.

A: If I understand your question correctly, you want to use a box plot to display TRUE values, and points to display (the few) FALSE values, and you want to divide them up according to the resource.
I am going to use the data which is currently shown in your question, which @Richard Telford has kindly cleaned up.
With facet_wrap()
We are going to use subset() to split your data by the value of live. TRUE rows are plotted using a box plot, and FALSE rows are plotted using points. I used an green and red color for each group respectively, but you may want to change this.
ggplot() +
  geom_boxplot(data = subset(cleanData, live == 't'),
    aes(x = id, y = result, group = resource), color = 'green') +
  geom_point(data = subset(cleanData, live == 'f'),
    aes(x = id, y = result), color = 'red', size = 3) +
  facet_wrap( ~ resource, scales = 'fixed') +
  scale_x_continuous(breaks = c(101:109), minor_breaks = NULL)

Without facet_wrap()
Depending on how you set the scales of the grid, you may end up with a lot of empty space (as we did on the plot above). The code below does not use facet_wrap(), but uses a single plot with a vertical line which approximately divides the a and b values of the resource variable.
ggplot() +
  geom_boxplot(data = subset(so.data, live == 't'),
    aes(x = id, y = result, group = resource), color = 'green') +
  geom_point(data = subset(so.data, live == 'f'),
    aes(x = id, y = result), color = 'red', size = 3) +
  scale_x_continuous(breaks = c(101:109), minor_breaks = NULL) +
  geom_vline(xintercept = 104.15, linetype = 'dashed')

Hopefully this puts you on the track to working out exactly what you wanted.


text:
Q: Connect a Bluetooth keyboard as a game controller to an iPad? Is it possible to connect a Bluetooth keyboard as a game controller to an iPad?

A: Go to settings - accessibility - switch control, then set up switches using external devices and use the keyboard buttons. Then create a recipe and add all the buttons as taps on the screen where the buttons are located. To make it easier, set the preset recipe as your controls, and when you triple press the home button it will turn on the keyboard taps.

A: You can jailbreak and then use the Cydia app controllers for all.


text:
Q: Select function based only on month and year I have a column in the MySQL database that stores data as Date 17-6-2021 for example
the user choose a month and year from input fields as follow
<form method="POST">

          choose month
          <input name="month">

          choose year
          <input name="year">

    <input type="submit" name="add1" value="submit">
</form>

I want to compare the date chosen by the user with dates stored in the database to get all values within the month and the year
what function should I use??
my purpose here is to generate a monthly report based on user choices


text:
Q: Как проверить существует ли значение в массиве объектов Всем привет. Подвис на такой проблеме. Есть следующая структура
array  из 3х  объектов Post. Post имеет свойство date,которое в свою очередь есть коллекцией  Datatime. Как проверить содержится ли определенная дата в в данной структуре?

A: Если "есть коллекцией" является, например, ArrayCollection, то можно так:
$searchValue = new DateTime();
$searchValue->setTime(0,0,0);

$founded = array_filter($postArray, static function ($post) use ($searchValue) {
    return !$post->date->filter(static function ($date) use ($searchValue) {
        // Для простого сравнения даты используем '=='
        // можете применить другой алгоритм сравнения, который вернет true или false
        return $date == $searchValue;
    })->isEmpty();
});

if(count($founded) > 0) {
    // искомое значение содержится в структуре
}


text:
Q: Make an image's background transparent or white programmatically If one is creating an application in which one would like to make the "background" of an image transparent or white, is there a way to do this?
For example :
In the image,  http://upload.wikimedia.org/wikipedia/commons/b/b9/Bronze_Statuette_of_a_Veiled_and_Masked_Dancer_1.jpg , I would like to transform the image programmatically, such that only the statue remains, and the background (i.e. the rest of the image) is all white, or transparent.
Also, the user might point out to the part of the image that should "remain", and the rest should be all white or transparent.
How can this be done? Also, if there is a suitable java library or piece of code, it would be helpful.
Regards

A: What you're asking for is programmatic segmentation of foreground and background.  As this is an active research area, you're unlikely to find any ready-mode source code that works out of the box (especially in Java).
If you have the time, look up image segmentation and browse through relevant papers on Google Scholar.  You will see that in the general case, it's not an easy problem for a computer to solve.  In specific cases, you can try to take advantage of certain conditions.  In the image you've specified, the background is really blurry, so the edges of the figure really stand out well.  Edge detection with the Canny operator gives you this:

It's not perfect, but it's a start.  Using the edge information, you can locate major external contours and extract the dancer figure.

A: For that particular image there are several methods that could solve part of the problem. Maybe if you combine several methods and offer the user interactive choices you could develop a good software in a reasonably short period of time. I'd use it!
You and Misha already discussed the first two items:

*

*Edge detection using Canny or other means. I would suggest that you should work on a "raw" edge strength image rather than thresholding the edge strengths to generate a binarized image. Note that in this case the figure is in sharp focus, and much of the background is out of focus. Although it's not a general solution, for this particular image you could filter out edges that (a) belong to lines (using Hough or RANSAC) but that (b) have gradients that fall below a threshold steepness.

*Flood fill. Misha already provided the link. Flood filling a "static" value shouldn't be too hard to implement (e.g. fill all neighboring pixels of value +/- N relative to the clicked pixel). Implementing a dynamic flood fill that could account for gradients due to lighting and 3D curvature into account is, well . . . ouch!

*Mean shift clustering. This might work even as a first step to help clump together pixels of the same HSV values. Just eyeballing the image, though, the hue of the foreground figure and the hue of most of the background is similar. OpenCV has an implementation of mean shift. There's a video of the related CAMSHIFT algorithm at work: http://www.youtube.com/watch?v=iBOlbs8i7Og

*Edge following for strong edges. If the user clicks close to an edge, you identify the closest strong edge and then use a contour-following (or "contour tracing") algorithm. Basic contour-following algorithms work on binary images; you could adapt your algorithm to try to follow a strong edge in RGB space. Tricky!

*Since you're writing software for a user, devote some of your time to software usability rather than just trying to solve the general image processing problem.

*Check for occlusion of background curves. Another way to determine if an item is part of the background is to determine if it is occluded (hidden) by a foreground object. If you find two line segments that are colinear and have gentle gradients (i.e. they're out of focus), then they may be two line segments rather than one because they are occluded by a foreground object.

*If by any chance you can work with a camera rather than existing images, you can mimic a "light field" or plenoptic camera (such as the Lytro https://www.lytro.com/camera) by taking multiple successive images at different focus settings. This can help you identify figures at different depths based on changes in gradients. If the statue is relatively close to the camera, it will go out of focus as the camera focuses towards infinity.

Improving usability

*

*Assuming you can segment the image into chunks that are reasonably distinct, prompt the user to click on chunks that belong to the same object of interest. Each chunk could have its own set of tweaking parameters for edge strength, acceptance range for color, etc. Having chunk-specific parameters can help make the software usable even if there are shadows, varying lighting, etc., that present problems for segmentation. Something like this can be done in GIMP and Photoshop by combining selections, but it's less usable than it could be.

*For the chunks that have been identified, implement a "snap to edge" feature that helps the user moves the discovered edge curve onto the true edge curve. If the user grabs a chunk contour and drags it in one direction, the contour could snap to the next strong edge in that direction.

*Offer a batch processing option. If a user has a series of photos taken under the same conditions, then the user-selected chunks for the first image could help guide the software in setting parameters for successive images. This isn't intended to solve the general segmentation problem, but might save the user a bit of time and effort for certain groups of images.
It's a fun problem. Good luck!


text:
Q: I want to show data which got from a php file to all tab pages by using 'storage event' I want that when I click on logout, ck() function will be fired and there is an ajax method. By ajax method I have send some data to object.php file. After success all process I will get I got It string. Now I want that when this data I will get, 'storage' event will execute and I got It will show all index.php tab pages at a times without any refresh or click again logout. I am very very sorry for my poor English. It is my first question.
index.php:

logout

object.php
<?php
if(isset($_GET['mt']) && $_GET['mt']=="thx"){
    echo "I got It";
}
?>


text:
Q: Deallocking an object that contains a block First of all (and since this question has to do with memory management), I have to say I'm running on ARC.
I have an object (MyObject) which contains an array of MyProcess objects. MyObject, at a certain point, creates a new MyProcess, adds it to the array, gives it a completion handler in the form of a block, and then tells the process to start.
MyProcess* newProcess = [MyProcess new];

[allProcessesArray addObject: newProcess];

newProcess.completionBlock = ^(MyProcess* process){
    [allProcessesArray removeObject: process];
    // Other things are done here
};

[newProcess start];

Now, on MyProcess side of things, when start is called, MyProcess internally calls threadedStart (that runs on a background thread) which does its work and then calls the block when finished:
- (void)threadedStart
{
    // Do something

    dispatch_async(dispatch_get_main_queue(), ^{ self.completionBlock(self); });
}

The completion block is defined as a property in the interface of MyProcess in this way:
typedef void(^MyCallbackBlock)(MyProcess* process);
@property (strong) MyCallbackBlock completionBlock;

Now, MyProcess is only kept alive during its lifetime by allProcessesArray, since that array is the only object that has a reference to the process. When on the completion block I remove the process from the array, I reckon the process is immediately deallocked. Then, since the process contains the block itself, the block gets deallocked as well while it is still running!
I would expect this to cause problems, but I've tested this code and the block runs fine until the end. Now, there are two options: either my reasoning is wrong and this code is perfectly safe, or I'm right (or at least partially right) and this isn't safe as it only works sometimes.
Basically, my question is: is this approach to a callback block safe? And if not, can you suggest something different?

A: For your block property, it should be a copy, not a strong. Blocks should always be copied.
@property (copy) MyCallbackBlock completionBlock;

Whether running your block causes problems is based on what code is run and how the variables that it uses are defined.
Inside your block, because of the way myProcess is defined outside of the block, it's retained inside the block. So, when you remove it from the array it is still being retained until the end of the block.
Technically this could be classed as a form of retain cycle, but it works for you because of its structure.
The block itself can't be "dealloc'd" while it's running.

For your updated code, the instance is now (and probably was before, I just didn't look) retained by the call to the block (because it is supplied as a parameter). Again, the instance will be retained until the end of the block execution.


text:
Q: Why should I be interested in Lua? I have been using LuaLaTex since I got acquainted with TeX, because it can easily work with system fonts, which I really need.  Font packages in TeX are not friends of the Russian language, though they are friends of the Lua language.
I have found some examples here: What is a simple example of something you can do with LuaTeX?, but I still do not fully understand what can Lua do.
So, my questions are the following:

*

*Was Lua specially designed for TeX, or it is just a programming language that can be implemented in TeX? Answer: It is just a programming language, not specific to TeX.

*How can it be used in typesetting? Can it somehow substitute any packages?

*Is it OS dependent, i. e. is there anything specific while using it on Windows?

*Can it work with non-latin characters? Answer: YES.

A: As an example of what can be done with LuaLaTeX, I created a script that automatically converts CSV data into the LaTeX tabular or matrix format. It is quite useful for lab reports since the user no longer has to worry about manually updating data or simulation results in the TeX file.
https://gist.github.com/calebreister/8dd7ab503c91dea4dd2c499b9d004231

A: You asked, inter alia:

What for can [Lua] be used in typesetting? Can it somehow substitute any packages?

*

*Some typesetting tasks can be achieved only in LuaTeX, but not pdfTeX or XeTeX. We're starting to see more and more packages that require LuaLaTeX to accomplish their objectives; these packages simply couldn't have been written at all in pdfLaTeX or XeLaTeX. Examples are the showhyphens and selnolig packages. (Full disclosure: I'm the main author of the selnolig package.)

*Some typesetting tasks can be accomplished more easily (or, at least, with no more work) in LuaLaTeX than in either pdfLaTeX or XeLaTeX. Compare, for instance, the following two code chunks (from the posting Arithmetic temporaries in tex). In both cases, the macro \StrMid serves to extract a substring from a string:
\usepackage{luacode} % for "\luastring" macro
\newcommand\StrMid[3]{\directlua{tex.sprint(string.sub(\luastring{#1},#2,#3))}}

versus
\usepackage{xparse}
\ExplSyntaxOn
\NewExpandableDocumentCommand{\StrMid}{mmm}
 {
  \tl_map_function:fN { \tl_range:onn { #1 } { #2 } { #3 } } \use:n
 }
\cs_generate_variant:Nn \tl_map_function:nN { f }
\cs_generate_variant:Nn \tl_range:nnn { o }
\ExplSyntaxOff

By contrasting these two chunks of code, I certainly do not mean to slight the author of the LaTeX3 code. Not at all! All I mean to do is to show that some tasks can be rather easy to accomplish if one knows even just a little bit of Lua. This is especially true when it comes to manipulating strings, as Lua provides quite a few powerful string-handling functions.

*If you're used to working with a modern programming language but haven't ever fully mastered all the fine points of a macro expansion language -- I myself must plead guilty to just this charge... -- you'll probably find it much easier to program some non-trivial typesetting tasks by using Lua code and the clear interface between Lua and TeX that's built into LuaTeX.

A: Lua is a programming language designed to run in a small easily embedded virtual machine (much smaller than the Java JVM for example) and so ideal for embedding in other systems (it is used as the configuration language for several games for example).
So it is not developed by the luatex people (in fact Lua itself is currently at at least at version 5.3, ahead of the Lua 5.2 version shipped with luatex) but chosen as a suitable extension language.
It can be used to re-implement several of the built in TeX algorithms
It's more or less OS independent
Yes as you see in Luatex it can handle Unicode fonts and Unicode strings (Unicode strings are exposed as UTF-8 encoding so a single unit is a byte rather than a character)


text:
Q: Введение URL c текстового поля Есть текстовое поле tf1 и есть строка кода
NSURLRequest *request=[NSURLRequest requestWithURL:NSURL URLWithString:@"qwe"]
               cashePolicy:NSURLRequestUseProtocolCashePolicy timeoutInterval:15.0];

Как сделать, чтобы вместо qwe там было то что ввел пользователь в tf1? Заранее спасибо.
A: NSURLRequest *req = [NSURLRequest requestWithURL:
                                             [NSURL URLWithString: [tf1 stringValue]]
                                     cashePolicy: NSURLRequestUseProtocolCashePolicy
                                 timeoutInterval: 15.0];


text:
Q: WPF animation only moves in one direction I have a series of triggers for controlling a bar that is supposed to move up and down. Each time it is given one of these randomly selected values, it slides into the appropriate position:
<Trigger Property="Content" Value="B000">
    <Trigger.EnterActions>
        <BeginStoryboard Name="B000" HandoffBehavior="SnapshotAndReplace">
            <Storyboard FillBehavior="HoldEnd" Duration="0:0:1">
                <DoubleAnimation Storyboard.TargetName="bar1" Storyboard.TargetProperty="Offset" To="0" Duration="0:0:1" BeginTime="0:0:0" />
                <DoubleAnimation Storyboard.TargetName="bar2" Storyboard.TargetProperty="Offset" To="0" Duration="0:0:1" BeginTime="0:0:0" />
            </Storyboard>
        </BeginStoryboard>
    </Trigger.EnterActions>
</Trigger>
<Trigger Property="Content" Value="B125">
    <Trigger.EnterActions>
        <BeginStoryboard Name="B125" HandoffBehavior="SnapshotAndReplace">
            <Storyboard FillBehavior="HoldEnd" Duration="0:0:1">
                <DoubleAnimation Storyboard.TargetName="bar1" Storyboard.TargetProperty="Offset" To=".125" Duration="0:0:1" BeginTime="0:0:0" />
                <DoubleAnimation Storyboard.TargetName="bar2" Storyboard.TargetProperty="Offset" To=".125" Duration="0:0:1" BeginTime="0:0:0" />
            </Storyboard>
        </BeginStoryboard>
    </Trigger.EnterActions>
</Trigger>
<Trigger Property="Content" Value="B250">
    <Trigger.EnterActions>
        <BeginStoryboard Name="B250" HandoffBehavior="SnapshotAndReplace">
            <Storyboard FillBehavior="HoldEnd" Duration="0:0:1">
                <DoubleAnimation Storyboard.TargetName="bar1" Storyboard.TargetProperty="Offset" To=".25" Duration="0:0:1" BeginTime="0:0:0" />
                <DoubleAnimation Storyboard.TargetName="bar2" Storyboard.TargetProperty="Offset" To=".25" Duration="0:0:1" BeginTime="0:0:0" />
            </Storyboard>
        </BeginStoryboard>
    </Trigger.EnterActions>
</Trigger>
<Trigger Property="Content" Value="B500">
    <Trigger.EnterActions>
        <BeginStoryboard Name="B500" HandoffBehavior="SnapshotAndReplace">
            <Storyboard FillBehavior="HoldEnd" Duration="0:0:1">
                <DoubleAnimation Storyboard.TargetName="bar1" Storyboard.TargetProperty="Offset" To=".5" Duration="0:0:1" BeginTime="0:0:0" />
                <DoubleAnimation Storyboard.TargetName="bar2" Storyboard.TargetProperty="Offset" To=".5" Duration="0:0:1" BeginTime="0:0:0" />
            </Storyboard>
        </BeginStoryboard>
    </Trigger.EnterActions>
</Trigger>
<Trigger Property="Content" Value="B750">
    <Trigger.EnterActions>
        <BeginStoryboard Name="B750" HandoffBehavior="SnapshotAndReplace">
            <Storyboard FillBehavior="HoldEnd" Duration="0:0:1">
                <DoubleAnimation Storyboard.TargetName="bar1" Storyboard.TargetProperty="Offset" To=".75" Duration="0:0:1" BeginTime="0:0:0" />
                <DoubleAnimation Storyboard.TargetName="bar2" Storyboard.TargetProperty="Offset" To=".75" Duration="0:0:1" BeginTime="0:0:0" />
            </Storyboard>
        </BeginStoryboard>
    </Trigger.EnterActions>
</Trigger>
<Trigger Property="Content" Value="B1k0">
    <Trigger.EnterActions>
        <BeginStoryboard Name="B1k0" HandoffBehavior="SnapshotAndReplace">
            <Storyboard FillBehavior="HoldEnd" Duration="0:0:1">
                <DoubleAnimation Storyboard.TargetName="bar1" Storyboard.TargetProperty="Offset" To="1" Duration="0:0:1" BeginTime="0:0:0" />
                <DoubleAnimation Storyboard.TargetName="bar2" Storyboard.TargetProperty="Offset" To="1" Duration="0:0:1" BeginTime="0:0:0" />
            </Storyboard>
        </BeginStoryboard>
    </Trigger.EnterActions>
</Trigger>

But for some reason, it only ever moves up. The parts where it's supposed to move down again, it just sits there. Stopping the animation between changes only causes it to begin again from the bottom, and that's not what I want.

A: I am not sure what you mean with going down lol but every animation/trigger has EnterAction and ExitAction.
To me it sounds like you are seeking for ExitAction which will allow you to move that thingy back to its start position. :)
Take a look at this link:
http://msdn.microsoft.com/en-us/library/system.windows.triggerbase.exitactions%28v=vs.110%29.aspx
Here is an example :
<Style x:Key="PropertyTriggerExampleButtonStyle" TargetType="{x:Type Button}">

  <Setter Property="Opacity" Value="0.25" />

  <Style.Triggers>
    <Trigger Property="IsMouseOver" Value="True">

      <Trigger.EnterActions>
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation Storyboard.TargetProperty="Opacity"
              To="1" Duration="0:0:1" />
          </Storyboard>
        </BeginStoryboard>
      </Trigger.EnterActions>
      <Trigger.ExitActions>
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation Storyboard.TargetProperty="Opacity"
              To="0.25" Duration="0:0:1" />
          </Storyboard>
        </BeginStoryboard>
      </Trigger.ExitActions>
    </Trigger>
  </Style.Triggers>
</Style>

Edit:
Then you need to have multiple DoubleAnimations like this:
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation .... />
            <DoubleAnimation ... />
            <DoubleAnimation ... />
            <DoubleAnimation ... />
          </Storyboard>
        </BeginStoryboard>


text:
Q: Microcontroller PIC32MX If we are powering our PIC32 with a USB, why do we also need Vcc from an external power supply to provide to PIN8.
In my circuit I am powering the PIC32 with a USB, but when I check the value of voltage at the pin 8, it shows 0V. Shouldn't it show 3.3V ?

A: The VDD/VSS (VCC/GND) pins must be connected for the chip to work. These pins are not internally connected with each other in most cases, and they power different parts of the logic inside the chip (peripherals).
Take a look at the data sheet, this is for the PIC23MX5XX/6XX/7XX but they are the same for all PIC32MX families:

You must also use decoupling capacitors:

And here is the recommended minimum connections:

Additionally, you need to provide the chip with 3.3V only, so you need to use a voltage regulator to translate the 5V from USB to 3.3V for the power pins.
Pay special attention to I/O especially if it is powered via a different source. If you inject 3.3V into a 3.3V pin, you will burn out the chip when it is not powered. You can provide up to 3.2V into a 5V tolerant pin without burning it out, but any more than that will cause damage.
VBUS pin is an input that monitors the USB bus power, it does not power the chip. VUSB3v3 is a transciever supply, and should be connected to VDD if USB is not used, however do not provide more than 3.3V into this pin (as the name implies).


text:
Q: How to break out of Next/React import hell? After using Vue and Nuxt for more than a year, I decided to learn React and Next.js and almost immediately noticed the horrible Developer Experience.
Every stylesheet and component needs to be imported so there's always bloated import hell at the start of each component.
Not to mention if you need an extra library as you can't hook into any global object like Nuxt's this.$plugin option.
Is there some package to manage these imports for Nextjs? As far as I know, everyone who uses it doesn't mind it and that's what surprises me.
This Question may come as an insult to React and it is, but I just want at least one reason to join the hype-train as to why React is more popular.

A: create a file in pages directory named it _doucument.js or _document.ts (for TypeScript) and import React in it like below :
(below codes are TypeScript)
import React from 'react';
import Document, {
    DocumentContext,
    Head,
    Html,
    Main,
    NextScript,
} from 'next/document';

export default class CustomDocument extends Document {
    static async getInitialProps(ctx: DocumentContext) {
        const initialProps = await Document.getInitialProps(ctx);
        return { ...initialProps };
    }

    render() {
        return (
            <Html lang="en">
                <Head>
                    <title>Your title</title>
                </Head>
                <body>
                <Main />
                <NextScript />
                </body>
            </Html>
        );
    }
}

and any more doesn't require that import React in any components.


text:
Q: Store session value in $_post hi i know how to store post value into session but how can i store session value into post.
post into session
   $_SESSION['name'] = $_POST['name'];
   $_SESSION['email'] = $_POST['email'];
   $_SESSION['mno'] = $_POST['mno'];
   $_SESSION['age'] = $_POST['age'];

I have an array stored in session and i want to store it into post.
Can i do this? If yes then how?
I want to store all array value in post from session

A: The opposite should work without any problems.
   $_POST['name'] = $_SESSION['name'];
   $_POST['email'] = $_SESSION['email'];
   $_POST['mno'] = $_SESSION['mno'];
   $_POST['age'] = $_SESSION['age'];

If you want to hold an array you can do it like this:
$datapost = array ( 'name' => $_SESSION['name'], 'email' => $_SESSION['email']);
$_POST['info'] = $datapost;

A: $_POST is not a persistent store where you can put things. The point of $_POST is that it is populated at the start of the request, with the data that was passed to the server from the client (usually, web browser).
You can write into that array, but it won't have any special effect. It's just an array variable that's globally available in all scopes of your code. Normally, you'd just want to create a new array, and assign whatever you want in there:
$data = [];
$data['stored_foo'] = $_SESSION['foo'];
$data['submitted_foo'] = $_POST['foo'];

See also Why are Global Variables Evil?
If you want to send data back to the browser, you can:

*

*put it in the output (using echo etc)

*put it in an HTTP header (using the header() function)

*put it in a cookie (which will be sent as an HTTP header, crafted for you by the setcookie() function)


text:
Q: Where can I find the energy spectrum of larger atoms (e.g. Nd$^{3+}$)? I would like to find a ressource where the binding energies of the outer electrons of larger atoms are listed.
I'm discussing Neodymium lasers and I think it would be nice to have a graphic with all the different energy levels that will be used during the lasing process.
I would ideally have a nice picture similar to this one from Neodymium.

Image source: Hyperphysics, http://hyperphysics.phy-astr.gsu.edu/hbase/quantum/lithium.html, accessed 25. October 2020.

A: The data for levels would be on the NIST database, but I don't know where or how you could generate a chart of levels and transitions as you ask for (except by hand, of course).  The data base does have details of multiply ionized states as well.  To find $\mathrm{Nd}^{3+}$ you would search for "Nd IV", as "ND I" (and "Nd $0$" means the neutral states), and they use roman numerals to increment from that.
The database will also give you a lot of original source references where available, so it's possible some of those could provide graphs.


text:
Q: FB Login button not calling onlogin function I have my fb login button created as so
<fb:login-button perms="email" size="small" onlogin="check_login_session()">Sign Up Using Facebook</fb:login-button>

I have also defined the check_login_session function already as I'm using it on a .click link elsewhere on the page(which does work). However, my problem is when I'm already logged in to FB and I click the button, the FB popup appears, then dissapears and it does nothing. The onlogin is not called nor is any error displayed.
If I was to logout however, and then click the button, it would give me the fb login prompt, and after filled out and submitted would behave as it is supposed to. It's only when I'm already logged in and I click the FB login button that the issue occurs. Any Ideas?
Edit: I found that it does call it if I say put alert("Test") in the onlogin but any function I define on the page and try to call it returns saying it's not defined.

A: I think you want to be notified about a logged in user either after a login happened or of a user comes to teh page and is already logged in. In this case you have to subscribe to the auth event and handle it:
FB.Event.subscribe('auth.authResponseChange', function(response) {
    if (response.status === 'connected') {
//yourcode
    } else if (response.status === 'not_authorized') {
//your code
    } else {
//yourcode
    }
  });

A: The new facebook login flow says to only display the facebook login button if the user is not currently logged into facebook. If you display it anyway, nothing will happen when they click on it because it will detect that the user is already logged into facebook and so will exit the login process and the post login hook won't be called. The facebook documentation says to first detect whether the user is already logged into facebook, and if they are logged in, grab the facebook uid and simply execute the function you would have called as part of the post login hook. The facebook login button is simply that--a button to log into facebook and not a button to log into your site.

A: The event says onlogin, so it will only execute when you login through Facebook Connect.
If you are already logged in on Facebook Connect, then the function won't execute because you're already logged in...?

A: Most likely the function you're trying to call isn't accessible on that page even though you think it should be. Make sure you removed the () after the function's name. The fact that "alert" does work but your function doesn't kind of proves that. Make sure your function can be accessed by the script by making it global and ensuring your script is loaded.

A: The function has to be defined on the window. The solution is:
// somewhere before the button is rendered
window.loginCallback = () => {
    // callback logic
}

    <div
      className="fb-login-button"
      data-max-rows="1"
      data-size="large"
      data-button-type="continue_with"
      data-onlogin="loginCallback();"
    ></div>


text:
Q: Error al importar archivo Js en react vite Hola el error que me sale es el siguiente:
 [plugin:vite:import-analysis] Failed to parse source for import analysis because the content contains
 invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.

Sucede al importar el siguiente archivo
import { programsData } from "../../data/programsData";

Y lo que contiene mi programsData es lo siguiente
export const programsData = [
  {
    image: (
      <svg
        width="16"
        height="15"
        viewBox="0 0 16 15"

        xmlns="http://www.w3.org/2000/svg"
      >

      </svg>
    ),
    heading: "Strength Training",
    details:
      "In this program, you are trained to improve your strength through many exercises.",
  },
];

Mi vite config lo tengo así
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()]
})

No entiendo el error, intente poner una posible solución que mire en internet pero no funciono, lo que intente fue lo siguiente
 resolve: {
    extensions: [
      ".mjs",
      ".js",
      ".ts",
]
}

Alguna idea del porque sucede dicho error y como solucionarlo? gracias


text:
Q: Hit Test WPF 3D Model parts I have a big ModelVisual3D (e.g. car) which is divided into many smaller GeometryModel3D objects (e.g. tyres, seats, wheels, etc.).
I would like to hit test the ModelVisual3D when the mouse is clicked and determine which GeometryModel3D was hit. I can hit test my car (the ModelVisual3D) but cannot determine which part of the car (the GeometryModel3D objects) was clicked.
Does anybody have an idea how I can determine the exact part of my model when handling a MouseLeftButtonDown event (or any other Mouse event)?

A: Have a look at http://www.kindohm.com/technical/ComplexVisuals.htm - I believe the mechanisms explained there will help.

A: This blog post shows how to do ray testing with the framework:
http://blogs.msdn.com/b/wpf3d/archive/2009/05/18/3d-hit-testing.aspx
The result in the callback has detail on the intersected mesh from which you can get the specific part of the mesh which was intersected.


text:
Q: 404 Not Found when access html under subdirectory I can not access pages under tw folder
eg: about.html
I will got this error 404 Not Found
But I can access the index.html page
Nginx conf
server{
    server_name great.com;
    root /www/gp;
    expires off;
    try_files $uri/index.html /dev/null =404;

    location ~* \.(js|jpg|png|css)$ {
        root /www/gp;
        expires 30d;
    }

    location /tw/ {
        autoindex on;
        root /www/gp/tw;
    }

}

Folder structure
.
├── index.html
└── tw
    ├── about.html
    ├── brand01.html
    ├── brand.html
    ├── contact.html
    ├── css
    ├── faq01.html
    ├── faq02.html
    ├── images
    ├── js
    └── news.html

Error log in nginx log
2014/10/31 12:00:15 [error] 12047#0: *6 open() "/www/gp/tw/tw/images/waves.gif" failed (2: No such file or directory), client: 118.163.149.126, server: great-compassion.com, request: "GET /
tw/images/waves.gif HTTP/1.1", host: "www.great-compassion.com", referrer: "http://www.great-compassion.com/tw/css/banner.css"
2014/10/31 12:00:18 [error] 12047#0: *5 open() "/www/gp/tw/tw/brand.html" failed (2: No such file or directory), client: 118.163.149.126, server: great-compassion.com, request: "GET /tw/bra
nd.html HTTP/1.1", host: "www.great-compassion.com", referrer: "http://www.great-compassion.com/"

A: Duplicate root
Just don't redefine root in both locations. As you can see in the error log, /www/gp/tw/tw/brand.html occurs twice. That is to say, a path in location is inclusive, just like the documentation states about root.
location /i/ {
  root /data/w3;
}

The /data/w3/i/top.gif file will be sent in response to the /i/top.gif request.


text:
Q: Saving multiple files using Promise I have a Node URL (created using Express) that can be used to download a static image of an address. So, the calling app calls the /download url and passes multiple addresses using json, then the download service would call Google Maps  and save the static image of each of these addreses on the node server (it would then send it back to the calling application, but for the purpose of this question I am only interested in saving the images in the node server).
Initially, we were only interested in saving satellite view of the addresses, so I wrote this code
var request = require('request');
function saveMap(addressJson) {
    return Promise.all(
        //iterate over address json, get each address, call the Google Maps URL and save it.
        addressJson.map(function(item) {
             return new Promise(function (resolve, reject) {
                 var mapUrl = 'http://maps.googleapis.com/maps/api/staticmap?maptype=roadmap&markers=size:mid|color:red|' + item.address;
                 request(mapUrl)
                     .pipe(fs.createWriteStream('/temp/' + item.id + '.jpg'))
                     .on('finish', function () {
                         resolve("Promise resolved");
                     }).on('error', function (error) {
                         reject('Error in creating map', error);
                     })
             });
        })
    )
}

The Promise for saving each address is wrapped inside Promise.all(..), since I want to the saveMap() to return when all maps have finished downloading (so that I can zip them and send to the calling app, so need to be sure that everything has been downloaded).
Now, we need to extend this function to also include satellite maps. I was hoping, that within same json iteration, I can have another Promise which would download satellite maps. Something like this
function saveMap(addressJson) {
    return Promise.all(
        //iterate over address json, get each address, call the Google Maps URL and save it.
        addressJson.map(function(item) {
             return new Promise(function (resolve, reject) {
                 var mapUrl = 'http://maps.googleapis.com/maps/api/staticmap?maptype=roadmap|' + item.address;
                 request(mapUrl)
                     .pipe(fs.createWriteStream('/temp/r/' + item.id + '.jpg'))
                     .on('finish', function () {
                         resolve("Promise resolved");
                     }).on('error', function (error) {
                         reject('Error in creating map', error);
                     })
             });
             return new Promise(function (resolve, reject) {
                 var mapUrl2 = 'http://maps.googleapis.com/maps/api/staticmap?maptype=satellite|' + item.address;
                 req(mapUrl2)
                     .pipe(fs.createWriteStream(fs.createWriteStream('/temp/s/' + item.id + '.jpg'))
                     .on('finish', function () {
                         resolve("Promised resolved");
                     }).on('error', function (error) {
                         reject('Error in creating map', error);
                     })
             });
        })
    )
}

However, this does not work as expected. I don't get an error but it is not generating all the jpg files. Can someone please help me understand what I am doing wrong and how to get this corrected.

A: I would do :

*

*Generate an Array with all the promises.

*Use one Promise.all() call with the full array of promises

Look how it looks : (Note the use of spread operator to concatenate both arrays) :
function saveMap(addressJson) {
    return Promise.all([
        //iterate over address json, get each address, call the Google Maps URL and save it.
        ...addressJson.map(function(item) {
             return new Promise(function (resolve, reject) {
                 var mapUrl = 'http://maps.googleapis.com/maps/api/staticmap?maptype=roadmap|' + item.address;
                 request(mapUrl)
                     .pipe(fs.createWriteStream('/temp/r/' + item.id + '.jpg'))
                     .on('finish', function () {
                         resolve("Promise resolved");
                     }).on('error', function (error) {
                         reject('Error in creating map', error);
                     })
             })
        }), //End Array#map
        ...addressJson.map(function(item) {
             return new Promise(function (resolve, reject) {
                 var mapUrl = 'http://maps.googleapis.com/maps/api/staticmap?maptype=satellite|' + item.address;
                 req(mapUrl)
                     .pipe(fs.createWriteStream(fs.createWriteStream('/temp/s/' + item.id + '.jpg'))
                     .on('finish', function () {
                         resolve("Promised resolved");
                     }).on('error', function (error) {
                         reject('Error in creating map', error);
                     })
             })
        }), //End Array#map
    ])//End Promise#all
}

EDIT
Okay, You may think there's no need for two iterations, because of Array#reduce :
function saveMap(addressJson) {
    return Promise.all(
        //iterate over address json, get each address, call the Google Maps URL and save it.
        addressJson.reduce(function(array, item) {
          array.push(...[
             new Promise(function (resolve, reject) {
                 var mapUrl = 'http://maps.googleapis.com/maps/api/staticmap?maptype=roadmap|' + item.address;
                 request(mapUrl)
                     .pipe(fs.createWriteStream('/temp/r/' + item.id + '.jpg'))
                     .on('finish', function () {
                         resolve("Promise resolved");
                     }).on('error', function (error) {
                         reject('Error in creating map', error);
                     })
             }),
             new Promise(function (resolve, reject) {
                 var mapUrl = 'http://maps.googleapis.com/maps/api/staticmap?maptype=satellite|' + item.address;
                 req(mapUrl)
                     .pipe(fs.createWriteStream(fs.createWriteStream('/temp/s/' + item.id + '.jpg'))
                     .on('finish', function () {
                         resolve("Promised resolved");
                     }).on('error', function (error) {
                         reject('Error in creating map', error);
                     })
             })
        ]); //Array#push
        return array;
      }, []); //Array#reduce
    ) //End Promise#all
}

DEMOS

var length = 10;
var arr1 = Array.from({length}, (el, i)=> new Promise( re => re(i) ) );
var arr2 = Array.from({length}, (el, i)=> new Promise( re => re(i) ) );

Promise.all([...arr1, ...arr2]).then(console.log.bind(console));

var length = 10;
var arr1 = Array.from({length}, (el, i)=> i );

var finalArr = arr1.reduce((array, item)=>{
  array.push(...[
    new Promise( re => re(item) ),
    new Promise( re => re(item*2) )
  ]);
  return array;
}, []);

Promise.all(finalArr).then(console.log.bind(console));

A: You have two return statements in that code which is why it does not work.
But what you really should start with is to abstract out your promisification of the download:
function download(url, target) {
    return new Promise(function (resolve, reject) {
        request(uUrl).pipe(fs.createWriteStream(target))
        .on('finish', resolve)
        .on('error', reject)
    });
}

Now you can use that twice. For simplicitly, I would not try to iterate your array just once but simply map it twice and concat the results. The alternative would be to concatMap or sequence the promises of each item.
function saveMap(addressJson) {
    var mapUrl = 'http://maps.googleapis.com/maps/api/staticmap?maptype=';
    return Promise.all(addressJson.map(function(item) {
        return download(mapUrl + 'roadmap|' + item.address, '/temp/r/' + item.id + '.jpg');
    }).concat(addressJson.map(function(item) {
        return download(mapUrl + 'satellite|' + item.address, '/temp/s/' + item.id + '.jpg');
    })));
}

A: Just use Promise.all() again:
function saveMap(addressJson) {
    return Promise.all(
        //iterate over address json, get each address, call the Google Maps URL and save it.
        addressJson.map(function(item) {
             return Promise.all([
               new Promise(function (resolve, reject) {
                 var mapUrl = 'http://maps.googleapis.com/maps/api/staticmap?maptype=roadmap|' + item.address;
                 request(mapUrl)
                     .pipe(fs.createWriteStream('/temp/r/' + item.id + '.jpg'))
                     .on('finish', function () {
                         resolve("Promise resolved");
                     }).on('error', function (error) {
                         reject('Error in creating map', error);
                     })
               }),
               new Promise(function (resolve, reject) {
                 var mapUrl2 = 'http://maps.googleapis.com/maps/api/staticmap?maptype=satellite|' + item.address;
                 req(mapUrl2)
                     .pipe(fs.createWriteStream(fs.createWriteStream('/temp/s/' + item.id + '.jpg'))
                     .on('finish', function () {
                         resolve("Promised resolved");
                     }).on('error', function (error) {
                         reject('Error in creating map', error);
                     })
               })
            ]);
        })
    )
}


text:
Q: Removing a dinamically LI inside a UL using button i have a text Area which i am writing text in it and buy pressing enter, the text  is being added to an UL. i am trying to remove the specific dynamically created LI from an UL using a dynamically created button but the function does not working
this is the html code:
<!DOCTYPE html>

    <title>list</title>

    <textarea id="textBox"></textarea>

    <button type="button" onclick=addItem()>Send</button>

and this is the javascript code:
function addItem() {
    var ul = document.getElementById("dynamic-list");
    var candidate = document.getElementById("textBox");
    var li = document.createElement("li");
    li.setAttribute("id", "li");
    var removeBtn = document.createElement("button");
    removeBtn.innerHTML = "remove";
    removeBtn.onClick = function () { this.parentNode.removeChild(this); }
    li.appendChild(document.createTextNode(candidate.value));
    ul.appendChild(li);
    li.appendChild(removeBtn);
    document.getElementById('textBox').value = "";
}

function remove() {
    this.parentNode.removeChild(this);
}
var input = document.getElementById("textBox");
input.addEventListener("keyup", function (event) {
    event.preventDefault();
    if (event.keyCode == 13 && !event.shiftKey && document.getElementById('textBox').value != "") {
        addItem();
        input.text = "";
        if (event.preventDefault) {
            event.preventDefault();
        }
    }
    if (event.keyCode == 13 && event.shiftKey) {
        if (evt.type == "keypress") {
            pasteIntoInput(this, "\n");
        }
        evt.preventDefault();
    }

});

i am clicking the remove button but nothing happens.

A: You can do it like this:

function addItem() {
    var ul = document.getElementById("dynamic-list");
    var candidate = document.getElementById("textBox");
    var li = document.createElement("li");
    li.setAttribute("id", "li");
    var removeBtn = document.createElement("button");
    removeBtn.innerHTML = "remove";
    removeBtn.setAttribute("id", "remove");
    //removeBtn.onClick = function () { this.parentNode.removeChild(this); }
    li.appendChild(document.createTextNode(candidate.value));
    ul.appendChild(li);
    li.appendChild(removeBtn);
    document.getElementById('textBox').value = "";
}

function remove() {
    this.parentNode.removeChild(this);
}
var input = document.getElementById("textBox");
input.addEventListener("keyup", function (event) {
    event.preventDefault();
    if (event.keyCode == 13 && !event.shiftKey && document.getElementById('textBox').value != "") {
        addItem();
        input.text = "";
        if (event.preventDefault) {
            event.preventDefault();
        }
    }
    if (event.keyCode == 13 && event.shiftKey) {
        if (evt.type == "keypress") {
            pasteIntoInput(this, "\n");
        }
        evt.preventDefault();
    }

});

$(document).ready(function () {
        $("body").on("click", "li #remove", function () {
            $(this).parent().remove();
        });
    });
<!DOCTYPE html>

    <title>list</title>

    <textarea id="textBox"></textarea>

    <button type="button" onclick=addItem()>Send</button>

A: Below are the changes you need to be done in your code
Index.html
<!DOCTYPE html>

    <title>list</title>

    <textarea id="textBox"></textarea>

    <button type="button" onclick=addItem()>Send</button>

Scriptt.js
function addItem() {
    var ul = document.getElementById("dynamic-list");
    var candidate = document.getElementById("textBox");
    var li = document.createElement("li");
    li.setAttribute("id", "li");
    var removeBtn = document.createElement("button");
    removeBtn.innerHTML = "remove";
    removeBtn.onclick = remove;
    li.appendChild(document.createTextNode(candidate.value));
    ul.appendChild(li);
    li.appendChild(removeBtn);
    document.getElementById('textBox').value = "";
}

function remove() {
    this.parentNode.parentNode.remove(this.parentNode);
}

var input = document.getElementById("textBox");
input.addEventListener("keyup", function (event) {
    event.preventDefault();
    if (event.keyCode == 13 && !event.shiftKey && document.getElementById('textBox').value != "") {
        addItem();
        input.text = "";
        if (event.preventDefault) {
            event.preventDefault();
        }
    }
    if (event.keyCode == 13 && event.shiftKey) {
        if (evt.type == "keypress") {
            pasteIntoInput(this, "\n");
        }
        evt.preventDefault();
    }

});

By using  removeBtn.onclick = remove, you would register click event on button only instead of entire document.


text:
Q: Base type query in Entity Framework I have a base class inherited by another class:
class Base { }
class Derived : Base { }

Entity Framework stores only instances of derived class. I want to select only columns, corresponding to the fields in base class and return them as IEnumerable<Base>. Is there an easy way to do this?

A: Actually, as soon as Base type is not recognized as entity by EF (because for some reason it does not allow projecting to entity types), you can use the following simple helper from my answer to c# How can I create a collection of custom objects without going through each field:
public static class QueryableExtensions
{
    public static IQueryable<TResult> SelectTo<TResult>(this IQueryable source)
    {
        var sourceType = source.ElementType;
        var resultType = typeof(TResult);
        var parameter = Expression.Parameter(sourceType, "x");
        var bindings =
            from rm in resultType.GetProperties().Concat<MemberInfo>(resultType.GetFields())
            join sm in sourceType.GetProperties().Concat<MemberInfo>(sourceType.GetFields())
                on rm.Name equals sm.Name
            select Expression.Bind(rm, Expression.MakeMemberAccess(parameter, sm));
        var body = Expression.MemberInit(Expression.New(resultType), bindings);
        return source.Provider.CreateQuery<TResult>(Expression.Call(
            typeof(Queryable), "Select", new[] { sourceType, resultType },
            source.Expression, Expression.Quote(Expression.Lambda(body, parameter))));
    }
}

like this:
IQueryable<Derived> yourQuery = ...;
return yourQuery.SelectTo<Base>();


text:
Q: What is the difference between Segment of ConcurrentHashMap and buckets of HashMap theoretically? I understand that in HashMap, the entries (Key, Value) are placed in buckets based on hash(Key.hashCode)--> The index that denotes the bucket location. In case an entry is already placed at that location, there is a linked list created and the new entry (if it has a different key --> via equals() method) is placed at the beginning of the linked list.

*

*Can I co-relate this concept with that of ConcurrentHashMap, but instead of Buckets, there are Segments upon which individual threads have a lock. And instead of Entries, there are HashEntry(ies). In similar fashion, a linked list is created and if the Key-Value pair being inserted is different, based on equals() of the key, it is placed at end of the linked list.

*Am I correct when I say that:
put of CHM is not synchronized, thus any thread can access this method, this put method calculates hash value of the key passed to it and gets the segment index (kind of like buckets). Then for that segment only, it calls the put method. Now under Segment, the put method specifies that there will be a lock(), so that only one thread can alter data in a particular segment, thus concluding that if the concurrency level is 16 there shall be 16 threads and thus these threads will be able to PUT values only one segment at a time.

A: *

*A bucket is an individual slot in the map's array. This is the same with both HashMap and ConcurrentHashMap. Conceptually, the latter has its array broken into segments (each segment is an array of references), but that's it. Note that the CHM in Java 8 no longer has segments, it's all a single array.

*Yes, it's the scheme known as segmented locking. It reduces inter-thread contention, but does not eliminate it.


text:
Q: Index file can not run direct when enter URL in my java website? I am working on a Java project on a webserver. Uploading the .war file goes fine. When I navigate to the site name, for example www.example.com, the website gives me an error; but entering www.example.com/index.jsp works fine. I want the second request to be equivalent to the first.

A: In web.xml you need to specify the following
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

And index.jsp must placed in root context folder


text:
Q: Putting gzipped data into a script as a string I snagged a Lorem Ipsupm generator last week, and I admit, it's pretty cool.
My question: can someone show me a tutorial on how the author of the above script was able to post the contents of a gzipped file into their code as a string? I keep getting examples of gzipping a regular file, and I'm feeling kind of lost here.
For what it's worth, I have another module that is quite similar (it generates random names, companies, etc), and right now it reads from a couple different text files. I like this approach better; it requires one less sub-directory in my project to place data into, and it also presents a new way of doing things for me.
I'm quite new to streams, IO types, and the like. Feel free to dump the links on my lap. Snipptes are always appreciated too.

A: Assuming you are in a *nix environment, you just need gzip and a base64 encoder to generate the string. Lets assume your content is in file.txt, for the purpose of this example I created the file with random bytes with that specific name.
So you need to compress it first:
$ gzip file.txt

That will generate a file.txt.gz  file that you now need to embed into your code. To do that, you need to encode it. A common way to do so is to use Base64 encoding, which can be done with the base64 program:
$ base64 file.txt.gz
H4sICGmHsE8AA2ZpbGUudHh0AAGoAFf/jIMKME+MgnEhgS4vd6SN0zIuVRhsj5fac3Q1EV1EvFJK
fBsw+Ln3ZSX7d5zjBXJR1BUn+b2/S3jHXO9h6KEDx37U7iOvmSf6BMo1gOJEgIsf57yHwUKl7f9+
Beh4kwF+VljN4xjBfdCiXKk0Oc9g/5U/AKR02fRwI+zYlp1ELBVDzFHNsxpjhIT43sBPklXW8L5P
d8Ao3i2tQQPf2JAHRQZYYn3vt0tKg7drVKgAAAA=

Now you have all what you need to use the contents of that file in your python script:
from cStringIO import StringIO
from base64 import b64decode
from gzip import GzipFile

# this is the variable with your file's contents
gzipped_data = """
H4sICGmHsE8AA2ZpbGUudHh0AAGoAFf/jIMKME+MgnEhgS4vd6SN0zIuVRhsj5fac3Q1EV1EvFJK
fBsw+Ln3ZSX7d5zjBXJR1BUn+b2/S3jHXO9h6KEDx37U7iOvmSf6BMo1gOJEgIsf57yHwUKl7f9+
Beh4kwF+VljN4xjBfdCiXKk0Oc9g/5U/AKR02fRwI+zYlp1ELBVDzFHNsxpjhIT43sBPklXW8L5P
d8Ao3i2tQQPf2JAHRQZYYn3vt0tKg7drVKgAAAA=
"""

# we now decode the file's content from the string and unzip it
orig_file_desc = GzipFile(mode='r',
                          fileobj=StringIO(b64decode(gzipped_data)))

# get the original's file content to a variable
orig_file_cont = orig_file_desc.read()

# and close the file descriptor
orig_file_desc.close()

Obviously, your program will depend on the base64, gzip and cStringIO python modules.

A: I'm not sure exactly what you're asking, but here's a stab...
The author of lipsum.py has included the compressed data inline in their code as chunks of Base64 encoded text.  Base64 is an encoding mechanism for representing binary data using printable ASCII characters.  It can be used for including binary data in your Python code.  It is more commonly used to include binary data in email attachments...the next time someone sends you a picture or PDF document, take a look at the raw message and you'll see very much the same thing.
Python's base64 module provides routines for converting between base64 and binary representations of data...and once you have the binary representation of the data, it doesn't really matter how you got, whether it was by reading it from a file or decoding a string embedded in your code.
Python's gzip module can be used to decompress data.  It expects a file-like object...and Python provides the StringIO module to wrap strings in the right set of methods to make them act like files. You can see that in lipsum.py in the following code:
sample_text_file = gzip.GzipFile(mode='rb',
    fileobj=StringIO(base64.b64decode(DEFAULT_SAMPLE_COMPRESSED)))

This is creating a StringIO object containing the binary representation of the base64 encoded value stored in DEFAULT_SAMPLE_COMPRESSED.
All the modules mentioned here are described in the documentation for the Python standard library.
I wouldn't recommend including data in your code inline like this as a good idea in general, unless your data is small and relatively static.  Otherwise, package it up into your Python package which makes it easier to edit and track changes.
Have I answered the right question?

A: How about this: Zips and encodes a string, prints it out encoded, then decodes and unzips it again.
from StringIO import StringIO
import base64
import gzip

contents = 'The quick brown fox jumps over the lazy dog'

zip_text_file = StringIO()

zipper = gzip.GzipFile(mode='wb', fileobj=zip_text_file)

zipper.write(contents)
zipper.close()

enc_text =  base64.b64encode(zip_text_file.getvalue())
print enc_text

sample_text_file = gzip.GzipFile(mode='rb',
    fileobj=StringIO(base64.b64decode(enc_text)))
DEFAULT_SAMPLE = sample_text_file.read()
sample_text_file.close()
print DEFAULT_SAMPLE

A: Old question but I had to do this recent for AWS logs. In Python3 use BytesIO instead of StringIO:
import base64
from io import BytesIO

DEFAULT_SAMPLE_COMPRESSED = "Some base 64 encoded and gzip compressed string"

sample_text_file = gzip.GzipFile(
    mode='rb',
    fileobj=BytesIO(base64.b64decode(DEFAULT_SAMPLE_COMPRESSED))
)

binary_text = sample_text_file.read() # This will be the final string as bianry
text = binary_text .decode() # This will make the binary text a string.


text:
Q: Why the difference between octave's prctile and numpy's percentile? I've been rewriting a matlab/octave program into numpy and ran across a difference in some resultant values.
This occurs with both the percentile/prctile and the stdard-deviation functions.
In Numpy:
import matplotlib.mlab as ml
import numpy

>>> t = numpy.linspace(0,100, 100)
>>> numpy.percentile(t,95)
95.0
>>> numpy.std(t)
29.157646512850626
>>> ml.prctile(t,95)
95.000000000000014

In Octave:
octave:1> t = linspace(0,100,100)';
octave:2> prctile(t,95)
ans =  95.454545
octave:3> std(t)
ans =  29.304537

Although the array values of 't' are the same, the results are more different than I would suspect.
In the numpy help(numpy.std) they specifically mention that the algorithm is:
std = sqrt(mean(abs(x - x.mean())**2))

So I implemented that in octave and got the exact answer numpy gives.  So it seems the std-deviation function differs.
But why/how? And which is correct? (if there is such a thing)
And even prctile/percentile?
Just in case since I'm in Linux aptosid...
GNU Octave, version 3.6.2
numpy.version '1.6.2rc1'

A: Numpy simply uses a different algorithm when the percentile lies between two data points. Octave, Matlab and R always center it exactly between two points when needed (I believe), numpy does a bit more then that... if you check http://en.wikipedia.org/wiki/Percentile you will see there are a couple of ways to calculate percentiles.

A: It seems like Octave assumes ddof=1, at least by default, and numpy uses 0 by default:
>>> numpy.std(t, ddof=0)
29.157646512850633
>>> numpy.std(t, ddof=1)
29.304537349375785


text:
Q: How to decrypt 256-bit AES key with initialization vector and decryption key when the key is 21-22 characters? I am quite new to the field of encryption.
I have an encrypted string that I receive from a website which is AES 256 encrypted. In their return parameters, I am given a dictionary containing the following key-value pairs in a JSON table (pseudo-code):
{
    ct: ciphertext-key (i assume)
    iv: initialization vector
    s: salt
}

All three are strings and the decryption key I receive from another endpoint varies from 21-22 characters in length. I know that AES 256 is usually 16 bits for a decryption key, so this is unusual to me.
So, how do I decrypt the encrypted message given the iv, ct, salt and encryption key (which i assume is the wrong length..?)
Am I doing something wrong? If anybody can help me, I would greatly appreciate your insight into this enquiry.