text:
Q: Cannot Get Apollo addItem Mutation to work on the client keep getting 400 error All I want to do is add an item to the items array in my Cart object.

What I am trying to do is simply execute my backend addItem mutation. After that I want to manually update the cache, but for now I am just re-fetching the query because I am unable to even successfully get the query to run.

In this code I am using the pothos withinput plugin: link to docs
I have tried:

*

*Just putting the hardcoded input object into the addItem hook

*Listing each Variable out one by one into the addItem hook

*Describing the types of each prop in the original gql MUTATION

*And passing the hardcoded input into the addItem hook via variables object

*Passing hardcoded values into the actual addItem mutation

*I have tried inputting the proper typing via a gql tag example below:

    const THE_TYPE = gql`input addItemInput {
  cartId: String!
  id: String!
  name: String!
  price: Float!
}
`

    const MUTATION = gql`
mutation AddItem($input: ${THE_TYPE}!) {
  addItem(input: $input){carts{
id
items{
name
}}}
`;

*When I run the following mutation in my graphiql interface it works:
mutation MyMutation{
addItem(input:{
  cartId: "2",
  id: "12",
  name: "New Item!",
  price: 1900,
}){
  items{
    name
  }
}}

However when I run the mutation below I get a 400 error:
Error: Response not successful: Received status code 400
import { useQuery, gql, useMutation } from '@apollo/client';

