text:
Q: A Batch script to call virustotal api and add a windows firewall rule if a baddie is detected? Basically, when I connect to any site, it loads not only stuff on that server, but also stuff like background images, scripts, icons, fonts from third party sites. I was wondering if it would be possible to run a virustotal check and block the baddies prior I download them or my browser loads them?

A: You need to use something like this extension VT4Browsers
Scan your downloads with VirusTotal before storing them, free and easy


text:
Q: Global memoizing fetch() to prevent multiple of the same request I have an SPA and for technical reasons I have different elements potentially firing the same fetch() call pretty much at the same time.[1]
Rather than going insane trying to prevent multiple unrelated elements to orchestrate loading of elements, I am thinking about creating a gloabalFetch() call where:

*

*the init argument is serialised (along with the resource parameter) and used as hash

*when a request is made, it's queued and its hash is stored

*when another request comes, and the hash matches (which means it's in-flight), another request will NOT be made, and it will piggy back from the previous one

async function globalFetch(resource, init) {
  const sigObject = { ...init, resource }
  const sig = JSON.stringify(sigObject)

  // If it's already happening, return that one
  if (globalFetch.inFlight[sig]) {

  // NOTE: I know I don't yet have sig.timeStamp, this is just to show
  // the logic
  if (Date.now - sig.timeStamp < 1000 * 5) {
    return globalFetch.inFlight[sig]
  } else {
    delete globalFetch.inFlight[sig]
  }

  const ret = globalFetch.inFlight[sig] = fetch(resource, init)
  return ret
}
globalFetch.inFlight = {}

It's obviously missing a way to have the requests' timestamps. Plus, it's missing a way to delete old requests in batch. Other than that... is this a good way to go about it?
Or, is there something already out there, and I am reinventing the wheel...?
[1] If you are curious, I have several location-aware elements which will reload data independently based on the URL. It's all nice and decoupled, except that it's a little... too decoupled. Nested elements (with partially matching URLs) needing the same data potentially end up making the same request at the same time.

A: Your concept will generally work just fine.
Some thing missing from your implementation:

*

*Failed responses should either not be cached in the first place or removed from the cache when you see the failure.  And failure is not just rejected promises, but also any request that doesn't return an appropriate success status (probably a 2xx status).

*JSON.stringify(sigObject) is not a canonical representation of the exact same data because properties might not be stringified in the same order depending upon how the sigObject was built.  If you grabbed the properties, sort them and inserted them in sorted order onto a temporary object and then stringified that, it would be more canonical.

*I'd recommend using a Map object instead of a regular object for globalFetch.inFlight because it's more efficient when you're adding/removing items regularly and will never have any name collision with property names or methods (though your hash would probably not conflict anyway, but it's still a better practice to use a Map object for this kind of thing).

*Items should be aged from the cache (as you apparently know already).  You can just use a setInterval() that runs every so often (it doesn't have to run very often - perhaps every 30 minutes) that just iterates through all the items in the cache and removes any that are older than some amount of time.  Since you're already checking the time when you find one, you don't have to clean the cache very often - you're just trying to prevent non-stop build-up of stale data that isn't going to be re-requested - so it isn't getting automatically replaced with newer data and isn't being used from the cache.

*If you have any case insensitive properties or values in the request parameters or the URL, the current design would see different case as different requests.  Not sure if that matters in your situation or not or if it's worth doing anything about it.

*When you write the real code, you need Date.now(), not Date.now.
Here's a sample implementation that implements all of the above (except for case sensitivity because that's data-specific):
function makeHash(url, obj) {
    // put properties in sorted order to make the hash canonical
    // the canonical sort is top level only,
    //    does not sort properties in nested objects
    let items = Object.entries(obj).sort((a, b) => b[0].localeCompare(a[0]));
    // add URL on the front
    items.unshift(url);
    return JSON.stringify(items);
}

async function globalFetch(resource, init = {}) {
    const key = makeHash(resource, init);

    const now = Date.now();
    const expirationDuration = 5 * 1000;
    const newExpiration = now + expirationDuration;

    const cachedItem = globalFetch.cache.get(key);
    // if we found an item and it expires in the future (not expired yet)
    if (cachedItem && cachedItem.expires >= now) {
        // update expiration time
        cachedItem.expires = newExpiration;
        return cachedItem.promise;
    }

    // couldn't use a value from the cache
    // make the request
    let p = fetch(resource, init);
    p.then(response => {
        if (!response.ok) {
            // if response not OK, remove it from the cache
            globalFetch.cache.delete(key);
        }
    }, err => {
        // if promise rejected, remove it from the cache
        globalFetch.cache.delete(key);
    });
    // save this promise (will replace any expired value already in the cache)
    globalFetch.cache.set(key, { promise: p, expires: newExpiration });
    return p;
}
// initalize cache
globalFetch.cache = new Map();

// clean up interval timer to remove expired entries
// does not need to run that often because .expires is already checked above
// this just cleans out old expired entries to avoid memory increasing
// indefinitely
globalFetch.interval = setInterval(() => {
    const now = Date.now()
    for (const [key, value] of globalFetch.cache) {
        if (value.expires < now) {
            globalFetch.cache.delete(key);
        }
    }
}, 10 * 60 * 1000); // run every 10 minutes

Implementation Notes:

*

*Depending upon your situation, you may want to customize the cleanup interval time.  This is set to run a cleanup pass every 10 minutes just to keep it from growing unbounded.  If you were making millions of requests, you'd probably run that interval more often or cap the number of items in the cache.  If you aren't making that many requests, this can be less frequent.  It is just to clean up old expired entries sometime so they don't accumulate forever if never re-requested.  The check for the expiration time in the main function already keeps it from using expired entries - that's why this doesn't have to run very often.

*This looks as response.ok from the fetch() result and promise rejection to determine a failed request.  There could be some situations where you want to customize what is and isn't a failed request with some different criteria than that.  For example, it might be useful to cache a 404 to prevent repeating it within the expiration time if you don't think the 404 is likely to be transitory.  This really depends upon your specific use of the responses and behavior of the specific host you are targeting.  The reason to not cache failed results is for cases where the failure is transitory (either a temporary hiccup or a timing issue and you want a new, clean request to go if the previous one failed).

*There is a design question for whether you should or should not update the .expires property in the cache when you get a cache hit.  If you do update it (like this code does), then an item could stay in the cache a long time if it keeps getting requested over and over before it expires.  But, if you really want it to only be cached for a maximum amount of time and then force a new request, you can just remove the update of the expiration time and let the original result expire.  I can see arguments for either design depending upon the specifics of your situation.  If this is largely invariant data, then you can just let it stay in the cache as long as it keeps getting requested.  If it is data that can change regularly, then you may want it to be cached no more than the expiration time, even if its being requested regularly.

A: Consider using a ServiceWorker or Workbox to separate caching logic from your application. The Stale-While-Revalidate strategy could apply here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get Watir to return actual HTML when site redirects? When I read out the HTML returned by Watir, it gives me a page directing me to come back on a browser through my Mac or PC.  It seems I am being redirected by a user agent given through Watir.  I thought I was driving the browser with Watir, but this doesn't seem to be the case.
ie = Watir::IE.new
ie.goto "http://www.apple.com/safari/download"

ie.checkbox(:name, "21.1.9.12.3.1.3.0").clear

Which returns an UnkownObjectException.  Same with trying to click the submit button.
Using firebug I can find the checkbox fine, that's how I found the :name.  So I next redirected the HTML output from Watir into a file for inspection,
myfile = File.new("safaridebug.html", "w+")
myfile.puts ie.html
myfile.close

Looking through safaridebug.html is where I noticed I was on a different page from the web browser.  Is there someway in watir I can get the actual HTML that is present in my web browser, maybe a user agent spoof?  Thanks.
System Specs:
VM running Win XP SP2,
ruby 1.8.7,
IE 8

A: Watir is working correctly in that case. There is no special user-agent or anything used by Watir because plain old IE is used and it's user-agent is sent by the IE itself of course.
The reason why you cannot find the checkbox with Watir or from the HTML is that the checkbox is in a frame :) Look for a frame tag in that html and you can understand why you were not able to find it before.
You can access it from the frame instead:
b.frame(:id, "download-frame").checkbox(:name, "21.1.9.12.3.1.3.0").clear

If you're getting access denied errors when trying to access frames, then just read the instructions at http://wiki.openqa.org/display/WTR/Frames


text:
Q: Could not find a matching type in ExpressionSerialization.dll I use ExpressionSerialization library for serializing Expression Tree but get me an error
Could not find a matching type

WCF Service :
public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
}
[ServiceContract]
public interface IService1
{
    [OperationContract(Name = "GetByPredicate")]
    List<Person> Get(XElement expression);
    [OperationContract]
    List<Person> Get();
}

public class Service1 : IService1
{
    private readonly List<Person> _persons;
    public Service1()
    {
        var p = new List<Person>
        {
            new Person() {ID = 1, Name = "A"},
            new Person() {ID = 2, Name = "B"},
            new Person() {ID = 3, Name = "C"},
            new Person() {ID = 4, Name = "D"},
            new Person() {ID = 5, Name = "E"},
            new Person() {ID = 6, Name = "F"},
            new Person() {ID = 7, Name = "G"},
            new Person() {ID = 8, Name = "H"}
        };

        _persons = p;
    }
    public List<Person> Get(XElement expression)
    {
        var s = new ExpressionSerializer();
        var exp = s.Deserialize<Func<Person, bool>>(expression).Compile();
        return _persons.Where(exp).ToList();
    }

    public List<Person> Get()
    {
        return _persons;
    }
}

WCF Proxy :
public class Class1
{
    public List<Person> Get(Expression<Func<Person, bool>> expression)
    {
        var exp = new ExpressionSerialization.ExpressionSerializer().Serialize(expression);

        var srv = new Service1Client();
        var lst = srv.GetByPredicate(exp);
        srv.Close();
        return lst;
    }

    public List<Person> Get()
    {
        var srv = new Service1Client();
        var lst = srv.Get();
        srv.Close();
        return lst;
    }
}

Console Test :
        var prx = new ClassLibrary1.Class1();
        var lst = prx.Get(x => x.ID > 3);

BUT when run project ExpressionSerialization give me an error :
Could not find a matching type

Inner Exception : null
Message : Could not find a matching type
Parameter name: ClassLibrary1.ServiceReference1.Person

