text:
Q: How to display two NSAttributedStrings in different lines in a UILabel I need to display two lines of an attributed string in a UILabel, for example, theTopMessage on the first line and theBottomMessage on the second line. Both of them are NSAttributedStrings.
I used the following code, but I did not get what I want. theTopMessage and theBottomMessage are on the same line. Can anyone help me? Thanks very much.
_eventInfoLbl.lineBreakMode = NSLineBreakByWordWrapping;
_eventInfoLbl.numberOfLines = 0;
_eventInfoLbl.attributedText = info(nsattributed string which holds theTopMessage and theBottomMessage);
[_eventInfoLbl sizeToFit];


text:
Q: vertical align a "button" I´ve made a transparent "button" and place it on a fullwidth background image
 I use the class in an
I would like the button to be centered responsively on the image. I got it done horizontally but not exactly vertically. (My idea is to make a one page type a page)
Here is the html:

nav area

              Butt text
second line
third

This is centered text.

main area

the CSS
.abs {
  position: absolute;
  z-index: 2;
margin: 25% auto 0;
  left: 0;
  right: 0;
}
.button-transp {
  display: inline-block;
  min-width: 170px;
  max-width: 500px;
  width: 30%;
  padding: 8px;
  color: #fff;
  background-color: transparent;
  border: 2px solid #fff;
  text-align: center;
  outline: none;
}

I use margin: 25% auto 0; to get it something near right..

A: You wanted the button to stay center responsively to the image, which, in this case you should use background image. Then position your button to be 50% from the top, 50% from the left and pull it back -1/2 of its height to the top and -1/2 of its width to the left. Doing this to enforce the button to always stay in the center of the bg-image.

nav area

       Butt text
second line
third

This is centered text.

main area