export default function DisplayCarts() {

    interface Cart {
        id: string;
        items: string[];
    }

    interface Items {

    }

    const GET_CARTS = gql`
query {
carts{
id
items{
name
}}} `;

    const MUTATION = gql`
mutation AddItem($input: Any) {
addItem(input: $input){
carts{
id
items{
name
}}
}}`;

    const { loading, error, data } = useQuery(GET_CARTS)

    const [addItem] = useMutation(MUTATION, {

        refetchQueries: [{ query: GET_CARTS }]

        // update(cache, { data: { addItem } }) {
        // addItem is the response of the query of add item function
        // console.log(data);
        // @ts-ignore
        //     const { carts } = cache.readQuery({ query: GET_CARTS });

        //     cache.writeQuery({
        //         query: GET_CARTS,
        //         data: { carts: [...carts, addItem] }
        //     })
        // }
    })

    function AddTodo() {
        let theInput = {
            cartId: "2",
            id: "12",
            name: "New Item!",
            price: 1900,
            quantity: 2
        }
        // @ts-ignore
        addItem({ variables: { input: theInput } });
    };

Here is my backend resolver function using pothos
Keep in mind my query does work in my graphiql interface so the issue is probably not on the backend
builder.mutationType({
    fields: (t) => ({
        addItem: t.fieldWithInput({
            input: {
                cartId: t.input.string({ required: true }),
                id: t.input.string({ required: true }),
                name: t.input.string({ required: true }),
                price: t.input.int({ required: true }),
                quantity: t.input.int({ required: true, defaultValue: 1 }),
            },
            type: Cart,
            resolve: (_, { input: { cartId, ...input } }) => {
                const cart = CARTS.find((cart) => cart.id === cartId);

                if (!cart) {
                    throw new Error(`Cart with id ${cartId} not found`)
                }

                return {
                    id: cartId,
                    items: [...cart?.items, input]
                }
            }
        }),
    }),
})

A: The problem lies with:
mutation AddItem($input: Any) {
  addItem(input: $input){…}

There is no Any in GraphQL. The 400 is a result of an invalid query/mutation. Note that you're not actually running the same mutation that you are in GraphiQL.
Try using an input type for example in your typeDefs (on the server), add:
input addItemInput {
  cartId: String!
  id: String!
  name: String!
  price: Float!
}

Then in your client code:
const MUTATION = gql`
  mutation AddItem($input: addItemInput) {
    addItem(input: $input){…}
  }
`

A: Firstly some necessary information:

When using pothos with input plugin it formulates the query type for you following the following rule: ${ParentType.name}${Field.name}Input. I hoghly recomend you follow the link and look at the docs yourself so you can understand exactly how your query should look.

Here is the link to the corresponding docs
The correct query:
    const MUTATION = gql`
  mutation AddItem($input:MutationAddItemInput!) {
    addItem(input: $input){
            items{
                name
            }
        }
    }
`;

*

*If you get a 400 error it is probably your query is just wrong

*If you get a weird error with  in it check your brackets you might be missing one or two


text:
Q: Best practices for object oriented patterns with strict aliasing and strict alignment in C I've been writing embedded C code for many years now, and the newer generations of compilers and optimizations have certainly gotten a lot better with respect to their ability to warn about questionable code.
However, there is at least one (very common, in my experience) use-case that continues to cause grief, wheres a common base type is shared between multiple structs.  Consider this contrived example:
#include <stdio.h>

struct Base
{
    unsigned short t; /* identifies the actual structure type */
};

struct Derived1
{
    struct Base b; /* identified by t=1 */
    int i;
};

struct Derived2
{
    struct Base b; /* identified by t=2 */
    double d;
};

struct Derived1 s1 = { .b = { .t = 1 }, .i = 42 };
struct Derived2 s2 = { .b = { .t = 2 }, .d = 42.0 };

void print_val(struct Base *bp)
{
    switch(bp->t)
    {
    case 1:
    {
        struct Derived1 *dp = (struct Derived1 *)bp;
        printf("Derived1 value=%d\n", dp->i);
        break;
    }
    case 2:
    {
        struct Derived2 *dp = (struct Derived2 *)bp;
        printf("Derived2 value=%.1lf\n", dp->d);
        break;
    }
    }
}

int main(int argc, char *argv[])
{
    struct Base *bp1, *bp2;

    bp1 = (struct Base*) &s1;
    bp2 = (struct Base*) &s2;

    print_val(bp1);
    print_val(bp2);

    return 0;
}

Per ISO/IEC9899, the casts within code above should be OK, as it relies on the first member of the structure sharing the same address as the containing structure.  Clause 6.7.2.1-13 says so:
Within a structure object, the non-bit-field members and the units in which bit-fields
reside have addresses that increase in the order in which they are declared. A pointer to a
structure object, suitably converted, points to its initial member (or if that member is a
bit-field, then to the unit in which it resides), and vice versa. There may be unnamed
padding within a structure object, but not at its beginning.

The casts from derived to base work fine, but the cast back to the derived type within print_val() generates an alignment warning.  However this is known to be safe as it is specifically the "vice versa" part of the clause above.  The problem is that the compiler simply doesn't know that the we've already guaranteed that the structure is in fact an instance of the other type via other means.
When compiled with gcc version 9.3.0 (Ubuntu 20.04) using flags -std=c99 -pedantic -fstrict-aliasing -Wstrict-aliasing -Wcast-align=strict -O3 I get:
alignment-1.c: In function 'print_val':
alignment-1.c:30:31: warning: cast increases required alignment of target type [-Wcast-align]
   30 |         struct Derived1 *dp = (struct Derived1 *)bp;
      |                               ^
alignment-1.c:36:31: warning: cast increases required alignment of target type [-Wcast-align]
   36 |         struct Derived2 *dp = (struct Derived2 *)bp;
      |                               ^

A similar warning occurs in clang 10.
Rework 1: pointer to pointer
A method used in some circumstances to avoid the alignment warning (when the pointer is known to be aligned, as is the case here) is to use an intermediate pointer-to-pointer.  For instance:
struct Derived1 *dp = *((struct Derived1 **)&bp);
However this just trades the alignment warning for a strict aliasing warning, at least on gcc:
alignment-1a.c: In function 'print_val':
alignment-1a.c:30:33: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
   30 |         struct Derived1 *dp = *((struct Derived1 **)&bp);
      |                                ~^~~~~~~~~~~~~~~~~~~~~~~~

Same is true if cast done as an lvalue, that is: *((struct Base **)&dp) = bp; also warns in gcc.
Notably, only gcc complains about this one - clang 10 seems to accept this either way without warning, but I'm not sure if that's intentional or not.
Rework 2: union of structures
Another way to rework this code is using a union.  So the print_val() function can be rewritten something like:
void print_val(struct Base *bp)
{
    union Ptr
    {
        struct Base b;
        struct Derived1 d1;
        struct Derived2 d2;
    } *u;

    u = (union Ptr *)bp;
...

The various structures can be accessed using the union.  While this works fine, the cast to a union is still flagged as violating alignment rules, just like the original example.
alignment-2.c:33:9: warning: cast from 'struct Base *' to 'union Ptr *' increases required alignment from 2 to 8 [-Wcast-align]
    u = (union Ptr *)bp;
        ^~~~~~~~~~~~~~~
1 warning generated.

Rework 3: union of pointers
Rewriting the function as follows compiles cleanly in both gcc and clang:
void print_val(struct Base *bp)
{
    union Ptr
    {
        struct Base *bp;
        struct Derived1 *d1p;
        struct Derived2 *d2p;
    } u;

    u.bp = bp;

    switch(u.bp->t)
    {
    case 1:
    {
        printf("Derived1 value=%d\n", u.d1p->i);
        break;
    }
    case 2:
    {
        printf("Derived2 value=%.1lf\n", u.d2p->d);
        break;
    }
    }
}

There seems to be conflicting information out there as to whether this is truly valid.  In particular, an older aliasing write-up at https://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html specifically calls out a similar construct as being invalid (see Casting through a union (3) in that link).
In my understanding, because pointer members of the union all share a common base type, this doesn't actually violate any aliasing rules, because all accesses to struct Base will in fact be done via an object of type struct Base - whether by dereferencing the bp union member or by accessing the b member object of the d1p or d2p.  Either way it is accessing the member correctly via an object of type struct Base - so as far as I can tell, there is no alias.
Specific Questions:

*

*Is the union-of-pointers suggested in rework 3 a portable, safe, standards compliant, acceptable method of doing this?

*If not, is there a method that is fully portable and standards compliant, and does not rely on any platform-defined/compiler-specific behavior or options?

It seems to me that since this pattern is fairly common in C code (in the absence of true OO constructs like in C++) that it should be more straightforward to do this in a portable way without getting warnings in one form or another.
Thanks in advance!
Update:
Using an intermediate void* may be the "right" way to do this:
struct Derived1 *dp = (void*)bp;

This certainly works but it really allows any conversion at all, regardless of type compatibility (I suppose the weaker type system of C is fundamentally to blame for this, what I really want is an approximation of C++ and the static_cast<> operator)
However, my fundamental question (misunderstanding?) about strict aliasing rules remains:
Why does using a union type and/or pointer-to-pointer violate strict aliasing rules?  In other words what is fundamentally different between what is done in main (taking address of b member) and what is done in print_val() other than the direction of the conversion?  Both yield the same situation - two pointers that point to the same memory, which are different struct types - a struct Base* and a struct Derived1*.
It would seem to me that if this were violating strict aliasing rules in any way, the introduction of an intermediate void* cast would not change the fundamental problem.

A: You can avoid the compiler warning by casting to void * first:
struct Derived1 *dp = (struct Derived1 *) (void *) bp;

(After the cast to void *, the conversion to struct Derived1 * is automatic in the above declaration, so you could remove the cast.)
The methods of using a pointer-to-a-pointer or a union to reinterpret a pointer are not correct; they violate the aliasing rule, as a struct Derived1 * and a struct Base * are not suitable types for aliasing each other. Do not use those methods.
(Due to C 2018 6.2.6.1 28, which says "… All pointers to structure types shall have the same representation and alignment requirements as each other…," an argument can be made that reinterpreting one pointer-to-a-structure as another through a union is supported by the C standard. Footnote 49 says "The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions." At best, however, this is a kludge in the C standard and should be avoided when possible.)

Why does using a union type and/or pointer-to-pointer violate strict aliasing rules?  In other words what is fundamentally different between what is done in main (taking address of b member) and what is done in print_val() other than the direction of the conversion?  Both yield the same situation - two pointers that point to the same memory, which are different struct types - a struct Base* and a struct Derived1*.
It would seem to me that if this were violating strict aliasing rules in any way, the introduction of an intermediate void* cast would not change the fundamental problem.

The strict aliasing violation occurs in aliasing the pointer, not in aliasing the structure.
If you have a struct Derived1 *dp or a struct Base *bp and you use it to access a place in memory where there actually is a struct Derived1 or, respectively, a struct Base, then there is no aliasing violation because you are accessing an object through an lvalue of its type, which is allowed by the aliasing rule.
However, this question suggested aliasing a pointer. In *((struct Derived1 **)&bp);, &bp is the location where there is a struct Base *. This address of a struct Base * is converted to the address of a struct Derived1 **, and then * forms an lvalue of type struct Derived1 *. The expression is then used to access a struct Base * using a type of struct Derived1 *. There is no match for that in the aliasing rule; none of the types it lists for accessing a struct Base * are a struct Derived1 *.

A: Linux kernel offers an interesting alternative to described concepts.
It's based on idea of embedding.
struct Base {
  int x;
};

struct Derived {
  struct Base base; // base is embedded into Derived
  int y;
};

Transformation from a pointer to derived is easy:
struct Derived derived;
struct Base* base = &derived.base;

The reverse transformation is done using container_of macro.
This macro is bit tricky but it can be simplified subtracting offset of base member within Derived from the pointer to Base.
(struct Derived *)(void*)((char*)base - offsetof(struct Derived, base))

Casting to char* is essential because:

*

*allow pointer arithmetic with result of offsetof()

*as char* can alias with everything, the code is correct with strict aliasing rules

*casting through void* is used to silence -Wcast-align=strict as resulting object will be correctly aligned

Examplary usage:
struct Derived* derived = container_of(base, struct Derived, base);

This approach is attractive because:

*

*the pointer operation is a simple subtraction, no need do dereference any pointer, no extra cache miss

*the base class can be located anywhere within the derived structure

*easy support for multiple inheritance

*structure layout can be modified without breaking existing code

With a help of function pointers, the polymorphism can be robustly implemented.
#include <stdio.h>
#include <stddef.h>

#define container_of(ptr, type, member) \
  (type*)(void*)((char*)ptr - offsetof(type, member))

struct Person {
  int age;
  void (*greet)(struct Person *);
};

struct NamedPerson {
  char name[32];
  struct Person base;
};

void NamedPerson_greet(struct Person *p) {
   struct NamedPerson *np = container_of(p, struct NamedPerson, base);
   printf("Hello!. My name is %s, and I'm %d years old.\n",
          np->name, np->base.age);
}

struct NamedPerson George = {
  .name = "George",
  .base.age = 42,
  .base.greet = NamedPerson_greet,
};

int main() {
  struct Person *person = &George.base;
  person->greet(person); // Hello, my name is George ...
}

Compiles without any warnings with all aliasing warnings enabled, and in pedantic mode.
gcc prog.c -std=c99 -Wall -pedantic -fstrict-aliasing -Wstrict-aliasing -Wcast-align=strict -O3

A: To be clear, the original code is correct and does not require re-working ; the only issue is an unaesthetic warning .
The rest of the question, and the answers so far, focus on how to mangle the code in order to coax the compiler to not issue a warning .
IMHO it's preferable to deal directly with undesirable warnings, instead of mangling the code. Because mangled code is harder to read and understand; and future versions of the compiler might change the way that warnings are triggered.
Approaches along this line would include:

*

*disabling that warning entirely

*conditionally disabling that warning for sections of code that perform the safe operation (perhaps with assistance of a macro or inline function)

*filtering the compiler output (e.g. via grep -v) to remove the warning

redpajama_set_name: RedPajamaStackExchange


text:
Q: multiple sort criteria with different sort order equivalent is not available MongoDB .net SDK I could not find equivalent .net code for "A".
Desc:
A:

db.Some_Coll.find({"Feild1" : 123}).sort({"Some_Flag" :
1,"Some_Date":-1})

B:

db.Some_Coll.find({"Feild1" : 123}).sort({"Some_Flag" :
1}).sort({"Some_Date":-1})

A != B

B===

db.Some_Coll.find({"Feild1" : 123}).sort({"Some_Flag" :
1,"Some_Date":-1})

===
Some_CollObj.collection.Find(aggQuery)
     .SetSortOrder(SortBy.Ascending("Some_Flag"))
     .SetSortOrder(SortBy.Descending("Some_Date")).ToList();

A === ???
the below doesn't serve the purpose: as it does sort all keys as ascending
Some_CollObj.collection.Find(aggQuery)
 .SetSortOrder("Some_Flag","Some_Date") ===
  Some_CollObj.collection.Find(aggQuery)
 .SetSortOrder("Some_Flag","Some_Date").ToList();

Reference:
MongoCursor SetSortOrder(params string[] keys)
public virtual MongoCursor SetSortOrder(params string[] keys)
https://github.com/mongodb/mongo-csharp-driver/blob/master/src/MongoDB.Driver.Legacy/MongoCursor.cs


text:
Q: Registering all exceptions from rails app I have in some applications a custom library that gathers sensitive information.
This information comes from various sites, like: Twitter, Facebook, governamental blogs, college sites and common blogs.
I created a parser for each source because some of them are not well written and some of them need some hard coded parsing (regexp and stuff).
Everything worked fine. A few days ago I saw in my monitoring tool some exeptions on the client side. when I went looking for it I discovered that one of my "watched" sites had changed their HTML+CSS so I had to reimplement the parser for that website.
So this made me think, what would happen if others sites also changed their markup?
So I did all my parsers raise custom exeptions for my monitor to log. But when it comes to ruby I know I can do something more elaborated.
My question is: Is there a way to catch all exceptions in my application, adding custom behaviour, like a before filter, and letting the others trigger their default actions?
To illustrate:
I have in my twitter parser this exception if i got a parser error: raise Twitter::ParserError
somewhere, inside a initializer or something, i have this register (this is what i want):
# after 5 exceptions of Twitter::ParserError i want to act
registerException(Twitter::ParserError, 5.times) do
  # Send me an email warning me about this error
  # or do something with my environment
  # Parser.find_by_website(website: :twitter).report_offline
end

A: I won't comment on whether I think this is the right approach to this problem... but this was a fun little metaprogramming challenge.
The thing to realize is that raise, like most things in ruby, is just a method. So you can alias method chain it and do whatever you want before or after calling the original, giving you effectively a "before" and "after" hook on the raising of methods.
Here's an implementation of your pseudo code above. The one thing you DON'T get with this is a handle on the actual instance of the exception being raised, so you couldn't, for example, include a stack trace in the email sent to you. I'm not sure if there would be a way to get your hands on that exception, since the creation of it is in C code.
But here you go:
module Kernel
  @@registered_exceptions ||= {}
  @@raises ||= {}

  def register_exception(exception_class, times = 5, &block)
    @@registered_exceptions[exception_class] = {
      times: times,
      block: block
    }
  end

  alias_method :original_raise, :raise
  def hacked_raise(*args)
    # figure out what class we are about to `raise`
    # see http://www.ruby-doc.org/core-2.0/Kernel.html#method-i-raise
    # about why this is the correct logic.
    exception_class = if args.empty?
                        if $!
                          $!.class
                        else
                          RuntimeError
                        end
                      elsif args[0].is_a? String
                        RuntimeError
                      else
                        args[0]
                      end

    # this exception is not registered so forget it and act normally
    (original_raise(*args) and return) unless @@registered_exceptions.keys.include?(exception_class)

    @@raises[exception_class] ||= 0
    @@raises[exception_class] += 1

    if @@raises[exception_class] == @@registered_exceptions[exception_class][:times]
      @@raises[exception_class] = 0 # reset counter for this exception class
      @@registered_exceptions[exception_class][:block].call
    end
  end
  alias_method :raise, :hacked_raise
end

register_exception RuntimeError, 3 do
  puts "hey, there were 3 runtime exceptions raised!"
end

raise
raise
raise
raise
raise
raise
raise


text:
Q: Building a REST form to send data on blur I'm working on building a form where each field entered will send a portion of the object to the server and wait for a response back on blur.  My issue at the moment is that state is not updating quick enough before the user moves to the next input field.  The scenario is:

*

*User types info into the field

*User goes to the next field

*During this moment, a REST call is being made carrying an object of what the user has typed in

*The response comes back carrying data to fill in the next field

*However, at times, it seems the response wasn't quick enough or state wasn't updated fast enough so the next field is not pre-filled in

I'm hoping someone can give me some assistance on what the best approach is here to help speed things up.  I can provide some code, but I'm hoping more for some guidance rather than code answers.
Regarding the axios post call:
try {
  await this.plansApi
    .compileFields({ obj, carrier, benefitQuery })
    .catch(error => {
      const { required } = error.response.data;
      const { validation } = error.response.data;
      const arr = [];
      if (required !== undefined) {
        required.forEach(item => {
          arr.push(item.name);
        });
        this.setState({ required: arr });
      }
      if (validation !== undefined) {
        validation.forEach(item => {
          arr.push(item.name);
        });
      }
      const check = _.find(goldenListKeys, { name: 'loadingRate' });
      if (check !== undefined) {
        Object.assign(obj.inputData, { loadingRate: 1 });
      }
    });
} catch (err) {
  process.stdout.write(err);
}


text:
Q: Windows netsh WinForm Process.Start unable to take arguments I'm using Visual Studio 2017 C#.  I'm trying to create a simple Winform application for our remote small site employees that will help them assist IT remote support diagnose latency issues between their client computer and some enterprise application (exchange servers, webapps, databases, etc. on the network) from a netsh trace capture file.
IT remote small site support is expected to open the trace file and isolate the cause of packet latency between the two end points.
The goal here is for remote small site employees to launch a Winform App, click a button that launches netsh, capture a trace to a file, and to close netsh after a period of minutes.  I haven't written the code for the timer yet.  The initial code below is supposed to launch netsh which it does without arguments.  It displays a window and the netsh> prompt appears.  When I try to run netsh with arguments the Winform netsh command window flashes and then immediately closes. I've searched numerous articles and tried many of the suggested code segments but none seem to work.  Any help would be appreciated.
****************** Code**********************
    private void DegradationCaptureStartButton_Click(object sender, EventArgs e)
    {
        try
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.WindowStyle = ProcessWindowStyle.Normal;
            startInfo.FileName = "netsh.exe";
            startInfo.Arguments = "trace start persistent=yes capture=yes tracefile=c://temp//billstrace.etl";
            startInfo.RedirectStandardOutput = false;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = false;
            Process.Start(startInfo);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }


text:
Q: Wrong version of dependence gem when run test for my gem I have been developing gem.
For test my gem I use ActiveRecord.
When I run test I get some error because my gem doesn't support version 5.0 of ActiveRecord.
But in my gemspec I have:
spec.add_development_dependency 'activerecord', '~> 4.2'

Also I tried to user Gemfile.local but it didn't get positive result.
What a right way for set particular version for a gem?

A: I figure out problem was in my test_helper file:
begin
  require File.dirname(__FILE__) + '/../../../../config/environment'
rescue LoadError
  require 'rubygems'
  gem 'activerecord'
  gem 'actionpack'
  require 'active_record'
 end

When I setted  explicit  version for gem everything has worked fine:
gem 'activerecord', "4.2.7.1"
gem 'actionpack', "4.2.7.1"


text:
Q: Extracting URL from tweets and getting numbers of tweets containing that url Here I am getting url from tweets, converting that url to long url.
And then getting count value for numbers of tweets containing that url.
if(preg_match($reg_exUrl, $tweet, $url)) {
                    preg_match_all($reg_exUrl, $tweet, $urls);
                    foreach ($urls[0] as $url) {
                    echo "Tiny url :  {$url}
";\
                    $full = MyURLDecode($url);
                    echo "Full url : $full
";
                    if (strpos($full, '//t.co') === true)
                        continue;
                    if (strpos($full, '//twitter.com') === true)
                        continue;
                    else if (strpos($full, '//bit.ly') === true)
                        $full = MyURLDecode($full);
                    $url_count = get_twitter_url_count($full);
                    echo "Url count: $url_count";
                    //echo "Numbers of tweets containing this link : ", $code['count']
                    echo "
";
                    }
                } else {
                    echo "Mismatch
";
                }

function MyURLDecode($url)

    {

        $ch = @curl_init($url);

        @curl_setopt($ch, CURLOPT_HEADER, TRUE);

        @curl_setopt($ch, CURLOPT_NOBODY, TRUE);

        @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);

        @curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        $url_resp = @curl_exec($ch);

        preg_match('/Location:\s+(.*)\n/i', $url_resp, $i);

        if (!isset($i[1]))

        {

        return $url;

        }

        return $i[1];

    }

    function get_twitter_url_count($url) {
        $encoded_url = urlencode($url);
        $content = @file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $encoded_url);
        return $content ? json_decode($content)->count : 0;
    }

problem:

*

*If full_url is again short url then get actual long url

*If url is link to twitter photo like http://twitter.com/ADSPLAYINDIA/status/415847973210181632/photo/1  then skip further getting tweet count

I added continue but still it does not skip it

A: For the first problem try setting follow location to true in your MyURLDecode function
@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

For your second problem,i think strpos will never return true.Check out this link to a comment on php.net http://www.php.net/manual/en/function.strpos.php#107240
Please let me know if it helped
Thanks


text:
Q: Define different font color and size of text in Menu Items android I have menu items e.g
<item
                  android:id="@+id/text"
                  android:title="@string/mainMenu"
                  android:enabled="false"
                  >

            </item>

I have a style defined as
<style name="MenuTextStyle" parent="@android:style/TextAppearance.Medium">
        <item name="android:textColor">6F6B6B</item>
        <item name="android:textStyle">bold</item>
        <item name="android:textSize">14sp</item>

I basically want to change the color and text size of Menu item. How can I implement this style in above Item?

A: Did you try
<item
    android:id="@+id/text"
    android:title="@string/mainMenu"
    android:enabled="false"
    style="@style/MenuTextStyle" />

?


text:
Q: Custom user fields using devise I'm using devise and I want to add the fields first_name and last_name to the sign_up form.
After creating the respective columns, I tried to sign_up with the new form, but the values of the new fields in DB were nil.
After that I created this controller:
class RegistrationsController < Devise::RegistrationsController

  private

      def sign_up_params
        params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation)
      end

      def account_update_params
        params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :current_password)
      end