Stack Trace :    at ExpressionSerialization.TypeResolver.GetType(String typeName) in c:\Users\Hamed\Desktop\Expression-Tree-Serializer-master\ExpressionSerialization\TypeResolver.cs:line 161
   at ExpressionSerialization.ExpressionSerializer.ParseNormalTypeFromXmlCore(XElement xml) in c:\Users\Hamed\Desktop\Expression-Tree-Serializer-master\ExpressionSerialization\ExpressionSerializer(Deserialize).cs:line 375
   at ExpressionSerialization.ExpressionSerializer.ParseTypeFromXmlCore(XElement xml) in c:\Users\Hamed\Desktop\Expression-Tree-Serializer-master\ExpressionSerialization\ExpressionSerializer(Deserialize).cs:line 363
   at ExpressionSerialization.ExpressionSerializer.ParseTypeFromXml(XElement xml) in c:\Users\Hamed\Desktop\Expression-Tree-Serializer-master\ExpressionSerialization\ExpressionSerializer(Deserialize).cs:line 355
   at ExpressionSerialization.ExpressionSerializer.ParseParameterExpressionFromXml(XElement xml) in c:\Users\Hamed\Desktop\Expression-Tree-Serializer-master\ExpressionSerialization\ExpressionSerializer(Deserialize).cs:line 332
   at ExpressionSerialization.ExpressionSerializer.ParseExpressionFromXmlNonNull(XElement xml) in c:\Users\Hamed\Desktop\Expression-Tree-Serializer-master\ExpressionSerialization\ExpressionSerializer(Deserialize).cs:line 60
   at ExpressionSerialization.ExpressionSerializer.ParseExpressionFromXml(XElement xml) in c:\Users\Hamed\Desktop\Expression-Tree-Serializer-master\ExpressionSerialization\ExpressionSerializer(Deserialize).cs:line 41
   at ExpressionSerialization.ExpressionSerializer.ParseMemberExpressionFromXml(XElement xml) in c:\Users\Hamed\Desktop\Expression-Tree-Serializer-master\ExpressionSerialization\ExpressionSerializer(Deserialize).cs:line 179
   at ExpressionSerialization.ExpressionSerializer.ParseExpressionFromXmlNonNull(XElement xml) in c:\Users\Hamed\Desktop\Expression-Tree-Serializer-master\ExpressionSerialization\ExpressionSerializer(Deserialize).cs:line 70
   at ExpressionSerialization.ExpressionSerializer.ParseExpressionFromXml(XElement xml) in c:\Users\Hamed\Desktop\Expression-Tree-Serializer-master\ExpressionSerialization\ExpressionSerializer(Deserialize).cs:line 41
   at ExpressionSerialization.ExpressionSerializer.ParseBinaryExpresssionFromXml(XElement xml) in c:\Users\Hamed\Desktop\Expression-Tree-Serializer-master\ExpressionSerialization\ExpressionSerializer(Deserialize).cs:line 404
   at ExpressionSerialization.ExpressionSerializer.ParseExpressionFromXmlNonNull(XElement xml) in c:\Users\Hamed\Desktop\Expression-Tree-Serializer-master\ExpressionSerialization\ExpressionSerializer(Deserialize).cs:line 55
   at ExpressionSerialization.ExpressionSerializer.ParseExpressionFromXml(XElement xml) in c:\Users\Hamed\Desktop\Expression-Tree-Serializer-master\ExpressionSerialization\ExpressionSerializer(Deserialize).cs:line 41
   at ExpressionSerialization.ExpressionSerializer.ParseLambdaExpressionFromXml(XElement xml) in c:\Users\Hamed\Desktop\Expression-Tree-Serializer-master\ExpressionSerialization\ExpressionSerializer(Deserialize).cs:line 258
   at ExpressionSerialization.ExpressionSerializer.ParseExpressionFromXmlNonNull(XElement xml) in c:\Users\Hamed\Desktop\Expression-Tree-Serializer-master\ExpressionSerialization\ExpressionSerializer(Deserialize).cs:line 62
   at ExpressionSerialization.ExpressionSerializer.Deserialize(XElement xml) in c:\Users\Hamed\Desktop\Expression-Tree-Serializer-master\ExpressionSerialization\ExpressionSerializer(Deserialize).cs:line 25
   at ExpressionSerialization.ExpressionSerializer.Deserialize[TDelegate](XElement xml) in c:\Users\Hamed\Desktop\Expression-Tree-Serializer-master\ExpressionSerialization\ExpressionSerializer(Deserialize).cs:line 30
   at WcfService1.Service1.Get(XElement expression) in e:\...\WcfService1\WcfService1\Service1.svc.cs:line 33
   at SyncInvokeGet(Object , Object[] , Object[] )
   at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)

Can anyone explain how resolve this problem ?
and How use this library in Client and WCF project ?


text:
Q: implement a form to display a set of forms, which have one or more fields the same everybody,
I have a table in database which is used to show the note for a student for a certain course.

*

*Student    Course    note

*Aaa  Math    A

*Bbb  English C

How can I show them in one form like:

*

*Student :  aaa

*Course:    math      note: a

*Course: english    note: a


text:
Q: Consuming Polymorphic Jsons with Retrofit and Kotlin My API sends me a polyphonic Json in with the variable addon_item can be either a String or an Array, I have spend days trying to make a CustomDezerializer for it without any success.
Here is the Json response:
({
    "code": 1,
    "msg": "OK",
    "details": {
        "merchant_id": "62",
        "item_id": "1665",
        "item_name": "Burrito",
        "item_description": "Delicioso Burrito en base de tortilla de 30 cm",
        "discount": "",
        "photo": "http:\/\/www.asiderapido.cloud\/upload\/1568249379-KDKQ5789.jpg",
        "item_cant": "-1",
        "cooking_ref": false,
        "cooking_ref_trans": "",
        "addon_item": [{
            "subcat_id": "144",
            "subcat_name": "EXTRA",
            "subcat_name_trans": "",
            "multi_option": "multiple",
            "multi_option_val": "",
            "two_flavor_position": "",
            "require_addons": "",
            "sub_item": [{
                "sub_item_id": "697",
                "sub_item_name": "Queso cheddar",
                "item_description": "Delicioso queso fundido",
                "price": "36331.20",
                "price_usd": null
            }]
        }]
    }
})