.abs {
    position: absolute;
    z-index: 2;
    top: 50%;
    margin-top: -37px;  /** the button height is 74, so pull it half to the top the make the gap top and bottom equal */
    left: 50%;
    margin-left: -95px; /** again, full button width / 2 */
}
.button-transp {
    display: inline-block;
    min-width: 170px;
    max-width: 500px;
    width: 30%;
    padding: 8px;
    color: #fff;
    background-color: transparent;
    border: 2px solid #fff;
    text-align: center;
    outline: none;
}
.bg-image {
    background: url(http://www.online-image-editor.com//styles/2014/images/example_image.png) no-repeat 0 0;
    width: 475px;
    height: 360px;
    position: relative;
}

See fiddle

A: I've abbreviated the structure but this option will work for any size button and will always center both horizontally & vertically.
CSS3 transforms are basically IE9 and up (suitably prefixed as required)

.bg-image {
    height: 200px;
    background: orange;
    position: relative; /* positioning contexr */
}

.button-transp {
    width: 30%;
    white-space:nowrap;
    padding: 8px;
    color: #fff;
    background-color: transparent;
    border: 2px solid #fff;
    text-align: center;
    outline: none;
    position: absolute;
    z-index: 2;
    top:50%;
    left: 50%;
    transform:translate(-50%,-50%);
}

        Butt text
second line
third

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to prevent an assembly from loading when not used I am working in Winforms, C# .NET4.5
I have a class in assembly A called classA, which provides method1
In my main assembly I can call this method, but in some cases I am 100% sure that
this can not happen because of some internal flag from a registry key:
if( valueFromRegistryIsAlwaysFalse)
{
   var A = new classA();
   A.method1();
}

When I set this value in the registry I do not want to provide assembly A with the main executable, however even when I do not use the method it needs assembly A to start. Of course I get this, however is there some way of getting around this?

A: Normally, assembly load and fusion happens on-demand when the CLI is JITting any containing method that uses types from an assembly that hasn't been loaded yet. So: the way to "fix" this is to move ALL of the code involving types in this assembly into methods that will never be executed. For example:
if( valueFromRegistryIsAlwaysFalse)
{
   DoStuff();
}

[System.Runtime.CompilerServices.MethodImpl(
    System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
void DoStuff()
{
   var A = new classA();
   A.method1();
}

With this change, the original method doesn't mention classA, so that method can be JITted without needing the extra assembly; and because DoStuff is never executed / JITted, it never loads from there either.

A: Create an interface assembly that both the caller, and classA reference.
Remove the reference and dynamically load the assembly and instantiate the class.
Assembly asm = Assembly.LoadFile(@"C:\classAAssembly.dll");
Type type = asm.GetType("classA");
IClassA a = Activator.CreateInstance(type) as IClassA;

A: I think for your particular case you can also use MEF http://msdn.microsoft.com/en-us/library/dd460648.aspx

A: Normally the framework loads the assemblies on-demand. A different approach would be to use a dynamic load pattern or composite pattern. Starting from the framework 4.0, MS introduced the System.Addin namespace to help programmers in this. I have the following class which I use in my projects to achieve the same with Framework 2.0 compatibility:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;

namespace MyNamespace
{
    [Serializable]
    public enum CompositeLoaderFilter
    {
        ImplementsInterface = 0,
        InheritsBaseClass = 1
    }

    [Serializable]
    public static class Composite
    {
        private static readonly CompositeManager manager = new CompositeManager();

        public static CompositeManager Manager { get { return manager; } }
    }

    [Serializable]
    public class CompositeManager : MarshalByRefObject
    {
        private SortedList<string, Type> m_addIns;

        public int GetInMemoryComponents(Type addInType, CompositeLoaderFilter filter)
        {
            m_addIns = internal_GetInMemoryServices(addInType, filter);
            return m_addIns.Count;
        }

        public int GetComponents(Type addInType, CompositeLoaderFilter filter)
        {
            string addInPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            return GetComponents(addInPath, "*.dll", SearchOption.TopDirectoryOnly, addInType, filter);
        }

        public int GetComponents(string addInSearchPattern, Type addInType, CompositeLoaderFilter filter)
        {
            string addInPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            return GetComponents(addInPath, addInSearchPattern, SearchOption.TopDirectoryOnly, addInType, filter);
        }

        public int GetComponents(string addInPath, string addInSearchPattern, Type addInType, CompositeLoaderFilter filter)
        {
            return GetComponents(addInPath, addInSearchPattern, SearchOption.TopDirectoryOnly, addInType, filter);
        }

        public int GetComponents(string addInPath, string addInSearchPattern, SearchOption addInSearchOption, Type addInType, CompositeLoaderFilter filter)
        {
            AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
            setup.PrivateBinPath = addInPath;
            setup.ShadowCopyFiles = "false";

            AppDomain m_appDomain = AppDomain.CreateDomain("MyNamespace.CompositeManager", null, setup);
            CompositeManager m_remoteLoader = (CompositeManager)m_appDomain.CreateInstanceFromAndUnwrap(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MyAssembly.dll"), "MyNamespace.CompositeManager");
            m_addIns = m_remoteLoader.RemoteGetServices(addInPath, addInSearchPattern, addInSearchOption, addInType, filter);

    #if DEBUG
            DebugLoadedAssemblies();
    #endif

            AppDomain.Unload(m_appDomain);
            return m_addIns.Count;
        }

        public object CreateInstance(string typeName)
        {
            if (!m_addIns.ContainsKey(typeName))
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Type {0} was not loaded..", typeName), "typeName");

            MethodInfo method = m_addIns[typeName].GetMethod("GetInstance", BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
            if (method != null)
                return method.Invoke(m_addIns[typeName], null);
            else return Activator.CreateInstance(m_addIns[typeName]);
        }

        public object CreateInstance(Type type)
        {
            if (type == null)
                throw new ArgumentNullException("type", "Type is null");

            if (!m_addIns.ContainsKey(type.FullName))
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Type {0} was not loaded..", type.FullName), "type");

            MethodInfo method = type.GetMethod("GetInstance", BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
            if (method != null)
                return method.Invoke(type, null);
            else return Activator.CreateInstance(type);
        }

        public T CreateInstance<T>()
        {
            if (!m_addIns.ContainsKey(typeof(T).FullName))
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Type {0} was not loaded..", typeof(T).FullName), "T");

            MethodInfo method = typeof(T).GetMethod("GetInstance", BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
            if (method != null)
                return (T)method.Invoke(typeof(T), null);
            else return Activator.CreateInstance<T>();
        }

        public IEnumerable<Type> AvailableServices
        {
            get
            {
                foreach (KeyValuePair<string, Type> item in m_addIns)
                {
                    yield return item.Value;
                }
            }
        }

        public Type[] AvailableTypes
        {
            get
            {
                List<Type> list = new List<Type>();
                foreach (KeyValuePair<string, Type> item in m_addIns)
                    list.Add(item.Value);
                return list.ToArray();
            }
        }

        public T[] GetObjects<T>()
        {
            List<T> list = new List<T>();
            foreach (KeyValuePair<string, Type> item in m_addIns)
                list.Add((T)CreateInstance(item.Value));
            return list.ToArray();
        }

        public object[] AvailableObjects
        {
            get
            {
                List<object> list = new List<object>();
                foreach (KeyValuePair<string, Type> item in m_addIns)
                    list.Add(CreateInstance(item.Value));
                return list.ToArray();
            }
        }

        internal SortedList<string, Type> internal_GetInMemoryServices(Type addInType, CompositeLoaderFilter filter)
        {
            SortedList<string, Type> validAddIns = new SortedList<string, Type>();
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly assembly in assemblies)
            {
                try
                {
                    Type[] types = assembly.GetTypes();
                    foreach (Type type in types)
                    {
                        switch (filter)
                        {
                            case CompositeLoaderFilter.ImplementsInterface:
                            if (type.GetInterface(addInType.Name) != null)
                                validAddIns.Add(type.FullName, type);
                            break;

                            case CompositeLoaderFilter.InheritsBaseClass:
                            if (type.BaseType == addInType)
                                validAddIns.Add(type.FullName, type);
                            break;
                        }
                    }
                }
                catch (FileLoadException flex)
                {
                    Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} MyNamespace.CompositeManager: {1}", DateTime.Now.ToString(), flex.Message));
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} MyNamespace.CompositeManager: {1}", DateTime.Now.ToString(), ex.Message));
                }
            }
            return validAddIns;
        }

        internal SortedList<string, Type> RemoteGetServices(string addInPath, string addInSearchPattern, SearchOption addInSearchOption, Type addInType, CompositeLoaderFilter filter)
        {
            string[] files = Directory.GetFiles(addInPath, addInSearchPattern, addInSearchOption);
            SortedList<string, Type> validAddIns = new SortedList<string, Type>();

            if (files.Length > 0)
            {
                foreach (string file in files)
                {
                    if (String.CompareOrdinal(addInPath, file) != 0)
                    {
                        try
                        {
                            Assembly assembly = Assembly.LoadFrom(file);
                            Type[] types = assembly.GetTypes();
                            foreach (Type type in types)
                            {
                                switch (filter)
                                {
                                    case CompositeLoaderFilter.ImplementsInterface:
                                    if (type.GetInterface(addInType.Name) != null)
                                        validAddIns.Add(type.FullName, type);
                                    break;

                                    case CompositeLoaderFilter.InheritsBaseClass:
                                    if (type.BaseType == addInType)
                                        validAddIns.Add(type.FullName, type);
                                    break;
                                }
                            }
                        }
                        catch (FileLoadException flex)
                        {
                            Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} MyNamespace.CompositeManager: {1}", DateTime.Now.ToString(), flex.Message));
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} MyNamespace.CompositeManager: {1}", DateTime.Now.ToString(), ex.Message));
                        }
                    }
                }
            }

    #if DEBUG
            DebugLoadedAssemblies();
    #endif

            return validAddIns;
        }

    #if DEBUG
        internal void DebugLoadedAssemblies()
        {
            foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
            {
                //Debug.WriteLine(string.Format("Domain: {0} Assembly: {1}", AppDomain.CurrentDomain.FriendlyName, a.FullName));
            }
        }
    #endif
    }
}

Following a sample usage:
Composite.Manager.GetComponents(typeof(IMyService), CompositeLoaderFilter.ImplementsInterface);
IMyService[] services = Composite.Manager.GetObjects<IMyService>();

The class will load all the assemblies in current folder, inspecting them to see if they contains a Type that match the input parameters. Because is impossible to unload an assembly once loaded, the class will load them inside a different AppDomain, which in contrary to single assemblies, can be dropped.
In order to use it in your project you should proceed as following:

*

*Remove the (hard) reference to your assembly

*Implement an interface to communicate with your class

*Load the types that implements the above interface

*Use your class through the interface

Hope it helps :)


text:
Q: npm install error when following Angular2 5 min quickstart I get an error when following the Angular2 5 min quick start. How can I get past it?
vagrant@vagrant-ubuntu-trusty-64:/vagrant/angular2-tutorial$ sudo npm install   angular2-quickstart@1.0.0 /vagrant/angular2-tutorial
└── foxy@11.1.4  extraneous

npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: fsevents@1.0.6
npm WARN angular2-quickstart@1.0.0 No description
npm WARN angular2-quickstart@1.0.0 No repository field.
npm ERR! Linux 3.13.0-74-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/local/bin/npm" "install"
npm ERR! node v5.4.0
npm ERR! npm  v3.5.2
npm ERR! path /vagrant/angular2-tutorial/node_modules/.staging/lodash-496d43d7
npm ERR! code EPERM
npm ERR! errno -1
npm ERR! syscall rename

npm ERR! Error: EPERM: operation not permitted, rename '/vagrant/angular2-tutorial/node_modules/.staging/lodash-496d43d7' -> '/vagrant/angular2-tutorial/node_modules/browser-sync/node_modules/lodash'
npm ERR!     at destStatted (/usr/local/lib/node_modules/npm/lib/install/action/finalize.js:25:7)
npm ERR!     at FSReqWrap.oncomplete (fs.js:82:15)
npm ERR!
npm ERR! Error: EPERM: operation not permitted, rename '/vagrant/angular2-tutorial/node_modules/.staging/lodash-496d43d7' -> '/vagrant/angular2-tutorial/node_modules/browser-sync/node_modules/lodash'
npm ERR!     at Error (native)
npm ERR!  { [Error: EPERM: operation not permitted, rename '/vagrant/angular2-tutorial/node_modules/.staging/lodash-496d43d7' -> '/vagrant/angular2-tutorial/node_modules/browser-sync/node_modules/lodash'] parent: 'browser-sync' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.
npm ERR! Linux 3.13.0-74-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/local/bin/npm" "install"
npm ERR! node v5.4.0
npm ERR! npm  v3.5.2
npm ERR! path npm-debug.log.727051537
npm ERR! code ETXTBSY
npm ERR! errno -26
npm ERR! syscall rename

npm ERR! ETXTBSY: text file is busy, rename 'npm-debug.log.727051537' -> 'npm-debug.log'
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     /vagrant/angular2-tutorial/npm-debug.log

Here is the error log:
https://www.dropbox.com/s/xr6ha3z4re0npvi/npm-debug.log.727051537?dl=0

A: It looks like this is the permission issue. The npm is configured to put downloaded modules to a directory that is not authorized.
You can configure npm to install the modules to a custom directory with its prefix configuration.
Refer to following articles:
Use one of these techniques to install node and npm without having to sudo
Installing Node and npm


text:
Q: UserManager.FindAsync does not work Hi my code is working perfectly fine on my own machine and another VM. Now, i have deployed it on Azure VM (not by publishing but by simply copying and creating a virtual directory). Now when i try to login
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            try
            {
                System.Web.HttpContext.Current.Session["SchoolCode"] = model.SchoolCode;
                logger.Debug("assigning school code [" + model.SchoolCode + "] to session, password: " + model.Password);

                var user = await UserManager.FindAsync(model.Username, model.Password);

                logger.Debug("is school code valid: ");

                if (user != null && isSchoolCodeValid(model.SchoolCode))
                {
                    await SignInAsync(user, model.RememberMe);
                    return RedirectToLocal(returnUrl);
                }
                else if(user == null)
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
                else
                {
                    ModelState.AddModelError("", "Invalid School Code.");
                }
            }
            catch (Exception e) {
                logger.Error(e.Message);
            }

        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

my log file only shows the first log and then nothing happens

2017-09-27 09:41:56,915 [16] DEBUG - assigning school code [sc002] to
  session

I am also using a different port (93) on iis because it gave me the error that two sites cannot run simultaneously on the same port

A: So, my issue was entirely different from what i thought it was.
Firstly, i had increased the logging but my iis was picking the cached version which was why i was unable to see the logs. After i was able to see the Error in logs, it said

String was not recognized as a valid Boolean

It took me quiet a while to realize this error was coming due to database aspnetusers table. I changed EmailConfirmed from 0 to False and that fixed the issue!


text:
Q: sourceMappingURL in output Angular 9 SSR I have setup SSR for Angular 9 project. I am using NX workspace with Angular CLI for my application. When I run the application with serve-ssr option, and when I open the page and check a source code, I see sourceMappingURL output in it.
angular.json has already set "sourceMap": false but it is still producing sourceMappingURL in output.


text:
Q: Specify region & culture for Microsoft Office interop I'd like to access Excel through .net interop.  I need to use a different region, but don't want to change the region for the whole OS.  Is there any way to specify this programmatically?  The LanguageSettings property of the ApplicationClass is read-only.

A: You may set the current thread's culture :
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us");

Furthermore, there is/was a bug in Excel when it was necessary to specify en-US culture to use
Interop. It depends on excel configuration (whether updates were applied or not)
Your OS culture may be, for an instance, Russian, but if you explicitly set thread's culture to en-US all will be allright.

A: If it's about the separators, you can do it this way:
    var ci = new CultureInfo(locale);
    var excelApp = new Microsoft.Office.Interop.Exce.Application();

    excelApp.UseSystemSeparators = false;
    excelApp.DecimalSeparator = ci.NumberFormat.NumberDecimalSeparator;
    excelApp.ThousandsSeparator = ci.NumberFormat.NumberGroupSeparator;

A: It could be ddangerous to your application.
In my program when OS language version was different than Office language version then program crashed because Office tried to run automatically language pack. Strange behaviour.


text:
Q: How to reduce the amount of gas? I need to keep track of some events - lots
struct Lot{
        address owner,
        uint256 price,
        uint256 time
    };

There is no need to go into the details of this entity, it is only important that there are many lots and they are regularly created.
Initially, I made a mapping of all lots:
mapping(address=>Lot) lots;

However, this approach requires a lot of gas, especially when trying to change any lot.
Therefore, I thought to do it the following way - to encode each lot and store all lots as a bytecode sequence in the contract.
That is, F let the encoding function:
F(x) = b1b2...bN; bi - byte
F-1(b1b2...bN) = x
S = F(lot1, lot2, ..., lotM)

Now only S will be contained in the storage and store all existing lots in itself.
Are there implementations of this?

A: I assume you want to store all the information on-chain.
I don't see a way in which your encoding is useful. Since S is basically a sequence of all lots together, it will occupy the same storage space of the mapping. Also modifying/adding a lot will use at best the same gas.
The only trick you can use is compress the Lot struct from 3 storage slot to 2 (or even 1). You can do it by lowering the bytes of the variables, for example:
    // this is 3 slots
    struct Lot{
        address owner,
        uint256 price,
        uint256 time
    };

    // this is 2 slots
    struct Lot{
        address owner,
        uint128 price,
        uint128 time
    };

    // this is 2 slots
    struct Lot{
        address owner,
        uint96 price,
        uint256 time
    };

    // this is 1 slot
    struct Lot{
        address owner,
        uint48 price,
        uint48 time
    };

Of course it all depends if price and time need to be fine-grained, their range, etc...


text:
Q: jshint: enforcing "globalstrict" : false when "node" : true In my .jshintrc file I have globalstrict set to false and node set to true.  A side affect of this is that is appears to suppress the warnings I would expect if a global use strict was in place.
Is there any way of overriding this behaviour so that the warning is not suppressed?
Edit
Having re-read the docs on jshint.com and some of the issues on GitHub (notably #1922 and #2551) I have modified my .jshintrc as follows:
{
  "bitwise": true,
  "curly": true,
  "debug": false,
  "eqeqeq": true,
  "forin": true,
  "freeze": true,
  "futurehostile": true,
  "globalstrict": false,
  "latedef": true,
  "noarg": true,
  "nonbsp": true,
  "nonew": true,
  "singleGroups": true,
  "strict": true,
  "undef": true,
  "unused": "strict",

  "browser": false,
  "devel": false,

  "node": true,

  "predef": [
    "-console"
  ],

  "+W097": true
}

However this doesn't work for this particular message (it does though if, for example, I change it to -W034, which is the functional equivalent).
Thanks

A: This currently isn't possible however issue #2575 and associated pull request #2576 will provide the functionality if they are accepted.


text:
Q: In Javascript, how can I check the existence of a specific key/value pair nested inside another key/value pair? For example, this is the value of the object I am processing:
object = {"message":"success","dataList":{"state":"error","count":"25"}}

I know that to check if key "message" exists, I can do the following:
if(object['message']){
    //"message" exists. do stuff.
} else{
    //"message" does not exist
}

How do I check for the existence of "state" or "count" though?

A: if(object['dataList']['state']){
    // dataList["state"] exists. do stuff.
} else {
    // dataList["state"] does not exist
}

or the (in my opinion) more readable:
if(object.dataList.state){ ... }

Edit: It would also be a good idea to check for all parent objects so you will not get an unexpected  error when, for example, dataList does not exist on the object:
if (object && object.dataList && object.dataList.state)

A: try like this:
object = {"message":"success","dataList":{"state":"error","count":"25"}};

    if(object.message =='success'){
        console.log(object.dataList);// your datalist object here use it
        console.log(object.dataList.state);
         console.log(object.dataList.count);
    } else{
        //"message" does not exist
    }

if you are trying to check state do this:
if(typeof(object.dataList.state) !='undefined' && object.dataList.state.length > 0){
    // dataList.state exists. do stuff.
} else {
    // dataList.state does not exist
}

A: First of all, if you are checking the existence of a property, you should use if ('message' in object). If you use if (object['message']), for the case object = {'message': null}, the result is wrong.
In your question, the object is nested into two layers. If there are more than two, you can try a generic solution using recursion:
function findProperty (obj, key) {
    if (typeof obj === "object") {
        if (key in obj) return true;
        var childReturned = false;
        for (k in obj) {
            childReturned = findProperty(obj[k], key);
            if (childReturned) return true;
        }
    }
    return false;
}

var obj = {"message":"success","dataList":{"state":"error","count":"25"}};
findProperty(obj, 'message');   // => true
findProperty(obj, 'dataList');  // => true
findProperty(obj, 'state');     // => true
findProperty(obj, 'count');     // => true

A: if (object.dataList.state || object.dataList.count) {
    // ...
}


text: Q: How do I Install Ubuntu on an iMac running OS X Lion on a SSD and Windows 7 on a HDD? How do I Install Ubuntu on an iMac running OS X Lion on a SSD and Windows 7 on a HDD? I once successfully triple booted when I ran Snow Leopard, Windows 7, and Ubuntu. Now how can it be done with my more complicated and less forgiving lion set up?


text:
Q: regex expression for delete python comment I want to delete all comment in python file.
file like this:
--------------- comment.py ---------------
# this is comment line.
age = 18  # comment in line
msg1 = "I'm #1."  # comment. there's a # in code.
msg2 = 'you are #2. ' + 'He is #3'  # strange sign ' # ' in comment.
print('Waiting your answer')

I write many regex to extract all comments, some like this:
(?(?<=['"])(?<=['"])\s*#.*$|\s*#.*$)
get:  #1."  # comment. there's a # in code.

(?<=('|")[^\1]*\1)\s*#.*$|\s*#.*$
wrong. it's not 0-width in lookaround (?<=..)

But it dosn't work right. What's the right regex?
Could you help me, please?

A: You can try using tokenize instead of regex, as @OlvinRoght said, parsing code using regex maybe is bad idea in this case. As you can see here, you can try something like this to detect the comments:
import tokenize
fileObj = open('yourpath\comment.py', 'r')
for toktype, tok, start, end, line in tokenize.generate_tokens(fileObj.readline):
    # we can also use token.tok_name[toktype] instead of 'COMMENT'
    # from the token module
    if toktype == tokenize.COMMENT:
        print('COMMENT' + " " + tok)

Output:
COMMENT # -*- coding: utf-8 -*-
COMMENT # this is comment line.
COMMENT # comment in line
COMMENT # comment. there's a # in code.
COMMENT # strange sign ' # ' in comment.

Then, to get the expected result, that is python file without comments, you can try this:
nocomments=[]
for toktype, tok, start, end, line in tokenize.generate_tokens(fileObj.readline):
    if toktype != tokenize.COMMENT:
        nocomments.append(tok)

print(' '.join(nocomments))

Output:
 age = 18
 msg1 = "I'm #1."
 msg2 = 'you are #2. ' + 'He is #3'
 print ( 'Waiting your answer' )

A: Credit: https://gist.github.com/BroHui/aca2b8e6e6bdf3cb4af4b246c9837fa3
This will do. It uses tokenize. You can modify this code as per your use.
""" Strip comments and docstrings from a file.
"""

import sys, token, tokenize

def do_file(fname):
    """ Run on just one file.
    """
    source = open(fname)
    mod = open(fname + ",strip", "w")

    prev_toktype = token.INDENT
    first_line = None
    last_lineno = -1
    last_col = 0

    tokgen = tokenize.generate_tokens(source.readline)
    for toktype, ttext, (slineno, scol), (elineno, ecol), ltext in tokgen:
        if 0:   # Change to if 1 to see the tokens fly by.
            print("%10s %-14s %-20r %r" % (
                tokenize.tok_name.get(toktype, toktype),
                "%d.%d-%d.%d" % (slineno, scol, elineno, ecol),
                ttext, ltext
                ))
        if slineno > last_lineno:
            last_col = 0
        if scol > last_col:
            mod.write(" " * (scol - last_col))
        if toktype == token.STRING and prev_toktype == token.INDENT:
            # Docstring
            mod.write("#--")
        elif toktype == tokenize.COMMENT:
            # Comment
            mod.write("\n")
        else:
            mod.write(ttext)
        prev_toktype = toktype
        last_col = ecol
        last_lineno = elineno

if __name__ == '__main__':
    do_file("text.txt")

text.txt:
# this is comment line.
age = 18  # comment in line
msg1 = "I'm #1."  # comment. there's a # in code.
msg2 = 'you are #2. ' + 'He is #3'  # strange sign ' # ' in comment.
print('Waiting your answer')

Output:
age = 18

msg1 = "I'm #1."

msg2 = 'you are #2. ' + 'He is #3'

print('Waiting your answer')

Input:
msg1 = "I'm #1."  # comment. there's a # in code.  the regex#.*$ will match #1."  # comment. there's a # in code. . Right match shoud be # comment. there's a # in code.

Output:
msg1 = "I'm #1."


text:
Q: Excel cell addresses from Excel formula with EPPlus I have application which read data from excel file including formula using EPPlus.
my routine extract cell address from formula.
few sample formula which my application can still parse using RegEx.

a) (W2/R2)-1
b) W23-U23

But Now a formula occur bit long which my regex could not parse. formula looks like
(U2+W2)/2*1000/W25
This is my code which parse formula and iterate in cell address
string regex = @"\$?[A-Z]{1,3}\$?[0-9]{1,7}";
string strDefaultCalculations="(U2+W2)/2*1000/W25";

List<string> lstAddress = Regex.Matches(strDefaultCalculations, regex).Cast<Match>().Select(m => m.Value).ToList();

foreach (var data in lstAddress)
{

}

Please some one suggest any changed RegEx as a result it can extract all cell address from this formula (U2+W2)/2*1000/W25. cell address would be U2, W2, W25.
also changed regex should be parse my others formula too means these formula below which are being parsed properly.

a) (W2/R2)-1
b) W23-U23

Please some one help me. i stuck very badly for my RegEx. thanks


text:
Q: Displaying Percentages in a Sankey Diagram using D3 JS I am new to D3 js and trying display percentages on the sankey diagram by nodes. I am able to display percentages in the sankey but it calculates the percentage by total value. Any help is appreciated.
Thank you!!

d3.sankey = function() {
  var sankey = {},
      nodeWidth = 24,
      nodePadding = 8,
      size = [1, 1],
      nodes = [],
      links = [];

  sankey.nodeWidth = function(_) {
    if (!arguments.length) return nodeWidth;
    nodeWidth = +_;
    return sankey;
  };

  sankey.nodePadding = function(_) {
    if (!arguments.length) return nodePadding;
    nodePadding = +_;
    return sankey;
  };

  sankey.nodes = function(_) {
    if (!arguments.length) return nodes;
    nodes = _;
    return sankey;
  };

  sankey.links = function(_) {
    if (!arguments.length) return links;
    links = _;
    return sankey;
  };

  sankey.size = function(_) {
    if (!arguments.length) return size;
    size = _;
    return sankey;
  };

  sankey.layout = function(iterations) {
    computeNodeLinks();
    computeNodeValues();
    computeNodeBreadths();
    computeNodeDepths(iterations);
    computeLinkDepths();
    return sankey;
  };

  sankey.relayout = function() {
    computeLinkDepths();
    return sankey;
  };

  sankey.link = function() {
    var curvature = .5;

    function link(d) {
      var x0 = d.source.x + d.source.dx,
          x1 = d.target.x,
          xi = d3.interpolateNumber(x0, x1),
          x2 = xi(curvature),
          x3 = xi(1 - curvature),
          y0 = d.source.y + d.sy + d.dy / 2,
          y1 = d.target.y + d.ty + d.dy / 2;
      return "M" + x0 + "," + y0
           + "C" + x2 + "," + y0
           + " " + x3 + "," + y1
           + " " + x1 + "," + y1;
    }

    link.curvature = function(_) {
      if (!arguments.length) return curvature;
      curvature = +_;
      return link;
    };

    return link;
  };

  // Populate the sourceLinks and targetLinks for each node.
  // Also, if the source and target are not objects, assume they are indices.
  function computeNodeLinks() {
    nodes.forEach(function(node) {
      node.sourceLinks = [];
      node.targetLinks = [];
    });
    links.forEach(function(link) {
      var source = link.source,
          target = link.target;
      if (typeof source === "number") source = link.source = nodes[link.source];
      if (typeof target === "number") target = link.target = nodes[link.target];
      source.sourceLinks.push(link);
      target.targetLinks.push(link);
    });
  }

  // Compute the value (size) of each node by summing the associated links.
  function computeNodeValues() {
    nodes.forEach(function(node) {
      node.value = Math.max(
        d3.sum(node.sourceLinks, value),
        d3.sum(node.targetLinks, value)
      );
    });
  }

  // Iteratively assign the breadth (x-position) for each node.
  // Nodes are assigned the maximum breadth of incoming neighbors plus one;
  // nodes with no incoming links are assigned breadth zero, while
  // nodes with no outgoing links are assigned the maximum breadth.
  function computeNodeBreadths() {
    var remainingNodes = nodes,
        nextNodes,
        x = 0;

    while (remainingNodes.length) {
      nextNodes = [];
      remainingNodes.forEach(function(node) {
        node.x = x;
        node.dx = nodeWidth;
        node.sourceLinks.forEach(function(link) {
          nextNodes.push(link.target);
        });
      });
      remainingNodes = nextNodes;
      ++x;
    }

    //
    moveSinksRight(x);
    scaleNodeBreadths((width - nodeWidth) / (x - 1));
  }

  function moveSourcesRight() {
    nodes.forEach(function(node) {
      if (!node.targetLinks.length) {
        node.x = d3.min(node.sourceLinks, function(d) { return d.target.x; }) - 1;
      }
    });
  }

  function moveSinksRight(x) {
    nodes.forEach(function(node) {
      if (!node.sourceLinks.length) {
        node.x = x - 1;
      }
    });
  }

  function scaleNodeBreadths(kx) {
    nodes.forEach(function(node) {
      node.x *= kx;
    });
  }

  function computeNodeDepths(iterations) {
    var nodesByBreadth = d3.nest()
        .key(function(d) { return d.x; })
        .sortKeys(d3.ascending)
        .entries(nodes)
        .map(function(d) { return d.values; });

    //
    initializeNodeDepth();
    resolveCollisions();
    for (var alpha = 1; iterations > 0; --iterations) {
      relaxRightToLeft(alpha *= .99);
      resolveCollisions();
      relaxLeftToRight(alpha);
      resolveCollisions();
    }

    function initializeNodeDepth() {
      var ky = d3.min(nodesByBreadth, function(nodes) {
        return (size[1] - (nodes.length - 1) * nodePadding) / d3.sum(nodes, value);
      });

      nodesByBreadth.forEach(function(nodes) {
        nodes.forEach(function(node, i) {
          node.y = i;
          node.dy = node.value * ky;
        });
      });

      links.forEach(function(link) {
        link.dy = link.value * ky;
      });
    }

    function relaxLeftToRight(alpha) {
      nodesByBreadth.forEach(function(nodes, breadth) {
        nodes.forEach(function(node) {
          if (node.targetLinks.length) {
            var y = d3.sum(node.targetLinks, weightedSource) / d3.sum(node.targetLinks, value);
            node.y += (y - center(node)) * alpha;
          }
        });
      });

      function weightedSource(link) {
        return center(link.source) * link.value;
      }
    }

    function relaxRightToLeft(alpha) {
      nodesByBreadth.slice().reverse().forEach(function(nodes) {
        nodes.forEach(function(node) {
          if (node.sourceLinks.length) {
            var y = d3.sum(node.sourceLinks, weightedTarget) / d3.sum(node.sourceLinks, value);
            node.y += (y - center(node)) * alpha;
          }
        });
      });

      function weightedTarget(link) {
        return center(link.target) * link.value;
      }
    }

    function resolveCollisions() {
      nodesByBreadth.forEach(function(nodes) {
        var node,
            dy,
            y0 = 0,
            n = nodes.length,
            i;

        // Push any overlapping nodes down.
        nodes.sort(ascendingDepth);
        for (i = 0; i < n; ++i) {
          node = nodes[i];
          dy = y0 - node.y;
          if (dy > 0) node.y += dy;
          y0 = node.y + node.dy + nodePadding;
        }

        // If the bottommost node goes outside the bounds, push it back up.
        dy = y0 - nodePadding - size[1];
        if (dy > 0) {
          y0 = node.y -= dy;

          // Push any overlapping nodes back up.
          for (i = n - 2; i >= 0; --i) {
            node = nodes[i];
            dy = node.y + node.dy + nodePadding - y0;
            if (dy > 0) node.y -= dy;
            y0 = node.y;
          }
        }
      });
    }

    function ascendingDepth(a, b) {
      return a.y - b.y;
    }
  }

  function computeLinkDepths() {
    nodes.forEach(function(node) {
      node.sourceLinks.sort(ascendingTargetDepth);
      node.targetLinks.sort(ascendingSourceDepth);
    });
    nodes.forEach(function(node) {
      var sy = 0, ty = 0;
      node.sourceLinks.forEach(function(link) {
        link.sy = sy;
        sy += link.dy;
      });
      node.targetLinks.forEach(function(link) {
        link.ty = ty;
        ty += link.dy;
      });
    });

    function ascendingSourceDepth(a, b) {
      return a.source.y - b.source.y;
    }

    function ascendingTargetDepth(a, b) {
      return a.target.y - b.target.y;
    }
  }

  function center(node) {
    return node.y + node.dy / 2;
  }

  function value(link) {
    return link.value;
  }

  return sankey;
};
<!DOCTYPE html>
<meta charset="utf-8">
<title>SANKEY Experiment</title>

<link rel="stylesheet" type="text/css" href="sankey.css">

Equipment

Resolution

Repeat_call_Flag

A: If I understand correctly, you want to calculate the ratio of any node value over some total, so that each column sums to 100%.
You need to compute total by taking into account only source nodes (those which are not the target of any link), which should give the total you want. Replace your current formula for total with this one:
var total = d3.sum(graph.nodes, function(d) {
     if (d.targetLinks.length>0)
        return 0; //node is not source, exclude it from the total
     else
        return d.value; //node is a source: add its value to the sum
     });

It's hard to say more without a running example or a clear idea of what you want.


text:
Q: Sql NOT IN optimization I'm having trouble optimizing a query. Here are two example tables I am working with:
Table 1:
UID
A
B

Table 2:
UID   Parent
A       2
B       2
C       3
D       2
E       3
F       2

Here is what I am doing now:
Select Table1.UID
FROM Table1 R

INNER JOIN Table2 T ON
R.UID = T.UID

INNER JOIN Table2 E ON
T.PARENT = E.PARENT
AND E.UID NOT IN (SELECT UID FROM Table1)

I'm trying to avoid using the NOT IN clause because of obvious hindrances in performance for large numbers of records.
I know the typical ways to avoid NOT IN clauses like the LEFT JOIN where the other table is null, but can't seem to get what I want with all of the other Joins going on.
I will continue working and post if I find a solution.
EDIT: Here is what I am trying to end up with
After the first Inner Join I would have
A
B

AFter the second Inner join I would have:
A    D
A    F
B    D
B    F

The second column above is just to represent that it is matching to the other UIDs with the same parent, but I still need the As and Bs as the UID.
EDIT: RDBMS is SQL server 2005, 2008r2, 2012
Table1 is declared in the query with no index
DECLARE @Table1 TABLE ( [UNIQUE_ID] INT PRIMARY KEY )

Table2 has a clustered index on Unique ID

A: The general approach to this is to use a LEFT JOIN with a where clause that only selects the non-matching rows:
Select Table1.UID
FROM Table1 R
JOIN Table2 T ON R.UID = T.UID
JOIN Table2 E ON T.PARENT = E.PARENT
LEFT JOIN Table3 E2 ON E.UID = R.UID
WHERE E2.UID IS NULL

A: SELECT Table2.*
FROM Table2
INNER JOIN (
  SELECT id FROM Table2
  EXCEPT
  SELECT id FROM Table1
) AS Filter ON (Table2.id = Filter.id)


text:
Q: Can I get rid of this read lock? I have the following helper class (simplified):
public static class Cache
{
    private static readonly object _syncRoot = new object();
    private static Dictionary<Type, string> _lookup = new Dictionary<Type, string>();

    public static void Add(Type type, string value)
    {
        lock (_syncRoot)
        {
            _lookup.Add(type, value);
        }
    }

    public static string Lookup(Type type)
    {
        string result;

        lock (_syncRoot)
        {
            _lookup.TryGetValue(type, out result);
        }

        return result;
    }
}

Add will be called roughly 10/100 times in the application and Lookup will be called by many threads, many of thousands of times. What I would like is to get rid of the read lock.
How do you normally get rid of the read lock in this situation?
I have the following ideas:

*

*Require that _lookup is stable before the application starts operation. The could be build up from an Attribute. This is done automatically through the static constructor the attribute is assigned to. Requiring the above would require me to go through all types that could have the attribute and calling RuntimeHelpers.RunClassConstructor which is an expensive operation;

*Move to COW semantics.
public static void Add(Type type, string value)
{
    lock (_syncRoot)
    {
        var lookup = new Dictionary<Type, string>(_lookup);

        lookup.Add(type, value);

        _lookup = lookup;
    }
}

(With the lock (_syncRoot) removed in the Lookup method.) The problem with this is that this uses an unnecessary amount of memory (which might not be a problem) and I would probably make _lookup volatile, but I'm not sure how this should be applied. (John Skeets' comment here gives me pause.)

*Using ReaderWriterLock. I believe this would make things worse since the region being locked is small.

Suggestions are very welcome.
UPDATE:
The values of the cache are immutable.

A: To remove locks completely (slightly differnt then "lock free" where locks almost eliminated and remaining are cleverly replaced with Interlocked instructions) you need to make sure that your dictionary is immutable. If items in the dictionary are not immutable (and as result have they own locks) you probably should not worry about locking on dictionary level.

*

*is the best and easiest solution if you can use it.

*reasonable and easy to debug. (Note: as written it does not work well for concurrent adding of the same item. Conside double checking locking pattern if needed - Double-checked locking in .NET)

*I would not do it if 1/2 is an option.

If you can use new 4.0 collections - ConcurrentDictionary there matches your criteria (see http://msdn.microsoft.com/en-us/library/dd997305.aspx and  http://blogs.msdn.com/b/pfxteam/archive/2010/01/26/9953725.aspx).

A: At work at the moment, so nothing elegant, came up with this (untested)
public static class Cache
{
    private static readonly object _syncRoot = new object();
    private static Dictionary<Type, string> _lookup = new Dictionary<Type, string>();

    public static class OneToManyLocker
    {
        private static readonly Object WriteLocker = new Object();
        private static readonly List<Object> ReadLockers = new List<Object>();
        private static readonly Object myLocker = new Object();

        public static Object GetLock(LockType lockType)
        {
            lock(WriteLocker)
            {
                if(lockType == LockType.Read)
                {
                    var newReadLocker = new Object();
                    lock(myLocker)
                    {
                        ReadLockers.Add(newReadLocker);
                    }
                    return newReadLocker;
                }

                foreach(var readLocker in ReadLockers)
                {
                    lock(readLocker) { }
                }

                return WriteLocker;
            }
        }

        public enum LockType {Read, Write};
    }

    public static void Add(Type type, string value)
    {
        lock(OneToManyLocker.GetLock(OneToManyLocker.LockType.Write))
        {
            _lookup.Add(type, value);
        }
    }

    public static string Lookup(Type type)
    {
        string result;
        lock (OneToManyLocker.GetLock(OneToManyLocker.LockType.Read))
        {
            _lookup.TryGetValue(type, out result);
        }

        return result;
    }
}

You will need some sort of cleanup for the read lockers, but should be threadsafe allowing multiple reads at a time while also locking on writes, unless I'm totally missing something

A: Either:

*

*Dont use normal locks, go spinlock if the lookup is fast (dictionary is not).

*If that is not the case, then use http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlock.aspx. This allows multiple readers and only one writer.


text:
Q: Do the fields in string theory only live on the world line of the string? Say for instance we have a $D0$ brane, and this $D0$ brane is charged under the KK field. Does the strength of the KK field only exist on the worldline of the $D0$ brane? Same goes for strings: do the charged SUGRA fields live on the world sheet of the string?
Or does the field strength of the $D0$ brane or string extend outwards in space (like the classic EM field generated by a charged particle)? My apologies if this seems confusing.

A: The fields in string theory aren't restricted to the worldvolume any more than the electromagnetic field is restricted to the worldline of a classical charged particle: they extend throughout spacetime. It pays to consider the coupling of a 1D particle to the background electromagnetic gauge potential: the action is augmented by the interaction term
$$
\int \mathrm{d}\tau\ A_\mu(X)\dot{X}^\mu
$$
which is precisely the pull-back of the gauge one-form $A_\mu\mathrm{d}x^\mu$ onto the worldline, though one does not immediately spot this. The same thing happens for the background fields in string theory, be it the Kalb-Ramond field or the graviton: while they naturally carry spacetime indices, they enter the string action/vertex operators through the pull-back of the spacetime field onto the worldvolume, and corresponding coupling terms are introduced into the Polyakov action. Here's an example for the Kalb-Ramond field:
$$
S_\text{int}=\frac{1}{4\pi\alpha'}\int\mathrm{d}^2\sigma\sqrt{g} \ i\epsilon^{\alpha\beta}B_{\mu\nu}(X)\partial_aX^\mu\partial_bX^\nu
$$
where the pullback is a lot more evident. Now consider the essentially analogous scenario where the D-branes act as sources for the RR-fields. The RR-fields/potentials are again defined on the spacetime, and the worldvolume of the Dp-branes can couple locally to the $(p+1)$-form background gauge potential, once again via the pullback (don't be misled by the terminology, the worldvolume of a Dp-brane is also $(p+1)$-dimensional). For simplicity, consider the electric coupling (in the absence of the mixing Kalb-Ramond field, to keep things simple):
$$
S_\text{int} = \frac{e_p}{(p+1)!}\int \mathrm{d}^{p+1}\sigma \ A_{\mu_1...\mu_{p+1}}\partial_0 X^{\mu_1}...\partial_p X^{\mu_{p+1}}
$$
[See e.g. Equation (6.54); Becker, Becker, Schwarz, String Theory and M-Theory]
When you see the dimensions of the gauge fields in the RR-sector of the theory under consideration, you can immediately determine which Dp-branes are allowed to carry the RR-charges via the electric and magnetic coupling. Accordingly, the Bianchi identity of the RR gauge fields is violated in the presence of the sources:
$$
\mathrm{d}G_{p}=0\longrightarrow\mathrm{d}G_{p}=\mathcal{J}_{p+1}
$$
Note that this the exterior derivative on the target spacetime. Similar to how a local charge source in electrodynamics modifies the field strength outside of its worldline due to the p-form Maxwell equation, the charged D-branes thus act as sources for the RR-field not just on the brane itself, but also in the bulk.


text:
Q: How @prototype scope helps in multithreading I was given a single threaded application and asked to make it multithreaded. There are many singleton instances used.
I know that when a singleton instance is shared between multiple threads, all the variables of that instance will be shared between multiple threads.
For example, there is a count variable, it is a singleton instance variable. My idea is that each thread should increment the 'count' .Each thread increments only once. So the counter should be 1. If I increment this variable of the shared object, all the threads will get that value. So when the 2nd thread does it, the value will not be 1, but 2. For the nth thread that increments it, the value it sees will be n, not 1.
Inorder to prevent this, I used a prototype scope on that class. Now I will get a new object for each thread and the counter will remain 1 for each thread.
This is how I thought I would use prototype scope. Does this makes sense? I gave an example for counter, there are many, many such variables of different types in that shared instance.
Is my use of prototype justified?

A: You can use a local variable for the above-said purpose, it doesn't have to be an instance variable.

In order to prevent this, I used a prototype scope on that class. Now
  I will get a new object for each thread and the counter will remain 1
  for each thread.
This is how I thought I would use prototype scope. Does this makes
  sense?

This makes sense, but only thing is, I don't see a case for an instance variable, as I said before, you can easily pull this off with a local variable.
Be careful with a prototype scoped bean injected into a singleton scoped bean.
Spring Prototype scoped bean in a singleton


text:
Q: Can i add a comma (,) dynamically to a CSS pseudo element which its value is coming from CSS variable I want to insert the commas appropriately between the numbers.
eg: 6,350
is there any way I can achieve this in the following scenario

setTimeout(function () {
  $('.number-counter').each(function () {
    $(this).addClass('inView');
  });
}, 500);
@property --num {
  syntax: "<integer>";
  initial-value: 0;
  inherits: false;
}

.number-counter {
  transition: --num 3s;
  counter-set: num var(--num);
  font: 800 40px system-ui;
}
.number-counter::after {
  content: counter(num);
}
.number-counter.inView {
  --num: var(--count);
}

A: I have tried to add this code in CSS but there is no way to count the digits in CSS so I have added the comma(,) using jQuery. I hope this will help you. It will add the comma after 3 digit.

setTimeout(function () {
  jQuery('.number-counter').each(function () {
    jQuery(this).addClass('inView');
    var $this = jQuery(this);
     countTo = $this.attr('data-count');
  jQuery({ countNum: $this.text()}).animate({countNum: countTo},
    {
      easing: 'linear',
      step: function() {
              $this.text(commaSeparateNumber(Math.ceil(this.countNum)));
  },
  complete: function() {
    $this.text(commaSeparateNumber(Math.ceil(this.countNum)));
      }
    });
  });
}, 500);
function commaSeparateNumber(val) {
  while (/(\d+)(\d{3})/.test(val.toString())) {
    val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
  }
  return val;
}
@property --num {
  syntax: "<integer>";
  initial-value: 0;
  inherits: false;
}

.number-counter {
  transition: --num 3s;
  counter-set: num var(--num);
  font: 800 40px system-ui;
}


text:
Q: javascript how to save base64 data as png I am using the getDirectoryHandle and getFileHandle APIs. I want to save a picture in the specified directory. I have the base64 data of the picture, but I don't know how to save the base64 as a picture
const hDir = await showDirectoryPicker();
const hImageFile = await hDir.getFileHandle("test.png", {
  create: true,
});
const w$ = await hImageFile.createWritable();
await w$.write( canvas.toDataURL('image/png') );
await w$.close();

I tried:
await w$.write( atob(canvas.toDataURL('image/png')) );

but the saved picture is not recognized.

A: It seems you just miss some code.
Under Chrome console, you can print the DataURL of
canvas.toDataURL('image/png')

and you will see it begins with
data:image/png;base64,

This is the header of DataURL, not the header of image file.
So we need to remove it, by ignore the 22 charactors
canvas.toDataURL('image/png').substring(22)

and then turn the string contents into byte array
function _base64ToArrayBuffer(base64) {
    var binary_string = window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}

finally,
replace
await w$.write( atob(canvas.toDataURL('image/png')) );

with
await w$.write( _base64ToArrayBuffer(canvas.toDataURL('image/png').substring(22)));

enjoy.

A: canvas.toBlob(async function (blob) {
  const w$ = await hImageFile.createWritable();
  await w$.write(blob);
  await w$.close();
});


text:
Q: Wiring a Bean Which Itself has a Constructor I have a web service client that has an Authenticator class. The Authenticator requires a username/password. Looking for help on how to inject the credentials using Spring.
Should I inject the user/pass into the Authenticator or into the client that is instantiating the Authenticator.
Any concrete examples would be appreciated, as I am new to Spring.
These are what the two components look like:
@Controller
    public class WSClient {
        @Autowired
        MyAuthenticator myAuthenticator;
    }
}

The Authenticator, with the credentials:
public class MyAuthenticator extends Authenticator {
    private final String userName;
    private final String passWord;

    public MyAuthenticator(String userName, String passWord) {
        this.userName = userName;
        this.passWord = passWord;
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(this.userName, this.passWord.toCharArray());
    }
}

A: Use @Value to set username/password in Authentication bean
@Component
public class MyAuthenticator extends Authenticator {
    @Value("${credentials.username}")
    private final String userName;
    @Value("${credentials.password}")
    private final String passWord;

    public MyAuthenticator(String userName, String passWord) {
        this.userName = userName;
        this.passWord = passWord;
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(this.userName, this.passWord.toCharArray());
    }
}

and in XML file
add
<util:properties id="credentials" location="classpath:credentials.properties"/>

and put credentials.properties in classpath


text:
Q: Optical properties of metal-dielectric-metal microcavities I would like to figure out the optical properties of metal-dielectric-metal microcavities, used in the fabrication of micro patch antenna.
The paper that I'm reading is this one. Now the specific questions:

*

*How is the incoming electromagnetic field directed perpendicular to the metallic patch confined under the patch itself? I suppose that the reason should be the light funneling phenomena here described, but I'm not so sure.

*Once the field is confined under the patch only the "component" with adequate frequency remains trapped: this is due to the dimension of the patch but also to the impedance mismatch that should be the origin of the guided mode. How does it happen? What is the behaviour of the light near the edges of the patch?
Any kind of help will be appreciated.


text:
Q: Is it possible to exclude certain POS tags in spaCy? Python I want to mark the position of verbs in sentences by adding an 'X' before the verb. My function takes the following steps to achieve this.

*

*Locate the verb. I use spaCy for POS tagging. SpaCy outputs a list of POS tags that I call pos, where each word in the sentence is represented as a tag.

*Convert the sentence also into a list L.

*Determine the index x of the verb tag (e.g. "VBZ") in the POS list.

*Insert the desired 'X' mark at index x into the sentence list.

Step 4  assumes that the length of the list pos is identical to the length of the sentence list L. This is generally the case, except when spaCy assigns tags to sentence elements that Python does not index separately. In that case the POS list is longer than the sentence list. For example, spaCy sees a bracket '(' or full stop behind a word '.' as a separate position, whereas Python does not. As a result, the 'X' is misplaced in the sentence.
How to solve this?
Below is an example.
import pandas as pd
import spacy
nlp = spacy.load('en')

s = "Dr. John (a fictional chartacter) never shakes hands."
df = pd.DataFrame({'sentence':[s]})
k = df['sentence']

def marking(row):
    L = row
    sentence_spacy = nlp(L)
    pos = [] # store the pos tags in a list 'pos'
    for token in sentence_spacy:
        pos.append(token.tag_)
        print(pos)
    if "VBZ" in pos:
        x = pos.index("VBZ")
        L = L.split()
        L.insert(x, "X")
        L = " ".join(L) # split the sentence also in a list
        print(L)
        return L
x = k.apply(marking)
print(x)

This gives:
pos = ['NNP', 'NNP', '-LRB-', 'DT', 'JJ', 'NN', '-RRB-', 'RB', 'VBZ', 'NNS', '.']
L = ['Dr.', 'John', '(a', 'fictional', 'chartacter)', 'never', 'shakes', 'hands.']

And because the pos-list pos is longer than the sentence list L, the result is:
 x = "Dr. John (a fictional chartacter) never shakes hands. X"

But I want this:
x = "Dr. John (a fictional chartacter) never X shakes hands."

My question is two-fold:

*

*Is it possible to exclude certain POS tags in spaCy? For example, can I exclude ['-LRB-', '-RRB-', etc.] ? This would make length pos == length L

*If this is not possible, how should I change my function so that a list of POS tags can be specified ['-LRB-', '-RRB-', etc.] that are deleted from pos so that the length of the pos-list is identical to the length of sentence list?

A: Tokenization is more complex than split. Even dropping tokens will not make split correspond to spaCy's tokens (try nlp('non-trivial')). Fortunately there's a better way: you can reconstruct the sentence from the tokens and insert your mark at the desired point:
def marking(row):
    chunks = []
    for token in nlp(row):
        if token.tag_ == 'VBZ':
            chunks.append('X')
        chunks.append(token.text_with_ws)
    return ' '.join(chunks)

print(marking("Dr. John (a fictional chartacter) never shakes hands."))


text:
Q: GoDaddy tells me my Heroku app doesn't exist I followed this answer to deploy an app with Heroku on a GoDaddy domain.
But when I check my url, I get the following error message:
Heroku | No such app
There is no app configured at that hostname.
Perhaps the app owner has renamed it, or you mistyped the URL.

Under my GoDaddy "Edit Zone Record" page, I have Host => "www", Points To => "(heroku app name)", and TTL => "1 hour"
When I copy and paste the contents of the Points To field into the url bar, it brings up my live site with no errors.
So why would it be telling me there is no such app?

A: Did you add the domain name to your Heroku app?
https://devcenter.heroku.com/articles/custom-domains


text:
Q: Hunting memory leaks I'm finding leaked heap blocks by using the following command in WinDbg
!heap –l

With each leaked heap block I get, I'm running to following to get the stack trace.
!heap -p -a leakedheapblock

The following is the result of this command:
address 1c841cc0 found in
_HEAP @ 3930000
  HEAP_ENTRY Size Prev Flags    UserPtr UserSize - state
    1c851cc0 0009 0000  [03]   1c851ce8    0000c - (busy)
    Trace: 84f8
    7c873c19 ntdll!RtlpDphNormalHeapAllocate+0x00000030
    7c876870 ntdll!RtlpDebugPageHeapAllocate+0x00000335
    7c8794a8 ntdll!RtlDebugAllocateHeap+0x0000002d
    7c8531e4 ntdll!RtlAllocateHeapSlowly+0x00000041
    7c83d97a ntdll!RtlAllocateHeap+0x00000e9f
    1699d238 MyLibrary!malloc+0x0000007a

How can I find the piece of code in 'MyLibrary' that leaks.

A: There is a nice guide about this in MSDN: Memory Leak Detection Enabling


text:
Q: Perl : match multiple lines With the use of perl regex, if two consecutive lines match than count the number of lines.
I want the number of lines until matches the pattern
D001
0000

open ($file, "$file") || die;
   my @lines_f = $file;
   my $total_size = $#lines_f +1;

   foreach my $line (@lines_f)
   {
       if ($line =~ /D001/) {
           $FSIZE = $k + 1;
       } else {
           $k++;}
    }

Instead of just D001, I also want to check if the next line is 0000. If so $FSIZE is the $file size.
The $file would look something like this
00001
00002
.
.
.
D0001
00000
00000

A: Here is an example. This sets $FSIZE to undef if it cannot find the marker lines:
use strict;
use warnings;

my $fn = 'test.txt';
open ( my $fh, '<', $fn ) or die "Could not open file '$fn': $!";
chomp (my @lines = <$fh>);
close $fh;

my $FSIZE = undef;
for my $i (0..$#lines) {
    if ($lines[$i] =~ /D0001/) {
        if ( $i < $#lines ) {
            if ( $lines[$i+1] =~ /00000/ ) {
                $FSIZE = $i + 1;
                last;
            }
        }
    }
}


text:
Q: If or/and statement advanced custom fields I'm really unexperienced when it comes to conditonal statements with php and unfortunately the documentation of Advanced Custom Fields isn't covering this topic as fair as I know. But anyway, what I'm trying to do is to display some markup and custom fields but only if one of the fields or both fields have data.
For example I have a footer that could display an email address and/or website link. If both custom fields are not filled with data the footer markup shouldn't be displayed. If there's an email address and/or website link available it should display the footer markup and of course the data of the fields.
This is what I currently have:

<?php if( get_field('website') ): ?>

<a href="<?php the_field('website'); ?>"><?php the_field('website'); ?>

<?php endif; ?>

<?php if( get_field('emailaddress') ): ?>

<a href="mailto:<?php the_field('emailaddress'); ?>"><?php the_field('emailaddress'); ?

<?php endif; ?>

But this code displays the footer markup even if both custom fields are not available. How can I make it that the footer markup is only shown if one of both of the custom fields have a value?
If been trying to do it with an || statement but that returns an unexpected T_BOOLEAN_OR error
<?php if( get_field('website') ) || ( get_field('emailaddress') ): ?>

// do this

<?php endif; >

If anyone knows if this is possible, how to do this or could point me in the right direction that would be much appreciated.

A: I believe you are on the right track with your second idea there, but you have some syntax errors with your conditional. In PHP all of your logic should be wrapped inside one set of ( ) for your conditional. Try this:
<?php
if ( get_field('website') || get_field('emailaddress') ) {
    ?>

        <?php
        if ( get_field('website') ) {
            ?>
            <a href="<?php the_field('website'); ?>"><?php the_field('website'); ?>
            <?php
        }
        if ( get_field('emailaddress') ) {
            ?>
            <a href="mailto:<?php the_field( 'emailaddress' ); ?>"><?php the_field( 'emailaddress' ); ?>
            <?php
        }
        ?>

    <?php
}

A: I prefer to keep my PHP inline when possible to avoid scattering its start or end tags and possibly miss one. It's closer to the OP's original attempt and imo reads cleaner/clearer:
<?php if(get_field('website') || get_field('emailaddress')) : ?>

    <?php if(get_field('website')) : ?>
      <a href="<?php the_field('website'); ?>"><?php the_field('website'); ?>
    <?php endif; ?>
    <?php if(get_field('emailaddress')) : ?>
      <a href="mailto:<?php the_field('emailaddress'); ?>"><?php the_field('emailaddress'); ?>
    <?php endif; ?>

<?php endif; ?>


text:
Q: Adding a Renderer for VCF in Rails 3 I'm attempting to add a renderer to allow one of my models to respond to the .vcf format. I have added the following code to my vcf_renderer.rb file which is in my initializers directory:
Mime::Type.register 'text/x-vcard', :vcf
ActionController::Renderers.add :vcf do |object, options|
  exit! # Testing to see if this even gets called at all...
end

It seems as if the following code is never even being executed because if I go to /model/123.vcf I get at "Template is Missing" error.
Does anyone know why the ActionController::Renderers.add block doesn't seem to be called?
AuthorsController.rb
respond_to :vcf

def show

  respond_with(@author)

end

A: Seems like the old style works, executing the renderer format.vcf  { render :vcf => @object }.
With respond_with (which now raises "Missing template") you have to add a to_vcf method in the models. Tried for show and it worked (for index it doesn't recognize to_vcf for arrays).
# config/initializers/vcf_renderer.rb
Mime::Type.register 'text/x-vcard', :vcf
ActionController::Renderers.add :vcf do |object, options|
  self.content_type ||= 'text/x-vcard'
  self.response_body  = object.respond_to?(:to_vcf) ? object.to_vcf : object
end


text:
Q: Merge temporally continuous records based on common id This is my data of time intervals
dates <- seq(from=as.Date("1980-01-01"), to=as.Date("1980-01-31"), by = 'day')

my_data <-
  data.frame(from_date = c(dates[1], dates[15], dates[20], dates[30]),
             to_date = c(dates[14], dates[19], dates[22], dates[31]),
             id = c(1, 1, 2, 3))

Few of the observations are continuous, they end the day before the following starts.
my_data$is_continued <- c(TRUE, TRUE, FALSE, FALSE)

my_data
   from_date    to_date id is_continued
1 1980-01-01 1980-01-14  1         TRUE
2 1980-01-15 1980-01-19  1         TRUE
3 1980-01-20 1980-01-22  2        FALSE
4 1980-01-30 1980-01-31  3        FALSE

Now I want to simplify my table. I want one observation instead of two (or more than two) when:

*

*Observations are continuous

*They share the same id
That is, I want this result
desired_result <-
  data.frame(from_date = c(dates[1], dates[20], dates[30]),
             to_date = c(dates[19], dates[22], dates[31]),
             id = c(1, 2, 3))

What would be the best approach?

A: By looping:
groupContinous <- function(df) {

  df <- df[order(df$from_date),]

  df$continuing <- c(FALSE, c(df$from_date[2:nrow(df)] - df$to_date[1:(nrow(df))-1] == 1))

  membership <- 1
  for (i in 2:nrow(df)) {
    if (df$continuing[i] == TRUE) {
      membership <- c(membership, max(membership))
    } else {
      membership <- c(membership, max(membership)+1)
    }
  }
  df$membership <- membership

  require(dplyr)
  df_simp <-
    df %>%
    dplyr::group_by(id, membership) %>%
    dplyr::summarize(from_date = min(from_date),
                     to_date = max(to_date))
  df_simp$membership <- NULL

  return(as.data.frame(df_simp))
}


text:
Q: On $\delta_{0}$-continuity sets in the class of finite dimensional sets Let $S=C[0,1]$ and $\mathcal{S}$ be the Borel algebra given the sup metric. Furthermore consider the class of so called "finite dimensional sets" in $\mathcal{S}$ defined by
$\pi_{\{t_{I}\}_{0}^{n}}f=(f(t_{1}), \ldots,f(t_{n}))$ is the projection into $R^k$. Call a set a finite dimensional set in $C[0,1]$ if it is the inverse image of some Borel set in $R^k$ under this map.
Consider the function
$z_{n}(t)=nt\chi_{[0,\frac{1}{n}]}(t) +(2-nt)\chi_{[\frac{1}{n},\frac{2}{n}]}(t) \in C[0,1]$
which converges pointwise but not uniformly to $0$.
I try to understand why the class of finite dimensional sets is not convergence determining by considering the measures $\delta_{z_{n}}$ and $\delta_{0}$ on $\mathcal{S}$.
A family of subsets is converging determining if it is sufficient to have that $P_{n}A \rightarrow PA$ for all $P$-continuity sets of that class to obtain weak convergence of the measures $P_{n}$ to $P$
As $z_{n}$ does not convergence uniformly to $0$ it is clear that $\delta _{z_{n}}$ don't converge weakly to $\delta _{0}$.
What I don't see is why this proves the finite dimensional sets are not converging determining. Since I don't understand how one should think about the $\delta _{0}$-continuity sets.
Why is the condition
$\delta _{z_{n}}A \rightarrow \delta _{0}A$ for all $\delta _{0}$-continuity sets $A$ in the class of finite dimensional sets satisfied?

A: It holds not only for finite-dimensional $\delta_0$-continuity sets, but even for all finite-dimensional sets. Those are of the form
$$
A = \{f(t_1)\in B_1,\dots, f(t_k)\in B_k\}
$$
for some distinct $t_1,\dots,t_k\in[0,1]$ and measurable $B_1,\dots,B_k\subset \mathbb{R}$.
For all $n$ large enough we have $(0,2/n)\cap\{t_1,t_2,\dots,t_k\} = \varnothing$. Then $$\delta_0(A) = \delta_{z_n}(A) = \mathbb{1}_{0\in B_i\text{ for all }i=1,\dots,k}.$$


text:
Q: Solve the partial differential equation $-2xyu_x+4xu_y+yu=4xy, x>0$, subject to Cauchy boundary data $u=2\sqrt{x}$ on $y=0, x>0$. This is what I have so far:
$\frac{dx}{dt}=-2xy, \frac{dy}{dt}=4x, \frac{du}{dt}=4xy-yu$
and $x(0,s)=s, y(0,s)=0, u(0,s)= 2\sqrt{x},$ where $x,y,z$ are functions of s and t.
This is where I get stuck and have attempted several different methods. The standard approach we have learned is to integrate the characteristic equations and use the functions in term of $t,s$ to incorporate the initial conditions. However, I am not sure how to integrate the equations when the variables are mixed like this (like $-2xy$ and $4xy-yu$ I have tried integrating $\frac{dy}{dt}=4x$ first and I get $y=4xt$. I have then tried solving for t and plugging this into the other characteristic equations before integrating, but I believe my result is often too complicated and I am making a mistake somewhere.
All the example problems are much simpler and don't have mixed variables like this so I am unsure how to finish solving this.

A: $$-2xyu_x+4xu_y=-yu+4xy$$
Charpit-Lagrange system of characteristic ODEs :
$$\frac{dx}{-2xy}=\frac{dy}{4x}=\frac{du}{-yu+4xy}=dt$$
A first characteristic equation comes from solving $\frac{dx}{-2xy}=\frac{dy}{4x}$
$$4x+y^2=c_1$$
A second characteristic equation comes from solving $\frac{dx}{-2xy}=\frac{du}{-yu+4xy}$
$$\frac{u}{\sqrt{x}}+4\sqrt{x}=c_2$$
The general solution  of the PDE expressed on the form of implicit equation $c_2=F(c_1)$ is :
$$\frac{u}{\sqrt{x}}+4\sqrt{x}=F\left(4x+y^2\right)$$
$$\boxed{u(x,y)=-4x+\sqrt{x}\:F\left(4x+y^2\right)}$$
$F$ is an arbitrary function (to be determined according to the boundary condition).
Condition :
$$u(x,0)=2\sqrt{x}=-4x+\sqrt{x}\:F\left(4x+0^2\right)$$
$$F(4x)=2+4\sqrt{x}$$
Let $X=4x$
$$F(X)=2+2\sqrt{X}$$
Now the function $F$ is known. We put it into the above general solution where $X=4x+y^2$
$$u=-4x+\sqrt{x}\left(2+2\sqrt{4x+y^2}\right)$$
$$u=-4x+2\sqrt{x}+2\sqrt{4x^2+y^2x}$$


text:
Q: writing jQuery instead of $ to access controls in a page Can I write jQuery( "body" ).append('Hello')  instead of $( "body" ).append('Hello') in jQuery

A: Yes you can write that way.
jQuery.noConflict();
jQuery( "body" ).append('Hello');

Read it here


text:
Q: How to load plwordnet (Słowosieć) 3.0 into NLTK PlWordNet version 3.0 comes with two .xml files. First file is plwordnet-3.0.xml (which is in Princeton WordNet format) and second file is plwordnet-3.0-visdisc.xml (which is in VizDic format). The readme file of this projects seems to be somehow obscure, because suggested way of loading the data into NLTK doesn't work. The PlWordNet is available for download from the official project site.
I'm trying to load this wordnet into NLTK, so I can iterate over synsets. I already tried two ways, but both of them don't work.
a) copying the xml files into (...)\nltk_data\corpora\omw\pol and (...)\nltk_data\corpora\wordnet. Code to test results:
from nltk.corpus import wordnet as wn
wn.synsets('Politechnika')

unfortunately returns empty list
b) using XMLCorpusReader from the nltk package (as described in How to use the Spanish Wordnet in NLTK?) to load the xml file. Code to test:
from nltk.corpus.reader import XMLCorpusReader
reader = XMLCorpusReader(dir, 'plwordnet-3.0.xml')

but when I run the reader.words(), it returns only a list of ids (unicode objects, representing numbers only). Moreover I don't see a method for getting relations between synsets.
Anyone used the Princeton Wordnet 3.1 or PlWordNet (Słowosieć) 3.0 before?
I managed to use python's xml.etree to manually get list of synsets and their descriptions, but I don't understand how to get relations between them.
Thanks!

A: PlWordNet 3.0 is not supported in NLTK anymore.
I'll write my own parser.


text:
Q: Conditions for $f(x_n,y_n) - f(x_0, y_n) \to 0$ if $(x_n,y_n) \to (x_0,y_0)$? I have $x_n \to x_0$ and $y_n \to y_0$ as $n \to \infty$. Let $f(x,y)$ be a real-valued function.

Question: Under which conditions do I have
$$f(x_n, y_n) - f(x_0, y_n) \to 0 $$
as $n \to \infty$?

I know two separate conditions, but I was wondering if there were other less restrictive assumptions for the convergence listed above.

Condition 1: There is a neighborhood $\mathcal{B}$ of $y_0$ on which $f(x,y)$ is continuous in $x$ uniformly in $y$, i.e
$$ \sup_{y \in \mathcal{B}} \left|f(x_n, y) - f(x_0, y)\right| \to 0 $$

in which case we have, for $n$ larger enough so that $y_n \in \mathcal{B}$,
$$|f(x_n, y_n) - f(x_0, y_n)| \le \sup_{y \in \mathcal{B}} \left|f(x_n, y) - f(x_0, y)\right| \to 0$$
Alternatively,

Condition 2: $f(x,y)$ is continuous at $(x_0,y_0)$.

We then have, through the triangle inequality,
$$\begin{align}|f(x_n, y_n) - f(x_0, y_n)|
 &\le  |f(x_n, y_n) - f(x_0, y_0)| + |f(x_0, y_n) - f(x_0, y_0)| \to 0
 \end{align}$$
Neither condition implies the other. For example, the following condition satisfies Condition 1 but not Condition 2 for $(x_0,y_0) = (0,0)$,

Example 1:
  $$      f(x,y) = \left\{\begin{align}
        1  ,   & \text{ for } y \in    \mathbb{Q}\\
        -1 ,   & \text{ for } y \notin \mathbb{Q}
        \end{align}\right.  $$

while this function satisfies Condition 2 but not Condition 1,

Example 2:
  $$      f(x,y) = \left\{\begin{align}
         y,   & \text{ for }   x \in    \mathbb{Q} \\
         - y,   & \text{ for } x \notin \mathbb{Q}
        \end{align}\right.  $$

Maybe I am missing a more fundamental condition?

A: This is not amazingly useful, but I've seen in the literature an assumption similar to the following:

Condition 3: For any sequence of balls $\{ B(y_0, \delta_n )\}$ centered at $x_0 $ of radius $\delta_n \to 0$, we have
  $$ \sup_{y \in B(y_0,\delta_n)} \left|f(x_n, y) - f(x_0, y)\right| \to 0 $$

That Condition 3 is sufficient can be seenby taking $\{ \delta_n \}$ such that $\delta_n > |y_n - y_0|$ for every $n$.
Clearly Condition 1 implies Condition 3.
Condition 2 also implies Condition 3.
Proof.
First, note that, from the triangle inequality,
$$\begin{align}\sup_{y \in B(y_0,\delta_n)} \left|f(x_n, y) - f(x_0, y)\right|
&\le \sup_{y \in B(y_0,\delta_n)} \left|f(x_n, y) - f(x_0, y_0)\right| \\
&+\sup_{y \in B(y_0,\delta_n)} \left|f(x_0, y) - f(x_0, y_0)\right|
 \end{align}$$
From continuity at $(x_0,y_0)$ both terms can be made arbitrarily small by picking a $n$ large enough.
We can then apply Condition 3 to Example 2.

Example 2 continued: We have
$$ \sup_{y \in B(y_0,\delta_n)} \left|f(x_n, y) - f(x_0, y)\right| =  \left\{\begin{align}
         0,   & \text{   if both $x_n$ and $x_0$ are in $\mathbb{Q}$, or both not in $\mathbb{Q}$ }    \\
         2\delta_n   & \text{   otherwise }
        \end{align}\right.  $$
which clearly goes to zero.


text:
Q: Image resizing and resolution - change in image file, but nothing happens on site I am wondering if anybody else ever encounters this problem, and if there is something I'm not doing or missing in order to resolve it:
While building a site I am trying to resize my images so that they are all the same height.
I change all the image files to the same height and resolution in a photo-editing software, but yet when I replace the old images with the new image in the root folder, nothing changes when I preview it on the page. It's not a file naming/structure issue or anything like that, the right files are in the right folders, everything is correct there. When I open the html file in chrome and see that no change in the size is appearing I have tried clearing the cache, incognito windows, hard refreshes, reboots, waiting days to see if the magic internet gods change it ... but nothing works. The images remain in their original non-uniform sizes they were before. It's like the new image sizes/files are not being registered.
Has this ever happened to anyone else?


text:
Q: How to use values from a hashmap as text on separate fragments of an app? My team and I are creating an app that displays menu options for breakfast, lunch, and dinner for today, tomorrow, and the whole week. We have the week menu put into a hashmap with the key being the day of the week. How can we display that string in the today tab, tomorrow tab, and week tab? I have included the code for the separate tabs and our main activity.
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "Dining Hall Menu";
    private LinkedHashMap<String, String> menu = new LinkedHashMap<>();
    private SectionsPageAdapter mSectionsPageAdapter;
    private ViewPager mViewPager;

    public void readJsonStream(InputStream in) throws IOException {
        JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
        try {
            readMessagesArray(reader);
        } finally {
            reader.close();
        }
    }

    public void readMessagesArray(JsonReader reader) throws IOException {
        int count = 0;
        reader.beginArray();
        while (reader.hasNext()) {
            readMessage(reader, count);
            count++;
        }
        reader.endArray();
    }

    public void readMessage(JsonReader reader, int count) throws IOException {
        String day = null;
        String food = null;
        reader.beginObject();
        while (reader.hasNext()) {
            String name = reader.nextName();
            if (name.equals("Monday") || name.equals("Tuesday") || name.equals("Wednesday")
                    || name.equals("Thursday") || name.equals("Friday")
                    || name.equals("Saturday") || name.equals("Sunday")) {
                day = name;
                food = reader.nextString();
                if (count == 0) {
                    menu.put(day, food);
                } else if (count == 1) {
                    menu.put(day, menu.get(day) + food);
                } else {
                    menu.put(day, menu.get(day) + food);
                }
            } else {
                reader.skipValue();
            }
        }
        reader.endObject();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            InputStream in = getAssets().open("Week11.json");
            readJsonStream(in);
        }
        catch(IOException e) {
            e.printStackTrace();
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "onCreate: Starting");

        mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.container);
        setupViewPager(mViewPager);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        setupTabIcons(tabLayout);

    }

    private void setupViewPager(ViewPager viewPager) {
        SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
        adapter.addFragment(new Tab1Fragment(), "Today");
        adapter.addFragment(new Tab2Fragment(), "Tomorrow");
        adapter.addFragment(new Tab3Fragment(), "Week");
        viewPager.setAdapter(adapter);
    }

public class Tab1Fragment extends Fragment {
    private static final String TAG = "Today";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab1_fragment, container, false);
        setHasOptionsMenu(true);
        return view;
    }
}

public class Tab2Fragment extends Fragment {
    private static final String TAG = "Tomorrow";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab2_fragment, container, false);
        setHasOptionsMenu(true);
        return view;
    }
}

public class Tab3Fragment extends Fragment {
    private static final String TAG = "Week";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab3_fragment, container, false);
        setHasOptionsMenu(true);
        return view;
    }
}