end

But I still get nil in the columns first_name and last_name.
Am I missing something?
The form:

Sign up

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

<%= f.label :first_name %>

    <%= f.text_field :first_name %>

<%= f.label :last_name %>

    <%= f.text_field :last_name %>

<%= f.label :profile_name %>

    <%= f.text_field :profile_name %>

<%= f.label :email %>

  <%= f.email_field :email, autofocus: true %>

<%= f.label :password %> <% if @validatable %>(<%= @minimum_password_length %> characters minimum)<% end %>

    <%= f.password_field :password, autocomplete: "off" %>

<%= f.label :password_confirmation %>

    <%= f.password_field :password_confirmation, autocomplete: "off" %>

<%= f.submit "Sign up" %>

<% end %>

<%= render "devise/shared/links" %>

A: did you add devise_for :users, :controllers => { registrations: 'devise/registrations' } in your routes file ? If not then add it in your routes file. Other things are looks Okay

A: 1 option.
I think adding the following to application_controller.rb would eliminate the issue (instead of overridding the devise's controller):
private

  def configure_devise_params
    devise_parameter_sanitizer.for(:sign_up) do |u|
      u.permit(:first_name, :last_name, :email, :password, :password_confirmation)
    end
    devise_parameter_sanitizer.for(:account_update) do |u|
      u.permit(:first_name, :last_name, :email, :password, :password_confirmation)
    end
  end

2 option.
Check passing the controllers: { registrations: 'devise/registrations' } block do devise_for :users line in routes.rb


text:
Q: Are there any books on Lucene.NET I have searched on amazon and could not find a book on lucene.net. Have you guys came across a decent book on lucene.net?

A: You may want to look at: Lucene In Action.
Since Lucene.NET is a .NET port of the project, you may find it covers the necessary concepts, even though it's for Java. There should be a 2nd edition of it coming out soon.
The book covers:

*

*How to integrate Lucene into your applications

*Ready-to-use framework for rich document handling

*Case studies including Nutch, TheServerSide, jGuru, etc.

*Lucene ports to Perl, Python, C#/.Net, and C++

*Sorting, filtering, term vectors, multiple, and remote index searching

*The new SpanQuery family, extending query parser, hit collecting

*Performance testing and tuning

*Lucene add-ons (hit highlighting, synonym lookup, and others)

*Foreworded by Doug Cutting, the inventor of Lucene

A: There's 'Lucene in Action' for Java. It's quite similar.


text:
Q: When digitizing, polygons are inverted I need to use QGIS to digitize my images. My images are scanning electron microscope (SEM) images of rocks. I am interested in analyzing the pore space in the images. Here is the steps I follow:

*

*I use imagej to threshold the images; convert the gray scale image to a black and white image (0s an 1s).

*I use QGIS to digitize the black and white image to create a shapefile of polygons that I can use for further analysis. The polygons represent the pores in the images.
I ran into a little problem while following these steps. When I digitize my images using raster-conversions-polygonize, the polygons come out inverted.
Any ideas as to why this is happening?
PS: I noticed that the origin of the image changes when I load it into QGIS form the bottom left corner to the top left corner. I couldn't change it to check if it is the source of error.


text:
Q: GCC support for Compile-time string literals C++20 introduces Class Types in Non-Type Template Parameters. As mentioned in the proposal, one of the motivations was the compile-time strings, and it enables to do this:
template < size_t size >
struct Literal : std::array<char,size>
{
  constexpr Literal(char const (&str)[size+1]) { for (size_t ii = 0; ii < size; ++ii) (*this)[ii] = str[ii]; }
};
template < size_t size > Literal(char const (&str)[size]) -> Literal<size-1>;
template < Literal literal > constexpr auto operator "" _lit() { return literal; }

template < Literal > struct Use { };
Use<"foo"_lit> use;

The proposal also says:

There have been multiple proposals[N3599][P0424R0] to relax the
prohibition on string user-defined literals that take their raw form
as individual char template arguments, and so far all of these
proposals have failed to gain consensus.
The primary concern that gets
raised in response to such proposals is that handling strings as packs
of char template arguments is extremely costly in terms of the
compiler's CPU and memory usage, and allowing such UDLs would make
very large packs of char values much more common than they are today.
This may in turn result in pressure on compiler vendors to make their
products perform well under such compile-time string processing
workloads, which is difficult due to the strings being represented
using a syntax and mechanism that was never intended to support such
use cases.

Thus, though not mentioned directly, I assume this proposal was designed to avoid the extremely costly CPU and memory usage for the compilers while dealing with compile-time strings. Maybe this is to be possible because of the mangling approach and using Three-way comparison operator mentioned in the first section of the proposal. Is this assumption correct?
gcc-9.3 doesn't support the Three-way comparison operator but it supports Class Types in Non-Type Template Parameters. However, having compile-time strings in the above mentioned way with gcc-9.3 actually seems to result into extremely costly CPU and memory usage.
Is there any appropriate flag for gcc-9 or gcc-10 that will tune the compiler for such code?


text:
Q: Give an example of a positive function $f(n)$ which is neither $O(n^2)$ nor $\Omega(n^2)$ I am having trouble with this question as I don't know how to approach it.

A: The basic idea is to take $f(n)=n^{g(n)}$, where $g(n)$ is some bounded oscillatory function. What would be a good choice of $g(n)$ in this case?


text:
Q: css and javascript didn't include on refresh I'm a beginner on AngularJs and I have encountered a problem that I don't understand why and I hope you guys can help or enlighten me. I'm trying to build a single page application with angularJS + expressJS everything work fine but until I refresh my page, for example I'm at localhost:3000(which is my homepage) and I access to localhost:3000/login it work perfectly fine but if I refresh the page the css doesn't include on localhost:3000/login , because i'm injecting the login.ejs file into the ng-view on "/"(where css file located "index.ejs") but once i refresh the page the browser only load login.ejs which i didn't include css on it. your help is greatly appreciated
Before i post the question on stack overflow i have posted it on google+ group to seek help on it however my problem is still unsolved i think i have written the code wrongly or something. if you have the time please check out my code below :
this is my express middleware
( one of the user on google+ told me to move my app.router to below express.static)
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/public/views');
app.set('view engine', 'ejs');
app.use(express.cookieParser());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);

this is the routes after the middleware(the main is main.ejs just some data i inject on "/" route)
app.get('/', routes.index,function(req, res){
res.render('main')
});
app.get('/:path',function(req, res){
var path = req.params.path;
res.render(path);
});
app.get('*', function(req, res) {
  res.redirect('/' + req.path);
});

in this case i inject data into index.ejs
inside index.ejs contain

