text:
Q: What is the difference between "on-track" and "on track" I'm trying my best since this is for a college application essay:
What is the difference between "on-track" and "on track" and which one should I use?
Here is the sentence I'm using:

Taking responsibility for my actions and keeping myself on-track was one of the most important lessons I learned last year.

Grammarly keeps telling me I'm wrong and I want to know why.

A: Most of the time there is a rule that governs the difference between hyphenatd (x-y) and unhyphenated (x y) use of idiomatic prepositional phrases: when they are used as adjectives preceding the noun, they are often hyphenated; when they do not precede a noun (or are used adverbially) they are not hyphenated. Example: "an over-the-counter drug" vs. "a drug I bought over the counter".

A: Needs a hyphen when it's modifying a noun = "an on-track [SOMETHING]."
Sorry but I can't really think of an example for this use case at the moment.
Doesn't need a hyphen when it's not = "let's get you back on track."
BTW: This applies to the use of hyphens to link any words. If they come BEFORE the subject (noun), you need to hyphenate.  If they come AFTER it, you don't.
EXAMPLES:

*

*It was an on-time flight  vs. The flight was on time

*It's a custom-made shirt  vs The shirt is custom made

*He made a heart-warming speech  vs. The speech he made was heart warming

Hoping I've made this clear and simple.

A: Grammarly, which normally should be taken as a guide to correct usage not a definitive oracle, is, in this case, correct. If you try to Google "on-track" the only hits you get will be for the un-hyphenated "on track".
This means that major dictionaries such as Collins don't recognise "on-track" as an accepted hyphenated word.
You do see it sometimes but it's better practice to use it as a phrase rather than as a hyphenated word.


text:
Q: Object reference not set to an instance of an object when Invoking generic reflective method So this problem is quite confusing. And its fairly complicated and abstract so I'm going to try my best to explain it.
I have 3 classes LinkedIn, Facebook, and Twitter. All of them inherit from a common base class SocialBase which only has one property: uuid and this property is only used so we can find the actual types in the database.
So I have this one function that accepts a Profile class which contains foreign keys to all LinkedIn, Facebook, and Twitter tables, as well as an Enum value that will tell us whether to look for the LinkedIn, the Facebook, or the Twitter foreign keys
public static async Task UnlinkSocialAccountFromProfile(Profile prof, SocialNetworks provider)
    {
        //TYPE variable of LinkedIn, Facebook, or Twitter
        var handler = HandlerMapping[provider];
        //client is MobileServiceClient
        var method = client.GetType().GetMethod("GetTable", Type.EmptyTypes);
        //MobileServiceClient.GetTable<handler>()
        var generic = method.MakeGenericMethod(handler);
        //IMobileServiceTable<handler>
        var table = generic.Invoke(client, null);
        //Profile has 3 foreign keys, LinkedinUUID, FacebookUUID, TwitterUUID, we want the <handler>UUID
        string propertyValue = prof.GetType().GetProperty(handler.Name + "UUID").GetValue(prof) as string;
        //Invoke Extension method with our generic types
        var genMethod =
            typeof (Extensions).GetMethod("FilterByNamedProperty")
                .MakeGenericMethod(table.GetType().GetGenericArguments()[0], propertyValue.GetType());
        //Get the List<handler> that results from our query
        var result = await (Task<List<Linkedin>>)(genMethod.Invoke(null, new [] {table, "uuid", propertyValue}));
        //var result = await (table as IMobileServiceTable<SocialBase>).FilterByNamedProperty("uuid", propertyValue);
        await new SocialResources().DeleteIfExists((result as IList<SocialBase>)[0]);
}

So what I'm doing here is getting the Type of the class, so this will be one of the SocialBase subclasses. For this particular example I know I'm going to be looking for the LinkedIn type. So after getting type LinkedIn I need to invoke the generic method from my MobileServiceTable so normally it would look like MobileServiceTable.GetTable<LinkedIn>() but thanks to reflection we have to take the longer route around this.
After getting my returned instance of IMobileServiceTable<LinkedIn> I get value of the foreign key I'm looking for. In this case it will be called LinkedInUUID. Now here comes the tricky part. I have this extension method that will construct my query expression for me since it has to be of type Expression<Func<LinkedIn, bool>>
public async static Task<List<TSource>> FilterByNamedProperty<TSource, TValue>(this IMobileServiceTable<TSource> source, string propertyName, TValue value)
    {
        // uuid
        var property = typeof(TSource).GetProperty(propertyName);
        // (TSource)p
        var parExp = Expression.Parameter(typeof(TSource));
        //p.uuid
        var methodExp = Expression.Property(parExp, property);
        // value
        var constExp = Expression.Constant(value, typeof(TValue));
        // p.uuid == value
        var binExp = Expression.Equal(methodExp, constExp);
        // p => p.uuid == value
        var lambda = Expression.Lambda<Func<TSource, bool>>(binExp, parExp);
        return await source.Where(lambda).ToListAsync();
    }

I believe the comments do a pretty good job of explaining the build process as each statement occurs. However, once we get to the return await ... the application will crash. Here is the output right before that line and the error immediately following.
IMobileServiceTable<TSource> source = {Microsoft.WindowsAzure.MobileServices.MobileServiceTable<SocialConnect.Linkedin>} (Correct)
propertyName = uuid (Correct)
TValue value = dscRJQSIxJaEfd (Correct)
I have a strong feeling the problem is with my lambda expression, but if I test the extension with this line var test = await (source as IMobileServiceTable<Linkedin>).Where(p => p.uuid == (value as string)).ToListAsync(); it works perfectly fine. But as soon as I change it to use the lambda variable than I get the exception. The actual value of the lambda expression is {Param_0 => (Param_0.uuid == "dscRJQSIxJaEfd")} which looks correct
Any ideas?
EDIT
Sorry, here is the actual exception from stack trace
`A first chance exception of type 'System.NullReferenceException' occurred in mscorlib.dll
System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.WindowsAzure.MobileServices.Query.FilterBuildingExpressionVisitor.GetTableMemberName(Expression expression, MobileServiceContractResolver contractResolver)
   at Microsoft.WindowsAzure.MobileServices.Query.FilterBuildingExpressionVisitor.VisitMemberAccess(MemberExpression expression)
   at Microsoft.WindowsAzure.MobileServices.Query.FilterBuildingExpressionVisitor.Visit(Expression node)
   at Microsoft.WindowsAzure.MobileServices.Query.FilterBuildingExpressionVisitor.VisitBinary(BinaryExpression expression)
   at Microsoft.WindowsAzure.MobileServices.Query.FilterBuildingExpressionVisitor.Visit(Expression node)
   at Microsoft.WindowsAzure.MobileServices.Query.FilterBuildingExpressionVisitor.Compile(Expression expression, MobileServiceContractResolver contractResolver)
   at Microsoft.WindowsAzure.MobileServices.Query.MobileServiceTableQueryTranslator1.AddFilter(MethodCallExpression expression)
   at Microsoft.WindowsAzure.MobileServices.Query.MobileServiceTableQueryTranslator1.VisitMethodCall(MethodCallExpression expression)
   at Microsoft.WindowsAzure.MobileServices.Query.MobileServiceTableQueryTranslator1.Visit(Expression expression)
   at Microsoft.WindowsAzure.MobileServices.Query.MobileServiceTableQueryTranslator1.Translate()
   at Microsoft.WindowsAzure.MobileServices.Query.MobileServiceTableQueryProvider.Compile[T](IMobileServiceTableQuery1 query)
   at Microsoft.WindowsAzure.MobileServices.Query.MobileServiceTableQueryProvider.<Execute>d__31.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
   at Microsoft.WindowsAzure.MobileServices.Query.MobileServiceTableQuery1.<ToListAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
   at SocialConnect.Models.Extensions.<FilterByNamedProperty>d__22.MoveNext() in MobileServiceSample\MobileServiceSample\Extensions.cs:line 55`

A: Alright I finally solved this issue. Apparently the problem wasn't with the query or anything I was doing, but with the SocialBase class. I had been using it to make methods where I knew the generic type TEntity would have a uuid property so I could easily find it in any database. But I guess the field was not getting serialized properly and that was what was causing the NullReferenceException. After removing the base class and just reflectively finding the property and value then everything starting working fine.
I don't understand why it wasn't working properly before because I had been using the base SocialBase class for a lot of situations before this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does CSS Blend mode get overridden by fullPage.js, a jquery plugin? CSS Blend mode is "deactivated" when used inside fullPage's default containers, section and slide.
Creator Alvaro Trigo instructed me to use option css3: false to solve the problem, but it only works with section and not with slide and besides, it makes page rolling animation quite choppy.
He also advised me that this is not a fullpage issue, but rather a css one.
Here is a codepen illustrating the issue:
https://codepen.io/zerino/pen/MXRvbb
And here is the topics in fullPage´s issue forum:
https://github.com/alvarotrigo/fullPage.js/issues/3288

A: Plugin is not the problem, you can delete all js from your example and blend mode still doesn't work.
According to the spec:

The mix-blend-mode CSS property describes how an element's content should blend with the content of the element's direct parent and the element's background.

Blend mode interacts with element's direct parent only. You can test it by setting a background color for .intermediary like I did in this example.


text:
Q: How can I use another attribute instead of the name attribute in jquery.validation?
I have an input that I change the name attribute and other attributes by selecting each radio button. Now I check the name attribute of each state of the input by jquery.validation and display its error
How can I use another attribute to do this instead of using the name attribute?

    $("input[type=radio]").prop("checked", false);
    $("input[type=radio]:nth-child(1)").prop("checked", true);

    $("input[type=radio]").click(function (event) {
        $("label.error").remove();
        $("input").removeClass('error');
        $("#BillIdentity").val('');

        $("input[type=radio]").prop("checked", false);
        $(this).prop("checked", true);
        var id = $(this).attr("id");
        console.log(id);
        if (id === "BillIdentitySelect") {
            $("#BillIdentity").attr("maxLength", "30")
            $("#BillIdentity").attr("name", "BillIdentityMode")
            $("#BillIdentity").attr("placeholder", "Insert billing id")
            //if ($('.iinput').value.length > 10) { return false; }

        }
        else if (id === "NationalCodeSelect") {
            $("#BillIdentity").attr("maxLength", "10")
            $("#BillIdentity").attr("name", "NationalCodeMode")
            $("#BillIdentity").attr("placeholder", "Inser national code")
        }

        //event.preventDefault();
    });

var $form = $("form");
$form.validate({
    rules: {
        BillIdentityMode: {
            required: true,
            minlength: 11
        },
        NationalCodeMode: {
            required: true,
            minlength: 10
        }
    },
    messages: {
        BillIdentityMode: "You must enter at least 11 characters",
        NationalCodeMode: "The number is wrong!"
    }
});

     <input type="radio" id="BillIdentitySelect" name="radio1" />
     Billing ID
     <input type="radio" id="NationalCodeSelect" name="radio2" />
     National Code

<form>
<input maxlength="20" name="BillIdentityMode" id="BillIdentity" class="w-100 text-center" type="text" placeholder="Insert billing id" />
</form>