text:
Q: how to pass parameter to generator function in redux saga from jsx? I have 3 generator function first is "loginUserStart" where the actual request comes then the second one is "LoginUserAsync" which is called in the "loginUserStart" and third is api call function
so I am trying to pass the parameter from my signin component to the loginUserStart function but whenever I console.log(arguments) it is showing nothing
Code:-
Sign-in component
const login = async () => {
 arr.userEmail = "sample_email";
 arr.userPassword = "sample_password";
 console.log(arr);
 signinUserStart(arr);
};

const logSubmit = () => {
 login();
};
const mapDispatchToProps = (dispatch) => ({
 signinUserStart: (data) => dispatch(signinUserStart(data))
});

Action file code
export const signinUserStart = (data) => ({
 type: UserActionTypes.Set_SigninUser_Start,
 payload: data
})

saga File code
API generator function code
export async function fetchUser(info) {
 console.log(info);
 const email = 'Admin@gmail.com'; //sample_email
 // const passwords = info.userPassword;
 const password = 'Admin@123'; //sample_password
 try {
  const user = await axios.post("http://localhost:5050/sign", {
   data: {
     email: email,
     password: password,
   },
  });
  console.log(user);
  return user;
  } catch (error) {
   console.log(error);
   return error;
  }
}

LoginUserAsync function
export function* LoginUserAsync(data) {
 console.log("in saga");
 console.log(data);
 try {
  let userInfo = yield call(fetchUser, data)
  console.log(userInfo);
  yield put(setUserId('62b1c5ee515317d42239066a')); //sample_token
  yield put(setCurrentUserName(userInfo.data.userName));
 } catch (err) {
  console.log(err);
 }
}