Here is the Custom Dezerializer, which includes BodyConverter that removes two braces that encompassed the Json response:
'''
/**
 * This class was created due to 2 issues with the current API responses:
 * 1. The API JSON results where encapsulated by parenthesis
 * 2. They had dynamic JSON variables, where the Details variable was coming as a String
 * or as an Object depending on the error message (werer whe user and password wereh correct.
 *
 */

class JsonConverter(private val gson: Gson) : Converter.Factory() {

    override fun responseBodyConverter(
        type: Type?, annotations: Array<Annotation>?,

        retrofit: Retrofit?
    ): Converter<ResponseBody, *>? {
        val adapter = gson.getAdapter(TypeToken.get(type!!))
        return GsonResponseBodyConverter(gson, adapter)
    }

    override fun requestBodyConverter(
        type: Type?,
        parameterAnnotations: Array<Annotation>?,
        methodAnnotations: Array<Annotation>?,
        retrofit: Retrofit?
    ): Converter<*, RequestBody>? {
        val adapter = gson.getAdapter(TypeToken.get(type!!))
        return GsonRequestBodyConverter(gson, adapter)
    }

    internal inner class GsonRequestBodyConverter<T>(
        private val gson: Gson,
        private val adapter: TypeAdapter<T>
    ) : Converter<T, RequestBody> {
        private val MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8")
        private val UTF_8 = Charset.forName("UTF-8")

        @Throws(IOException::class)
        override fun convert(value: T): RequestBody {
            val buffer = Buffer()
            val writer = OutputStreamWriter(buffer.outputStream(), UTF_8)
            val jsonWriter = gson.newJsonWriter(writer)
            adapter.write(jsonWriter, value)
            jsonWriter.close()
            return RequestBody.create(MEDIA_TYPE, buffer.readByteString())
        }
    }

    // Here we remove the parenthesis from the JSON response

    internal inner class GsonResponseBodyConverter<T>(
        gson: Gson,
        private val adapter: TypeAdapter<T>
    ) : Converter<ResponseBody, T> {

        @Throws(IOException::class)
        override fun convert(value: ResponseBody): T? {
            val dirty = value.string()
            val clean = dirty.replace("(", "")
                .replace(")", "")

            try {
                return adapter.fromJson(clean)
            } finally {
                value.close()
            }
        }
    }

    class DetalleDeProductoDeserializer : JsonDeserializer<DetallesDelItemWrapper2> {
        override fun deserialize(
            json: JsonElement,
            typeOfT: Type,
            context: JsonDeserializationContext
        ): DetallesDelItemWrapper2 {

             if ((json as JsonObject).get("addon_item") is JsonObject) {
            return Gson().fromJson<DetallesDelItemWrapper2>(json, ListaDetalleAddonItem::class.java)

            } else {

                 return Gson().fromJson<DetallesDelItemWrapper2>(json, DetallesDelItemWrapper2.CookingRefItemBoolean::class.java)
            }
        }
    }

    companion object {

        private val LOG_TAG = JsonConverter::class.java!!.getSimpleName()

        fun create(detalleDeProductoDeserializer: DetalleDeProductoDeserializer): JsonConverter {
            Log.e("Perfill Adapter = ", "Test5 " +  "JsonConverter" )

            return create(Gson())
        }

        fun create(): JsonConverter {
            return create(Gson())
        }

        private fun create(gson: Gson?): JsonConverter {
            if (gson == null) throw NullPointerException("gson == null")
            return JsonConverter(gson)
        }
    }
}

Here is the RetrofitClient.class:
class RetrofitClient private constructor(name: String) {
    private var retrofit: Retrofit? = null

    fun getApi(): Api {
        return retrofit!!.create(Api::class.java)
    }

    init {

        if (name == "detalleDelItem") run {
            retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(JsonConverterJava.create(JsonConverterJava.DetallesDelItemDeserializer()))
//                .addConverterFactory(GsonConverterFactory.create(percentDeserializer))
                .client(unsafeOkHttpClient.build())
                .build()
            Log.e("RetrofitClient ", "Instace: " + "detalle " +  name)
        }
    }

    companion object {

        //Remember this shit is https for the production server
        private val BASE_URL = "http://www.asiderapido.cloud/mobileapp/api/"

        private var mInstance: RetrofitClient? = null

        @Synchronized
        fun getInstance(name: String): RetrofitClient {
                mInstance = RetrofitClient(name)
            return mInstance!!
        }
    }
}

Finally my POJO:
open class DetallesDelItemWrapper2 {
     @SerializedName("code")
     val code: Int? = null
     @Expose
     @SerializedName("details")
     var details: ItemDetails? = null
     @SerializedName("msg")
     val msg: String? = null

     class ItemDetails {
         @Expose
         @SerializedName("addon_item")
         val addonItem: Any? = null
         @SerializedName("category_info")
         val categoryInfo: CategoryInfo? = null
         @SerializedName("cooking_ref")
         val cookingRef: Any? = null
         @SerializedName("cooking_ref_trans")
         val cookingRefTrans: String? = null
     }

class ListaDetalleAddonItem: DetallesDelItemWrapper2(){
   @SerializedName("addon_item")
   val detalleAddonItem: List<DetalleAddonItem>? = null

}

class StringDetalleAddonItem: DetallesDelItemWrapper2(){
    @SerializedName("addon_item")
    val detalleAddonItem: String? = null
}

A: I took a shot at this and came up with 2 possible ideas. I don't think they're the only way to achieve this, but I think I can share my thoughts.
First, I've reduced the problem to actually only parsing the items. So I've removed retrofit from the equation and use the following jsons:
val json = """{
    "addon_item": [{
            "subcat_id": "144",
            "subcat_name": "EXTRA",
            "subcat_name_trans": "",
            "multi_option": "multiple",
            "multi_option_val": "",
            "two_flavor_position": "",
            "require_addons": "",
            "sub_item": [{
                "sub_item_id": "697",
                "sub_item_name": "Queso cheddar",
                "item_description": "Delicioso queso fundido",
                "price": "36331.20",
                "price_usd": null
            }]
        }]
}
""".trimIndent()

(for when the addon_item is an array)
val jsonString = """{
   "addon_item": "foo"
}
""".trimIndent()

(for when the addon_item is a string)

First approach
My first approach was to model addon_item as a generic JsonElement:
data class ItemDetails(
  @Expose
  @SerializedName("addon_item")
  val addonItem: JsonElement? = null
)

(I'm using data classes because I find them more helpful, but you don't have too)
The idea here is to let gson deserialize it as a generic json element and you can then inspect it yourself. So if we add some convenience methods to the class:
data class ItemDetails(
  @Expose
  @SerializedName("addon_item")
  val addonItem: JsonElement? = null
) {
  fun isAddOnItemString() =
    addonItem?.isJsonPrimitive == true && addonItem.asJsonPrimitive.isString

  fun isAddOnItemArray() =
    addonItem?.isJsonArray == true

  fun addOnItemAsString() =
    addonItem?.asString

  fun addOnItemAsArray() =
    addonItem?.asJsonArray
}

So as you can see, we check the addOnItem for what it contains and according to that, we can obtain its contents. Here's an example of how to use it:
fun main() {
  val item = Gson().fromJson(jsonString, ItemDetails::class.java)
  println(item.isAddOnItemArray())
  println(item.isAddOnItemString())
  println(item.addOnItemAsString())
}

I think the biggest advantage of this is that it's fairly simple and you don't require custom logic to deserialize. For me, the huge drawback is the type-safety loss.
You can get the add on as an array, but it will be an array of json elements that have to be "manually" deserialized. Hence, my 2nd approach tries to tackle this.

Second approach
The idea here is to use Kotlin's sealed classes and have 2 types of add ons:
sealed class AddOnItems {
  data class StringAddOnItems(
    val addOn: String
  ) : AddOnItems()

  data class ArrayAddOnItems(
    val addOns: List<SubCategory> = emptyList()
  ) : AddOnItems()

  fun isArray() = this is ArrayAddOnItems

  fun isString() = this is StringAddOnItems
}

The SubCategory class is just what was inside the list. Here's a simple version of it:
data class SubCategory(
  @SerializedName("subcat_id")
  val id: String
)

As you can see the AddOnItems is a sealed class that has the only 2 possible types for your use case.
Now we need a custom deserializer:
class AddOnItemsDeserializer : JsonDeserializer<AddOnItems> {
  override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?) =
    when {
        json?.isJsonArray == true -> {
            AddOnItems.ArrayAddOnItems(context!!.deserialize(
                json.asJsonArray,
                TypeToken.getParameterized(List::class.java, SubCategory::class.java).type))
        }

        json?.isJsonPrimitive == true && json.asJsonPrimitive.isString ->
            AddOnItems.StringAddOnItems(json.asJsonPrimitive.asString)

        else -> throw IllegalStateException("Cannot parse $json as addonItems")
    }
}

In a nutshell, this checks if add on is an array and creates the respective class and the same for string.
Here's how you can use it:
fun main() {
  val item = GsonBuilder()
    .registerTypeAdapter(AddOnItems::class.java, AddOnItemsDeserializer())
    .create()
    .fromJson(jsonString, ItemDetails::class.java)
  println(item.addOnItems.isString())
  println(item.addOnItemsAsString().addOn)

  val item = GsonBuilder()
    .registerTypeAdapter(AddOnItems::class.java, AddOnItemsDeserializer())
    .create()
    .fromJson(json, ItemDetails::class.java)
  println(item.addOnItems.isArray())
  println(item.addOnItemsAsArray().addOns[0])
}

I think the biggest advantage here is that you get to keep the types. However, you still need to check what it is before calling addOnItemsAs*.
Hope this helps


text:
Q: Почему display: inline не работает Почему то в моем браузере ( Opera ) display: inline абсолютно никак не работает и div-ы просто занимают всю строку

body {
  position: relative;
  font-family: 'Noto Sans', sans-serif;
  font-size: 3em;
  line-height: 1.4;
  color: #000;
  /*min-width: 320px;
    overflow-x: hidden;
    height: auto;*/
}

.just {
  display: inline;
}

.inline {
  border: 2px solid rgb(255, 0, 0);
  padding: 10px;
  font-size: 1em;
  list-style-type: none;
}

Новости

Ураганы

Холдинги

A: потому что применить нужно к li

body {
  position: relative;
  font-family: 'Noto Sans', sans-serif;
  font-size: 1em;
  line-height: 1.4;
  color: #000;
  /*min-width: 320px;
    overflow-x: hidden;
    height: auto;*/
}

.just {
  display: inline;
}

.inline {
  border: 2px solid rgb(255, 0, 0);
  padding: 10px;
  font-size: 1em;
  list-style-type: none;
  display: inline;
}

Новости

Ураганы

Холдинги

A: Внутри вашего элемента ul с display: inline находятся блочные элементы li, которые "распирают" строчный элемент изнутри до состояния блока. Это как в целлофановый пакетик положить кирпич. Пакетик примет габариты кирпича как минимум.
Если вам нужно выстроить элементы в одну строку, то задайте элементам li display: inline, как вам в соседнем комментарии посоветовали.
А если вам нужно чтобы весь ul был строчным, а li внутри него так и остались столбиком, то нужно задавать элементу ul свойство display: inline-block.


text: Q: Process Handle Increases using ThreadPool I have a c# application which is refreshed every time interval. I used ThreadPool to do this. Because of this system Handle increases due to that my application is not running long time means after 2 days i am getting System out Of memory Exception. I forcefully releases the Memory but don't have luck to decrease the system Handles. I googled also to decrease Handles but no luck. Can you tell me what i have to do for this. I am using Framework 2.0.


text:
Q: Division by multiple subtraction in Assembly code (NASM) I am trying to perform a division by multiple subtraction in assembly code and am getting the following errors:
subtract.nasm:19: error: invalid combination of opcode and operands
subtract.nasm:20: error: invalid combination of opcode and operands
subtract.nasm:24: error: invalid combination of opcode and operands
subtract.nasm:25: error: invalid combination of opcode and operands

I cannot figure this out, any ideas on what it could be?
section .data

        VAL1: db 10
        VAL2: db 2

section.text

        global _start
_start:

        mov eax, VAL1
        mov ecx, VAL2
        mov ebx, 0

sub_loop:

        sub eax,eax,ebx
        add ebx,ebx,1

        test eax,eax
        jnz sub_loop
        add edx,eax,ecx
        sub ebx,ebx,1

        mov eax,1
        mov ebx,0
        int 80h


text:
Q: SharePoint List permission issue I am using SharePoint Server 2007 with Windows Server 2008, using publishing portal template. I have a list in a page. I want to set permission to allow all authenticated (i.e. non-anonymous) user to be able to add new item to the list, but not allow them to change schema (e.g. add a new column, delete a column or create a new view for the list).
What kinds of permission should I set and how to set?
thanks in advance,
George

A: You'll need to grant contribute rights to "NT AUTHORITY\authenticated users". There's an "Add all authenticated users" link when you add a new user to the list permissions.
Unless they have "Manage Lists" or similar permissions, they won't be able to alter said list.
I don't know that you can restrict personal view creation without limiting all personalization. Check out "Item-level Permissions" under your lists "Advanced Settings" for some alternatives that might suit your needs (you don't say why you want to inhibit view creation).


text:
Q: How do you author Mac package to install without requiring admin privileges on Lion? I'm trying to understand how to fix my Mac package developed in Packagemaker (that comes with Xcode 2.4.1) to install on OS Lion 10.7 without requiring admin privileges when it is being run as a standard user.  In 10.4, 10.5, 10.6, I was able to install this package as a standard user without admin privileges.  The contents of the package are installed into the user's home folder, so no additional privileges should be required.
Does anyone know how to do this? Or why the package would now require root permissions?
Or does anyone know if there are new restrictions in OS Lion that all installations require administrative privileges short of having an app bundle package that you just drag the app bundle to your home folder?
I looked on developer.apple.com, but haven't been able to find any information.
Brian

A: It is likely an issue with the trust of the software vendor, in this case, you.
http://www.bu.edu/infosec/howtos/bypass-gatekeeper-safely/
By default, Gatekeeper is set to 'Mac App Store and identified developers.'  This means that a Mac running Mountain Lion will only run applications you have downloaded from the App Store or applications that have been signed with an official Apple Developer ID.  This helps to prevent malware from infecting your computer, as it makes it harder for malicious software posing as real applications to be installed by the user.
You have to sign your installation packages with your developer ID. Odds are, that version of packagemaker does not prompt you for it, or it is less obvious how to do it. See this about signing for lion. Making OS X Installer Packages like a Pro - Xcode Developer ID ready pkg

A: Make sure that it installs for just one user by default. If it does an install for all users root is required.


text:
Q: Focus on jQuery UI Calender accessibility with TAB key We are using the jQuery datepicker to show calender control and provide an option to user to select a date from the keyboard without using mouse.
While testing the Tab key accessibility for given form, I've noticed that when the focus reaches the date field, the calendar popup appears onscreen, but when I press the Tab key again, the focus shifts to next input control but not to the calender popup.
Is there any way to shift the focus to the calendar control as soon as the popup is focused on?
HTML
<input type="text" value="first input field">
<input type="text" id="myDate">
<input type="text" value="second input field">

JS
$(document).ready(function() {
    $("#myDate").datepicker();
});

Demo
Code Fix
After giving a try to various code fixes, ended up writing below code to enable accessibility for date picker.
$("#datepicker").attr('readonly', 'readonly')
            .datepicker({})
            .keydown(function(event) {
                event.preventDefault();
                event.stopPropagation();
                //   KEY MAP
                //  [TAB: 9, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40]
                var code = event.keyCode || event.which;
                // If key is not TAB
                if (code != '9') {
                    // And arrow keys used "for performance on other keys"
                    if (code == '37' || code == '38' || code == '39' || code == '40') {
                        // Get current date
                        var parts = $(this).val().split("/"),
                            currentDate = new Date(parts[2], parts[0] - 1, parts[1]);
                        // Show next/previous day/week
                        switch (code) {
                            // LEFT, -1 day
                            case 37:
                                currentDate.setDate(currentDate.getDate() - 1);
                                break;
                                // UP, -1 week
                            case 38:
                                currentDate.setDate(currentDate.getDate() - 7);
                                if (!_.isNull(currentDate)) {
                                    $(this).datepicker("setDate", currentDate);
                                    return false;
                                }

                                break;
                                // RIGHT, +1 day
                            case 39:
                                currentDate.setDate(currentDate.getDate() + 1);
                                break;
                                // DOWN, +1 week
                            case 40:
                                currentDate.setDate(currentDate.getDate() + 7);
                                break;
                        }
                    } else {
                        return false;
                    } // If other keys pressed.. return false
                }
            });

A: I don't think the datepicker fields/controls can be tabbed thru.
http://api.jqueryui.com/datepicker/ shows that the datepicker has specific keyboard interactions built in, perhaps because they realized tab was not a viable option.  This post, jQuery UI datepicker: Configure keyboard shortcuts, talks about changing them which might help you out.

A: The year is 2021 and sadly I had the same issue. Was really disappointed when I saw there was no published fix for this issue, so after a couple of days of work, I managed to find a workaround. Screen readers make life harder for everyone and sometimes they can't even read that you press a key (in my case with NVDA on the browser was not reading any of the arrow keys, even if I tried using them in combination with CTRL/CMD). The biggest problem is that the html block is being created at the end of the body, so you have to force focus into that block. See below how I managed to make the JQuery UI Datepicker accessible on desktop and mobile:

function setVoiceOverFocus(element) {
  var focusInterval = 10; // ms, time between function calls
  var focusTotalRepetitions = 10; // number of repetitions

  element.attr('tabindex', '0');
  element.blur();

  var focusRepetitions = 0;
  var interval = window.setInterval(function() {
    element.focus();
    focusRepetitions++;
    if (focusRepetitions >= focusTotalRepetitions) {
    window.clearInterval(interval);
    }
  }, focusInterval);
}
if (window.util.isMobile()) {
  $(".Form__CustomInput").on("click", function () {
      $(this).attr("selected-input", "true");
      setVoiceOverFocus($(".ui-state-default:first"));
      $(".ui-datepicker").attr("role", "dialog");
      $(".ui-datepicker-calendar").attr("tabindex", "-1");
      $(".ui-datepicker-calendar thead").attr("aria-hidden", "true");
  });

  $(document).on("click", function () {
      $(".ui-state-default").on("click", function () {
          setVoiceOverFocus($("[selected-input = 'true'"));
          $("[selected-input = 'true'").attr("selected-input", "false");
          $(".ui-datepicker").hide();
          $(".ui-datepicker").attr("display", "none");
      });

      $(".ui-datepicker-prev, .ui-datepicker-next").on("click", function () {
          setVoiceOverFocus($(".ui-state-default:first"))
          $(".ui-datepicker").attr("role", "dialog");
          $(".ui-datepicker-calendar").attr("tabindex", "-1");
          $(".ui-datepicker-calendar thead").attr("aria-hidden", "true");
      });
  })
  } else {
  //open form with arrow up/down
  $(".Form__CustomInput").on("keydown", function (event) {
      if (event.keyCode === 40 || event.keyCode === 38) {
          $(this).attr("selected-input", "true");
          setVoiceOverFocus($(".ui-state-default:first"));
          $(".ui-datepicker").attr("role", "dialog");
      }
  });
  //when you select the date close the calendar and focus the input
  $(".Form__CustomInput").on("change", function () {
      setVoiceOverFocus($("[selected-input = 'true'"));
      $("[selected-input = 'true'").attr("selected-input", "false");
      $(".ui-datepicker").hide();
  });

  $(document).on("keydown click", function (event) {
      var uiDatePicker = ".ui-datepicker";
      var calendarDay = ".ui-state-default";
      var calendarArrows = ".ui-datepicker-prev, .ui-datepicker-next";
      var selectedInputElement = "[selected-input = 'true'";
      var selectedInputAttr = "selected-input";
      var isFocus = ":focus";

      function exitDatePicker () {
          setVoiceOverFocus($(selectedInputElement));
          $(selectedInputElement).attr(selectedInputAttr, "false");
          $(uiDatePicker).hide();
      };

      if ($(calendarDay).is(isFocus) && event.keyCode === 27) {
          exitDatePicker();
      };
      if ($(".TimePicker").length) {
          if ($(uiDatePicker + "-period:last").is(isFocus) && event.keyCode === 9) {
              event.preventDefault();
              exitDatePicker();
          }
      } else {
          if ($(calendarDay + ":last").is(isFocus) && event.keyCode === 9) {
              event.preventDefault();
              exitDatePicker();
          }
      }
      if ($(calendarDay + ":first").is(isFocus) && event.keyCode === 9 && event.shiftKey) {
          event.preventDefault();
          $(uiDatePicker + "-header " + calendarArrow).attr("tabindex", "0");
          setVoiceOverFocus($(uiDatePicker + "-next"));
      };
      if ($(uiDatePicker + "-prev").is(isFocus) && event.keyCode === 9 && event.shiftKey) {
          event.preventDefault();
          exitDatePicker();
      };

      $(calendarDay).on("click", function () {
          setVoiceOverFocus($(selectedInputElement));
          $(selectedInputElement).attr(selectedInputAttr, "false");
          $(uiDatePicker).hide();
      });

      $(calendarArrows).on("click", function () {
          setVoiceOverFocus($(calendarDay + ":first"));
          $(uiDatePicker).attr("role", "dialog");
      });
  });
}


text:
Q: jquery data tables disabling sorting not working I'm having an issue trying to turn off sorting in my DataTables code. Everytime I add "bSort": false I get an ajax error from the datables plugin. But when I take out bSort the table loads without issue.
$("#companies").dataTable({
    "bSort": false,
    "bServerSide": true,                // user server side processing
    "sAjaxSource": sohAjaxUrl,          // load data from an external source
    "bProcessing": true,                // enable the processing indicator whilst table is loading
    "searching": false,                 // disable search box
    "sPaginationType": "full_numbers",
    "aoColumns": [
        { "mDataProp":"itemDescription","bSortable":false,sDefaultContent:"","sWidth":"40%" },
        { "mDataProp":"size","bSortable":false,sDefaultContent:"","sWidth":"15%"  },
        { "mDataProp":"style","bSortable":false,sDefaultContent:"","sWidth":"15%"  },
        { "mDataProp":"supplyStyle","bSortable":false,sDefaultContent:"","sWidth":"15%"  },
        { "mDataProp":"item","bSortable":false,sDefaultContent:"","sWidth":"15%"  }
    ]
});

My end aim is to remove all sorting on all columns. You can see here that the first column is sortable even though I have specified "bSortable":false in the column definition.

Can someone help me understand why adding bSort causes an ajax error please?
thanks


text:
Q: w3c validation error on document type html 5 I am using html 5 for web page. When i validate my webpage in http://validator.w3.org/check it showed me the following error.
Line 1, Column 10: delimiter ">" invalid: only name, "#IMPLIED" and parameter separators are allowed

<!DOCTYPE>

If i change this it showed me lot of errors. How can i rectify that?

A: It should be <!doctype html>
Read here on how you can validate HTML5 page on W3C Validator - http://www.werockyourweb.com/html5-validator


text:
Q: What does "work a rope line" mean? When Presidential race and caucuses are close, the candidates seem to be busy in "working a lope line" as in the following examples:.

*

*Wolf needs to work on his rope line speed. - www.pennlive.com/.../gov - Jnuary 20. 2015

*Caucus Click: Romney works the rope line. After his campaign event in Mobile, Ala., was canceled due to rain, Mitt Romney spoke to
  supporters who waited outside along the rope line. - New York Times
  March 12, 2012

*Ever see Bush work a "rope line"? Remember when we had a president who did? - Democratic Undergroundcom.

Though it's imaginable, but what does "work a rope line" exactly mean?
Does it refer to candidates' shake-hands, hugging, and speaking to supporters in line? Is "work a lope line" an idiom? Is it applicable to "rope line work" with fans of personalities such as actors / actresses and singers other than politicians?

A: It's rope line with an "r."  It refers to a line of supporters at a politician's public event.  The supporters are kept behind a rope stretched between stanchions.  The politicians walks down the line shaking hands, and chatting with people.  This is called "working the rope line," akin to the terms "working a crowd" or "working a room," meaning to meet and greet groups of people successfully. Here are some tips if you ever have to do it.  Here is a video of of candidate Mitt Romney working a rope line in Sanford, Florida the day before he became private citizen Mitt Romney.  At about :40 in you can see the rope.

A: Work the room  (Wiktionary)

(idiomatic, of a host, hostess, or guest) To interact enthusiastically
  with   the attendees at an event, by moving among them, greeting them,
  and engaging them in conversation. "As a campaigning politician, he
  really knew how
  to shake hands, kiss babies, and work the room."
(idiomatic, of a performer or public speaker) To interact with one's
  audience, taking cues from its reactions and adapting one's
  performance or words to elicit the audience's attention and
  enthusiasm.

also

work the crowd   (idiomatic) To work the room, especially
  out-of-doors.

Rope line  (Wikipedia)

A rope line is a rope, often covered with velvet, that separates
  celebrities from a crowd. It is hung from portable metal or plastic
  posts. In American political terminology, a politician "walking down
  the rope line" or "working the rope line" is shaking hands of his or
  her supporters and guests.


text:
Q: Is there any way I can read a Python pickle (test1.pickle) from Java or Kotlin? I have found this page : http://www.picklingtools.com/html/java.html  but I don't understand it very well and I think it's what I am looking. My situation is like this:
-I have to read a python pickle which contains a dictionary with some data that I need to get for my logic I am going to implement in my android project.


text:
Q: PostMessage and CALLWNDHOOK, missing registered messages? Here's the situation.  I've got a two different window hooks, one's a global hook of the WH_SHELL variety that watches for new top-level windows, the second's a thread hook of the WH_CALLWNDPROC which is set on some of the top-level windows discovered by the first hook.  The two hooks are implemented in different DLLs.
As far as I can tell, both hooks are being installed properly.  However, nothing I Post to the hooks windows with a message code > WM_USER a register message is ever handled by the custom WH_CALLWNDPROC hook, but "normal" windows messages are passing thought it just fine.
Code that hooks a discovered window:
... Getting handle, mod, and procHook ...
DWORD threadId = GetWindowThreadProcessId(handle, NULL);

HHOOK hook = SetWindowsHookEx(WH_CALLWNDPROC, (HOOKPROC)procHook, mod, threadId);

if(!PostMessage(handle, CUSTOM_MESSAGE, NULL, NULL))
{
  ... fetch and print error message ...
}

The body of the hook itself:
... Report sends a message to an agreed upon window with the passed wParam & lParam
Report(20, nCode);

if(nCode == CUSTOM_MESSAGE)
{
  ... This code is never reached ...
  Report(50, ERROR_SUCCESS);

  if(PerformTask())
    Report(200, ERROR_SUCCESS);
  else
    Report(400, ERROR_SUCCESS);
}

... More code handling more messages in the same basic form

The first Report call is what's confirmed that the hook is installed and working, as it posts back a bunch of messages in the low teens and twenties (ERASEBACKGROUND, PAINT, etc.).
CUSTOM_MESSAGE is defined as WM_USER + 314.  The message used for Report(...) is WM_USER + 317.
I have since updated my code to use RegisterWindowMessage to obtain a UINT to send, it was incorrect of me to use WM_USER for inter-process communication.
So, basically, what is wrong with either my design or my usage of windows hooks and PostMessage?  If I've omitted any details, let me know; there's alot of code involved and this is a pretty large question already, so I've tried to only include what I think is relevant.
As an aside, is there an agreed upon better way to debug hooks?  I've been using the moral equivalent to cout << ... everything by posting messages to an agreed upon window and debugging its WndProc.
Thanks,
-Kevin Montrose

A: While @Michael is correct regarding the use of WM_USER messages (they should be used within an application only - registered messages are the better way to go here), at the same time I think the reason that you aren't receiving them is due to the nature of the CallWndProc hook and posted messages. I'm not positive, but I think that you want to hook the GetMessage hook for posted messages.
Another option is to hook the Debug hook, which receives all messages before all other hooks. You could have that watch for your custom message, and then from there determine which hook (if any) received your custom message.
EDIT: For debugging hooks, just attach to the process in question, and set a breakpoint in your hook procedure. That ends up being the easiest way I've found to debug them.

A: I think I figured it out.  Simple case of not quite absorbing the documentation.
My CallWndProc hook behaved as if nCode, wParam, and lParam were what would be passed to the hooked threads WndProc.  In fact, lParam contained a pointer to a CWPSTRUCT; read the data out of that structure and everything works fine.


text:
Q: Is it possible to start ignite cache by only providing the cache configuration in a java client? I would like to know if I can start a ignite cache from  java client . I am using Cassandra as the persistence store and use POJO configurations to work with the cache and Cassandra. With out providing any named cache configuration in server side is it possible ?
Please share your thoughts.

A: Cache itself can be dynamically started using Ignite#createCache method. However, classes that are required for this cache need to be deployed explicitly in advance, before servers are started.
In your case you will have to deploy POJO classes because they are currently required by Cassandra store. You will be able to skip this step though after this ticket is implemented: https://issues.apache.org/jira/browse/IGNITE-5270


text:
Q: Android long-touch event I have two buttons that increment and decrement a value by one with each press and they're working just fine with the onClickListener. I see that an onLongClickListener exists, which I assume is for touch and hold events. How would I have the number rapidly increment/decrement if the button is held?
Am I correct in assuming that onLongClickListener only fires once per long click? Is there a more appropriate listener or a property somewhere that I'm not aware of?

A: I had this same goal and ended up using an OnLongClick to catch the down portion to start a repeating event via a handler, then the normal OnClick to catch the release and stop it.  Works beautifully for me.
mOngoingRunnable = new Runnable() {
    public void run() {
        // do stuff
        mHandler.postDelayed(mOngoingRunnable, delayMsecs);
    }
};

public boolean onLongClick(View view) {
    mHandler.post(mOngoingRunnable);
    mOngoing = true;
    return false;
}

public void onClick(View view) {
    if (mOngoing) {
        mHandler.removeCallbacks(mOngoingRunnable);
        mOngoing = false;
    }
}

A: You may implement it as in the following code.
package org.me.rapidchange;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainActivity extends Activity implements OnKeyListener,
        OnTouchListener, OnClickListener {
    private class UpdateCounterTask implements Runnable {
        private boolean mInc;

        public UpdateCounterTask(boolean inc) {
            mInc = inc;
        }

        public void run() {
            if (mInc) {
                mHandler.sendEmptyMessage(MSG_INC);
            } else {
                mHandler.sendEmptyMessage(MSG_DEC);
            }
        }
    }

    private static final int MSG_INC = 0;
    private static final int MSG_DEC = 1;

    private Button mIncButton;
    private Button mDecButton;
    private TextView mText;
    private int mCounter;

    private Handler mHandler;
    private ScheduledExecutorService mUpdater;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MSG_INC:
                        inc();
                        return;
                    case MSG_DEC:
                        dec();
                        return;
                }
                super.handleMessage(msg);
            }
        };
        mIncButton = (Button) findViewById(R.id.inc_button);
        mDecButton = (Button) findViewById(R.id.dec_button);
        mText = (TextView) findViewById(R.id.text);
        mIncButton.setOnTouchListener(this);
        mIncButton.setOnKeyListener(this);
        mIncButton.setOnClickListener(this);
        mDecButton.setOnTouchListener(this);
        mDecButton.setOnKeyListener(this);
        mDecButton.setOnClickListener(this);
    }

    private void inc() {
        mCounter++;
        mText.setText(Integer.toString(mCounter));
    }

    private void dec() {
        mCounter--;
        mText.setText(Integer.toString(mCounter));
    }

    private void startUpdating(boolean inc) {
        if (mUpdater != null) {
            Log.e(getClass().getSimpleName(), "Another executor is still active");
            return;
        }
        mUpdater = Executors.newSingleThreadScheduledExecutor();
        mUpdater.scheduleAtFixedRate(new UpdateCounterTask(inc), 200, 200,
                TimeUnit.MILLISECONDS);
    }

    private void stopUpdating() {
        mUpdater.shutdownNow();
        mUpdater = null;
    }

    public void onClick(View v) {
        if (mUpdater == null) {
            if (v == mIncButton) {
                inc();
            } else {
                dec();
            }
        }
    }

    public boolean onKey(View v, int keyCode, KeyEvent event) {
        boolean isKeyOfInterest = keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER;
        boolean isReleased = event.getAction() == KeyEvent.ACTION_UP;
        boolean isPressed = event.getAction() == KeyEvent.ACTION_DOWN
                && event.getAction() != KeyEvent.ACTION_MULTIPLE;

        if (isKeyOfInterest && isReleased) {
            stopUpdating();
        } else if (isKeyOfInterest && isPressed) {
            startUpdating(v == mIncButton);
        }
        return false;
    }

    public boolean onTouch(View v, MotionEvent event) {
        boolean isReleased = event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL;
        boolean isPressed = event.getAction() == MotionEvent.ACTION_DOWN;

        if (isReleased) {
            stopUpdating();
        } else if (isPressed) {
            startUpdating(v == mIncButton);
        }
        return false;
    }
}


text:
Q: what is called a design pattern similar to factory method which doesn't return an object but calls a method? In the factory method, for example if a variable is equal to 5 the creator should return object A, otherwise object B.
I need the name of a design pattern for:
if a variable is equal to 5 the creator should save some data to table A, otherwise it should save other date to table B.

A: Maybe you're looking for the strategy pattern?
From wikipedia:
In computer programming, the strategy pattern (also known as the policy pattern) is a behavioural software design pattern that enables an algorithm's behavior to be selected at runtime. The strategy pattern:

*

*defines a family of algorithms

*encapsulates each algorithm

*makes the algorithms interchangeable within that family.


text:
Q: Using AndroidInjections contribution module (abstract class) as subcomponent in Dagger 2 I study Dagger 2 and try to understand how I can attach it to an already existing project. Now I faced with the following problem with injectiing dependencies into BroadcastReceivers. I can't use DaggerReceiver because my receivers already extends another class. To use AndroidInjection inside BroadcastReceivers, I should inject DispatchingAndroidInjector to Application class. I don't want to include module with AndroidInjection contributors to main dependency graph so, how I understand, I should place it to dedicated component for Application class, but because of this duplication of Singletons occurs.
Here is my example (GitHub repo)
Classes to provide dependencies to MainActivity and other classes
AppModule.class
@Module
public class AppModule {

    Application mApplication;

    public AppModule(Application application) {
        mApplication = application;
    }

    @Singleton
    @Provides
    Application providesApplication() {
        return mApplication;
    }
}

UtilityModule.class
@Module
public class UtilityModule {

    @Singleton
    @Provides
    FirstUtilityClass providesFirstUtility(Application app) {
        return new FirstUtilityClass(app);
    }

    @Singleton
    @Provides
    SecondUtilityClass providesSecondUtility(Application app) {
        return new SecondUtilityClass(app);
    }
}

MainComponent.class
@Singleton
@Component(modules = { AppModule.class, UtilityModule.class })
public interface MainComponent {

    void inject(MainActivity activity);
}

Classes to provide DispatchingAndroidInjector to Application class
ReceiversModule.class
@Module
public abstract class ReceiversModule {

    @ContributesAndroidInjector
    abstract FirstReceiver contributesFirstReceiver();

    @ContributesAndroidInjector
    abstract SecondReceiver contributesSecondReceiver();
}

ReceiversComponent.class
@Singleton
@Component(modules = { AppModule.class, UtilityModule.class, ReceiversModule.class })
public interface ReceiversComponent {

    void inject(MyApplication application);
}

Injecting...
MyApplication.class
public class MyApplication extends Application implements HasBroadcastReceiverInjector {

    @Inject DispatchingAndroidInjector<BroadcastReceiver> mInjector;
    @Inject FirstUtilityClass mFirstUtility;
    @Inject SecondUtilityClass mSecondUtility;
    MainComponent mMainComponent;

    @Override
    public void onCreate() {
        AppModule appModule = new AppModule(this);
        mMainComponent = DaggerMainComponent.builder().appModule(appModule).build();
        // I should build new component only for Application class, because DispatchingAndroidInjector not required for another targets
        DaggerReceiversComponent.builder().appModule(appModule).build().inject(this); // Here created new scope
        super.onCreate();
        // do something
        mFirstUtility.doFistThings(getClass().getSimpleName());
        mSecondUtility.doSecondThings(getClass().getSimpleName());
    }

    public MainComponent getMainComponent() {
        return mMainComponent;
    }

    @Override
    public AndroidInjector<BroadcastReceiver> broadcastReceiverInjector() {
        return mInjector;
    }
}

MainActivity.class
public class MainActivity extends AppCompatActivity {

    @Inject FirstUtilityClass mFirstUtility;
    @Inject SecondUtilityClass mSecondUtility;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ((MyApplication) getApplication()).getMainComponent().inject(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Do something
        mFirstUtility.doFistThings(getClass().getSimpleName());
        mSecondUtility.doSecondThings(getClass().getSimpleName());
        // Sending broadcasts here
    }
}

Logcat output

FirstUtilityClass1: doing first things from MyApplication...
SecondUtilityClass1: doing second things from MyApplication...
FirstUtilityClass2: doing first things from MainActivity...
SecondUtilityClass2: doing second things from MainActivity...
FirstUtilityClass1: doing first things from FirstReceiver...
SecondUtilityClass1: doing second things from SecondReceiver...

How you see in log, Apllication and MainActivity receives different instances of utility classes. I had an idea to make ReceiversComponent as a subcomponent of MainComponent. But ReceiversModule is abstract and I cant add it dinamicaly to existed component instance.
MainComponent.class
@Singleton
@Component(modules = { AppModule.class, UtilityModule.class })
public interface MainComponent {

    ReceiversComponent with(ReceiversModule module);

    void inject(MainActivity activity);
}

ReceiversComponent.class
@Subcomponent(modules = { ReceiversModule.class })
public interface ReceiversComponent {

    void inject(MyApplication application);
}

And then in MyApplication:
// It does not work because I can't create ReceiverModule instance :(
mMainComponent.with(new ReceiversModule()).inject(this);

How can I use the ReceiversComponent as a subcomponent of MainComponent?
It's clear to me that I'm doing something wrong, but I just can't understand where. Maybe there is another way to solve my problem?

A: I just found the answer!
Since my ReceiversModule class has a default constructor without parameters, I can skip it as parameter when describing the subcomponent in MainComponent interface:
MainComponent.class
@Singleton
@Component(modules = { AppModule.class, UtilityModule.class })
public interface MainComponent {

    ReceiversComponent withReceiversModule(); // Here is the reference to the subcomponent with abstract module

    void inject(MainActivity activity);
}

MyApplication.class
@Override
public void onCreate() {
    AppModule appModule = new AppModule(this);
    mMainComponent = DaggerMainComponent.builder().appModule(appModule).build();
    mMainComponent.withReceiversModule().inject(this); // It's works!!! :)
    super.onCreate();
    // do something
    mFirstUtility.doFistThings(getClass().getSimpleName());
    mSecondUtility.doSecondThings(getClass().getSimpleName());
}

Maybe someone will think it is a trifle, but it took me several days to reach it. I'm very happy, because my code has become a little cleaner. Thanks to all!


text:
Q: Start firefox using apparmor (for extra security) I'm having some trouble starting firefox with apparmor. Here's what I've run:
$ sudo aa-enforce /etc/apparmor.d/usr.bin.firefox
$ firefox
/usr/lib/firefox/firefox: error while loading shared libraries: libpthread.so.0: cannot stat shared object: Permission denied

Does firefox now work out of the box with the configs provided by ubuntu? Do I need any extra configs?

A: I think you should run firefox as root too because you run apparmor as root.
maybe thats why it says

Premission denied

sudo firefox


text:
Q: what is the meaning of this symbolics rel ${I^.}?$ I have some confusion in symbolics
My confusion is given below and marked in red circle

What is the meaning of this symbolics $\operatorname{rel}\dot{I}$?
My attempt: I know that  $I$ represent closed interval $[0,1]$   but my confusion is  about a point  which is lie above on  $I$ and  word rel

A: I would be surprised if there wouldn't be a definition in your textbook. Anyway, "rel $\dot I$" means relative to the boundary of $I$, i.e. relative to $\{0,1\}$. And this means that the homotopy $H : u * u^{-1} \simeq c \text{ rel } \dot I$ is stationary on $\{0,1\}$, i.e, that $H(i,s) = u(0) = c(0)$ for all $s \in I$ and $i = 0, 1$.


text:
Q: Do new pygame surfaces have to be .convert()ed? When you create a new Pygame surface:
pygame.Surface((width, height), flags=0, depth=0, masks=None)

Do you have to call .convert() on it to change its pixel format, or is that already done for you when you create it?

A: convert is only used when changing pixel formats (for example, going from indexed to rgb).  The surface will be created with RGB by default and you should only need to convert it if that isn't what you need (it almost always is).

A: When you create a new surface, its format always matches (as best it can) the format of the current display surface (whatever you set when you called pygame.display.set_mode() last). You won't need to convert new surfaces unless their format demands will differ from the display surface (alpha, for one, or indexed colour, as Name mentioned).
Note that if the new surface does have per-pixel alpha depth (with or without other format particulars), you will want to use convert_alpha() instead.
From the docs: http://www.pygame.org/docs/ref/surface.html
(Which may have been updated in the almost twenty months since the question was asked.)


text:
Q: Maven - Different versions of same library automatically considered for 2 different projects in a same Eclipse/STS workspace
*

*I wanted to use same version of log4j2 for all my projects.

*So I manually deleted all other versions of log4j2 from ".m2" folder and only kept log4j2 2.17.0 version of the library.

*I also observed that, if I've kept any projects open which uses different version of log4j, then eclipse will trigger maven to automatically download them. Hence, I closed all other projects and only kept 2 projects in "Open" mode, where both of them are inside same workspace.

*Now when I checked the "Dependency hierarchy" of both the projects, I'm seeing the below difference.

4.a. Project 1 is using "2.13.2" version of log4j2. But since I've manually mentioned in the pom.xml to use "2.17.0" version, "2.13.2" has been overridden.

4.b. Project 2 is using "2.7" version of log4j2. But since I've manually mentioned in the pom.xml to use "2.17.0" version, "2.7" has been overridden.

So, if I remove the "2.17.0" version from pom.xml, then Project 1 will fall back to "2.13" and Project 2 will fall back to "2.7".
Based on this observation, I have 2 questions.

*

*Why "2.17.0" is not being used by both the projects by default?

*And what is causing them to use 2 different versions of log4j2 in 2 different projects. I mean to ask, at least both of them could have used "2.13" OR both of them could have used "2.7" right?


text:
Q: IIS authentication error I'm trying to simply run a local website which has sime basic HTML files using IIS.
Through the IIS Manager I have created a new website and have set the physical path to the directory with the HTML files.
However when I input the physical path I get the following warning:

The server is configured to use pass-through authentication with a
  built-in account to access the specified physical path. However, IIS
  Manager cannot verify whether the built-in account has access. Make
  sure that the application pool identity has Read access to the
  physical path. If this server is joined to a domain, and the
  application pool identity is NetworkService or LocalSystem, verify
  that \$ has Read access to the physical path.
  Then test these settings again.

Now, when I navigate to the site through localhost I get the following Unauthorized error:

You do not have permission to view this directory or page because of
  the access control list (ACL) configuration or encryption settings for
  this resource on the Web server.

What's going on here? When I right click my folder I seem to have given access to everyone. I haven't made any specific IIS changes so what could be the issue here?
EDIT:
MAN I cannot believe this. My case is so simple (I just wanna display some HTML files on localhost) which should require ZERO configuration at all. Yet IIS fails to meet the demand.
EDIT: I think everyone should have permission to my folder. Here's a picture of the permissions screen for the folder:

A: Working with a set of server protocols is different than adding files to a share. In this case, you're going to want to open IIS and navigate to the website you added it as.
There, you'll see a variety of icons, some under the heading of ASP.NET, some under IIS. The first heading you'll see under IIS is Authentication. That's the one you want. If this is strictly internal/for learning, go ahead and enable Anonymous Authentication. It's not safe, but it'll get you in the right place to start googling around.


text:
Q: Ignore folders in htaccess I'm making a webapp using AngularJS. For routing, I used a htaccess rewrite rule to allow direct access to routing pages (for example going directly to /settings). However there is one folder I would like to exclude from this rule, so I can check if a file exists (now every URL returns 200). I've tried every combination of rewrite conditions and rules I could find, but no luck.
So far this is my .htaccess file
<IfModule mod_rewrite.c>
RewriteEngine On
#Options FollowSymLinks
RewriteBase /

RewriteCond %{REQUEST_URI} !(orders)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /#/$1 [L]
</IfModule>

ErrorDocument 404 /404.php

I would appreciate any help
EDIT:
I would like to exclude all files and folders under orders

A: Try
RewriteCond %{REQUEST_URI} !^/orders [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /#/$1 [L]

%{REQUEST_URI} always starts with a / and because you aren't specifying something like .* at the beginning of the regex, you have to have the slash. I also added the [NC] flag so that a url like "/ORDerS" would be skipped as well.


text:
Q: How does the <:< operator work in Scala? In Scala there's a class <:< that witnesses a type constraint. From Predef.scala:
  sealed abstract class <:<[-From, +To] extends (From => To) with Serializable
  private[this] final val singleton_<:< = new <:<[Any,Any] { def apply(x: Any): Any = x }
  implicit def $conforms[A]: A <:< A = singleton_<:<.asInstanceOf[A <:< A]

An example of how it's used is in the toMap method of TraversableOnce:
def toMap[T, U](implicit ev: A <:< (T, U)): immutable.Map[T, U] =

What I don't understand is how this works. I understand that A <:< B is syntactically equivalent to the type <:<[A, B]. But I don't get how the compiler can find an implicit of that type if and only if A <: B. I assume that the asInstanceOf call in the definition of $conforms is making this possible somehow, but how? Also, is it significant that a singleton instance of an abstract class is used, instead of just using an object?

A: Suppose we've got the following simple type hierarchy:
trait Foo
trait Bar extends Foo

We can ask for proof that Bar extends Foo:
val ev = implicitly[Bar <:< Foo]

If we run this in a console with -Xprint:typer, we'll see the following:
private[this] val ev: <:<[Bar,Foo] =
  scala.this.Predef.implicitly[<:<[Bar,Foo]](scala.this.Predef.$conforms[Bar]);

So the compiler has picked $conforms[Bar] as the implicit value we've asked for. Of course this value has type Bar <:< Bar, but because <:< is covariant in its second type parameter, this is a subtype of Bar <:< Foo, so it fits the bill.
(There's some magic involved here in the fact that the Scala compiler knows how to find subtypes of the type it's looking for, but it's a fairly generic mechanism and isn't too surprising in its behavior.)
Now suppose we ask for proof that Bar extends String:
val ev = implicitly[Bar <:< String]

If you turn on -Xlog-implicits, you'll see this:
<console>:9: $conforms is not a valid implicit value for <:<[Bar,String] because:
hasMatchingSymbol reported error: type mismatch;
 found   : <:<[Bar,Bar]
 required: <:<[Bar,String]
       val ev = implicitly[Bar <:< String]
                          ^
<console>:9: error: Cannot prove that Bar <:< String.
       val ev = implicitly[Bar <:< String]
                          ^

The compiler tries the Bar <:< Bar again, but since Bar isn't a String, this isn't a subtype of Bar <:< String, so it's not what we need. But $conforms is the only place the compiler can get <:< instances (unless we've defined our own, which would be dangerous), so it quite properly refuses to compile this nonsense.

To address your second question: the <:<[-From, +To] class is necessary because we need the type parameters for this type class to be useful. The singleton Any <:< Any value could just as well be defined as an object—the decision to use a val and an anonymous class is arguably a little simpler, but it's an implementation detail that you shouldn't ever need to worry about.


text:
Q: Proguard obfuscation How to obfuscate more than one jars, and keep dir structure I have folder "plugins" library where I put my code packed as jars(2 files). Also i have my javafx application, which is packed with maven-assembly-plugin which generate jar with all dependencies.
 --
   |-plugins
       |-plugin-1.jar
       |-plugin-2.jar
   |-{filename}-jar-with-depenencies.jar
Is that possible to obfuscate not only jar with dependencies and keep directory structure.
p.s when I obfuscate {filename}-jar-with-depenencies.jar and copy to project directory all works fine, but i need my plugins being obfuscated
<plugins>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <inherited>true</inherited>
    <configuration>
        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>com.app.myapp.gui.MainWindow</mainClass>
                <packageName>com.app.myapp.gui</packageName>
                <addClasspath>true</addClasspath>
                <classpathPrefix>plugins/</classpathPrefix>
            </manifest>
        </archive>
    </configuration>
</plugin>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.8</version>
    <executions>
        <execution>
            <id>copy-dependencies</id>
            <phase>package</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
        <archive>
            <manifest>
                <mainClass>com.app.myapp.gui.MainWindow</mainClass>
            </manifest>
        </archive>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
        <appendAssemblyId>true</appendAssemblyId>
    </configuration>
    <executions>
        <execution>
            <id>make-assembly</id> <!-- this is used for inheritance merges -->
            <phase>package</phase> <!-- bind to the packaging phase -->
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.5.1</version>
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
    </configuration>
</plugin>
<plugin>
    <groupId>com.github.wvengen</groupId>
    <artifactId>proguard-maven-plugin</artifactId>
    <version>2.0.10</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals><goal>proguard</goal></goals>
        </execution>
    </executions>
    <configuration>
        <obfuscate>true</obfuscate>
        <injar>plugins\v-plugin-1.16.0-24.jar</injar>
        <injar>plugins\p-plugin-1.16.0-24.jar</injar>
        <injar>${project.build.finalName}-jar-with-dependencies.jar</injar> <!-- make sure to obfuscate the jar with dependencies -->
        <includeDependency>true</includeDependency>
        <proguardVersion>5.2</proguardVersion>
        <includeDependency>true</includeDependency>
        <options>
            <option>-allowaccessmodification</option>
            <option>-flattenpackagehierarchy ''</option>
            <option>-dontoptimize</option>
            <option>-dontshrink</option>
            <option>-dontnote</option>
            <option>-dontwarn</option> <!-- added option to ignore com.sun missing classes -->
            <option>-dontusemixedcaseclassnames</option>
            <option>-keepattributes Exceptions,InnerClasses,Signature,Deprecated,SourceFile,LineNumberTable,*Annotation*,EnclosingMethod, CallbackMethods </option>
            <option>-keep class !com.app.** { *; }</option>
            <option>-keepclasseswithmembers public class * { public static void main(java.lang.String[]); } </option>
            <option>-dontskipnonpubliclibraryclassmembers</option>
            <option>-dontskipnonpubliclibraryclasses</option>
            <option>-verbose</option>
        </options>
        <libs>
            <lib>${java.home}/lib/rt.jar</lib>
            <lib>${java.home}/lib/ext/jfxrt.jar</lib>
        </libs>
    </configuration>
    <dependencies>
        <dependency>
            <groupId>net.sf.proguard</groupId>
            <artifactId>proguard-base</artifactId>
            <version>5.2.1</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
</plugin>

A: I would suggest to obfuscate code while packaging them using proguard maven plugin.
So once your jar files reaches destination which is plugins in your case, they  would be already obfuscated.
This would be a cleaner approach.
This is all I can suggest without looking your build process.


text:
Q: Download the first 75 pages in an RSS feed to python Given the URL of a page's RSS XML for example http://feeds.abcnews.com/abcnews/topstories
How can I download the HTML for each of the latest 75 pages in the RSS feed using python and urllib2?
Or is there an easier way to access the sites of RSS feeds such as another python module?

A: Perhaps you could take a look at feedparser.
Also, check out this introductory usage information.


text:
Q: How do I connect to signalR hub on another server and my client app on another server I  have my signalR hub on another server, http://localhost:51109 and my client app on http://localhost:8100.
I know that placing the /signalr script in my html on my client server will result in a 404, how do I go about this. My client side is completely angular js.

A: Add the external script via the <script> tag:
<script src="http://localhost:51109/signalr/hubs"></script>

Then in the Javascript code, utilize it like this:
$.connection.hub.url = "http://localhost:51109/signalr";

That's it.


text:
Q: Xcode Project Files not appearing in Project Navigator Strange problem here...my project's Swift files, Main.Storyboard, additional images, delegate, etc. files are all missing from Xcodes Project Navigator.
What is really strange is that the project builds fine and I can also select them from the top of the main editor window even though they are not displayed on the left in the Project Navigator.
When I open my project, the files appear for about 1/2 a second, and then the list is condensed to the blue target file at the top and about 7 images. (I cannot post a picture because my reputation is not high enough.)
I've quit and reopened Xcode and also performed a few restarts, but I still can't select them...even though they're apparently there! Any ideas?

A: For me the issue was different.  My search bar was empty but I had mistakenly selected the clock icon in the search bar at the bottom of the navigator.
Unselected it looks like this

Selected it look like this

The clock icon filters the files for files that have been recently used and therefore, hides a number of your files.

A: May be you need check the Project Navigator's bottom, there is a search bar.
If the search bar had some keywords, the Project Navigator would only show the files which file's name contain the keyword(s), and you can't clear the keyword by only reopen Xcode.
When you open Xcode, Xcode will initial the search bar with nothing and you can see the complete files, after initial had done, Xcode will load last close time's state for the search bar and filter files, so that's why When I open my project, the files appear for about 1/2 a second.

A:
Untick this timer icon at the bottom of navigator in case you have selected it

A: I solved this problem by removing a copy of the file that was being referenced by the code module where the error was occurring but was not being referenced by the project file in Project Navigator.  Explanation:  I had long ago moved a file to a different directory and changed the reference in the project, but had not deleted the original version of the file.  The file still existed on the file system in the original location  but was being referenced by the project file and Project Navigator (.xcodeproj) in a new location.  The referencing code module still found the file in then old location and did not update the pointer to the new location automatically.  Simply deleting the file in the old location fixed this issue for me.
I debugged this by drilling into the referenced file by right clicking on the object name in code which opened up the module in a code window and then right clicking on the code and selecting "Show in finder".  I then compared this location to the location found in the Project Navigator by right clicking on the file name there and selecting "Show in Finder".

A: The problem for me was that I had added the project file instead of the project folder in Xcode. I recommend closing the window, opening another instance of Xcode with the FOLDER that contains the project in it instead.

A: This is usually caused by the clock icon as mentioned by @jonthornham. For a detailed explanation, please visit this site: https://xalting.com/2019/12/26/what-to-do-if-your-files-are-not-showing-up-in-xcode/.

A: This is caused by conflicts project.pbxproj file inside your projects, to get out of this error just follow bellow steps.

*

*Find the backup of your project, if you don't have any backup copy "project.pbxproj" file from another (any) project. its located inside "projectName.xcodeproj" just copy it by clicking show package contents.

*Replace this file in your current project.

Thats it!
Happy Coding


text:
Q: how can i make for google extension background page which using my website I need Chrome Extension which Open Newtab page and Newtabpage Will be My Website Link and this website will be only background Page because i dont want my webpage link will be in adres bar. can you help me ? or suggest my how can i make it

A: You can use background pages: https://developer.chrome.com/extensions/background_pages.
But if you want a new tab, the link will appear anyway. Using background pages, you can put custom html, as iframes and your website will load. But the user won't see.
If you want that your user see the page, use popups, tabs or custom javascript injection
instead.


text:
Q: OWIN DbContext and a single DbContext for all of my Repositories I am building a ASP.NET MVC application.  I'm new to the whole Repositories/Unit Of Work patterns.  I'm part way through implementing a generic repository for my EF objects.
I realise that there is an issue with ensuring that you only have a single DbContext per Http request... I'm pretty sure that I can achieve this by creating an instance using OWIN.
    /// <summary>
    /// Configures OWIN
    /// </summary>
    /// <param name="app"></param>
    public void Configuration(IAppBuilder app)
    {
        // Create instance of database context
        app.CreatePerOwinContext<QuizEntitiesDbContext>(GetQuizEntitiesDbContext);
    }

    /// <summary>
    /// Returns an instance of the QuizEntitiesDbContext database context
    /// </summary>
    /// <returns></returns>
    public static QuizEntitiesDbContext GetQuizEntitiesDbContext()
    {
        return new QuizEntitiesDbContext();
    }

Now that seems fine if I want to get that instance within my controller, but really I need to be able to access this instance through my generic repository...

*

*Is there a way that this can be achieved?

I'm also using Ninject dependency injector in my project and I've read that I can get an instance of objects per HTTP request for use in my application, something along the lines of this:
this.kernel.Bind(IMyDbContext).To(MyDbContext).InRequestScope();

*

*Should I be using this/OWIN or both?

*Do I need to wrap my DbContext in an interface or something?


text:
Q: How should I attach a picture in Limesurvey for the email template? When I try to attach a picture in Limesurvey v.1.87+ in the email template, it is attached correctly (it seems because I can see it) but when I send the invitation to the tokens, the picture does not appear in the email at all and I can´t figure out why.
Has somebody the same problem before?
Thank you very much to you all!

A: You need to put complete link of the picture,
Replace

by

LS 1.87 don't support attachment. And the link or not email ready (fixed in 2.0).


text:
Q: Can't export emacs display on ssh local_machine:$> ssh myself@external_machine_ip_address -p specific_port -X
external_machine:$> echo $DISPLAY
localhost:10.0
external_machine:$> emacs
Warning: Cannot convert string "-*-courier-medium-r-*-*-*-120-*-*-*-*-iso8859-*" to type FontStruct
Warning: Cannot convert string "-*-helvetica-medium-r-*--*-120-*-*-*-*-iso8859-1" to type FontStruct

I do see the emacs window, but I can't see any of the characters. What could be the error ?

A: Looks like the font you're trying to use isn't available on your machine. You probably chose it because it was available on external_machine_ip_address. It could be because the displays have different resolutions; try using -*-courier-medium-r-*-*-12-*-*-*-*-*-iso8859-* instead. The tool xfontsel can be helpful to find an existing font.

A: Just a quick workaround, not a complete solution
First see what fonts is available in your computer
$>xlsfonts
-arabic-newspaper-medium-r-normal--0-0-100-100-p-0-iso10646-1
-arabic-newspaper-medium-r-normal--32-246-100-100-p-137-iso10646ourChoosen-1
-ascender-droid-bold-i-normal--0-0-0-0-p-0-iso8859-1
....

Choose one of them then
$>emacs -font "yourChooenFont"

In my machine the font "9x15" looks quite neat, i.e.
$>emacs -font "9x15"


text:
Q: Making a foldl function for BinarySearchTree I've made a foldr function for BinSearchTree, but I'm not quite sure if it's correct. Do any of you see a problem here? Any tips? (I can't use deriving Foldable)
data BinSearchTree a
  = Empty
  | Branch (BinSearchTree a) a (BinSearchTree a)
  deriving (Eq, Show)

instance Foldable BinSearchTree where
  foldr f x Empty = x
  foldr f x (Branch left a right) = f a (foldr f y right)
         where y = foldr f x left

A: You fold the left subtree first here
y = foldr f x left
then you fold right subtree with left result as an accum
foldr f y right

and only after you fold a branch's argument
f a folding_result

To implement right fold you need to start from folding right subtree, then call a function on a branch's argument, and only then fold the left one
foldr f (f a (foldr f x right)) left


text:
Q: Wordpress Standard Fix Errors I get the following error while fixing my wordpress plugin standards.
 Use placeholders and $wpdb->prepare(); found $sql

Below is my code...
public function get_db_value() {
    //getting meta_value from wp_usermeta
    global $wpdb;
    $billing_phone = isset($_POST['billing_phone']);
    $sql           = "
    SELECT  user_id,meta_key, meta_value
    FROM {$wpdb->usermeta}
    WHERE ({$wpdb->usermeta}.meta_key = 'billing_phone'";
    $ansatte       = $wpdb->prepare($wpdb->get_results( $sql ));
    $users         = array();
    foreach ( $ansatte as $a ) {
        $users[ $a->user_id ][ $a->meta_key ] = $a->meta_value;
    }
    foreach ( $users as $u ) {
        $nums[] = $u['billing_phone']; //Saving phone numbers in $nums variable

    }
    return $nums;
}


text:
Q: UseCanonicalName On applied however host of request header still wasn't change I had an issue with website redirection and I found that my rewritecond input= 'www.example.com' and my request header host = 'example.com'. So I try to apply UseCanonimalName On in vhost where my ServerName define as 'www.example.com' by hoping that when both are matched, my website redirection will happen but unfortunately it doesn't and host in my request header still remain 'example.com'. I refer to this and this to do it.
Below are my httpd-vhost.conf:
<VirtualHost *:80>
    ServerName www.example.com
    ServerAlias example.com
    UseCanonicalName On
    DocumentRoot "d:/wamp64/www/example"
    <Directory  "d:/wamp64/www/example/">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
        Order allow,deny
        Allow from all
        Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains"
    </Directory>
</VirtualHost>

Below are the host that I got

Below are the expectation that I would want to receive:

The host is changing from example.com to www.example.com but unfortunately, it only works in Firefox but not other browsers which IDK why?!
***Am using Windows server
Please correct me if I understand or do it wrongly. Thanks all!

A: The UseCanonicalName is not related to redirections but to self-referential URLs.

*

*Off: "form self-referential URLs using the hostname and port supplied by the client"

*On: "use the hostname and port specified in the ServerName directive to"

The redirection you see is not related to this, but a result of the HSTS policy you have specified with Strict-Transport-Security. A browser that supports HSTS and has seen this header will perform an internal redirection to HTTPS regardless your <VirtualHost *:80> configuration.


text:
Q: Firefox - transparent png taking CSS background attribute's while firefox is refreshing cached images Working on an image heavy website, discovered a strange bug(?) in Firefox. Any CSS background properties are rendered onto transparent png's. It occurs after the initial render, during the cache refresh. This appears as a flicker if you're using broadband but becomes extremely noticeable as you scale down bandwidth.
General progression of the issue seems to be:

*

*Page and images rendered from cache

*Firefox removes the cached images.

*Firefox begins to reload images but displays a box with the CSS properties of the background.

I've recreated a (hideously colorful) example, but you may need to use fiddler, or another program with bandwidth throttling/emulation to see anything more than a flicker. Obviously, you'll also have to load once and then refresh to experience the error. And again, it's only in Firefox.
I have tried a plethora of various suggestions, none worked. Just need a fix, hacks will work as long as they don't effect other browsers.
EDIT: Here's a video so you can see it in action.

A: Since I cannot recreate the issue on my Firefox (10.0.2) on my computer (Win 7) with my particular hardware (which may or may not be a part of this problem), I offer the following as a guess at a solution, though one I would have assumed you tried already.
Target your img tags (preferably with some css more specific than below) that you have the issue with and try setting one of the following:
Either:
img {background-color: transparent;}

Or:
img {background-color: transparent !important;}

Update: Another Possible Workaround
Have javascript make the relevant img tags invisible to start and also bind an event to them so that when they load, they become visible again (JQuery example):
$('img').css('visibility', 'hidden'); /*not using "display" keeps layout*/
$('img').bind('load', function() {
    $('img').css('visibility', 'visible');
});

I cannot test the above, so no guarantee it will work, but is another idea.


text:
Q: Fixie convention to find test methods in subclasses By default Fixie smartly looks for test methods in classes with Tests postfix. It works smoothly and all you tests are executed without cumbersome xUnit-style attributes. But I tend to group my tests into nested classes according to the name of the method under test:
public class ConnectorTests
{
  public class Connect
  {
    ... //Connect method tests
  }

  public class Disconnect
  {
    ... //Disconnect method tests
  }
}

If tests are grouped this way, Fixie doesn't see test methods with default convention. How should custom convention look like to fix that?

A: I ended up writing the following convention:
    class TestingConvention : Convention
    {
        public TestingConvention()
        {
            Classes
                .Where(x =>
                {
                    if (x.Name.EndsWith("Tests"))
                        return true;

                    if (x.DeclaringType != null && x.DeclaringType.Name.EndsWith("Tests"))
                        return true;

                    return false;
                });
        }
    }

It covers both cases when I have test methods directly in xxxTests class (when tested class has one public method like Query/Command handlers) and when test methods are placed in an innner class.


text:
Q: i cant seem to know how to transform a Method in a class here is my code
: https://i.stack.imgur.com/FOGQ8.png
I don't know how to transform the self.weekly_salary into a float so i can multiply
it by another number in self.monthly_salary
class Employee:
    weeks_in_month = 4
    def __init__(self,w,wd):
        self.wage = w
        self.work_days = wd

    def weekly_salary(self):
        return self.wage*8*self.work_days

    def monthly_salary(self):
        return self.weeks_in_month *self.weekly_salary

    def yearly_salary(self):
        return self.monthly_salary*12
Joe = Employee(13.5,4)

I have tried using __int__ or __float__ on the method but it all comes back as an error
please help i am still a newbie

A: class Employee:
    weeks_in_month = 4
    def __init__(self, w, wd):
        self.wage = w
        self.work_days = wd

    def month_in_year(self):
        return 12

    def weekly_salary(self):
        #print('Weekly salary', self.wage * 8 * self.work_days)
        return float(self.wage * 8 * self.work_days)

    def monthly_salary(self):
        #print('Monthly Salary',self.weeks_in_month * self.weekly_salary())
        return float(self.weeks_in_month * self.weekly_salary())

    def yearly_salary(self):
        print('Yearly Salary', self.monthly_salary() * self.month_in_year())
        return self.monthly_salary() * 12

Joe = Employee(13.5, 4)

Joe.yearly_salary()

You forgot to call self.monthly_salary() instead you tried to subtract an int with a method directly which gives typeerror