A: You can use .rules("add", options) and add new rules based on selector which you're applying .rules on it:

    $("input[type=radio]").prop("checked", false);
    $("input[type=radio]:nth-child(1)").prop("checked", true);

    $("input[type=radio]").click(function (event) {
        $("label.error").remove();
        $("input").removeClass('error');
        $("#BillIdentity").val('');

        $("input[type=radio]").prop("checked", false);
        $(this).prop("checked", true);
        var id = $(this).attr("id");
        console.log(id);
        if (id === "BillIdentitySelect") {
            $("#BillIdentity").attr("maxLength", "30")
            $("#BillIdentity").attr("placeholder", "Insert billing id")
            $("#BillIdentity").attr("my-attr","billMode")
            $("#BillIdentity[my-attr='billMode']").rules("add",{
               required: true,
               minlength: 11,
               messages:{required:"required",minlength:"You must enter at least 11 characters" }
})

        }
        else if (id === "NationalCodeSelect") {
            $("#BillIdentity").attr("maxLength", "10")
            $("#BillIdentity").attr("placeholder", "Inser national code")
            $("#BillIdentity").attr("my-attr","nationalCode");
            $("#BillIdentity[my-attr='nationalCode']").rules("add",{
               required: true,
               minlength: 10,
               messages:{required:"required",minlength:"The number is wrong!" }
})
        }

        //event.preventDefault();
    });

var $form = $("form");
$form.validate();

     <input type="radio" id="BillIdentitySelect" name="radio1" />
     Billing ID
     <input type="radio" id="NationalCodeSelect" name="radio2" />
     National Code

<form>
<input maxlength="20" name="BillIdentity" id="BillIdentity" class="w-100 text-center" type="text" placeholder="Insert billing id" />
</form>


text:
Q: Get the size of the output zip file using NodeJs I'm using NodeJs (expressJs) and archiver module to stream zip file to the client, so the final ZIP file do not existe in server storage (streaming zip serving), but the probleme is that i can't get the size of the output file because the zip process happen in real time.
Code :
var archiver = require('archiver');
var files = ["file1","file2"];
var zipper = archiver('zip');

zipper.on('error', function(err) {
res.status(500).send({
    error: err.message
});
});

res.attachment('output.zip');
res.setHeader('Content-Type', 'application/zip');
zipper.pipe(res);
files.forEach(f => {
zipper.file(f, {
    name: f
});
});

zipper.finalize();

A: You have listen for the "data" event on the readable stream.
Here zipper is a readable stream,so you can calculate the whole size by adding the size of each chunk.
var sizeOfZipFile = 0;
zipper.on('data', (chunk) => {
 sizeOfZipFile += chunk.length
});
console.log(sizeOfZipFile) //logs the size of the zip file


text:
Q: Trouble visualizing sin and cos I'm working on building tetris now in Java and am at the point of rotations...
I originally hardcoded all of the rotations, but found that linear algebra was the better way to go.
I'm trying to use a rotation matrix to rotate my pieces, and found I need a good understanding of trigonometry.
That being said, the way I visualize sin and cos is on the bottom part of the picture... a circle drawn on a graph... but images online show the sin cos relationship as the above picture... two waves that are "90 degrees" away from each other...

So, my questions are:
1) I can't seem to visualize how they are 90 degree apart. I can't see how those angles are formed in the above graph from sin and cos.
2) It's said that the relationship is Sin X = Cos (90 - x), and that sin is opposite/hypotenuse and cos = adjacent/hypotenuse... but what exactly does that mean? What do the quotients of these mean in relation to an angle? Let's say x = 45 degrees, adjacent = 5 inches, hypotenuse = 5 inches, and opposite = 4 inches... so sin would be 5"/9" = .55 inches... What does this .55 inches mean in relation to the angle? How is it helpful?
Thank you!!

A: In your $345$ triangle, you have $\sin x = \frac 35$ and $\cos x = \frac 45$.  This gives $x \approx 36.87^\circ$.  Can you see where the first two come from the diagram?  The $90^\circ$ offset between sine and cosine comes from the fact that we measure horizontally for the cosine and vertically for the sine.  While it is true that $\sin x = \cos (90^\circ -x)$ the $90^\circ$ offset is better expressed $\sin x = \cos x - 90^\circ$.  This version has $x$ increasing in the same direction on both sides of the equation.
2) opposite is the side opposite the angle.  In your diagram, the $3$ side is opposite angle $x$, the $4$ side is adjacent, and $5$ is the hypotenuse.  As I said, this gives $\sin x=\frac 35 = 0.6$  It has no units.  The $3$ and $5$ have units of length (say, inches) but when you divide them the quotient has no units.  The trig functions result in unitless numbers.  The $0.6$ gives you one way to construct the angle, though the fact that $\tan x = \frac 34$ is easier to see.  You start going east $4$ units, then north $3$ units, and you have constructed the angle.

A: You have a lot of errors that need to be corrected (which may be the source of your confusion) -- but to address the specific question you asked, consider taking your diagram with the circle and rotating the whole thing 90 degrees and see how the expressions of $sin x$ and $cos x$ compare in the two pictures. Also consider a reflection of your diagram with the circle. (e.g. across the line $y=x$)


text:
Q: How to extract all repositories from GitHub given some criteria? I want to extract all GitHub repositories that have the following criteria:

*

*written in Python

*used the numpy package

*created after 2015

Currently, I am using the following query:
https://api.github.com/legacy/repos/search/numpy%20in:name,description&python?language=python&per_page=50&page=1

But, every time I change the page parameter, I get the same repositories in the response. How do I resolve this?

A: The documentation for the GitHub API says that you should use the GET /search/repositories endpoint, rather than GET /legacy/repos/search.
The following:
https://api.github.com/search/repositories?q=numpy%20in:name,description&python?language=python&per_page=50&page=1

returns results that are paginated correctly.


text:
Q: ECMA script - retrieving SPList property bag I have added a property bag to SPList. Since the SPList doesn't support property bag, I have added my custom property to SPList.RootFolder.Properties. I would like to retrieve this property using ECMA script. I couldn't find a getter method in ECMA script for SP.Folder for retrieving the properties.
I have tried the below, but this returns default properties like Name of folder and Item count, but doesn't return any other property and also custom properties that are added. I have tried rootFolder.get_properties(), but it throws exception that method is not supported.
function addToPlaylist() {
    var ctx = SP.ClientContext.get_current();
    var listId = SP.ListOperation.Selection.getSelectedList();

    //get propertybag
    var web = ctx.get_web();
    this.list = web.get_lists().getById(listId);
    this.rootFolder = list.get_rootFolder();
    ctx.load(rootFolder);
    ctx.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
    this.props = this.rootFolder.get_objectData().get_properties();
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Any help is appreciated.

A: The key is
clientContext.load(rootFolder, 'Properties');
function retrieveSpecificListProperties() {
    var clientContext = new SP.ClientContext();
    var rootFolder = clientContext.get_web().get_lists().getById('{F87D7E27-C692-49A2-ABC4-DC620766E0A8}').get_rootFolder();

    //rootFolder.get_properties().set_item('property_name', '1');
    //rootFolder.update();

    clientContext.load(rootFolder, 'Properties');

    clientContext.executeQueryAsync(
        function () {
            console.log(rootFolder.get_properties().get_fieldValues()['property_name']);
        },
        function (sender, args) { console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace()); }
    );
}

retrieveSpecificListProperties();

A: It seems that folder.get_properties() is only available in SP 2013 which means that retrieving properties from a folder property bag is easy (as shown above)...if you are in SP2013 that is.  I don't think you can do this in the 2010 CSOM/JSOM.  I think this was an oversight by the SP2010 dev team which has now been put right.  You can of course do this easily with server side code.
It's easy enough to read data from the web property bag but then if your property data only has a scope which is only relevant for the list and you are saving it at the web then you will have to find a way to clear things up i.e. remove unnessary properties, when say the list is deleted.

A: So having done some further investigation on this I cannot find any way to retrieve a custom property from a folder property bag using ECMA script in SP2010 - that object model simply just does not give us access to what we need.  As indicated in my previous answer it seems that this limitation has been addressed in SP2013 but that's not very useful if the application is required for 2010.
Accessing folder properties is simple if you are using the SharePoint sever OM but that's not helpful if you only have have ECMA script at your disposal.  So we're stuffed, or are we - time to think laterally.
If I correctly understand the intent behind the original question then what we are trying to do is find a way to save a simple property, say a string for some kind of configuratiuon purpose, at the list level.  However, we have already established that we can't save this custom property in the usual place i.e. the property bag of the root folder because we need to access it via ECMA script and sadly that that doesn't give the access we need for SP2010.  So, why not save this property elsewhere i.e. somewhere which can be accessed by the ECMA OM, but where?
Well in my previous answer I suggested that we could elevate the property and save it in the web property bag and this would work just fine because ECMA does give us what we need to access the AllProperties of the web.  However, there is a real risk that we would end up filling the web property bag with garbage as you would have to find a way to remove the unneccessary key/values when the list is deleted.  Now this clean up task could be done in several ways including attaching event receivers to the list or maybe a custom timer job - all of which seems like a lot of effort and complexity for such a simple task.
So if the web property bag won't cut it then how about missappropriating an existing list property for our purposes.  Surely we could find a spare string property of the list that serves not real prupose that we could grab and use/abuse to save our custom property value.  Well, sadly no such 'conveniently unused' read/write string property exists on an SPList object (at least I couldn't find one).  I briefly thought about abusing the List's Description field but that's no good because we might want to use that for it's intended purpose and it also shows up in the UI and can indeed be changed in the UI, all of which makes it an unlikley candidate.  The only time when abusing the Description field might work is if the list is hidden and therefore has no UI to speak of.
So we're done for, - well not quite.  If we can't find a property of the list to abuse how about a property of a View for the list.  Ok, so assumming that we have access to the OM to create a new view (which is likely because we must somehow have had access to add custom properties to the root folder which was the original plan) then creating a custom View to store a custom property has an immediate advantage in that we can make the view hidden to end users who will never know that it exists and the view will be deleted when the list is deleted i.e. it's a self cleaning solution.
So a View is a good candidate but which property to use?  Sadly an SPView has no Description property so we have to look wider and the best candidate I can find is the Toolbar property.  The Toolbar property is a read/write string property that will have no impact on the View because our View will be hidden and have no use for a UI and so need for a tool bar property.  And yeeha - the ECMA OM gives us a .get_toolbar() method which can be applied on a View object to get at the value!
So all we have to do now is to save our custom property to the Toobar field of a hidden view on the list (rather than the property bag of the root folder).  There are lots of ways to do this but I've chosen to abstract the process out to a custom static utilites class which provides me we a few useful extension methods as shown below:
    public static bool HasView(this SPList List, string Title)
    {
        return (List.Views.ToIEnumerable().Where(V => V.Title == Title).FirstOrDefault() != null);
    }

    private static SPView GetConfigView(this SPList List, string ViewName)
    {
        if (List.HasView(ViewName))
            return List.Views[ViewName];
        else
        {
            SPField fldTitle = List.Fields[SPBuiltInFieldId.Title];
            StringCollection ViewFields = new StringCollection(){fldTitle.InternalName};
            string strBasicQry = "<OrderBy><FieldRef Name='LinkTitle'/></OrderBy>";
            SPView ConfigView = List.Views.Add(ViewName, ViewFields, strBasicQry, 1, false, false);
            ConfigView.Hidden = true;
            ConfigView.Update();
            return ConfigView;
        }
    }

    public static void SetPropertyString(this SPList List, string Key, string Value)
    {
        SPView ConfigView = List.GetConfigView(Key);
        ConfigView.Toolbar = Value;
        ConfigView.Update();
    }

    public static string GetPropertyString(this SPList List, string Key)
    {
        if (List.HasView(Key))
            return List.Views[Key].Toolbar;
        else
            return string.Empty;
    }