loginUserStart function
export function* loginUserStart(action) {
 console.log(action.payload);//not logging anything for showing in console
 yield takeLatest(UserActionTypes.Set_SigninUser_Start, LoginUserAsync(action));
}

A: I can't be sure without seeing more code, but assuming that loginUserStart is either root saga or started from root saga it means there is no action for it to receive.
The main issue I think is this line
yield takeLatest(UserActionTypes.Set_SigninUser_Start, LoginUserAsync(action));

In the second parameter you are calling the generator function which is wrong, instead you should be passing the saga itself (as reference).
So it should look like this:
yield takeLatest(UserActionTypes.Set_SigninUser_Start, LoginUserAsync);

This way, the Redux Saga library will then call LoginUserAsync when Set_SigninUser_Start is dispatched with first param correctly set to the action object.


text:
Q: Binding Style Propety's Value in ResouceDictionary to ViewModel Properties i am trying to alter the style of my WPF-application (FontFamily, FontSize and so on). Searching SO wasn't successful.
Within the application I use MVVM Pattern. To give my application a uniform appearance, i am using resourcedictionaries to define different styles and skins. This works so far. What  i want to realise is the change single Properties by runtime using a styling window:
    <Window x:Class="StyleResourceDictionariesDemo.View.StyleWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="StyleWindow" Height="450" Width="800"
        Style="{DynamicResource WindowStyle}">
    <Window.Resources>
        <ResourceDictionary Source="../ResourceDictionaries/Styles/Controls/WindowStyle.xaml"/>
    </Window.Resources>
    <StackPanel Orientation="Vertical">
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
            <TextBlock Height="20" Width="75" Text="FontFamily:" Margin="10" TextAlignment="Right"/>
            <ComboBox x:Name="CbFonts" Width="200" Margin="10,10,7,0"
                      ItemsSource="{Binding Source={x:Static Fonts.SystemFontFamilies}}" SelectedItem="{Binding OwnFontFamily, UpdateSourceTrigger=PropertyChanged}"
                      SelectedValuePath="Source" Height="23" VerticalAlignment="Top">
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding}" FontFamily="{Binding}" Height="20"/>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>
        </StackPanel>
        <Border Height="2" Width="Auto" Background="Red" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
        <StackPanel Orientation="Horizontal"  HorizontalAlignment="Left">
            <TextBlock Height="20" Width="50" Text="Size:" Margin="10" TextAlignment="Right"/>
            <Slider Style="{DynamicResource SliderStyle}" Width="100" x:Name="FontSizeSlider" Value="{Binding OwnFontSize, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                    Minimum="{Binding OwnSmallFontSize}" Maximum="{Binding OwnBigFontSize}" TickPlacement="Both" Margin="10" TickFrequency="{Binding OwnFontSizeSteps}" IsSnapToTickEnabled="True"/>
            <TextBlock Height="20" Width="50" Text="{Binding ElementName=FontSizeSlider, Path=Value, UpdateSourceTrigger=PropertyChanged}" TextAlignment="Right"/>
        </StackPanel>
    </StackPanel>