along with javascript and css
in my angularjs file
var app = angular.module('myApp',[]).
 config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
    $routeProvider.
      when('/', {
        templateUrl: 'main.ejs',
        controller: 'IndexCtrl'
      }).
      when('/login',{
      templateUrl: 'login.ejs',
        controller: 'IndexCtrl'
      }).
      otherwise({
        redirectTo: '/'
      });
    $locationProvider.html5Mode(true);
  }]);

A: This line is your problem
$locationProvider.html5Mode(true);

To use the Html5 mode you have to configure your server to always serve the index page on requests. Another alternative is to make the login page a partial of index (index will be a container for all your css and javascript, "master page"). Have a look at ejs-locals.
So for it to work without changes you nedd to disable html5 mode
$locationProvider.html5Mode(false);

This will add a # tag to your browser address. So when you navigate to localhost:3000/ and click the login link it will send you to #/login, for the server you never moved from index page but angular knows how to pick that up and will render your page correctly.
there are lots of examples on the web, and stackoverflow.
Hope it helps.


text:
Q: Apply-PnPProvisioningTemplate : Input string was not in a correct format I try to export and import template using below PnP powershell scripts. There is no issue while exporting the template. But I get "Apply-PnPProvisioningTemplate : Input string was not in a correct format." message while applying template to target site collection. I couldn't find any error message in the log file.
How can I solve this issue?
Export:
Connect-PnPOnline –Url https://tenant.sharepoint.com/sites/sourcesitecoll –Credentials (Get-Credential)
Get-PnPProvisioningTemplate -out template.pnp

Import:
Connect-PnPOnline –Url https://tenant.sharepoint.com/sites/targetsitecoll –Credentials (Get-Credential)
Set-PnPTraceLog -On -LogFile "C:\Works\PnP\logs.txt" -Level Debug
Apply-PnPProvisioningTemplate -Path "C:\Works\PnP\template.pnp"

Error message:

Apply-PnPProvisioningTemplate : Input string was not in a correct
  format. At line:1 char:1
  + Apply-PnPProvisioningTemplate -Path "C:\Works\PnP\template.pnp ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : WriteError: (:) [Apply-PnPProvisioningTemplate], FormatException
      + FullyQualifiedErrorId : EXCEPTION,SharePointPnP.PowerShell.Commands.Provisioning.Site.ApplyProvisioningTemplate

SharePointPnPPowerShellOnline version is "3.10.1906.0"

A: This may not answer but you could try it as it's working in my environment.
Get:
#region Variables
$Username = "user@tenant.onmicrosoft.com"
$Password = "password"
$siteURL = "https://tenant.sharepoint.com/sites/lee"

#endregion Variables

#region Credentials
[SecureString]$SecurePass = ConvertTo-SecureString $Password -AsPlainText -Force
[System.Management.Automation.PSCredential]$PSCredentials = New-Object System.Management.Automation.PSCredential($Username, $SecurePass)
#endregion Credentials

Connect-PnPOnline -Url $siteURL -Credentials $PSCredentials

$listName = "Site Assets";
$outputTemplateFileName = "C:\Lee\Script\template.xml";

$template = Get-PnPProvisioningTemplate -OutputInstance -Handlers Lists
$listTemplate = $template.Lists | Where-Object { $_.Title -eq $listName }
$template.Lists.Clear()
$template.Lists.Add($listTemplate)
Save-PnPProvisioningTemplate -InputInstance $template -Out $outputTemplateFileName

Apply:
#region Variables
$Username = "user@tenant.onmicrosoft.com"
$Password = "password"
$siteURL = "https://tenant.sharepoint.com/sites/wiki"

#endregion Variables

#region Credentials
[SecureString]$SecurePass = ConvertTo-SecureString $Password -AsPlainText -Force
[System.Management.Automation.PSCredential]$PSCredentials = New-Object System.Management.Automation.PSCredential($Username, $SecurePass)
#endregion Credentials

Connect-PnPOnline -Url $siteURL -Credentials $PSCredentials

Apply-PnPProvisioningTemplate -Path "C:\Lee\Script\template.xml"


text:
Q: why there is performance difference when retrieving data from view vs underlying select of that view I am doing query on view with single predicates which gives me the record in 4-7 seconds, but when i try to retrieve the record with same predicate and directly with underlying query from that view it gives me records in less then seconds. I am using MySQL.
I have tried checking the execution plan of both the query and it gives major differences if i have hundreds of thousands of records in tables.
So any clue or idea why performance is better when using query  directly?
Following is my view definition
 SELECT    entity_info.source_entity_info_id      AS event_sync_id,
          entity_info.source_system_id           AS source_system_id,
          entity_info.target_system_id           AS destination_system_id,
          event_sync_info.integrationid          AS integration_id,
          event_sync_info.source_update_time     AS last_updated,
          entity_info.source_internal_id         AS source_entity_internal_id,
          entity_info.source_entity_project      AS source_entity_project,
          entity_info.target_internal_id         AS destination_entity_internal_id,
          entity_info.destination_entity_project AS destination_entity_project,
          entity_info.source_entity_type         AS source_entity_type,
          entity_info.destination_entity_type    AS destination_entity_type,
          event_sync_info.opshub_update_time     AS opshub_update_time,
          event_sync_info.entity_info_id         AS entity_info_id,
          entity_info.global_id                  AS global_id,
          entity_info.target_entity_info_id      AS target_entity_info_id,
          entity_info.source_entity_info_id      AS source_entity_info_id,
          (
                 SELECT Count(0) AS count(*)
                 FROM   ohrv_failed_event_view_count failed_event_view
                 WHERE  ((
                                      failed_event_view.integration_id = event_sync_info.integrationid)
                        AND    (
                                      failed_event_view.entityinfo = entity_info.source_entity_info_id))) AS no_of_failures
FROM      (ohrv_entity_info entity_info
LEFT JOIN ohmt_eai_event_sync_info event_sync_info
ON        ((
                              entity_info.source_entity_info_id = event_sync_info.entity_info_id)))
WHERE     (
                    entity_info.source_entity_info_id IS NOT NULL)

Query examples

*

*select * from view where integration_id=10
Execution plan of this processes 142668 rows for sub query that is there in this view

*select QUERY_OF_VIEW and integration_id=10
Execution plan of this looks good and only required rows are getting processed.

A: I think the issue is in the following query:
SELECT * FROM view WHERE integration_id = 10;

This forces MySQL to materialize an intermediate table, against which it then has to query again to apply the restriction in the WHERE clause.  On the other hand, in the second version:
SELECT (QUERY_OF_VIEW with WHERE integration_id = 10)

MySQL does not have to materialize anything other than the query in the view itself.  That is, in your second version MySQL just has to execute the query in the view, without any subsequent subquery.

A: refereeing to this link of documentation you can see,that its depend on if the MERGE algorithm can used it will , but if its not applicable so new temp table must generated to find the relations of data, also you can see this answer that talking about optimization and when to use view and when you should not .

If the MERGE algorithm cannot be used, a temporary table must be used
  instead. MERGE cannot be used if the view contains any of the
  following constructs:
Aggregate functions (SUM(), MIN(), MAX(), COUNT(), and so forth)
DISTINCT
GROUP BY
HAVING
LIMIT
UNION or UNION ALL
Subquery in the select list
Refers only to literal values (in this case, there is no underlying
  table)


text:
Q: After upgrade to Ubuntu 14.04.3 LTS, MOTD always says 0 new packages can be updated I'm not a server expert and so I'm experiencing some upgrade issues with Ubuntu. A little history: my Digital Ocean droplet was running Ubuntu 12.04 LTS, then a few months ago I upgraded to a newer HWE to continue to receive security updates for the 12.04. Recently I upgraded Ubuntu to the 14.04 LTS. Everything seems to be working fine except I'm not receiving any notifications that there are packages to be updated. Upon logging into my server the Message of the Day continues to display:
0 packages can be updated.
0 updates are security updates.

which just can't be right for 3 weeks now...?
running sudo apt-get update runs without error and sudo apt-get upgrade says 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
I have a feeling that my /etc/apt/sources.list was corrupted somehow after upgrading to the new HWE kernal and then the new LTS. Below are the sources listed currently. Does anyone see any issues with this list? any advice would be appreciated.
$ cat /etc/apt/sources.list

#

# deb cdrom:[Ubuntu-Server 12.04.3 LTS _Precise Pangolin_ - Release i386 (20130820.2)]/ precise main restricted

# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
## DigitalOcean mirrors for blazing speed!
deb http://mirrors.digitalocean.com/ubuntu/ trusty main restricted
deb-src http://mirrors.digitalocean.com/ubuntu/ trusty main restricted
# deb http://us.archive.ubuntu.com/ubuntu/ precise main restricted
# deb-src http://us.archive.ubuntu.com/ubuntu/ precise main restricted

## Major bug fix updates produced after the final release of the
## distribution.
## DigitalOcean mirrors for blazing speed!
deb http://mirrors.digitalocean.com/ubuntu/ trusty-updates main restricted
deb-src http://mirrors.digitalocean.com/ubuntu/ trusty-updates main restricted
# deb http://us.archive.ubuntu.com/ubuntu/ precise-updates main restricted
# deb-src http://us.archive.ubuntu.com/ubuntu/ precise-updates main restricted

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
## DigitalOcean mirrors for blazing speed!
deb http://mirrors.digitalocean.com/ubuntu/ trusty universe
deb-src http://mirrors.digitalocean.com/ubuntu/ trusty universe
deb http://mirrors.digitalocean.com/ubuntu/ trusty-updates universe
deb-src http://mirrors.digitalocean.com/ubuntu/ trusty-updates universe
# deb http://us.archive.ubuntu.com/ubuntu/ precise universe
# deb-src http://us.archive.ubuntu.com/ubuntu/ precise universe
# deb http://us.archive.ubuntu.com/ubuntu/ precise-updates universe
# deb-src http://us.archive.ubuntu.com/ubuntu/ precise-updates universe

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
## DigitalOcean mirrors for blazing speed!
deb http://mirrors.digitalocean.com/ubuntu/ trusty multiverse
deb-src http://mirrors.digitalocean.com/ubuntu/ trusty multiverse
deb http://mirrors.digitalocean.com/ubuntu/ trusty-updates multiverse
deb-src http://mirrors.digitalocean.com/ubuntu/ trusty-updates multiverse
# deb http://us.archive.ubuntu.com/ubuntu/ precise multiverse
# deb-src http://us.archive.ubuntu.com/ubuntu/ precise multiverse
# deb http://us.archive.ubuntu.com/ubuntu/ precise-updates multiverse
# deb-src http://us.archive.ubuntu.com/ubuntu/ precise-updates multiverse

## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
## DigitalOcean mirrors for blazing speed!
deb http://mirrors.digitalocean.com/ubuntu/ trusty-backports main restricted universe multiverse
deb-src http://mirrors.digitalocean.com/ubuntu/ trusty-backports main restricted universe multiverse
# deb http://us.archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse
# deb-src http://us.archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse

## DigitalOcean mirrors for blazing speed!
deb http://mirrors.digitalocean.com/ubuntu/ trusty-security main restricted
deb-src http://mirrors.digitalocean.com/ubuntu/ trusty-security main restricted
deb http://mirrors.digitalocean.com/ubuntu/ trusty-security universe
deb-src http://mirrors.digitalocean.com/ubuntu/ trusty-security universe
deb http://mirrors.digitalocean.com/ubuntu/ trusty-security multiverse
deb-src http://mirrors.digitalocean.com/ubuntu/ trusty-security multiverse
# deb http://security.ubuntu.com/ubuntu precise-security main restricted
# deb-src http://security.ubuntu.com/ubuntu precise-security main restricted
# deb http://security.ubuntu.com/ubuntu precise-security universe
# deb-src http://security.ubuntu.com/ubuntu precise-security universe
# deb http://security.ubuntu.com/ubuntu precise-security multiverse
# deb-src http://security.ubuntu.com/ubuntu precise-security multiverse

## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu precise partner
# deb-src http://archive.canonical.com/ubuntu precise partner

## Uncomment the following two lines to add software from Ubuntu's
## 'extras' repository.
## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
# deb http://extras.ubuntu.com/ubuntu precise main
# deb-src http://extras.ubuntu.com/ubuntu precise main

A: Ubuntu LTS versions don't get many updates. In fact, the only updates you see in a LTS version are

*

*security updates

*bugfixes for major bugs (file loss bugs etc)

See https://wiki.ubuntu.com/StableReleaseUpdates#When for when exactly an LTS version gets updates.


text:
Q: Unable to append options with bootstrap selectpicker

<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" rel="stylesheet">
    <script crossorigin="anonymous" integrity="sha384-ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script crossorigin="anonymous" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- Boostrap Select -->
    <link rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>
    <title></title>
</head>
<body>

<p>
    Select one:
    <!-- If class="selectpicker" then onclick doesn't add option -->
    <!-- onclick works if class is not set -->
    <select id="select1" onclick="addOption('#select1')" class="selectpicker">
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
    </select>
</p>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
    function addOption(select_id) {
        $(select_id).empty();
        $(select_id).append(`<option value="new">New Option</option>`);
        $(select_id).selectpicker("refresh");
    }
</script>
</body>
</html>

If the class of the <select> element is set to selectpicker then the addOption script will not work. However, if the class is not set, the script works just fine.
How can I make the script work with selectpicker?


text:
Q: Duplicate Primary Key in PostgreSQL table I created a table named 'link' in PostgreSQL database. Then I created another table 'link_copy' with same structure as 'link'
CREATE TABLE link (
id select PRIMARY KEY,
url VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL);

CREATE TABLE link_copy (LIKE link);

I copied a row from 'link' to 'link_copy' that had 'id' = 2. After that I copied all rows from 'link' to 'link_copy'. I was surprised to see row with 'id' = 2 twice in 'link_copy'.
If I had selected 'id' column to be primary key (which is UNIQUE NOT NULL by default), then why did it allowed the 'id' = 2 row to be inserted in 'link_copy' twice?
I am using postgresql 9.5 on Mac with pgadmin III.
screenshot for final link_copy status

A: When you use the CREATE TABLE command to create a new table with the same structure as another, it duplicates the columns, but not all of the constraints.  Your link_copy table will not have a primary key defined after it is created this way.

A: Create table like below.  This will create all constraints.
CREATE TABLE link_copy (LIKE link  including constraints including indexes);


text:
Q: Unable to resolve org.openqa.selenium.WebDriverException: Specified firefox binary location does not exist or is not a real file? We are getting "org.openqa.selenium.WebDriverException: Specified firefox binary location does not exist or is not a real file: /usr/local/bin/firefox/firefox" exception when we ran the selenium web driver code via linux
Configuration:
aws-cli/1.7.38 Python/2.7.9 Linux/3.14.48-33.39.amzn1.x86_64
Amazon ElasticBeanStalk
Already installed firefox on /usr/local/bin/firefox/firefox
when i ran firefox --version the version clearly getting displayed in the console
Mozilla Firefox 38.1.0
File pathToBinary = new File("/usr/local/bin/firefox/firefox");
FirefoxBinary ffBinary = new FirefoxBinary(pathToBinary);
fBinary.setEnvironmentProperty("DISPLAY", ":1");
FirefoxDriver driver = new FirefoxDriver(ffBinary,pro);

xvfb is already started. (Xvfb :1 -screen 0 1280x768x24)
Please kindly help me on how to resolve the issue?

A: This problem occurred due to selenium library and firefox version conflict issue.


text:
Q: Why is (notepad.exe) scheduled task running as SYSTEM process, but not displayed in the GUI? I have created the following scheduled task using an Administrator cmd.exe:
schtasks /CREATE /RU SYSTEM /SC ONLOGON /TN SYSTEM_notepad /TR C:\Windows\System32\notepad.exe

The scheduled task runs just fine on LOGON:

However, notepad.exe is nowhere to be seen in the GUI.
Why is my scheduled task running in the "background" without any GUI? How can I fix this?

A: Because you have /RU SYSTEM. The system account is a special account and doesn't have a session with GUI like any account used for login. It's designed e.g. for unattended services that needs to run even when users aren't logged in. You can't log in as SYSTEM.
Using Notepad as an example completely masks your true needs, but maybe (based on the comment) you are trying to build something that would actually need an architecture of an Interactive Service with a separate GUI client:

*

*Service starts without GUI during system startup.

*Hidden GUI client starts separately for every user session during login.

*The service communicates with the client, causing it to display the GUI whenever required.

Create a separate hidden GUI application and use the
  CreateProcessAsUser function to run the application within the context
  of the interactive user. Design the GUI application to communicate
  with the service through some method of interprocess communication
  (IPC), for example, named pipes. The service communicates with the GUI
  application to tell it when to display the GUI. The application
  communicates the results of the user interaction back to the service
  so that the service can take the appropriate action. Note that IPC can
  expose your service interfaces over the network unless you use an
  appropriate access control list (ACL).
If this service runs on a multiuser system, add the application to the
  following key so that it is run in each session:
  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run. If
  the application uses named pipes for IPC, the server can distinguish
  between multiple user processes by giving each pipe a unique name
  based on the session ID.

Don't try to use Windows Task Scheduler for this purpose, but design your software better.


text:
Q: Display two field in forms by reactnative Please Help i want to dipslay two field in forms first field about country
 second about city of country  the condition second field display after selection in first field for example if i have a field about country when  i choose america another field display all the city for america ?
Thanks


text:
Q: ThymeLeaf selection a specific enum type

package com.newconstructs.controller.home;

import com.newconstructs.domain.Animal;
import com.newconstructs.domain.api.Layout;
import com.newconstructs.service.api.AnimalService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.inject.Inject;
import java.util.Collections;
import java.util.List;

@Controller
public class HomeController {
  @Inject
  private AnimalService animalService;

  @Layout(
    title = "",
    description = "",
    selectedNav = "all"
  )
  @RequestMapping(value = {"/", "/home"})
  public String init(ModelMap modelMap) {
    List<Animal> animals = animalService.findAll();

    modelMap.put("animals", animals);

    return "home";
  }
}

package com.newconstructs.service;

import com.newconstructs.domain.Animal;
import com.newconstructs.domain.Animal.AnimalType;
import com.newconstructs.service.api.AnimalService;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class AnimalServiceImpl implements AnimalService {
  private static final List<Animal> ANIMALS;

  static {
    ANIMALS = new ArrayList<>();

    ANIMALS.add(new Animal(AnimalType.DOG, "Spot", 10, 7, 17, 0));
    ANIMALS.add(new Animal(AnimalType.DOG, "Rover", 15, 5, 2, 6));
    ANIMALS.add(new Animal(AnimalType.DOG, "Fido", 8, 6, 12, 15));
    ANIMALS.add(new Animal(AnimalType.CAT, "Mittens", 18, 3, 3, 0));
    ANIMALS.add(new Animal(AnimalType.CAT, "Snowball", 5, 0, 14, 1));
    ANIMALS.add(new Animal(AnimalType.CAT, "Waffles", 8, 11, 2, 18));
    ANIMALS.add(new Animal(AnimalType.SNAKE, "Slider", 6, 16, 14, 3));
    ANIMALS.add(new Animal(AnimalType.SNAKE, "Milton", 16, 6, 11, 17));
    ANIMALS.add(new Animal(AnimalType.SNAKE, "Spike", 6, 18, 2, 5));
    ANIMALS.add(new Animal(AnimalType.SNAKE, "Alice", 9, 11, 4, 6));
    ANIMALS.add(new Animal(AnimalType.RABBIT, "Flopsy", 14, 0, 12, 2));
    ANIMALS.add(new Animal(AnimalType.RABBIT, "Peter", 18, 18, 14, 3));
    ANIMALS.add(new Animal(AnimalType.RABBIT, "Oreo", 7, 4, 9, 1));
  }

  @Override
  public List<Animal> findAll() {

    return ANIMALS;
  }
}

package com.newconstructs.service.api;

import com.newconstructs.domain.Animal;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.Map;

@Validated
public interface AnimalService {
  public List<Animal> findAll();
}
a {
  text-decoration: none;
  color: black;
}

#content, #header, #footer {
  width: 600px;
}

.menu {
  display: flex;
}

.menu > a {
  border-bottom: 1px solid grey;
  border-right: 1px solid grey;
  text-align: center;
  flex-grow: 1;
  padding: 10px;
}

.menu > a.selected {
  background-color: lightgray;
}

.menu > a:last-child {
  border-right: 0;
}

.menu > a:focus, .menu > a:hover {
  background-color: #e5e5e5;
}

h2.header {
  padding-bottom: 0;
  margin-bottom: 15px;
  border-bottom: 1px solid grey;
}

.animal-list {
  width: 400px;
}

.animal {
  border-bottom: 1px solid grey;
  padding: 4px 5px;
}

.name {
  font-size: 1rem;
}

.characteristic {
  text-align: right;
}

.type {
  font-size: 0.8rem;
  float: right;
}

.rating-table, .rating-table th, .rating-table td, .stats-table, .stats-table th, .stats-table td {
  border: 1px solid grey;
  border-collapse: collapse;
  width: 4.0rem;
  padding: 4px;
}

All Animals

      Name
      Animal Type
      Offense
      Defense
      Health
      Items

I'm trying to only get specific enum types from a Java array. If the code below shows me all animals in the list ANIMALS. How can I alter it show only enum type DOG. I have created a Plunker to show all my code. https://embed.plnkr.co/exdZ7Uw2jraxpac8Zrlb/
Basically, I need to alter the code below to get only dogs, cats, etc.

A: This can be done a number of ways but I would add a method to the service, call it getAllByAnimalType(AnimalType type), and give yourself the flexibility to let the view (html) show whatever animal(s) you throw at it while not passing unneeded data.
Since the data gets loaded in the view model you'll provide a way to know what the user wants through the url(s). Maybe:
@RequestMapping(value = {"/dogs"})
public String dogs(ModelMap modelMap) {
    List<Animal> animals = getAnimals(AnimalType.DOG);
    modelMap.put("animals", animals);
    return "home";
}
...
private List<Animal> getAnimals(AnimalType type) {
    return animalService.findAllByAnimalType(type);
}