The code is fairly simple.  The list.HasView("View Title") extension method simply returns a boolean value which indicates whether the list has a view with the specified title.
The list.GetConfigView("View Name") method either returns the View with the matching name, or if one can't be found then simply create a new one using the supplied title which is in effect the Key to our custom property.
All that remains is to create a couple of accessor methods which get and set data to and from the Toolbar property of the view.
The calling code (from the SP Server OM) looks like this:
 const string KEY = "MY_CUSTOM_PROPERTY_KEY";
 SPList List = Web.Lists["My list"];

 //Save the property string to the KEY
 List.SetPropertyString(KEY, "Custom String Value");

 //Retreiving the property string
 string propValue = List.GetPropertyString(KEY);

To get at the property using ECMA script might look something like the following:
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var listId = SP.ListOperation.Selection.getSelectedList();
var list = web.get_lists().getById(listId);
var configView = list.get_views().getByTitle('KEY_CUSTOM_PROPERTY_KEY');
ctx.load(configView);
var configString = configView.get_toolbar();
Now for a few pros and cons:
Pros
 - It works!

*

*It's supported, we are just using the standard OM and object properties albeit that we are bending the rule slightly.

*It performs well.  Actually this is probably better (perfomance wise) than
adding custom properties to the object property bags.

*The complexity can easily be abstracted so that the calling code uses
this capability with just a couple of accessor method calls.

*You can create as may custom properties as you like.

*It's a self cleaning solution i.e. your custom properties live and die with the list
Cons

*

*Well we are bending things just a little by abusing the Toolbar
property for our own nefarious purpose.

*Creating an entire View for a single property string seems a bit
excessive - and it is! If you need 6 property strings you'll end up
with 6 hidden views.  Of course you could do something creative with
a single property string so by saving and XML fragment or a delimited
set of property/value pairs in a single string.

*You also need to take care that the view titles you use as properties
keys are not likely to be in use currently or required some time in
the future.
In summary I think that this is reasonable workaround for an obvious limitation in the ECMA 2010 OM but I think I would use this approach sparingly i.e. only in circumstances when I only have the ECMA OM at my disposal and I need to access custom properties.  Lateral thinking applied!


text:
Q: Docker build после сборки образа создает дочерние образы Docker build после сборки образа создает дочерние образы <none>, которые не удалить
Dockerfile:
FROM alpine:3.7

RUN apk add --no-cache nginx
RUN mkdir /run/nginx

COPY ./nginx/nginx.conf /etc/nginx/nginx.conf

Собираю образ:
docker build -t alpine_nginx .

или
docker build --rm -t alpine_nginx .

или
docker build --force-rm -t alpine_nginx .

Список образов:
anton@UbuntuDesktop:~/Projects/Docker/App$ docker image ls -a
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
alpine_nginx        latest              aba2846ed9a8        29 seconds ago      5.58MB
<none>              <none>              f66743a5c4c9        30 seconds ago      5.58MB
<none>              <none>              a7e63c600fcc        34 seconds ago      5.58MB
alpine              3.7                 9bea9e12e381        3 weeks ago         4.21MB

Пробовал docker image prune -f - ничего не удаляет
Так же docker images -q -f dangling=true - пусто, наверное фильтр устаревший
Docker version 18.09.1, build 4c52b90

A: docker images -q -f dangling=true | xargs -I ARGS docker rmi -f ARGS


text:
Q: Defining a variable in a JSON object response I am trying to crawl through a JSON array using the Twitch API, but I get the following for the thumbnail URL:
thumbnail_url:"https://static-cdn.jtvnw.net/previews-ttv/live_user_dakotaz-{width}x{height}.jpg"

How can I define the width and height properties of the image during the request?


text:
Q: Android programming - onitemclicklistener for multiple listviews doesn't work In my activity i have created seven listviews and am using viewpager to swipe between them in the same activity. I then have a sqlite database populating each listview. My problem is the onitemclicklistener is not working, there are no errors and the code executes fine but nothing happens on list item clicks. I tested it out by adding toast display messages etc but nothing happens on list item clicks.
I suspect the problem is i have not gotten the listviews from xml layouts like the conventional method so the itemclicklistener method is slightly different, however i don't know what method to use when utilising listviews this way and no other OS threads that i've seen creates listviews this way.
If anyone could please shed some light i'd be very grateful. Thanks in advanced.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mContext = this;
        setContentView(R.layout.activity_schedule);

        ListView listview1 = new ListView(mContext);
        ListView listview2 = new ListView(mContext);
        ListView listview3 = new ListView(mContext);
        ListView listview4 = new ListView(mContext);
        ListView listview5 = new ListView(mContext);
        ListView listview6 = new ListView(mContext);
        ListView listview7 = new ListView(mContext);

        Vector<View> pages = new Vector<View>();

        pages.add(listview1);
        pages.add(listview2);
        pages.add(listview3);
        pages.add(listview4);
        pages.add(listview5);
        pages.add(listview6);
        pages.add(listview7);

        ViewPager vp = (ViewPager) findViewById(R.id.viewpager);
        PageAdapter adapter = new PageAdapter(mContext,pages);
        vp.setAdapter(adapter);

        db.open();
        scheduleAdapter = new ScheduleAdapter(ScheduleActivity.this, db.getMonday(),CursorAdapter.NO_SELECTION );
        listview1.setAdapter(scheduleAdapter);
        db.close();

        db.open();
        scheduleAdapter = new ScheduleAdapter(ScheduleActivity.this, db.getTuesday(),CursorAdapter.NO_SELECTION );
        listview2.setAdapter(scheduleAdapter);
        db.close();

        db.open();
        scheduleAdapter = new ScheduleAdapter(ScheduleActivity.this, db.getWednesday(),CursorAdapter.NO_SELECTION );
        listview3.setAdapter(scheduleAdapter);
        db.close();

        db.open();
        scheduleAdapter = new ScheduleAdapter(ScheduleActivity.this, db.getThursday(),CursorAdapter.NO_SELECTION );
        listview4.setAdapter(scheduleAdapter);
        db.close();

        db.open();
        scheduleAdapter = new ScheduleAdapter(ScheduleActivity.this, db.getFriday(),CursorAdapter.NO_SELECTION );
        listview5.setAdapter(scheduleAdapter);
        db.close();

        db.open();
        scheduleAdapter = new ScheduleAdapter(ScheduleActivity.this, db.getSaturday(),CursorAdapter.NO_SELECTION );
        listview6.setAdapter(scheduleAdapter);
        db.close();

        db.open();
        scheduleAdapter = new ScheduleAdapter(ScheduleActivity.this, db.getSunday(),CursorAdapter.NO_SELECTION );
        listview7.setAdapter(scheduleAdapter);
        db.close();

         listview1.setOnItemClickListener(new ListView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                }
        });

A: From your describe I understand that the lists are showed up when you start the application.
The position parameter, holds where the user clicked on the (screen) - list.
Did you try to use it with switch case?
I mean like this:
list.setOnItemClickListener(new OnItemClickListener(){
                  public void onItemClick( AdapterView <?> parent, View view, int
                                           position,long id){

                       switch(position){
                            case 0:
                           // write what you need here when the user clicks on the first list item
                              break;
                            case 1:
                           // write what you need here when the user clicks on the 2nd list item
                               break;
                       }
                  }
               };

hope this will help you

A: I'm not quite sure why the itemClicklistener isn't being called when you press something in listview1, but I don't think that's the biggest problem.
You're off on a terrible start with adding 7 listviews in 1 activity, and with opening and closing your database 7 times straight after each other.
I'd suggest you start out with the app Android UI Patterns: https://play.google.com/store/apps/details?id=com.groidify.uipatterns
There you will find a page full of viewpagers and tabs examples. I'd suggest you take the Jake Wharton one.
You want to be doing this with Fragments.

A: In your ListFragment you should extends ListFragment then use onListItemClick, like this:
public class ArrayListFragment extends ListFragment {

@Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            setListAdapter(new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_list_item_1, Listnames.TITLES));
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            Log.i("FragmentList2", "Item clicked: " + id);

            String item = (String) getListAdapter().getItem(position);

            Intent intent = new Intent(getActivity(), SearchableActivity.class);
            intent.putExtra("item", item);
            Toast.makeText(getActivity(), item, Toast.LENGTH_LONG).show();
//          startActivity(intent);
        }

    }


text:
Q: Resharper changing Nuget package DLLs when Visual Studio starts I'm having an issue with my solution, where opening Visual Studio will cause some of my Nuget package DLLs to be overridden.
I've found this only happens when Resharper is installed. Uninstalling it, or suspending it makes the problem go away.
I'm finding that it's only happening for Nuget packages in my local repository, and the overridden DLLs look incomplete (possibly an older version, but still signed as the latest version). Building the solution then fails. I need to revert the DLLs in source control, then build for it to work.
I've tried finding references to old versions of the Nuget package in my solution, but there aren't any.
Does anyone know how to stop Resharper changing my DLLs when Visual Studio loads?
And, any suggestions about what might be the bigger issue with my Nuget packages?

A: Issue, seems, that you changed your local copy of DLL from package content in packages folder.
It's bad practice. If you need to modify DLL inside some package - you better to create your own package with necessary DLLs.


text:
Q: Mokito, Mocking method behavior I am fairly new to automated testing and I have been having some trouble with mocking a class with mockito. Basically what I am trying to do is make use of an interface that is being sent to a method, when this method (Request(Response)) is called I want mockito to intervene and call a method from the interface passing an object as a param (callback.OnSuccess(Obj)). Here is an example of what I mean, I will start off with my production code I have taken out everything that isnt needed:
ServerRequest class
public void Request(ResponseInterface callback){
 //The contents of this class isnt really important as I do not wish to use any of it
//but in general this makes a request to the server and if the request is a success then
Object obj = ProcessResponse(Response);
callback.OnSuccess(obj);
//otherwise
Object obj = ProcessResponse(Response);
callback.OnError(obj);
}

ResponseInterface
public interface ResponseInterface(){
void OnSuccess(Object resp);
void OnError(Object resp);
}