</Window>

with following viewmodel attached:
using System.Windows.Media;

namespace StyleResourceDictionariesDemo.ViewModel
{
  class StyleWindowViewModel : ViewModelBase
  {
    #region Variables
    private double _ownFontSize = 12, _ownSmallFontSize = 8, _ownBigFontSize = 16;
    private FontFamily _ownFontFamily = new FontFamily("Arial");
    #endregion

    #region Properties
    public double OwnFontSizeSteps { get; } = 4;
    public FontFamily OwnFontFamily
    {
      get => _ownFontFamily;
      set
      {
        _ownFontFamily = new FontFamily(value.Source);
        OnPropertyChanged(nameof(OwnFontFamily));
      }
    }

    public double OwnFontSize
    {
      get => _ownFontSize;
      set
      {
        _ownFontSize = value;
        OnPropertyChanged(nameof(OwnFontSize));
      }
    }
    public double OwnSmallFontSize
    {
      get => _ownSmallFontSize;
      set
      {
        _ownSmallFontSize = value;
        OnPropertyChanged(nameof(OwnSmallFontSize));
      }
    }
    public double OwnBigFontSize
    {
      get => _ownBigFontSize;
      set
      {
        _ownBigFontSize = value;
        OnPropertyChanged(nameof(OwnBigFontSize));
      }
    }
    #endregion