A: Use th:if to display only the  enum type DOG.

All Animals

      Name
      Animal Type
      Offense
      Defense
      Health
      Items


text:
Q: How do you update existing records in Google Cloud Dataflow? Is it possible to update or insert new rows in an existing table using Google Cloud Dataflow?
Say for example I have the table below:
Book Table
BookId String(10)
Title String(50)
Content String(300)
Genre String(10)

And I have the following records already inside:
__________________________________________________
BookID     |   Title    | Content      | Genre   |
           |            |              |         |
1          | Deadlock   | Some Content |         |
2          | Arefureta  | Contentss    |         |
--------------------------------------------------

In this case I wanted my dataflow to populate the Genre column without affecting the current records.
How can I do this? Is this even possible? Or is there some sort of limitation from Google Cloud dataflow?
I wanted a result like this, after running the Dataflow:
__________________________________________________
BookID     |   Title    | Content      | Genre   |
           |            |              |         |
1          | Deadlock   | Some Content | Action  |
2          | Arefureta  | Contentss    |Adventure|
--------------------------------------------------


text:
Q: Magento 2.3 shipping I have developed a system using Magento 2.3 and now almost everything is done even the payment gateway. Now the last part I have to do is adding the shipping method and cost. My requirements are so simple and my requirements are, when an order is placed and if the cart value is below 1000 I have to add 200 for shipping and if the cart value is more than 1000 then we give free shipping. Along with the cart value we also have to define the locations ( only from specific locations the orders can be placed ). For example if we take America only from California and Los Angeles can place the order and if the order value is less than 1000 then shipping cost is 200 and if it is above 1000 then free shipping.
Following are  methods I tried but I didn't get the expected results.

*

*Free shipping. In Magento shipping is done based on the country not based on the countries locations so this method failed.

*Flat rate. I couldn't define the minimum amount and I couldn't define the locations.

*Table rate. I could define the shipping cost and the locations but unfortunately cost is based on the maximum value ( sub total and above ) not the minimum value.
As I have mentioned my requirements are simple we have to define the location And if the cost is low we charge shipping and if it's high we give free shipping.

A: i am posting the answer so that it will be beneficial for others and the solution is, in general magento doesn't support shipping based on locations or it doesn't support certain conditions for example ( sub total between 2000 and 100000 or 0 and 2000 ) etc. so in order to overcome this issue we have to install extensions which suits our requirements. so for my scenario i used the ( webshopapps matrixrate ) which is a free extension and i am now fine with shipping.


text:
Q: perl mass text replace with literal dollar sign trying to replace text patterns with dollar signs and ()s, can't get it to work. please help
find /var/www/vhosts/prod/xxx/  -name "*.php"|xargs perl -w -i -p -e "s/mysql_fetch_array\($res,MYSQL_ASSOC\)/mysql_fetch_assoc(\$res);/g"

A: I suspect that your shell is expanding $res. Enclose the regex in single quotes to prevent this.
A slightly more efficient variation without xargs and perl:
find /var/www/vhosts/prod/xxx/ -name "*.php" -exec sed -i 's/mysql_fetch_array($res,MYSQL_ASSOC)/mysql_fetch_assoc($res);/g' {} \+

A: You also need to escape the $, ( and ) symbols in the search regex, you've already escaped the $ in the replacement string correctly.
With Perl 5.10.1 I have to use the -i.bak parameter to get this to work, otherwise the inplace edit switch complains that I don't have a backup.
find /var/www/vhosts/prod/xxx/ -name "*.php"|xargs perl -w -p -i.bak -e "s/mysql_fetch_array\(\$res,MYSQL_ASSOC\)/mysql_fetch_assoc(\$res);/g"


text:
Q: Passing aws access keys from another file to Ansible dynamic inventory file I am trying to pass aws credentials to dynamic inventory file from another file.
The dynamic inventory file aws_ec2.yaml contains (fake keys):
---
plugin: aws_ec2

aws_access_key: lksldeireorierbnebrirhireri
aws_secret_key: zeueze7er76

regions:
  - us-west-2

I don't want to use my keys here. Even I don't want to use aws_profile. Rather I want to create a seperate file with my credentials. Suppose, My credential file key.yaml contains:
my_access_key: lksldeireorierbnebrirhireri
my_secret_key: zeueze7er76

I am able to pass these keys to playbook by ansible-playbook -e @key.yaml my_playbook.yaml.
How I can pass these key in my dynamic inventory file aws_ec2.yaml? It can be by passing extra vars or vault or environment variable.


text:
Q: How do I run tail on a pcap file remotely? I have a pcap file that is growing over time on a server that I can ssh into. What I want to do is something like this:
ssh x@y tail -f -c +0 /path/to/pcapfile | wireshark -k -i

This command returns an error stating that the pcap file I specified cannot be found (it exists).
I have also tried
wireshark -k -i - < (ssh x@y "tail -f -c +0 /path/to/pcapfile")

None of these work. What I want to do is use the tail command remotely to display the packets that are streaming live from the growing pcap file in the server. How would I go about doing this? Thanks in advance.

A: This happens because tail does not know where a packet starts and where it ends.  The fact that it works locally is likely just a coincidence: packets come at a rate that is slow enough for tail to send them individually to wireshark through the pipe.
On the other hand, this is not a problem that other people have not had before.  Anton Berzin wrote pcaptail, which is the tool you're likely looking for:

It (pcaptail) will behave like tail -f but on the level of individual packets

pcaptail is a very small program: less than 300 lines of code, and you only need libpcap and libpcap headers to compile it.


text:
Q: Form parameters unpermitted by in rails app I have a controller for Walkers with the following action:
def update
    if !current_user
        redirect_to "/walkers"
    end
    walker = Walker.find(params[:id])
    walker.update(walker_params)
    walker.save
    redirect_to admin_path
end

There is also a private method:
    def walker_params
        params.require(:walker).permit(:id, :fname, :lname, :role, :active, :role, :avatar)
    end

In my resources I have:
resources :walkers

Then I have a form with the following erb.
    <%= form_for :walker, url: "/walkers/#{w.id}", method: "put" do |f| %>
      <%= f.hidden_field active: false %>
      <%= f.submit "Deactivate", class: "font-color-warning mdl-button" %>
    <% end %>

My rails server gives me the following error:
Unpermitted parameter: {:active=>false}

The parameters being sent are:
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"7vkuiaZG32x0EPr9IR9VvgURTQ7uniZH/7IPfMYdvb3AIGq8Psd+o9ykfs6qMKcozXYm08BKJ0/M3s5Q2DwiGg==",
"walker"=>{"{:active=>false}"=>""},
"commit"=>"Deactivate",
"id"=>"1"}

My expectation was that I was putting false on the :active parameter of the walker object found at PUT 'walkers/w.id'. My parameters show that my expectation is not correct.
I would like a solution to my problem. Ideally some understanding of why my parameters are being sent with walker"=>{"{:active=>false}"=>""} when my goal is submit parameters with walker"=>{:active=>false}.
I don't have an @walker object to reference because I'm looping through with |w|.

A: change
<%= f.hidden_field active: false %>

to
 <%= f.hidden_field :active, value: false %>


text:
Q: Excel Multiple rows to multiple columns for different values I am trying to produce something like discussed here (Transpose multiple rows to multiple columns)
Basically
I got data in Excel or MS-Access like as follows
ID   Desc Day1 Day2 Day3 ...
London  Apr17  12 34  36
London  May17  16 0   29
London  Jun17  17 18  43
Birm    May17  11 0   28
Birm    Jun17  12 18  42

I want to produce something like either in Excel or MS-Access
          --Apr---------   -----May ---------  -----------Jun-----
ID      Desc Day1 Day2 Day3   Day1  Day2 Day3     Day1  Day2 Day3
London Apr17  12 34  36      ...16  0   29        17   18   43
Birm                         ...11  0   28        12   18   42

Any ideas how this can be done
Did tried transpose , indirect etc
for me the challenge is I got around 10 columns remains same in beginning then about 10 columns on right hand side remain same and want around 400 columns for every day with calculated columns to be stored.

A: Whenever I need to do something like this in Excel I generally use a combination of formulas to create text cell references and then use the indirect function to grab the value. If your data is fairly uniform, then the formula to create the cell reference for the indirect function is fairly simple. If the data is not uniform, then a combination of match functions are needed to create the cell reference, and they get rather clumsy really quickly the more data that you have.
For example, if the first set of data shown starts in A1, and the second set of data starts in I1, then a formula such as:
=CHAR(CODE("J")+MATCH($B2,$J$10:$R$10,0)+MATCH(C$1,$J$2:$R$2,0)-2)&TEXT(MATCH($A2,$I$3:$I$9,0)+2,"#")
Note that I had to create a set of formulas in J10 through R10 that contained the correspond month Desc entry.
Now, this formula gets you a cell reference to where the data should go. The problem is that you need a reference from where the data should go, to where it is. So this is backwards. Here's where it gets cumbersome. You need another set of MATCH functions in a nested IF to get this:
=IF(NOT(ISNA(MATCH(J11,$C$36:$C$42,0))),"C"&TEXT(MATCH(J11,$C$36:$C$42,0)+1,"#"),IF(NOT(ISNA(MATCH(J11,$D$36:$D$42,0))),"D"&TEXT(MATCH(J11,$D$36:$D$42,0)+2,"#"),IF(NOT(ISNA(MATCH(J11,$E$36:$E$42,0))),"E"&TEXT(MATCH(J11,$E$36:$E$42,0)+2,"#"),"I1")))
which gets brutal as you add more Day columns. Note that I had to create an array that contained the location text values in J11 through R13, which will need to be bigger with more data, although you could use a combination of ROW and COL functions instead of an array.
Then in J3 through R9 (expanded as more data is needed), the INDIRECT functions are used to select the data from the second IF/MATCH/MATCH function.
You can eliminate some of the secondary calculation cells, e.g. putting the IF/MATCH/MATCH/... function directly in the INDIRECT function, I find it easier when developing something like this to create a bunch of intermediate formula cells which help determine where something isn't correct, and there almost always is something messed up somewhere.
In Access, you could use a number of crosstab queries combined together in another query to make a big multi column data output. As someone else noted, ther emay be limitations on the number of output columns, I haven't tried it to see.
Good luck!


text:
Q: Why does apply_filters behave different inside and outside a loop? What I want: the array of posts returned by creating $query = new WP_Query($args);
Why: to return specific content as a sort of API request in json format, ready to display on another site

What I tried first:
foreach($query->posts as $post) {
    $post->post_content = apply_filters('the_content', $post->post_content);
};

This performed the autop and do_shortcode filters correctly, but no the oembed transformation.

What I ended up doing:
while($query->have_posts()) : $query->the_post();
    $query->posts[$query->current_post]->post_content = apply_filters('the_content', get_the_content());
endwhile;