MainActivity
public void MakeRequest(){
ServerRequest.Request(new ResponseInterface(){
@Override
public void OnSuccess(Object objResponse){
 //do something to show user the request was successful depending on the current activity
}

@Override
public void OnError(String e){
 //do something depending on the current activity
})
}

So far I have tried multiple methods, the best I could come up with is in the code below, but as I am sure you can tell from the post it did not work but I will leave it here as it might give somebody a better idea of what I am trying to do.
ServerRequest mockReq = mock(ServerRequest.class);
    Mockito.doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            System.out.println("Running first time");
            Object[] arguments = invocation.getArguments();
            ResponseInterface inter = (ResponseInterface) arguments[2];
            Object obj = "Already taken";
            inter.OnSuccess(obj);
            return null;
        }
    }).when(mockReq).InformationRequest(ArgumentMatchers.anyMap(),anyString(),ArgumentMatchers.<ServerInterface>any());

Any help on this matter would be greatly appreciated as I have no clue what I am doing.

A: In case anybody else is ever trying to achieve something similar I have figured out how to call the method in the interface sent through the mocked method.
So to start off I created setup method annotated with before (not necessarily needed you can place this just before your test in the same method). Then I began setting up everything needed to achieve my goals, here is the setup required.
//class to be mocked
@Mock
ServerRequest mockReq;

@Before
public void setup(){
    //get the activity instance
    Registration reg = mActivityRule.getActivity();
    //make sure the actual method to be mocked does nothing, By default it should do nothing anyway but for some reason  not for me
    doNothing().when(mockReq).InformationRequest(ArgumentMatchers.anyMap(),anyString(),ArgumentMatchers.<ServerInterface>any());
    //set up an argument catcher
    captor = ArgumentCaptor.forClass(ServerInterface.class);
    //inject the mock into the activity
    reg.serverRequest = mockReq;
}

Next up in my test method the mocked method should be called when the submit button is clicked, in which case I verify the mocked method was actually called and capture the data sent to it, then I use the data in what ever manner I wish.
 //click the button
 onView(withId(R.id.SubmitBtn)).perform(scrollTo(), click());
 //check to see if method was called then capture the interface
 verify(mockReq).InformationRequest(ArgumentMatchers.anyMap(),anyString(),captor.capture());
  //get the interface
 ServerInterface serverInter = captor.getValue();
 Object obj = "Already taken";
 //make use of the interface
 serverInter.OnSuccess(obj);


text:
Q: Positioning divs inside a container div without the content of an upper div affecting the position of a lower div I'm trying to accomplish the following layout,
http://www.rae-mx.com/test/css-layout.jpg
and I'm almost there, except for the last green div, which is going lower and lower depending on the content of the content (white) div. If I set a value for the TOP property for the green div, and then I add some more text to the content div, the green div goes lower and lower.
Since the green div is child to the main container div, and the green div is relatively positioned, isn't it supposed to be placed specifically at the position indicated by the TOP value of it? If I'm incorrect...can someone please tell me how can i make it so that the green div is always displayed at the same spot within the container (gray) div, regardless of the height of the content/white div?
I tried to paste the css code here but was having problems with the brower. you can see the test site source/css at http://www.rae-mx.com/test
tia for the help.

A: I think you're misunderstanding how relative positioning works. If something is marked as position: relative then that does nothing to that element's positioning. However any descendant elements with position: absolute are positioning relative to that element.
So a basic skeleton for what you want is:
#main { position: relative; }
#menu { position: absolute; top: 10; right: 10; }
#content { position: absolute; top: 30; }
#contact { position: absolute; top: 180; right: 10; }

Take a look at Absolute and Relative Positioning. This is called relative+absolute positioning.

A: If you want something positioned at the same place, use position:absolute instead. Position: relative is used to move the element after it have been placed in the normal flow.
And remember: With position:absolute 0,0 is the upper left corner of the first(closest to the element, when walking from the element and to the root) parent with position:relative or position:absolute


text:
Q: Using netbeans automatic generated jtextfield in a jbutton for a mysql search I'm a rookie in the java language, but i'm trying to create a search function for a mysql database.
I've managed to get the search function working with a defined string, but i have no idea how a automatic generated jtextfield works or how they can connect it to an auto generated jbutton.
here is my code for the jtextfield and jbutton:
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {

   //  jTextField1.addActionListener(this);

}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

   jTextField1.getText();
   jComboBox1.getSelectedItem().toString();

    try {
        Connection con = DriverManager.getConnection("jdbc:ucanaccess://C:/Michel's Muziek Magazijn.accdb");

        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM mmm WHERE "+jComboBox1+" = '"+jTextField1+"'");

    while (rs.next()) {
            System.out.println("\t" + rs.getString(2) + "\t" + rs.getString(3)+ "\t" + rs.getString(4));
        }
        rs.close();

    } catch (SQLException e) {
        System.out.println(e);
    }

}

Like i said, i don't have any idea what to insert into the jtextfield or how to get the inserted data towards the jbutton.
I would be very grateful if anyone can help me, since an answer to this question can also completely finish my insert function for adding to the database.
Already thanks for reading,
Molnaris

A: You can redirect the text field action to the button using something like..
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {

   jButton1ActionPerformed(evt)

}

This means that when the user presses Enter, it will also trigger a search, which is a nice feature
You need to assign the values returned by the text field and combobox ...
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

   String text = jTextField1.getText();
   String combo =jComboBox1.getSelectedItem().toString();

    try {
        Connection con = DriverManager.getConnection("jdbc:ucanaccess://C:/Michel's Muziek Magazijn.accdb");

        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM mmm WHERE "+combo+" = '"+text+"'");

    while (rs.next()) {
            System.out.println("\t" + rs.getString(2) + "\t" + rs.getString(3)+ "\t" + rs.getString(4));
        }
        rs.close();

    } catch (SQLException e) {
        System.out.println(e);
    }

}

Having said that, I'd strongly encourage you to use a PreparedStatement instead
PreparedStatement stmt = con.prepareStatement("SELECT * FROM mmm WHERE ? = ?");
stmt.setString(1, combo);
stmt.setString(2, text);
ResultSet rs = stmt.executeQuery();

See Using PreparedStatements for more details
You also not managing your resources very well, you should ensure that you are closing the various resources when you have finished with them...
try (Connection con = DriverManager.getConnection("jdbc:ucanaccess://C:/Michel's Muziek Magazijn.accdb")) {
    try (PreparedStatement stmt = con.prepareStatement("SELECT * FROM mmm WHERE ? = ?")) {
        try (ResultSet rs = stmt.executeQuery()) {
            //...
        }
    }
} catch (SQLException e) {
    e.printStackTrace();
}

Take a look at The try-with-resources Statement for more details


text:
Q: Why doesn't clear_output() clear what's printed to the python console in VS code? New to programming and currently working on a web scraper.  I'm trying to monitor my progress and keep my terminal clean as I go using clear_output() from IPython.display, but it doesn't appear to be clearing my output in VSCode.  Here's an example:
from time import sleep
from IPython.display import clear_output

x = 0
while x < 5:
    x += 1
    sleep(.2)
    print(x)
    clear_output(wait=True)

I'd expect it to clear the previous value of x in place of the new value, but it doesn't.  Once the program finishes, my output changes from:
>>>1
>>>2
>>>3
>>>4
>>>5

to:

>>>1
>>>2[2K
>>>3[2K
>>>4[2K
>>>5[2K

Guessing this is something from IPython, but I'm not sure what it means or how to fix it.  Thanks for any help!

A: I'm not exactly sure if this is what you're asking but you could try using the sys library:
from time import sleep
from sys import stdout
for i in range(0, 1000):
    stdout.write("\b")  # \b for backspace, you may need \r depends on  system
    sleep(.9)
    stdout.write("\b\b\b>>>" + str(i))
    stdout.flush()

for me the output is:
>>>1

then the 1 is replaced by a 2
>>>2

2 replaced by 3 etc.
I threw in a sleep so you can see what happens, as stated in the comment you may need to change the \b to a \r or some combination of both

A: clear_output() only works in Jupyter. Consider using print('\n'100) to clear the output in other IDEs.


text:
Q: If $f'(x) = -f(x)$ and $f(1)=1$, then what is $f(x)$? If $f'(x) = -f(x)$ and $f(1)=1$, then $f(x)=$
(a) $1/2e^{-2x+2}$
(b) $e^{-x-1}$
(c) $e^{1-x}$
(d) $e^{-x}$
(e) $-e^{x}$
If you plug in $1$ for $x$ in option c it gives you $e^{1-1}$ or $e^0$ which is $1$ hence what is needed.

A: Hint: All you need to do in this case is to evaluate $f(1)$: $f_A(1), f_B(1), f_C(1), f_D(1), f_E(1)$.
Show your calculations in each case.
Doing that rules out all possibilities except $(C)$, irregardless of the first condition, though you want to evaluate $f'_C(x)$ to show that $f_C = f'_C$.

A: If $f'(x) = -f(x)$,
then
$0 = f'(x)+f(x)
= e^x(f'(x)+f(x))
= (e^x f(x))'
$
so $e^x f(x)$ is constant.
Set $e^x f(x) = c$
and set $x = 1$.
Then, since $f(1) = 1$,
$c = e f(1) = e$
so $f(x) = e e^{-x} = e^{1-x}$.
An alternative solution is to write
$f'(x)/f(x) = -1$
so $(\ln(f(x))'=-1$
so $\ln f(x) = c-x$
or $f(x) = e^{c-x}$
for some constant $c$.
This has the problem that $f(x) = 0$ causes problems,
and the first solution does not have this problem.

A: This is a separable differential equation.  We have $\frac{dy}{dx} = -y$, so
$$\int \frac{dy}{y} = \int -dx$$
and we get get the general solution $y = e^{-x + k}$.  The initial condition $y(1) = 1$ implies $k = 1$ in this case.

A: If $f'(x) = -f(x)$,
then
$\frac{f'(x)}{f(x)}=-1 \implies \int \frac{f'(x)}{f(x)}dx=-\int dx \implies f(x)= e^{-(x-k)}\ $ (Here k is the integration constant)
so $e^x f(x)$ is constant.
Here, $e^x f(x) = e^k$
and set $x = 1$.
Then, since $f(1) = 1$,
$e f(1) =e^k $
so $f(x) = e e^{-x} = e^{1-x}$.
so, $f(x)= e^{1-x} \implies\ \ $ Option (b) is correct.


text:
Q: _n() Single and Plural for search results? This code produces

Search Results for "hello" - 1 articles "

Search Results for <?php echo'"'?>
    <?php /* Search Count */
    $allsearch = &new WP_Query("s=$s&showposts=-1");
    $key = wp_specialchars($s, 1);
    $count = $allsearch->post_count;
    _e('');
    _e('');
    echo $key;
    _e('');
    echo '"';
    _e(' - ');
    echo $count . ' ';
    _e('articles');
    wp_reset_query(); ?>

How can I make it $single and $plural for eg. "1 article" or "2 articles"?

A: Instead of using 'if' loop it's better to use special function:
<?php echo _n( 'article', 'articles', $count, 'my-plugin-domain' ); ?>

http://codex.wordpress.org/Function_Reference/_n


text:
Q: What are the differences in coding a destruction algorithm for destroying double and singly linked lists separately in C? In my exam there was a question like this and I've been thinking that what are the differences in coding a destruction algorithm for destroying double and singly linked lists separately in C?

A: If your data type allows your doubly-linked list to be a ring, you need to break the link back to the head.  Then traverse the list as usual, copying pointers and freeing as you go.


text:
Q: Script executes after inspecting window What I'm doing here is changing the opacity of the header and adding a searchbar when it reaches a waypoint (A bigger searchbar). It works, the problem here is that the change is only applied after I inspect the window and change between screen sizes.
Even a simple console log only happens after inspecting the windows
CoffeeScript
$(document).ready ->  #The indentation is correct
  if $('#hero-image').length > 0
    $searchBarMin = $('header #search-bar-group')
    $searchaBar = $('#big-search-bar')
    $header = $('header')
    $nearYou = $('#near-you')
    $searchBarMin.hide()
    $header.css({background: "linear-gradient(rgba(0,0,0,1), rgba(0,0,0,0.3))", position: "absolute" })
    waypoint = new Waypoint({
        element: $('#near-you'),
        handler: (direction)->
            console.log '!///////////////////'
            if (direction == "down")
                $searchBarMin.show()
                $header.css({background: "linear-gradient(rgba(0,0,0,1), rgba(0,0,0,1))" })
            else
                $searchBarMin.hide()
                $header.css({background: "linear-gradient(rgba(0,0,0,1), rgba(0,0,0,0.3))" })
    })

Header html

    <%= link_to root_path do %>
        <%= image_tag("TA_logo01.png") %>
    <% end %>

<%= link_to "What is TattooAdvisor", what_is_tattoo_advisor_path %>

    <%= form_tag search_path, method: :get do %>

                <%= text_field_tag :query, params[:query], data: {autocomplete_source: Artist.order(:name).map{ |u| {id: u.slug, reference: u.reference,state: u.state, label: u.name, image: u.avatar.url(:thumb) }} + Parlour.order(:name).map{ |u| {id: u.slug, label: u.name, reference: u.reference, state: u.state, image: u.avatar.url(:thumb) }}}, class: "name_autocomplete_search input-group-field", placeholder: "Search for parlours and artists"%>

                <%= submit_tag "Search", class: "button" %>

    <% end %>

                <%= avatar_profile_link current_user, "thumb", class: 'logged-in-picture' %>

<%= current_user.display_name %>

                    <%= link_to "Profile", profile_standard_path %>

                <% if current_user.has_role? :artist %>

                        <%= link_to "Artist Profile", profile_artist_path %>

                <% end %>
                <% if  current_user.has_role? :parlour %>

                        <%= link_to "Parlour Profile", profile_parlour_path %>

                <% end %>

                    <%= link_to "Upgrade Account", subscription_path %>

                    <%= link_to "Invite", new_invite_path %>

                    <%= link_to "Log Out", destroy_user_session_path, method: :delete %>

        <%= link_to "Review", new_review_path, class:'button' %>

    <%= form_tag search_path, method: :get do %>

                <%= text_field_tag :query, params[:query], data: {autocomplete_source: Artist.order(:name).map{ |u| {id: u.slug, reference: u.reference,state: u.state, label: u.name, image: u.avatar.url(:thumb) }} + Parlour.order(:name).map{ |u| {id: u.slug, label: u.name, reference: u.reference, state: u.state, image: u.avatar.url(:thumb) }}}, class: "name_autocomplete_search input-group-field", placeholder: "Search for parlours and artists"%>

                <%= submit_tag "Search", class: "button" %>

    <% end %>

HomePage

Tattoos are art

                    Art is subjective

Find the right artist for your tattoo

                    <%= render 'search_box' %>

<%= render partial: 'near_you' %>

SearchBox Partial

    <%= form_tag search_path, method: :get do %>

                <%= text_field_tag :query, params[:query], data: {autocomplete_source: Artist.order(:name).map{ |u| {id: u.slug, reference: u.reference,state: u.state, label: u.name, image: u.avatar.url(:thumb) }} + Parlour.order(:name).map{ |u| {id: u.slug, label: u.name, reference: u.reference, state: u.state, image: u.avatar.url(:thumb) }}}, class: "name_autocomplete_search input-group-field", placeholder: "Search for parlours and artists"%>

                <%= submit_tag "Search", class: "button" %>

    <% end %>

Rails version: 4.2.6.
Turbolinks: 5.0.1
Foundation 6.3.
Waypoints (Latests version, installed with bower)

A: This is a css issue clashing with the way waypoint.js works.
First thing you need to change is remove the property height: 100% on body, but keep it on html.
html{
  height: 100%; # not on body, just html
  ...
}

Then, your header position attribute needs to be fixed and not absolute.
header{
  position: fixed; # not absolute
  ...
}

If you do all this it should work.


text:
Q: Elasticsearch cat indices in JSON format Using Elasticsearch 1.7, I want to see the results of _cat/indices in  JSON format.  I understand the results are meant to be aligned/pretty/readable, but is there a way to convert it to JSON using Elasticsearch API?

A: Per the documentation of cat APIs:

JSON is great… for computers. Even if it's pretty-printed, trying to find relationships in the data is tedious. Human eyes, especially when looking at an ssh terminal, need compact and aligned text. The cat API aims to meet this need.

In other words, the cat API is designed to give data in this format. So you will want to use a different form of the API. The problem is (at least this was my problem) that googling "elasticsearch list indices" brings up the cat API as the first result, so this question is pretty reasonable.
To get all of the indices in JSON form, it's as easy as running this:
GET /*/_stats

That's a lot of data though. You likely want JSON because you want to do some sort of processing on it. Going back to how I found this question, I actually wanted to get a list of indices sorted by the store size and I didn't want to have to use curl and sort unix commands to do so. That command looks like this:
GET /*/_stats/store

Unfortunately, the sort in the search body won't work for the _stats command (at least, I haven't been able to make it work). But adding the store attribute will make it so you only get back the information about the data stores for each index.
More information about the metrics attributes can be found in the _stats documentation.

A: Append format param, eg: _cat/indices?format=json
You can also make it pretty-formatted with: _cat/indices?format=json&pretty=true

A: In general with this and other REST apis, set the "Accept" header to the content type you need. For example, with elasticsearch 5.1.1 you need to specify "application/json" as the accepted content type and elasticsearch will honor that.

A: Yes it can be done by adding format=json at the end.
localhost:9200/_cat/indices?format=json

A: It looks like I can get what I need using /*/_aliases and use all the keys of the response, similar to what is suggested here.


text:
Q: Map unable to create seperate paragraph tags I'm trying to use map on an array of string to get multiple paragraphs preceded by headers, however all the strings wind up in the same paragraph tag. I expect

 Header 1

 String 1

 Header 2

 String 2

,but get

 Header 1

 String 1String 2

 Header 2

The incoming list seems fine and replacing the string in the map with a constant fixed the issue. Below is the function in question.
function instructionsRenderer(subtasks, element_name)
{
        var elements = [subtasks.map((subtask) => subtask['data']['text'])]
        console.log(elements)
        var zipElems = zip(INSTRUCTIONS_SUBTASKS,elements)
        /*const dispElem = zipElems.map((elem) =>

 {elem[0]}

 {elem[1]}

)*/
        const dispElem = elements.map((elem) =>
 {elem}
)

        console.log(dispElem)
        return(
        <Collapsible element={
 {dispElem}
} element_name={element_name}/>
        );
}

A: Try changing your method to this, I guess elements array only has one item.
function instructionsRenderer(subtasks, element_name)
{
        // .map will return an array
        var elements = subtasks.map((subtask) => subtask['data']['text'])
        console.log(elements)

        var zipElems = zip(INSTRUCTIONS_SUBTASKS,elements)
        /*const dispElem = zipElems.map((elem) =>

 {elem[0]}

 {elem[1]}

)*/
        const dispElem = elements.map((elem) =>
 {elem}
)

        console.log(dispElem)
        return(
        <Collapsible element={
 {dispElem}
} element_name={element_name}/>
        );
}

A: As Faisal pointed out, the length of the string array was different (1 rather than 4). The old code had  square brackets around map, which was the issue.
Iterating through the original array (substasks) rather than the array of strings fixed the issue and resulted in more compact code.
const dispElem = subtasks.map((subtask,idx) =>
 setSelect(subtask['id'])}>

 {subtask['id']}

 {subtask['data']['text']}

)
        return(
        <Collapsible element={
 {dispElem}
} element_name={element_name}/>
        );


text:
Q: Manipulation of values fed in from an hourly API with react.js I'm bringing in data from an API which is updated periodically (every hour on the hour), for example:
{
  "success":true,
  "terms":"https:\/\/currencylayer.com\/terms",
  "privacy":"https:\/\/currencylayer.com\/privacy",
  "timestamp":1479835508,
  "source":"USD",
  "quotes":{
    "USDUSD":1,
    "USDJPY":110.971001,
  }
}

Some of the values are numeric, and these will change. So, for example one hour later I could have:
{
  "success":true,
  "terms":"https:\/\/currencylayer.com\/terms",
  "privacy":"https:\/\/currencylayer.com\/privacy",
  "timestamp":1479835509,
  "source":"USD",
  "quotes":{
    "USDUSD":1,
    "USDJPY":111.03221,
  }
}

I call the API from within my react.js class component as (I've omitted my private API access key for privacy reasons):
  componentDidMount() {
    var component = this;
    var MY_ACCESS_KEY  = "<omitted private data>";
    var MY_CHOSEN_CURRENCIES = "USD,JPY,CAD,RUB,CNY,GBP,EUR,BTC,CHF"
      $.get("http://apilayer.net/api/live?access_key=" + MY_ACCESS_KEY + "&currencies=" + MY_CHOSEN_CURRENCIES + "&format=1", function(data) {
        component.setState(data)
      });
  }

I was wondering, if I could somehow store the previous JSON that was pulled down from my API, such that I could then calculate the percentage change in the USDJPY value>?
N.B. I understand the mathematics of it - ((USDJPY_new/USD_old)/USDJPY_old)*100 = percentage_change - I just need to know how to store and then access the data. Just not sure of any ideas of how to log the previous values to make such a calculation!
Q. I am wondering if there is a way of storing this API data locally (only the previous JSON pulled down) and then when the data changes in the API (and not when someone reloads the website - i.e., when the timestamps change) I can then work out this percentage change.

A: Look into the JavaScript Web Storage API. This allows you to locally store serialized data in a key-value-store for later access.
You could for example serialize the API response using JSON.stringify() and store it. In addition to that, store the date and time of the last request.
Now you can compare this timestamp to the current date and decide based on that whether you can reuse the data or if it is expired and you need to make an API call.


text:
Q: 'grunt' is not recognized as an internal or external command for some windows users Grunt is not working for all Windows users. Some users are facing some issues, when I run npm install command; it prints a message as below.
E:\Worksapce\web>npm install
npm WARN package.json registers@4.0.0 No repository field.

When I tried npm install -g grunt-cli, I think it is successful.
E:\Worksapce\web>npm install -g grunt-cli
npm http GET http://registry.npmjs.org/grunt-cli
npm http 304 http://registry.npmjs.org/grunt-cli
npm http GET http://registry.npmjs.org/nopt
npm http GET http://registry.npmjs.org/findup-sync
npm http GET http://registry.npmjs.org/resolve
npm http 304 http://registry.npmjs.org/nopt
npm http 304 http://registry.npmjs.org/resolve
npm http 304 http://registry.npmjs.org/findup-sync
npm http GET http://registry.npmjs.org/abbrev
npm http 304 http://registry.npmjs.org/abbrev
npm http GET http://registry.npmjs.org/glob
npm http GET http://registry.npmjs.org/lodash
npm http 304 http://registry.npmjs.org/glob
npm http 304 http://registry.npmjs.org/lodash
npm http GET http://registry.npmjs.org/inherits
npm http GET http://registry.npmjs.org/minimatch
npm http 304 http://registry.npmjs.org/minimatch
npm http 304 http://registry.npmjs.org/inherits
npm http GET http://registry.npmjs.org/lru-cache
npm http GET http://registry.npmjs.org/sigmund
npm http 304 http://registry.npmjs.org/lru-cache
npm http 304 http://registry.npmjs.org/sigmund
C:\Users\user1234\AppData\Roaming\npm\grunt -> C:\Users\user1234\AppData\Roaming
\npm\node_modules\grunt-cli\bin\grunt
grunt-cli@0.1.13 C:\Users\user1234\AppData\Roaming\npm\node_modules\grunt-cli
+-- resolve@0.3.1
+-- nopt@1.0.10 (abbrev@1.0.5)
+-- findup-sync@0.1.3 (lodash@2.4.1, glob@3.2.11)

But when I run grunt, I get an error message like this:
E:\Worksapce\web>
E:\Worksapce\web>grunt
'grunt' is not recognized as an internal or external command,
operable program or batch file.

My package.json is this.
{
  "author": "Company",
  "name": "registers",
  "version": "4.0.0",
  "homepage": "http://abcd.se",
  "dependencies": {},
  "devDependencies": {
    "grunt": "~0.4.4",
    "grunt-contrib-jshint": "~0.9.2",
    "grunt-contrib-watch": "~0.6.1",
    "grunt-contrib-less": "~0.11.0",
    "grunt-contrib-clean": "~0.5.0",
    "grunt-contrib-copy": "~0.5.0",
    "grunt-contrib-concat": "~0.3.0",
    "grunt-contrib-uglify": "~0.4.0",
    "grunt-ngmin": "0.0.3",
    "grunt-contrib-jasmine": "~0.5.2"
  }
}

Another user is succesfully able to execute grunt with out any issues. This only stands for some of the users.
Can some one tell me what has gone wrong.

A: Grunt is no longer installed globally. See the Getting Started page for more information.
The command below should help you fix this;
npm install -g grunt-cli

A: Grunt-CLI is installed inside %AppData%\npm, so the best directory to add to your %PATH% is:
%AppData%\npm

A: Your logs indicate that the grunt command was created in your global directory.  The errors also indicate that C:\Users\mc862634\AppData\Roaming\npm\ is not in your path.
You'll want to check your PATH and make sure that the \AppData\Roaming\npm location is added if it is missing.
The easiest way to check is to open a command prompt and type PATH.
See this other StackOverflow question as a reference: Grunt on Windows 8: 'grunt' is not recognized

A: npm install grunt -g (or) npm install -g grunt-cli
Please check your computer environmental variable path, it should contain the path of AppData. EX: E:\$APPDATA\npm\;
MyComputer->Right click-> Properties ->Advances System Setting-> Environment Variables -> Path

A: On Windows 8, Grunt needs to have the following added to the PATH:
C:\Users\your_username\AppData\Roaming\npm

On some systems, the number of characters allowable in the PATH is limited, and this can cause the correct path needed by grunt to not be added, even after npm install -g grunt-cli is run. Some settings (for example for certain programs you have installed) can be safely removed from the PATH, as they're generally there as a failsafe and often aren't required. If you have this issue:

*

*Backup the variables in your PATH (This PC > right-click > Properties > Advanced system settings > Environment Variables > 'Edit' the 'Path' user variables for the current user, and copy the 'Variable value' and save it somewhere)

*Remove some of the values from the PATH, and add in the path C:\Users\your_username\AppData\Roaming\npm
Also, make sure that after installing the Grunt CLI and adding the path, that you close any open command windows and re-open them before trying a Grunt

A: Incase that there some developer that used Windows XP, that have similar problem you'll need to change Path entry.
From:
C:\Users\change_username\AppData\Roaming\npm\grunt
To:
C:\Documents and Settings\change_username\Application Data\npm


text:
Q: CQL 3 Unable to Create Column Family With Randomized Name When shelled into my Cassandra instance via cqlsh, I am able to create a CF using
CREATE COLUMNFAMILY IF NOT EXISTS
  sandbox.foo
  ( created TIMESTAMP,
    updated TIMESTAMP,
    PRIMARY KEY (created) )  ;

but when I run
CREATE COLUMNFAMILY IF NOT EXISTS
  sandbox.6f4922f45568161a8
  ( created TIMESTAMP,
    updated TIMESTAMP,
    PRIMARY KEY (created) ) ;

The command fails w/ error SyntaxException: <ErrorMessage code=2000 [Syntax error in CQL query] message="line 3:2 no viable alternative at input '(' (... IF NOT EXISTS   sandbox.6f4922f45568161a8  [(]...)">.
Any idea where I'm going wrong?

A: Yes.  The CREATE TABLE documentation is pretty clear on this one:

Valid table names are strings of alphanumeric characters and underscores, which begin with a letter.

Try placing a (random?) letter at the beginning of your table name, and then it should work.


text:
Q: Pass same data to multiple view codeigniter Can you give me some pointers about load view in CI
$this->load->view('maindata', $data);
$this->load->view('footerdata', $data);

Is passing the same variable to multiple views is bad? Why?
That two view requires some of the same data

A: you can access $data variables like  title to maindata view and $footer_data to footerdata view .
$data['title'] = "Welcome";
$data['user_name'] = "John Doe";

$data['footer_text'] = "This is Footer";
$this->load->view('maindata', $data);

$this->load->view('footerdata', $data);

A: Use next syntax for such a requirement:
$this->load->vars($data);

$this->load->view('maindata');
$this->load->view('footerdata');

That way, $data array will be available to any loaded view. Docs.

A: In this context, it isn't bad to pass the same data. However, there could be better options, see my example below for one idea.
When I set up my sites, I try to make the header and footer as generic as possible and then I load them from within the view. So, my view code looks like this:
Controller:
public function page() {
    ...
    $this->load->view('main', $data);
}

View (main.php):
<?php $this->load->view('header'); ?>
<!-- HTML -->
<?php $this->load->view('footer'); ?>

With this method, all of the data passed to the main view is defined in each of the 'sub-views', the header and footer.


text:
Q: Recurrence Relation of Order 2. particular solution I am stuck on the following question:
$$g(n+2)+2g(n+1)+2g(n)=25n$$
Starting conditions: $$g(0)=0, g(1)=1$$
I have worked out the homogenous Solotion to be $$g(n)^h=C1 * (-1+i)^n+C2*(-1-i)^n$$
Because of $f(n)=25n$ i have tried the approach of $f{\check{}}(n)=An$
$$ A(n+2)+2A(n+1)+2An=25n$$
This simplifies to:
$$ A(5n+4)= 25n$$
How should I continue or what did I do wrong?

A: You should assume $f(n) = an + b$ You are running into trouble by forgetting that constant term.
Then
$$ a(5n + 4) + 5b = 25n $$
So: $4a + 5b = 0$ and $5a = 25$. So we get that $a = 5$ and $b = -4$


text:
Q: How can I get the response header error from JavaScript? Using Laravel -
abort(403, 'This is an exception message.');

How can I access this message from my JavaScript?
// Get the project based on projectID.
$.ajax({
    type: 'GET',
    url: '/api/projects/getProject/' + projectID
}).done(function(response){
    ProjectStore.getProjectSuccessful(response);
}).error(function(error){
    console.log(error)
});

My error object has a statusText property of 'Forbidden', and a responseText property that contains the entire HTML (in which I can see my error message) - but is there an easy way to access that message from my error object without parsing through the HTML?

A: I found that the abort() function takes a third argument - an array - and this gets sent up through the response header.
So - updated code in PHP:
$error = 'User not authorized to view project.';
abort(401, $error, array('errorText'=>$error));

In my JavaScript:
// Get the project based on projectID.
$.ajax({
    type: 'GET',
    url: '/api/projects/getProject/' + projectID
}).done(function(response){
    ProjectStore.getProjectSuccessful(response);
}).error(function(error){
    console.log(error.getResponseHeader('errorText'));
});


text:
Q: My Mastech MY-64 DMM shows incorrect voltage for specific selected option My Mastech MY-64 DMM suddenly started showing incorrect voltage on DC 20v option only. When I select dc 200 option it show correct value, even a aaa battery in 2v dc option show correct voltage.
Why is only 20v dc option showing incorrect reading, is there any way to fix this.
P.S. I changed the multimeter battery to a new one, didn't help.


text:
Q: Add and Retrieve array of custom datatype in mongodb using the C++ driver I have an array of custom datatype such as a class or a structure and would like to store it in mongodb as binary data.
How would I go about adding and retrieving that array from mongodb?
I need to do this via the C++ driver.
I was able to add and retrieve for simple arrays using appendbinData and getbinData but I can't find a way to do this for arrays of custom datatypes.


text:
Q: slidetoggle not removing when page size changes Hi all i have got my repsonsive menu working at mobile level.
when the website changes size the slideToggle does not get removed and I am not sure how to make this happen.
$(".click").click(function ()
$('#menu').slideToggle("veryslow"); });`

A: You're approaching this in the wrong way. You need to have 2 menus ideally, one for mobiles/tablets and another for desktop sites. Trigger the dropdown (like you have now) on mobiles with jQuery, but on desktops, hide the mobile navigation and show the normal desktop navigation.
What you have above is just constantly telling the menu to slide open/close. You aren't specifying at what point it needs to do something else. Responsive is 99% CSS 3 and 1% jQuery to do the slide open and close.
I hope this helps!


text:
Q: Response.Redirect error on mobile devices On my main login screen, i am checking to see if the browser is a mobile browser.  If the browser is a mobile browser i redirect the user to the mobile website login screen.  This works fine on my Android device but not on my Iphone.  I went and tried putting in Response.End() after my redirects but that caused my Android device to start getting the error message.  The message i am getting on both devices is that there are to many server redirects.  Any Hints?
Edit:
if (Request.Headers["User-Agent"] != null && (Request.Browser["IsMobileDevice"] == "true"
            || Request.UserAgent.ToUpper().Contains("MIDP") || Request.UserAgent.ToUpper().Contains("CLDC")
            || Request.UserAgent.ToLower().Contains("iphone") || Request.UserAgent.ToLower().Contains("avant")
            || Request.UserAgent.ToLower().Contains("nokia") || Request.UserAgent.ToLower().Contains("pda")
            || Request.UserAgent.ToLower().Contains("moto") || Request.UserAgent.ToLower().Contains("windows ce")
            || Request.UserAgent.ToLower().Contains("hand") || Request.UserAgent.ToLower().Contains("mobi")
            || Request.UserAgent.ToUpper().Contains("HTC") || Request.UserAgent.ToLower().Contains("sony")
            || Request.UserAgent.ToLower().Contains("panasonic") || Request.UserAgent.ToLower().Contains("blackberry")
            || Request.UserAgent.ToLower().Contains("240x320") || Request.UserAgent.ToLower().Contains("voda"))
            || Request.UserAgent.ToLower().Contains("android") || Request.UserAgent.ToLower().Contains("ipad"))
        {
            Response.Redirect("~/Mobile/Login.aspx");
        }

A: Check event viewer logs on the server.  Might also want to try doing Response.Redirect(urlString, false);
Response.Redirect(urlString); does a Response.End() inside and can cause issues with threads aborting.  This is expected and not a big deal but it will throw as an exception.


text:
Q: Losing screen object auto-focus I have a GridView displaying buttons to different screens of my app.  When this grid screen, the first cell is selected.  Is there a way to programmatically have no cells selected when the screen launches?  Or do I have to hide the selector?

A:
When this grid screen, the first cell is selected.

That should only be true if the user was using the navigator (D-pad, trackball, etc.) in the previous activity.

Is there a way to programmatically have no cells selected when the screen launches?

Generally, the user determines this based on whether they are in touch mode or not. You could try setSelection(-1) or something, but I would not be surprised if this fails to work.

Or do I have to hide the selector?

I would recommend just following the platform conventions. If the user is using the D-pad or trackball, they probably want to use the D-pad or trackball, and disabling the selector will simply make them frustrated with you and your app. Please see the article I linked to above for more details on touch mode and why it works the way it does.


text:
Q: How to Speed up my PC? Hello Everyone
How can I speed up my Asus X555LA Laptop while developing apps from Next JS and VS code . So while developing such React and Next JS apps my laptop hangs a lot. My Laptop's configurations are:

Ram : 4gb

CPU : Intel® Core™ i3-4030U CPU @ 1.90GHz × 4

Graphics : Intel® HD Graphics 4400 (HSW GT2)

Disk Space: 500gb

OS Name: Ubuntu 20.04 LTS

OS Type: 64 bit

Gnome Version : 3.36.8

Windowing System : x11

I Tried Updating my Ram but I dont get 8gb ram due to the lockdown. so upgradation of my hardware will not be possible right now.
Thankyou in Advance


text:
Q: configure: error: "could not find the zlib libaray." in Bash I am trying to install a program "bfast" on my linux system but i am getting following errors:
OS= CentOS
Package libdv-devel-1.0.0-17.el7.x86_64 already installed and latest version
Package glibc-devel-2.17-106.el7_2.1.i686 already installed and latest version
Bfast:
http://sourceforge.net/projects/bfast/files/latest/download
sh autogen.sh
./configure
**fatal: Not a git repository (or any of the parent directories): .git**
checking bzlib.h usability... yes
checking bzlib.h presence... yes
checking for bzlib.h... yes
**checking for special C compiler options needed for large files... no**
**checking for _FILE_OFFSET_BITS value needed for large files... no**
checking for an ANSI C-conforming const... yes
checking for stdlib.h... (cached) yes
checking for GNU libc compatible malloc... no
checking for stdlib.h... (cached) yes
**checking for GNU libc compatible realloc... no
checking for pow in -lm... no
checking for gzread in -lz... no
configure: error: "could not find the zlib libaray."**

However, I already installed prerequisite packages for this.
whereis zlib
**zlib: /usr/include/zlib.h** /usr/share/man/man3/zlib.3.g

whereis bzip2
**bzip2: /usr/bin/bzip2** /usr/share/man/man1/bzip2.1.gz

A: You need to install the development packages, usually called foo-devel or similar. Or you might be trying to build for the wrong architecture.


text:
Q: Materialize collapsible not expanding right It works fine if the html is already present but when I add the html dynamically it doesn't work at all. I tried initializing it $('.collapsible').collapsible(); and it expands sometimes but not always.
  $(document).on('click', '.controls .add-step', function(e) {
    var addto = $(this).next().find(".collapsible");
    var newIn = '

add

This is text

';
    var newInput = $(newIn);
    $(addto).append(newInput);
    $('.collapsible').collapsible();
  });

https://jsfiddle.net/ykpLne4o/

A: What you are experiencing is that it is constantly clicking on the addaction and it also triggers your collapse method. Try separating your icons into a div, that are not part of the header maybe?


text:
Q: Julia: Use an older version of a package I am really new to Julia and confused about using an old version of the SISL Vec package.
I am trying to setup ngsim_env and their instructions require you to use an older v0.1.0 of Vec. But, when I followed the instructions to install the Vec package and then checkout the v0.1.0 tag it didn't work.
Here's what I did

*

*$ julia ../build.jl for some package which includes this block
packages = keys(Pkg.installed())
if !in("Vec", packages)
    Pkg.clone("https://github.com/tawheeler/Vec.jl.git")
end
Note: This git URL actually goes to the SISL Vec page.

*cd ~/.julia/packages/Vec
git fetch tags
git checkout v0.1.0

*I did a bunch of other installations with many other packages. At some point I noticed that there is a package ~/.julia/dev/Vec and ~/.julia/packages/Vec. The one in dev has the correct v0.1.0 code and the one in packages has the newer wrong code. When I tried to use other packages that needed the older Vec they were throwing errors and the paths were to files in the packages directory.

*I tried Pkg.rm("Vec"). This did something to the project manifest. After nothing worked, every package would throw errors like KeyError: key "Vec" not found and Pkg.add("Vec") nor original Vec installation helped. I even tried removing both the Vec directories from ~/.julia but that didn't help.
I guess a big question is why does Julia put some packages into packages/ and others into dev/ and how to control which one's get used if the same package appears in both places like Vec is.
Would greatly appreciate any assistance, totally confused.

A:
The dev command fetches a full clone of the package to ~/.julia/dev/

via the docs. The only things I have in my dev directory there are the ones I am developing on my own.
I think that triggered when you did a check out manually with git checkout.
Accordingly:

to stop tracking a path and use the registered version again, use free

Try deleting the packages, and whipping mentions of Vec.jl from your manifest:
(v1.0) pkg> rm Vec
(v1.0) pkg> add https://github.com/tawheeler/Vec.jl.git@0.1.0

In general, try using Pkg when possible, cause it does a lot of house keeping magic in the back
(Also, the repl interface with pkg makes everything easier, so hit ] from a blank julia> to get there. And a quick Pkg.status() or ] st will show you what youre tracking and whats in dev and what version you have pinned, etc.)


text:
Q: Kafka Avro Serializer and deserializer exception. Avro supported types I am seeing following error
exception Unsupported Avro type. Supported types are null, Boolean, Integer, Long, Float, Double, String, byte[] and IndexedRecord

my kafka producer props are
Properties props = new Properties();
    props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KafkaConstants.BOOTSTRAP_SERVERS);
    props.put(ProducerConfig.BATCH_SIZE_CONFIG, 1000);
    props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
    props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class.getName());
    props.put("schema.registry.url", "http://localhost:8081");
    props.put("value.converter.schema.registry.url", "http://localhost:8081");
    props.put("producer.type", "sync");
    props.put(ProducerConfig.CLIENT_ID_CONFIG, KafkaConstants.CLIENT_ID);

    Producer<String, TweetInfoDto> producer = new KafkaProducer(props);

and my kafka consumer props are
Properties props = new Properties();
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KafkaConstants.BOOTSTRAP_SERVERS);
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, KafkaAvroDeserializer.class.getName());
    props.put(ConsumerConfig.GROUP_ID_CONFIG, "twitterCrawler");
    props.put(ConsumerConfig.CLIENT_ID_CONFIG, KafkaConstants.CLIENT_ID);
    props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
    props.put("schema.registry.url", "http://localhost:8081");
    props.put("value.converter.schema.registry.url", "http://localhost:8081");

    Consumer<String, TweetInfoDto> consumer = new KafkaConsumer(props);

not sure what am I doing wrong.

A: TweetInfoDto cannot be a plain Java object that you have defined yourself.
It ideally should be created from an Avro schema via the Avro Maven Plugin, for example.
Please refer to the Schema Registry Tutorial for all the steps including defining an AVSC, and generating a Java class for it.
Tutorial sample code here

A: Adding on to what cricket_007 has mentioned, could consider using
avro tools - Serializing and deserializing with code generation


text:
Q: Extracting words of a vector with names This is my vector:
m.v<- c("Aert~Derr", "Aert~Derr", "Aert~Derr", "Aert~Derr",
    "Aert~Derr", "Aert~Derr", "Aert~Derr", "Aert~Derr", "Aert~Derr")

How can I create another vector with only the first name before the ~?
So, how can I extract the first names?

A: Here you have some other alternatives:
> gsub("~.*$", "", m.v)
[1] "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert"

> library(stringr)
> str_extract(m.v, "^\\w+")
[1] "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert"

A: There are many ways of doing this. Here is a base R option using sub
sub("~\\w+", "", m.v)
[1] "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert"

or using strsplit
sapply(strsplit(m.v, "~"), "[[", 1)
[1] "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert"

A: Here's another example that will even work if you have more than one letter before the ~:
gsub('(.*)~.*', '\\1', m.v)

A: We can use word function from stringr and mention the separator explicitly.
library(stringr)
word(m.v, sep = "~")
#[1] "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert" "Aert"


text:
Q: why contend show multiple time in angular while using ajax call? I have two problem in my demo .I am making a pop over .I should open on icon click(here is used star icon).when i click star icon I am able to see pop up screen as I want but problem is that when I click another icon /star icon it open another pop over without closing the first one pop over.I need to display pop over one at time..

*

*1 ) can we show pop over one at one time .it show only one pop over
at one time.
2)when I include in my plunker (tooltip.js and pop over plugin).It show the contend on mouseover event .but when i remove this it show on click event why ?
Here is plunker with scripts  tooltip and popover .display on click ?
http://plnkr.co/edit/OYiawflIBnpJ1PKx02LG?p=preview
here is the plunker with these plugin display on mouser over event why ?
http://plnkr.co/edit/OYiawflIBnpJ1PKx02LG?p=preview
 <script src="https://dl.dropboxusercontent.com/s/a98aey2mlu0h511/bootstrap-tooltip.js"></script>
 <script src=" https://dl.dropboxusercontent.com/s/s1imyubboz1qjtl/bootstrap-popover.js?m="></script>

A: Well if you are still working on the problem, following is the solution. Though I am not sure if this is the best way to do it as I'm starting with AngularJS.
var getTemplate = function(contentType, scope, element) {

    var template = $templateCache.get("templateId.html");

    $.ajax({
        type: "GET",
        url: 'pop.html',
        dataType: 'html',
        success: function(data) {
          var options = {
            content: data,
            placement: "right",
            html: true,
            date: scope.date,
        };
    $(element).popover(options);

    //FIND ALL POPOVERS AND HIDE THEM EXCEPT CURRENT ONE//
    $(element).on("show.bs.popover",function(t,e){
      $("span[mypopover]").not(this).popover('hide');
    });

  },
  error: function(data) {
    alert(data);
  }
    });

    return template;
};

Following are the lines:
$(element).on("show.bs.popover",function(t,e){
    $("span[mypopover]").not(this).popover('hide');
});

Plunker:http://plnkr.co/edit/WM0K8sdPVHSNeuIlLBim


text:
Q: Is the hasOwnProperty method in JavaScript case sensitive? Is hasOwnProperty() method case-sensitive? Is there any other alternative case-insensitive version of hasOwnProperty?

A: Yes, it's case sensitive, because JavaScript is case sensitive.
There is no alternative built-into the language, but you could roll your own:
function hasOwnPropertyCaseInsensitive(obj, property) {
    var props = [];
    for (var i in obj) if (obj.hasOwnProperty(i)) props.push(i);
    var prop;
    while (prop = props.pop()) if (prop.toLowerCase() === property.toLowerCase()) return true;
    return false;
}

A: Old question is old; but still entirely relevant. I searched for a quick answer to this question as well, and ended up figuring out a good solution before I read this, so I thought I'd share it.
Object.defineProperty(Object, 'hasOwnPropertyCI', {
    enumerable: false,
    value: (keyName) => (
        Object.keys(this).findIndex(
            v => v.toUpperCase() === keyName.toUpperCase()
        ) > -1
    }
});

This resolves to true when keyName exists in the object it's called on:
var MyObject = { "foo": "bar" };
MyObject.hasOwnPropertyCI("foo");

Hope that helps someone else! :D
PS: Personally, my implementation slaps the conditional above into an IF statement, since I won't be using it anywhere else in my application (in addition to the fact that I'm not a huge fan of manipulating native prototypes).

A: Yes, it's case sensitive (so obj.hasOwnProperty('x') !== obj.hasOwnProperty('X')) You could extend the Object prototype (some people call that monkey patching):
Object.prototype.hasOwnPropertyCI = function(prop) {
      return ( function(t) {
         var ret = [];
         for (var l in t){
             if (t.hasOwnProperty(l)){
                 ret.push(l.toLowerCase());
             }
         }
         return ret;
     } )(this)
     .indexOf(prop.toLowerCase()) > -1;
}

More functional:
Object.prototype.hasOwnPropertyCI = function(prop) {
   return Object.keys(this)
          .filter(function (v) {
             return v.toLowerCase() === prop.toLowerCase();
           }).length > 0;
};


text:
Q: R remove tags starting with U How do I remove tags like  <U+0924><U+0930><U+0938><U+0902><U+0917><U+0924>
present in sentences.
Via- <U+0924><U+0930><U+094D><U+0915><U+0938><U+0902><U+0917><U+0924> - Tarksangat ~<U+0938><U+092F><U+094D><U+092F><U+0926> <U+092E><U+0902><U+095B><U+0930> <U+0907><U+092E><U+093E><U+092E>
I need output: Via- Tarksangat
Can anyone help me? Thanks!

A: Hope this might be useful
ab <- unlist(strsplit(abc,"[[:punct:]]"))
ab <- gsub("[[:punct:]]|[0-9]","",ab)

ab <- paste0(ab[nchar(ab)>2],collapse="-")
[1] "Via- Tarksangat "

data
abc <- "Via- <U+0924><U+0930><U+094D><U+0915><U+0938><U+0902><U+0917><U+0924> - Tarksangat ~<U+0938><U+092F><U+094D><U+092F><U+0926> <U+092E><U+0902><U+095B><U+0930> <U+0907><U+092E><U+093E><U+092E>"

A: Try this
<U.*?>

and replace by empty string
Explnation
You can try this:
re = /<U.*?>/
str = 'asdfasdf <U+0924><U+0930><U+0938><U+0902><U+0917> tsdfasf <U+0924> 1sadfasdf a2sdf 3sdafasdf <U+0924><U+0930>5<U+0938> 4asdfasdf <U+0902><U+0917><U+0924>'
subst = ''

result = str.gsub(re, subst)

# Print the result of the substitution
puts result


text:
Q: SwiftUI: Change navigation bar title in the more tab? I am begining to get my haead around swiftUI. So I have a simple tabView inside a Navigation View as below.
import SwiftUI

struct BasicView: View {
    var climbList: [ClimbDetail]
    var body: some View {
        NavigationView{
           VStack{
            Text("").navigationBarTitle("Climbers Log", displayMode:.inline)
                TabView {
                    Text("Search").tabItem{
                        Image(systemName:"magnifyingglass")
                        Text("Search")
                    }
                    Text("Stats").tabItem{
                        Image(systemName:"list.dash")
                        Text("Stats")
                    }
                    ClimbList(climbs: climbList).tabItem{
                        Image(systemName: "square")
                        Text("Climbs")
                    }
                    Text("Log").tabItem{
                        Image(systemName:"square.and.pencil")
                        Text("Log")
                    }

                    Text("Profile").tabItem{
                        Image(systemName:"person.circle")
                        Text("Profile")
                    }
                    Text("Settings").tabItem{
                        Image(systemName:"gear")
                        Text("Settings")
                    }
                    Text("Add Climb").tabItem{
                        Image(systemName:"plus")
                        Text("Add Climb")
                    }
                }
            }
        }
    }
}

Genrally it works as expected, however as I have 7 tabs it defults to the 'More' tab for the 5th tab. This is fine and good for the user.
However my issue is when you click the 'More' tab you get the a title bar and edit button with 'More' as the title. Which appears below the title bar I have set above.

So  my question is how can I hide my titleBar when the user is on the 'More' tab and only show it inside the other tabs?

A: First off all, thanks for the question. I didn't know Apple provides More page by default for too long TabBars. I always needed that.
Back to you question, you just need to rearrange things. First off all, make the TabBar top level. Then a NavigationView and here comes your content. Later on you might outsource every view, to an own file.
TabView {

    NavigationView
    {
        VStack
        {
            Text("Search")
        }
        .navigationBarTitle("Climbers Log", displayMode:.inline)
    }.tabItem {
        Image(systemName:"magnifyingglass")
        Text("Search")
    }

Every view takes it own NavigationView.. and then it works.


text:
Q: Can you construct a simple bipartite graph G, that has $\kappa (G) < \lambda(G) < \delta(G)$? Is it possible to construct a simple bipartite graph G, that has $\kappa (G) < \lambda(G) < \delta(G)$ ?
Where $\kappa (G) $ is vertex connectivity, $\lambda (G)$ is edge connectivity.
I can find examples where $ \kappa (G) \le \lambda (G) \le \delta(G)$ holds, like $K_1,_2$
But I am struggling to find a example where the strict inequality holds but it doesn't feel impossible

A: HINT: Let $G_1$ and $G_2$ be disjoint copies of $K_{3,3}$. Let $v$ be a new vertex not in $G_1$ or $G_2$. Connect $v$ to two vertices of $G_1$ and to two vertices of $G_2$ to form $G$.


text:
Q: Missing Something Sending Prop In Link In React What I'm Attempting To Do:
Have a list created from an API that lists several teams, each linked to a new team page via their team ID. Example:
Homepage:   Localhost:3000/
Lists several options:
Search By Team
Search By Player

click on Search By Team, listing each team   Localhost:3000/teams
Gladiators
Maniacs

Click on Maniacs   localhost:3000/Maniacs
So far when I click on each team, it takes me to the 404 page.
What I Have Now:
App.js
        <Route path="/teams" component={Teams} exact></Route>
        <Route exact path='/:teamName' component={EachTeam} />

Standings.js
import Atlantic from "../components/divisions/Atlantic"
function Standings() {
return (

        <Atlantic />

)
}
   export default NHLStandings

Altantic.js
import { Link } from 'react-router-dom';
import { useState, useEffect } from 'react';
function Atlantic() {
const [teams, setTeams] = useState(null);
useEffect(() => {
    getData();

async function getData() {
    const response = await fetch("RANDOM_API);
    const data = await response.json();
    setTeams(data) ;
    }
}, []);

return (

        {teams && (

Atlantic Division

            {teams['teams'].map((team, index) => (
                (team.division.name === "Atlantic" && (
                    <Link
                        to={`/${team.teamName}`}
                        teamName={team.teamName}
                        key={index}
                        className="team-container"
                    >

{team.name}

                    </Link>
                ))
            ))}

    )}

)
}

export default Atlantic
EachTeam.js
import { Link } from 'react-router-dom';
import { useState, useEffect, useSelector } from 'react';

function EachTeam(props) {

 return (

{props.teamName}

)
}
export default EachTeam

Apologies for the length, I did not want to omit anything. Thanks in advance for any help.

A: teamName isn't a valid prop on either the Link component or the Route component. The extraneous props are ignored. I suspect you are navigating correctly and just seeing props.teamName as undefined.
{teams['teams'].map((team, index) => (
  (team.division.name === "Atlantic" && (
    <Link
      to={`/${team.teamName}`}
      teamName={team.teamName} // <-- ignored, not a Link prop
      key={index}
      className="team-container"
    >

{team.name}

    </Link>
  ))
))}

To resolve you can access the route match params to get the teamName. In function components use the useParams React hook.
Given:
<Route exact path='/:teamName' component={EachTeam} />

EachTeam
import { useParams } from 'react-router-dom';

function EachTeam(props) {
  const { teamname } = useParams();

  return (

{teamName}

  )
}


text:
Q: first two case working in switch statement why last case is not worked? I am making dictionary website, for the proper word search within the API, I used there one switch statement (3rd case) which is not working , remaining cases running properly but 3rd case only given loader not output please give me proper solution.

// get element
const input = document.querySelector('#input');
const searchBtn = document.getElementById('button-addon2');
const loader = document.getElementById('loader');
const iword = document.querySelector('.iword');
const word = document.querySelector('.word');
const mean = document.querySelector('.meaning');
const audio = document.querySelector('audio');
// Event listner for search button
searchBtn.addEventListener('click', getData);

function getData(e) {
   e.preventDefault();
   iword.textContent = '';
   word.textContent = '';
   mean.textContent = '';

//    get input data
   let inputWord = input.value;

//    call api get data
   if (inputWord === '') {
       alert ('Word is Required')
       return;
   }
   getApiData(inputWord);
}

// get data from api
async function getApiData(inputWord) {
    loader.style.display = 'block';
    const apiKey = `https://www.dictionaryapi.com/api/v3/references/learners/json/${inputWord}?key=a6d01f54-9cfd-4941-957b-55935e9f4c5d`;

    try {
        let response = await fetch(apiKey);
        let data = await response.json();

switch (true) {
    case (!data.length) :
        loader.style.display = 'none';
         iword.textContent = inputWord;
         word.textContent = 'No Result Found';
        break;

        case (typeof data[0] === 'string') :
            loader.style.display = 'none';
           iword.textContent = inputWord;
            let sHeading = document.createElement('h3');
            sHeading.textContent = 'Did You Mean ?'
            mean.appendChild(sHeading);
            data.forEach(element => {
              let suggetion = document.createElement('span');
              suggetion.classList.add('suggested');
              suggetion.textContent = element;
              mean.appendChild(suggetion);
            });
            break ;

            case data[0].shortdef[0] :
                loader.style.display = 'none';
                iword.textContent = inputWord;
                word.textContent = meaning;
                console.log('hey');
                break ;
}}

 catch (error) {
    // catch error here
}
}