    #region Constructor
    public StyleWindowViewModel()
    {

    }
    #endregion

  }
}

In Addition i have created a ControlBaseStyle xaml file from which every other style inherits:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                   xmlns:viewModel="clr-namespace:StyleResourceDictionariesDemo.ViewModel">
    <viewModel:StyleWindowViewModel x:Key="StyleWindowViewModel" />
    <Style TargetType="{x:Type Control}" x:Key="ControlBaseStyle">
        <Style.Setters>
            <Setter Property="FontFamily" Value="{DynamicResource OwnFontFamily}"/>
            <Setter Property="FontStyle" Value="{DynamicResource FontStyleKey}"/>
            <Setter Property="FontWeight" Value="{DynamicResource FontWeightKey}"/>
            <Setter Property="FontSize" Value="{DynamicResource OwnFontSize}"/>
            <Setter Property="Background" Value="{DynamicResource SystemBackground}"/>
            <Setter Property="Foreground" Value="{DynamicResource SystemForeground}"/>
        </Style.Setters>
    </Style>
</ResourceDictionary>

The Problem i have is that the controlbasestyle does not recognize the changes from the ViewModel Properties, and i currently don't get why. Maybe i missed something simple, i just don't see or am i taking the wrong approach to solve this?
Thanks in advance.
Mirko
EDIT 1:
My goal is to change styles and skins at run time.
The structure is as follows:
Initially, all styles are assigned different properties by a skin.
The skin defines the colors, font, size, and other things that should be consistent in the application. These can be called by their specific name (defined with x:key).
The style retrieves the value defined above the skin using the name for the currently used setter (for example, Value=-DynamicResource SystemBackground-for the property background). So far so good.
The goal is to do this with the MVVM pattern. I have defined a Style window and a ViewModel (code above). But I can't make the style notice the change.
The first question now is, can I and if so, how can I change the value for FontFamily (or any other property) at run time.
The second question is, would this approach be correct in real life at all, or are there better approaches?
example skin:
LightSkin.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <ResourceDictionary.MergedDictionaries>
        <!--Default Style-->
        <ResourceDictionary Source="../00_Default/DefaultStyle.xaml"/>

        <!--Specific Style-->
        <ResourceDictionary Source="LightColor.xaml"/>
        <ResourceDictionary Source="LightSizes.xaml"/>
        <ResourceDictionary Source="LightFont.xaml"/>
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