The only difference in output, is that inside the loop it performs the oembed, outside it does not.  Where does this difference come from, and is there a better way I should have done this?
I checked global $wp_filters and oembed is definitely listed under [8], so it wasn't a filter loading issue.

A: There is a difference because you are not using the_post function in the first example. What this function does is it calls setup_postdata function, which sets up all the globals needed for other functions to work. You can call it manually, just at the beginning of your foreach loop, like this: setup_postdata( $post ). In addition it is possible that you would also need to call a global $post; before your foreach loop.


text:
Q: Let $f(x)=\sin(1/x)$, $x≠0$ and $f(0)=0$ then does there exist any function $g$ such that $g'=f$? My initial thought was in he direction let consider $\phi(x)=\int_0^{x} f(t) dt$. Now $\phi'(x)=f(x)$ if $f(t)$ is continuous at $x$. But here $f$ is not continuous so any help will be appreciated.

A: Set $g(x)=x^2\cos(1/x)$ $(x \not=0)$, $g(0)=0$ and
$h(x)=2x\cos(1/x)$ $(x \not=0)$, $h(0)=0$. Note that $g$ is differentiable
and $h$ is continuous on $\mathbb{R}$. Set
$$
F(x)=g(x)-\int_0^x h(t)dt
$$
Now for $x \not=0$
$$
F'(x)= 2x\cos(1/x) + \sin(1/x) -  2x\cos(1/x) =  \sin(1/x),
$$
and
$$
F'(0)=g'(0)-h(0)=0.
$$
Thus $F$ is a primitive of $f$.

A: The function $f$ has an antiderivative $g$ with the simple form,
$$g(x) = \int_0^x f(t) \, dt = \int_0^x \sin \frac{1}{t} \, dt$$
As observed, the continuity of $f$ away from $0$  implies that $g'(x) = f(x)$ for $x \neq 0$. It remains to show that $g'(0) = f(0) = 0$.  By definition of the derivative, we have
$$g'(0) = \lim_{h \to 0}\frac{1}{h}\int_0^h \sin \frac{1}{t} \, dt$$
Without loss of generality we can consider $h > 0$, since for $h < 0$ we have
$$\frac{1}{h}\int_0^h \sin \frac{1}{t} \, dt= -\frac{1}{|h|}\int_0^{-|h|} \sin \frac{1}{t} \, dt = -\frac{1}{|h|}\int_0^{|h|} \sin \frac{1}{(-t)} \, d(-t) =  -\frac{1}{|h|}\int_0^{|h|} \sin \frac{1}{t} \, dt$$
With the change of variables $y = 1/t$ and using integration by parts, we get
$$\int_0^h \sin \frac{1}{t} \, dt = \int_{1/h}^\infty \frac{\sin y}{y^2} \, dy = \left. \frac{2 \cos y}{y^3}\right|_{1/h}^\infty - 2 \int_{1/h}^\infty\frac{\cos y}{y^3} \, dy = -2h^3\cos \frac{1}{h}-  2\int_{1/h}^\infty\frac{\cos y}{y^3} \, dy $$
Thus,
$$g'(0) = \lim_{h \to 0}\left(-2h^2 \cos \frac{1}{h}\right) - \lim_{h \to 0}\frac{2}{h}\int_{1/h}^\infty \frac{\cos y}{y^3} \, dy $$
The first limit on the RHS is clearly $0$ since $\left|\cos \frac{1}{h}\right| \leqslant 1$.  The second limit is also $0$ since,
$$\left|\frac{2}{h}\int_{1/h}^\infty \frac{\cos y}{y^3} \, dy  \right|\leqslant \frac{2}{h}\int_{1/h}^\infty \frac{|\cos y|}{y^3}\leqslant \frac{2}{h} \int_{1/h}^\infty \frac{dy}{y^3} = h \underset{h \to 0} \longrightarrow 0$$
Therefore, $g'(0) = 0 = f(0)$.


text:
Q: How can I access second microphone signal in android device? How can I access second microphone signal in android device?
I'm trying to make 2-channel noise reduction app and I don't know how to access second microphone signal.
I use Galaxy S2 which has 2 microphone(bottom and top) and when I use AudioRecord method
bottom microphone signal is the only one that can I access.
I will appreciate any response~
thanks, youna

A: I'm not familiar with the Galaxy S2, but on the devices I've worked with one could typically get the secondary mic by doing a mono recording from the CAMCORDER AudioSource. And a stereo recording would use both mics.
Most of those devices had a bottom/back mic placement rather than bottom/top, though.
Also, as Edison commented, the data that you get when you record will typically already have gone though a noise suppressor regardless of the AudioSource you use. I've never come across an Android device where you can get a raw, unfiltered stereo signal from the two built-in mics (that's not to say that no such devices exist).


text:
Q: Flutter Image Widget: How to convert the Image widget to Byte array I am trying to use a network image as marker icon in google maps api. The google maps Marker accepts only the BitmapDescriptor as icon, so how do I convert my network image as icon?
BitmapDescriptor.fromBytes constructor accepts the bytes, how do I get the bytes from the Image widget?

A: Have you tried anything from here?
https://coletiv.com/blog/use-network-images-as-marker-icons-flutter-google-maps/


text:
Q: nef vs. 1-nef vector bundles Let $X$ be a compact, connected, Kähler manifold, of dimension $d$, with Hermitian metric $\omega$; let $E$ be a vector bundle on $X$ of rank $r\geq2$.
By [1] definition 3.1.2:

A line bundle $L$ over $X$ is said numerically effective (nef, for short) if for any $\epsilon>0$ there exists a smooth Hermitian metric $h_{\epsilon}$ on $L$ such that
  \begin{equation*}
\Omega_{h_{\epsilon}}(L)\geq-\epsilon\omega;
\end{equation*}
  that is the curvature form $\Omega_{h_{\epsilon}}(L)$ of the Chern connection on $L$ (with respect to $h_{\epsilon}$) can have an arbitrary negative part. $E$ is nef if the tautological bundle $\mathcal{O}_{\mathbb{P}(E)}(1)$ is nef.

By [1] definition 3.1.3:

$E$ is $1$-nef if for any $\epsilon>0$ there exists a Hermitian metric $h_{\epsilon}$ on $E$ such that $\Omega_{h_{\epsilon}}(E)\geq-\epsilon\omega$.

By [1] proposition 3.2.4, the $1$-nef bundles $E$ over $X$ are nef; but the inverse is unknown in general; excepted for:

*

*$d=1$ (i.e. algebraic curves), see [1] theorem 3.3.1;

*on toric and Abelian varieties $E\otimes\det E$ is $1$-nef;

*tangent bundle $TX$ of $X$, where it is nef and $d\in\{2,3\}$;

(2) is justified in [1] at page 113, (3) follows by [2] theorems 6.1, 7.1 and [1] proposition 3.2.4.
Question: Are there other examples of manifolds over which the nef bundles are $1$-nef? Or is there an example of nef not $1$-nef bundle over some manifold $X$?

[1] M. A. A. De Cataldo - Singular Hermitian metrics on vector bundles, J. reine ang. Math. 502 (1998) 93-122
[2] J.-P. Demailly, T. Peternell, M. Schneider - Compact complex manifolds with numerically effective tangent bundles, J. Algebraic Geom. 3 (1994) 295-345

A:
Let $(X,\omega)$ be a compact Kähler manifold of dimension $d\geq2$; let $E$ be a nef vector bundle of rank $r\geq2$ such that $\displaystyle\deg(E)=\int_Xc_1(E)\wedge\omega^{d-1}=0$. $E$ is a $1$-nflat vector bundle.

Proof. By [DPS, propositions 1.14.i and 1.15.i] $\det(E)$ is a ($1$-)nef line bundle; by [BGO2, remark 3.2.ii and lemma 3.13] $\det(E)$ is a ($1$-)nflat line bundle; because
\begin{equation*}
E^{\vee}\cong\bigwedge^{r-1}E\otimes(\det(E))^{\vee}
\end{equation*}
$E^{\vee}$ is a nef vector bundle. By definition $E$ is a nflat vector bundle.
By [DPS, theorem 3.2] $E$ has a filtration whose quotients are locally free and flat, by [BGO2, theorem 3.16] this is equivalent to say that $E$ is $1$-nflat. $\Box$
Remark. Using the notion of Numerically Flat Higgs bundle (H-nflat, for short) introduced in [BGO1], and $1$-Numerically Flat Higgs bundle ($1$-H-nflat, for short) introduced in [BGO2], and applying [BC, theorems 3.2 and 5.2] indeed of [DPS, theorem 3.2], one proves the following (partial) generalization to Higgs bundles case.

Let $(X,H)$ be a smooth complex projetive variety of dimension $d\geq2$, with a polarization $H$; let $\mathfrak{E}=(E,\phi)$ be a H-nef Higgs bundle of rank $r\geq2$ such that $\displaystyle\deg(E)=c_1(E)\cdot H^{d-1}=0$ and $c_2(E)\cdot H^{d-2}=0$. $\mathfrak{E}$ is a $1$-H-nflat Higgs bundle.

[BC] U. Bruzzo, A. Capasso, Filtrations of numerically flat Higgs bundles and curve semistable Higgs bundles on Calabi-Yau manifolds, arXiv:1904.10069 [math.AG]
[BGO1] U. Bruzzo and B. Graña Otero, Numerically Flat Higgs bundles, Commun. Contemp. Math. 9 (2007) 437-446
[BGO2] U. Bruzzo and B. Graña Otero, Metrics on semistable and numerically effective Higgs bundles, J. reine ang. Math. 612 (2007) 59-79.
[DPS] J.-P. Demailly, T. Peternell, M. Schneider - Compact complex manifolds with numerically effective tangent bundles, J. Algebraic Geom. 3 (1994) 295-345


text:
Q: How do I conditionally redirect referrers to different webpages? I am using a JavaScript "Count down then redirect" script for my website. I want to use something like http referer in the script attached below:
<script>
<!--

/*
Count down then redirect script
By JavaScript Kit (http://javascriptkit.com)
*/

//change below target URL to your own
var targetURL="www.domain.com";

//change the second to start counting down from
var countdownfrom=20;

var currentsecond = document.redirect.redirect2.value =
    countdownfrom + 1;

function countredirect() {
  if (currentsecond != 1) {
    currentsecond -= 1;
    document.redirect.redirect2.value = currentsecond
  } else {
    window.location = targetURL;
    return;
  }

  setTimeout(countredirect, 1000);
}

countredirect();
//-->
</script>

I want the script to work like:
If some one arrive from www.twitter.com, they will be redirected to www.domain.com/twitter.html after the count down.
If some one arrive from www.facebook.com, they will be redirected to www.domain.com/facebook.html after the count down.
If some one arrive from www.youtube.com, they will be redirected to www.domain.com/youtube.html after the count down.
I want to redirect 15-20 URL. Please help !! How can I do it ??

A: Simple:
var targetURL = /www\.xxx\.com/i.test(document.referrer) ?
    "www.domain-for-xxx.com" : "www.domain-for-yyy.com";