DefaultStyle.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="../../Styles/Controls/ButtonStyle.xaml"/>
    <ResourceDictionary Source="../../Styles/Controls/LabelStyle.xaml"/>
    <ResourceDictionary Source="../../Styles/Controls/ToggleButtonStyle.xaml"/>
    <ResourceDictionary Source="../../Styles/Controls/WindowStyle.xaml"/>
</ResourceDictionary.MergedDictionaries>

LabelBaseStyle.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="ControlBaseStyle.xaml"/>
    </ResourceDictionary.MergedDictionaries>
    <Style TargetType="{x:Type Label}" x:Key="LabelBaseStyle" BasedOn="{StaticResource ControlBaseStyle}">
        <Style.Setters>
            <Setter Property="Width" Value="300"/>
            <Setter Property="Height" Value="150"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Top"/>
            <Setter Property="Content" Value="{Binding Content}"/>
        </Style.Setters>
    </Style>
</ResourceDictionary>

Every (Base-)Style inherits directly or indirectly from ControlBaseStyle.xaml (code above).

A: You should bind the setters of the ControlBaseStyle to the properties of the view model:
<viewModel:StyleWindowViewModel x:Key="StyleWindowViewModel" />
<Style TargetType="{x:Type Control}" x:Key="ControlBaseStyle">
    <Style.Setters>
        <Setter Property="FontFamily" Value="{Binding OwnFontFamily, Source={StaticResource StyleWindowViewModel}}"/>
        ...
    </Style.Setters>