Multiple Referrers:
var targetUrl = "http://defaulturl.com/";
if (/www\.xxx\.com/i.test(document.referrer)) {
  targetUrl = "http://www.domain-for-xxx.com/";
} else if (/www\.yyy\.com/i.test(document.referrer)) {
  targetUrl = "http://www.domain-for-yyy.com/";
}
...


text:
Q: Would like to use generic base class as model for asp.net MVC view I have a viewmodel class foo that is a generic
public abstract class Base<T>

and its child types set the class when they inherit from it like this
public class Child : Base<Foo>

I would like to use them in a view as the model like
@model Base<T>

but i have heard this is not possible. I've seen people suggest putting dynamic in place of T, but that does not work unless i replace Foo with dynamic also. Is there any way to design the viewmodels like that? I suppose I could pass the Child object in the viewbag instead of the model, but i'd rather not do that if possible. EDIT: (that viewbag thing wouldn't actually work now that i think about it because i'd need to be able to cast it to a Base to use it as one, and that's basically the problem i'm having now)

A: You cannot write in View @model Base<T> cause it is not concrete Type. View cannot be typed with generic Type. But you can write
@model Base<Foo>

or
@model Base<dynamic>

If you show more about what properties in Base<T> i could give you more concrete advise.


text:
Q: Sum column values and show right below the column using label This is my gridview design.
 <asp:GridView ID="GridView1" runat="server" HorizontalAlign="Center" CellPadding="3"
                GridLines="Both" ShowFooter="True" CssClass="contentfont">
                <RowStyle Wrap="False" />
                <HeaderStyle Wrap="False" Height="25px" />
                <FooterStyle Forecolor="Black" BackColor="LightGray" />
            </asp:GridView>

After binding the columns from DB this grdiview has around 8 columns. Now I need to sum certain columns total values and show it right below the column by using labels. I can add footerrow with label if add, delete, edit and update functionality is required. Since the gridview is readonly and no updation is required, I am confused how to achieve this.
Query:
I am using this query to bind the grid. I need to sum all columns except first two in my select query.
command.CommandText = "select AppName, Year, RevisedValue, SalesProfit, Variance, MonthlyProfit, QuarterProfit, YearlyProfit from Reports

Can anyone help me solve this.

A: You are not specifying how you store your data, so I'll just go with a datatable, which will be called DTable in my example.
Add the following ode to your markup:
<asp:GridView ID="GridView1" /* .... */ OnRowDataBound="GridView1_RowDataBound">
</asp:GridView>

EDIT From here I edited the post, to change it with code I tested in a sample project. I used the AdventureWorks Database to get some sample data. To make it quick I used Linq-to-Entites to get the data and bind it to the GridView.
After this I used the above mentioned OnRowDataBound="GridView1_RowDataBound to calculate the footer values.
    void Page_Load(Object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            using (var context = new AdventureWorks2008R2Entities())
            {
                var result = context.Products.Where(p => p.ListPrice != 0)
                                    .Select(x => new
                                    {
                                        Name = x.Name,
                                        ListPrice = x.ListPrice,
                                        StandardCost = x.StandardCost
                                    })
                                    .Take(5);
                GridView1.DataSource = result.ToList();
                GridView1.DataBind();
            }
        }

    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        using (var context = new AdventureWorks2008R2Entities())
        {
            var result = context.Products.Where(p => p.ListPrice != 0)
                                .Select(x => new
                                {
                                    Name = x.Name,
                                    ListPrice = x.ListPrice,
                                    StandardCost = x.StandardCost
                                })
                                .Take(5);
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[1].Text = result.ToList().Sum(x => x.ListPrice).ToString();
                e.Row.Cells[2].Text = result.ToList().Sum(x => x.StandardCost).ToString();
            }
        }
    }

Output:

*Note: * This code is far from optimal, because I am querying the database twice. Please don't use it in productive code. It is probably better to get the data, store it in a database and then calculate the Sum() of the needed fields in memory.


text:
Q: Airflow DAG failing - ERROR - HTTP Error 404: Not Found I'm a noob on Apache Airflow. Literally just started and I'm running into an error. I wrote my first dag, and am calling a Python script. It successfully ran and worked initially when I set it up, and I scheduled it to run once a day. I came to check it today and the dag failed with the message  ERROR - HTTP Error 404: Not Found.
Everything is kinda new to me so apologies if this is an easy fix, but I don't understand why I'm getting a 404 Error. I've tried restarting docker to see if it was a webserver issue but no luck.
Thanks for the help
Screenshot
DAG
from airflow.models import DAG
from datetime import datetime, timedelta
from airflow.operators.python_operator import PythonOperator
from covid_cases import covid_data

default_args = {
    'owner': 'airflow',
    'start_date': datetime(2020, 10, 4),
    'retries': 2,
    'retry_delay': timedelta(seconds=20)}

dag =  DAG(dag_id = 'covid_updates',
           default_args = default_args,
           schedule_interval = "0 4 * * *")

t1 = PythonOperator(task_id = 'covid_update',
                    python_callable = covid_data,
                    dag = dag)

t1

PythonOperator - covid_cases.py
def covid_data():
    """

    Overview:
    ---------
    Downloads the USA COVID data directly from John Hopkins CSSEGISandData.
    This function merges all data from most current date to earliest date (2020-4-11).
    Using this function a user can conduct time series analysis in how COVID
    increases/decreases in various states.

    Output:
    -------
    One uncleaned .csv file called "usa_covid_cases.csv"

    """
    from datetime import datetime, timedelta
    import pandas as pd
    from urllib.error import HTTPError

    # Set starting index
    i = 1

    # Earliest dataset available on GitHub
    start_date = datetime.strptime('2020-4-11', '%Y-%m-%d').date()

    # Pulling today's date minus 1 day due to delay posting on GitHub
    today = datetime.now().date() - timedelta(days=i)

    # Setting llist to store dataframe file names
    file_names = []

    # Looping until date is equal to earlist date = Start Date
    while not (start_date.day == today.day and start_date.month == today.month and start_date.year == today.year):

        # Extracting variables from current date
        day = today.day
        month = today.month
        year = today.year

        # Cleaning and converting values for formatting on GitHub URL link
        if day < 10:
            day = '0' + str(day)

        if month < 10:
            month = '0' + str(month)

        # Setting variable for each url
        url = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports_us/{}-{}-{}.csv'\
                    .format(month, day, str(year))

        try:
            # Reading each url as a datafra,
            df = pd.read_csv(url, error_bad_lines=False)
        except HTTPError as e:
            # handle the error (print, log, etc)
            continue
        finally:
            # Code moved here to prevent an endless loop
            # Subtracting the new index to increase 1 less day from the current date
            today = datetime.now().date() - timedelta(days=i)

        # Saving each dataframe into the empty list
        file_names.append(df)

        # Increasing the index by 1
        i += 1

    # Once while loop ends - concat all the files into a single dataframe
    new_df = pd.concat(file_names)

    # Save output into new csv file
    new_df.to_csv('usa_covid_cases.csv')

A: From the logs, the error happens when you are trying to read data from a URL and that URL does not exists.
pd.read_csv(url, error_bad_lines=False) #Line 50 of covid_data.py

A: I just took a look at the GitHub repo and the earliest dataset is from 04-12-2020.
To prevent failing DAGs from possible deleted datasets you can wrap your pd.read_csv() in a try except block, like this:
# Import the HTTPError (error from you screenshot)
from urllib.error import HTTPError
...

try:
    # Reading each url as a datafra,
    df = pd.read_csv(url, error_bad_lines=False)
except HTTPError as e:
    # handle the error (print, log, etc)
    continue
finally:
    # Code moved here to prevent an endless loop
    # Subtracting the new index to increase 1 less day from the current date
    today = datetime.now().date() - timedelta(days=i)

 # Saving each dataframe into the empty list
 file_names.append(df)

 # Increasing the index by 1
 i += 1

...


text:
Q: .NET Core / Kubernetes - SIGTERM, clean shutdown I'm trying to verify that shutdown is completing cleanly on Kubernetes, with a .NET Core 2.0 app.
I have an app which can run in two "modes" - one using ASP.NET Core and one as a kind of worker process.  Both use Console and JSON-which-ends-up-in-Elasticsearch-via-Filebeat-sidecar-container logger output which indicate startup and shutdown progress.
Additionally, I have console output which writes directly to stdout when a SIGTERM or Ctrl-C is received and shutdown begins.
Locally, the app works flawlessly - I get the direct console output, then the logger output flowing to stdout on Ctrl+C (on Windows).
My experiment scenario:

*

*App deployed to GCS k8s cluster (using helm, though I imagine that doesn't make a difference)

*Using kubectl logs -f to stream logs from the specific container

*Killing the pod from GCS cloud console site, or deleting the resources via helm delete

*Dockerfile is FROM microsoft/dotnet:2.1-aspnetcore-runtime and has ENTRYPOINT ["dotnet", "MyAppHere.dll"], so not wrapped in a bash process or anything

*Not specifying a terminationGracePeriodSeconds so guess it defaults to 30 sec

*Observing output returned

Results:

*

*The API pod log streaming showed just the immediate console output, "[SIGTERM] Stop signal received", not the other Console logger output about shutdown process

*The worker pod log streaming showed a little more - the same console output and  some Console logger output about shutdown process

*The JSON logs didn't seem to pick any of the shutdown log output

My conclusions:

*

*I don't know if Kubernetes is allowing the process to complete before terminating it, or just issuing SIGTERM then killing things very quick.  I think it should be waiting, but then, why no complete console logger output?

*I don't know if console output is cut off when stdout log streaming at some point before processes finally terminates?

*I would guess that the JSON stuff doesn't come through to ES because filebeat running in the sidecar terminates even if there's outstanding stuff in files to send

I would like to know:

*

*Can anyone advise on points 1,2 above?

*Any ideas for a way to allow a little extra time or leeway for the sidecar to send stuff up, like a pod container termination order, delay on shutdown for that  container, etc?

A: SIGTERM does indeed signal termination.  The less obvious part is that when the SIGTERM handler returns, everything is considered finished.
The fix is to not return from the SIGTERM handler until the app has finished shutting down.  For example, using a ManualResetEvent and Wait()ing it in the handler.

A: I've started to look into this for my own purposes and have come across your question over a year after it was posted... This is a bit late, but have you tried GraceTerm?
There is an associated NuGET package for this.
From the description...

Graceterm middleware provides implementation to ensure graceful shutdown of AspNet Core applications. The basic concept is: After application received a SIGTERM (a signal asking it to terminate), Graceterm will hold it alive till all pending requests are completed or a timeout occur.

I haven't personally tried this yet, but it does look promising.

A: Try add STOPSIGNAL SIGINT to your Dockerfile


text:
Q: Postgres - pycopg2 - which is better - opening new connection for each process (50+ processes running 24*7) or a connection pool I'm trying to connect with my postgresql database with multiple processes.
Which of them would be the most efficient among these two?
from psycopg2 import pool

pg_conn = pg.connect()

OR
pg_conn_pool = psycopg2.pool.ThreadedConnectionPool()