</Style>

Also make sure that you set the properties of the actual StyleWindowViewModel instance that you have defined in the ResourceDictionary when you want to change the style.


text:
Q: How to change color polygon(kml+geoXml)? I show KML map on my site with help geoXml3. There are polygons and markers. But when I want to do something with polygons on click him, nothing happens. I want to change color pressed polygon and change color siblings polygons. Can help me?
It is my code:
function initialize(){
    myLatLng = new google.maps.LatLng(-34.397, 150.644);

    var myOptions = {
        center: {lat: 55.864237, lng: -4.251806},
        zoom: 12,
        scrollwheel: false,
        mapTypeId: google.maps.MapTypeId.HYBRID
    };

    map = new google.maps.Map(document.getElementById("map"), myOptions);

    geoXml = new geoXML3.parser({
        map: map,
        singleInfoWindow: true,
        afterParse: myfunction
    });
    geoXml.parse('http://165.227.72.239/wp-content/uploads/2016/09/glasgow.kml');
}

function myfunction(doc){

    google.maps.event.addListener(doc,"click",function() {
        console.log('gdf');
        for (var i=0;i<doc.gpolygons.length;i++)
            doc.gpolygons[i].setOptions({strokeColor: "#000"});
    });
}
initialize();

A: I believe I have a solution.
In addition, I will give a plug to my GeoXML3 example on Github
var geoXml;

function initialize() {
    myLatLng = new google.maps.LatLng(-34.397, 150.644);

    var myOptions = {
        center: {lat: 55.864237, lng: -4.251806},
        zoom: 12,
        scrollwheel: false,
        mapTypeId: google.maps.MapTypeId.HYBRID
    };

    map = new google.maps.Map(document.getElementById("map"), myOptions);

    geoXml = new geoXML3.parser({
        map: map,
        singleInfoWindow: true,
        afterParse: myfunction
    });
    geoXml.parse('http://165.227.72.239/wp-ontent/uploads/2016/09/glasgow.kml');
}

function myfunction(doc){
    // doc coming in is an array of objects from GeoXML3, one per KML.  Since there's only 1,
    // we'll assumpe 0 is our target and we wnant gpolygons, an array of Google Maps Polygon instances
    var polygons = doc[0].gpolygons;

    for (polygonindex = 0, loopend = polygons.length; polygonindex < loopend; polygonindex++) {
        google.maps.event.addListener(polygons[polygonindex], "click", function() {
            console.log('gdf');
            this.setOptions({strokeColor: "#000"});
        });
    }
}
initialize();