text:
Q: How do I include custom columns when fetching my records with Sequelize findAndCountAll method using the attribute property I have 2 tables in my database called 'Overdraft' and 'User' and I am trying perform a join operation using sequelize include property so that i can achieve something like this:
"message": "Fetched successfully",
"data": [
 ...
 {
  "id": 5,
  ...
  "uplineId": "a1234dc5-42ea-4385-a352-82f1a32aab57",
  "downlineId": "f1454996-ce3d-46fd-b5e3-a23123a5",
  "createdAt": "2022-04-27T06:03:30.000Z",
  "updatedAt": "2022-04-27T06:24:07.000Z",
  ...
  "uplineName": "Adele Tupac",
  "downlineName": "John Doe"
},
 {
  "id": 6,
  ...
  "uplineId": "a1234456-42ea-4385-a382-92f1a28aab57",
  "downlineId": "f1454886-ce3d-46fd-b5e3-a23123a5",
  "createdAt": "2022-04-27T06:03:30.000Z",
  "updatedAt": "2022-04-27T06:24:07.000Z",
  ...
  "uplineName": "Charles Edit",
  "downlineName": "John Doe"
 }
]

Here is what my User Table looks like:

id
userId
firstname
lastname

5
a1234dc5-42ea-4385-a352-82f1a32aab57
Adele
Tupac

6
a1234456-42ea-4385-a382-92f1a28aab57
Charles
Edit

7
f1454996-ce3d-46fd-b5e3-a23123a5
John
Doe

Here is what my Overdraft Table looks like:

id
transactionId
uplineId
downlineId

1
42ea-4385-a35
a1234dc5-42ea-4385-a352-82f1a32aab57
f1454996-ce3d-46fd-b5e3-a23123a5

2
1234-5678-c35
a1234456-42ea-4385-a382-92f1a28aab57
f1454996-ce3d-46fd-b5e3-a23123a5

Here is how I implemented it when I used Sequelize's findOne method and it worked:
Overdraft.findOne({
  where: { transactionId },
  attributes: {
    include: [
      [literal(`(SELECT CONCAT_WS(' ', User.firstname, User.lastname) AS fullname FROM ${this.dbName}.User INNER JOIN ${this.dbName}.Overdraft ON Overdraft.uplineId=User.userId WHERE Overdraft.transactionId='${transactionId}')`), 'uplineName'],
      [literal(`(SELECT CONCAT_WS(' ', User.firstname, User.lastname) AS fullname FROM ${this.dbName}.User INNER JOIN ${this.dbName}.Overdraft ON Overdraft.downlineId=User.userId WHERE Overdraft.transactionId='${transactionId}')`), 'downlineName'],
    ],
 },
});

But this doesn't work with findAndCountAll:
const offset = filters.page < 1 ? 1 : filters.page - 1;
const { limit } = filters;

Overdraft.findAndCountAll({
  distinct: true,
  where: {
   ...SEQUELIZE_QUERY_CONDITIONS
  },
  attributes: {
   include: [
     [literal(`(SELECT User.firstname FROM ${this.dbName}.User INNER JOIN ${this.dbName}.Overdraft ON Overdraft.uplineId=User.userId)`), 'uplineName'],
     [literal(`(SELECT User.firstname FROM ${this.dbName}.User INNER JOIN ${this.dbName}.Overdraft ON Overdraft.downlineId=User.userId)`), 'downlineName'],
   ],
  },
  order: filters.order.map((fieldAndOrderPair) => fieldAndOrderPair.split(':')),
  limit: limit && typeof limit === 'number' && !Number.isNaN(limit) ? limit : undefined,
  offset: offset * (limit || 0)
});

I got this error:
Subquery returns more than 1 row


text:
Q: Call syncState from fragment I'm trying to add navigation drawer to my FragmentList.
I set custom layout with frame container, all works nice, but there is no drawer toggle icon near app icon.
I think problem is that i do not override onPostCreate in my fragment, because, in a simple, i dont have it in fragment. But in on PostCreate i need to call toggle.SyncState.
How i can solve my problem?
Below my toggle implementation:
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, R.drawable.ic_drawer,
            R.string.app_name, // nav drawer open - description for
            // accessibility
            R.string.hello_world // nav drawer close - description for
    // accessibility
    ) {
        public void onDrawerClosed(View view) {
            getActivity().getActionBar().setTitle("Assigned");
            // calling onPrepareOptionsMenu() to show action bar icons
            getActivity().invalidateOptionsMenu();
        }

        public void onDrawerOpened(View drawerView) {
            getActivity().getActionBar().setTitle("Main");
            // calling onPrepareOptionsMenu() to hide action bar icons
            getActivity().invalidateOptionsMenu();
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
    getActivity().getActionBar().setHomeButtonEnabled(true);
    getActivity().getActionBar().setDisplayShowHomeEnabled(true);
    getActivity().getActionBar().setDisplayUseLogoEnabled(true);
    getActivity().getActionBar().setDisplayShowTitleEnabled(true);
    getActivity().getActionBar().setDisplayShowCustomEnabled(false);

A: Simply call it in onActivityCreated method. This method is called in fragment just before onPostCreate and after onCreate methods in Activity.

onActivityCreated(Bundle) tells the fragment that its activity has
  completed its own Activity.onCreate().

public class DrawerFragment extends Fragment {

    private ActionBarDrawerToggle drawerToggle;
    ...

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        drawerToggle.syncState();
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to display data from client service in ngx-wheel Angular I want to display the ngx-wheel using api but I'm having trouble displaying the data.
Here my Service :
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class RestServices {

restEndpoint:string = 'https://gorest.co.in/public/v2/users'
constructor(
    private httpClient: HttpClient
  ) { }

  async getServiceId() {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
      })
    }
  return this.httpClient.get<any[]>(this.restEndpoint, httpOptions)
}

Here my Component :
private subscription: Subscription | undefined;
items: any = []
ngOnInit(): void {
this.subscription = this._restService.getServices()
                                      .subscribe((res:any)=>{
                                          let item = res
                                          this.items = item.map((v:any) => ({
                                            text: v.name,
                                            id: v.id,
                                            textFillStyle: "white",
                                            textFontSize: "16"
                                          }));
                                        })
}
ngOnDestroy(): void {
   this.subscription?.unsubscribe()
}

Here for html
<ngx-wheel #wheel [width]='350' [height]='350' [spinDuration]='8' [disableSpinOnClick]='true' [items]='items'
                    [innerRadius]='10' [spinAmount]='10' [textOrientation]='textOrientation' [textAlignment]='textAlignment'
                    pointerStrokeColor='black' pointerFillColor='white' [idToLandOn]='idToLandOn' (onSpinStart)='before()'
                    (onSpinComplete)='after()'>

I hope to find the answer here. Thank you

A: First, you don't need await, async and ,toPromise()... remove them and simply return
return this.httpClient.get<any[]>(this.restEndpoint, httpOptions);

inside your component you should use your constructor only for simple data initialization: if you have to consume a rest api it is a better approach to move that piece of code inside the ngOnInit method:
items: any[] = []
constructor(private restService: RestService){}//dependency injection

ngOnInit(): void {
 this.restService.getServiceId().subscribe(response => {
    console.log('response success: ', response);
    this.items = response; //this may change a little based on your api
    console.log('items: ', this.items);
 }, errorLog => {
    console.log('response error: ', errorLog)
 });
}

The above solution is valid, you can enrich it by adding a *ngIf="isLoaded" on your html element and set to true the isLoaded INSIDE subscribe method. but if you prefer you can do the following in the component.ts
items$: Observable<any> = EMPTY;
constructor(private restService: RestService){}//dependency injection
ngOnInit(): void {
 this.items$ = this.restService.getServiceId();
}

then, in your html it would change to the following:
<ngx-wheel #wheel *ngIf="items$ | async as items" [width]='350' [height]='350' [spinDuration]='8' [disableSpinOnClick]='true' [items]='items'
                [innerRadius]='10' [spinAmount]='10' [textOrientation]='textOrientation' [textAlignment]='textAlignment'
                pointerStrokeColor='black' pointerFillColor='white' [idToLandOn]='idToLandOn' (onSpinStart)='before()'
                (onSpinComplete)='after()'>


text:
Q: how do i assign a default value if no argument is passed in + python How do I write letter = sys.argv[2] or 'a' so that if there is no argument passed in a will be assigned to letter.  So basically I want the default value of letter to be a unless something is passed in. If something is to be passed in, I want that to be assigned to letter
this is my simple program:
$ cat loop_count.py
import sys

def count(word,letter):
        for char in word:
                if char == letter:
                        count = count + 1
        return count
                                # WHAT I WANT
word = sys.argv[1] or 'banana'  # if sys.argv[1] has a value assign it to word, else assign 'banana' to word
letter = sys.argv[2] or 'a'     # if sys.argv[2] has a value assign it to letter, else assign 'a' to letter

print 'Count the number of times the letter',letter,' appears in the word: ', word

count = 0
for letter in word:
        if letter == 'a':
                count = count + 1
print count

This is me running the program by passing it 2 arguments pea and a
$ python loop_count.py pea a
Count the number of times the letter a  appears in the word:  pea
1

I want the arguments to be optional so I was hoping the letter arguemt does not have to be passed.  So how do I write letter = sys.argv[2] or 'a' so that if there is no argument passed in letter will be assigned to a
This is me running the program with only one argument, I want the arguments to be optional.
$ python loop_count.py pea
Traceback (most recent call last):
  File "loop_count.py", line 10, in <module>
    letter = sys.argv[2] or 'a'
IndexError: list index out of range

A: You can use the following:
letter = sys.argv[2] if len(sys.argv) >= 3 else 'a'

sys.argv[2] is the 3rd element in sys.argv, this means that the length of sys.argv should be at least 3. If it is not >= 3, we assign 'a' to letter


text:
Q: Computing integral with variable bounds in MATLAB Consider the following MWE in MATLAB:
f = @(t) integral(@(x) x.^2,0,t);
integral(f,0,1);

This yields the error
Error using integral (line 85) A and B must be floating-point scalars.

(and a bit more). How do I fix this? Is this even possible? I think the problem is the variable upper bound.

A: If you want to use integral then set 'ArrayValued' to true otherwise t would be an invalid end point in integral(@(x) x.^2,0,t). So it would be:
f = @(t) integral(@(x) x.^2,0,t);
integral(f,0,1,'ArrayValued',true)

% ans =
%     0.0833

Alternately, since you're doing double integration, so use the function dedicated for this purpose i.e. integral2. For your example, it would be:
f = @(t,x) x.^2 ;
integral2(f,0,1,0, @(t) t)

% ans =
%     0.0833

If you have Symbolic Math Toolbox, you can also use int as int(expr,var,a,b) but it would be slower. For your case, it would be:
syms x t;
f = x.^2;
req = int(int(f,x,0,t),t,0,1);    % It gives 1/12
req = double(req);                % Convert to double if required


text:
Q: Did English "borrow" or "inherit" from Proto-Germanic (PGmc)? I wanted to see a cage match on this question, which started in the comments to this answer.  We were left with these opposing assertions:

PGmc was never homogeneous. Most English expressions "borrowed" since
  Old English (OE), also trace to Proto-Indo-European (PIE) with
  analogous Germanic cognates. Heretical as it seems, a straight line
  through Germanic stock is an arbitrary designation of English, which
  "borrowed" more from PGmc than any other source.

Or,

PGmc was probably quite homogeneous at some point: it obviously
  developed far and wide, but at the starting point when it first
  separated itself enough to be a thing of its own, it must have been
  quite homogeneous. Yes, all IE languages have borrowed extensively
  from their neighbors (most of which have been IE also). There are lots
  of English borrowings that have analogous Germanic cognates, yes. But
  there are also lots of words which have not at any point since PIE been borrowed in any ancestral stage of what is now English from any other language: they are purely inherited.

The latter, if true, seems to argue that modern English does have a core that was inherited.  The former makes the more facile (but perhaps correct) argument that no modern language can claim direct inheritance; only different proportions of "borrowing" from an evolving patchwork of languages.
What are the strong arguments on each side?

A: It depends on how you look at 'inheriting' and 'borrowing'.
Allow me to start off by quoting from ScotM's comment above:

I would say that the inheritance is a discrete form of one generation borrowing from a former generation.

This is arguably a logical way of looking at it: after all, we all acquire language by emulating others and using words that we hear others use around us, and in that sense, we all do in a way 'borrow' our entire lexicon (and grammar) from others. I would argue, though, that acquisition would be a better term for this.
In that case, inheriting and borrowing become two distinct ways of acquiring new words (two more are deriving and inventing), which I personally think makes more sense. The difference between the two is simply whether we acquire the word as a word in our own language from the community of speakers that we acquire our lexicon and grammar from in general (inheriting); or whether we acquire it from speakers of a different language as a word in a different language (borrowing).
That's usually a relatively easy distinction to make, though there are of course many cases where you learn a word as a word in your own language by hearing it used all around you; but you and everyone else is still aware that the word is native to a different language (like, say, smorgasbord in English). Still, I would say English speakers who learn the word smorgasbord from their linguistic community nowadays are inheriting an English word, because they are not taking a Swedish word out of its native context in Swedish, as heard used by Swedish speakers, and applying it to English: they're simply using a word that their own, English-speaking community uses when speaking English.
Contrast this with a scenario like the expat community in China, where certain Chinese words are in frequent use, but always with the distinct knowledge that these are local, Chinese words that are currently being added to the variety of English spoken in that community—they are not words used by the wider English-speaking community, and speakers are still acutely aware of their Chineseness. For example, when taking pictures, many foreigners living in China take over the Chinese practice of saying 茄子 qiézi 'aubergine' instead of 'cheese'; but they do so knowing that they are 'humouring' the local practice, and that when they're not in China, they should say 'cheese', which is the inherited picture-taking word.
(There are grey areas as well, of course: 'language' is notoriously ill-defined, and dialects and sociolects constantly borrow from each other as well—but is it really 'borrowing' when Brits start to use apartment instead of flat more and more commonly, for example?)

That's looking at it from the perspective of each individual user of a language 'borrowing' or 'inheriting' a word. Another perspective is from the language or the word itself, and that's different. The history of each word in a language goes back much, much further than any individual speaker (excepting brand new words, like fleek, which have not been part of the English language very long at all), and it makes sense and is useful to make a similar distinction between inherited and borrowed words in the language as well as in each individual speaker.
The difference is that once a word is borrowed into one language from a different language, its status will always be 'borrowed'. Once its been in the language for a while, new speakers learn the word in an inhereted manner, and from their point of view, it will be an inherited word; but from the viewpoint of the language itself, it was borrowed at some point, so it's still a loan word in origin. This is similar to how migrations work in many places: you may have been born in a particular community, but your great-grandparents moved there from somewhere else, so you're still a blow-in, as our Antipodean friends call it.
Of course, the further back in history you have to go to see the borrowing, the less sense it makes to call something a borrowing. Nobody will think it odd to call smorgasbord or joie de vivre loan words, both being still quite un-English sounding and having been part of the English lexicon for only a bit over a hundred years. But some may find it strange to consider get or egg loan words, though they were borrowed (from Old Norse) no more than a millennium ago. And even most linguists will find it a stretch to call seven a loan word in Modern English, though it is almost unanimously accepted that Proto-Indo-European borrowed the word (*septḿ̥-) from Proto-Semitic some five or six thousand years ago.
Even so, there remain a group of words that do not, at any stage of the language that we have any kind of access to (i.e., back to Proto-Indo-European), appear to have been borrowed from a different language; words that have been acquired by speakers of the language stages that led up to Modern English entirely through inheriting, never through borrowing. These are the words that historical linguists call truly inherited words.


text:
Q: Derive words from string based on key words I have a string (text_string) from which I want to find words based on my so called key_words. I want to store the result in a list called expected_output.
The expected output is always the word after the keyword (the number of spaces between the keyword and the output word doesn't matter). The expected_output word is then all characters until the next space.
Please see the example below:
text_string = "happy yes_no!?.  why coding      without      paus happy yes"
key_words = ["happy","coding"]

expected_output = ['yes_no!?.', 'without', 'yes']

expected_output explanation:
yes_no!?.        (since it comes after happy. All signs are included until the next space.)
without          (since it comes after coding. the number of spaces surronding the word doesn't matter)
yes              (since it comes after happy)

A: You can solve it using regex. Like this e.g.
import re

expected_output = re.findall('(?:{0})\s+?([^\s]+)'.format('|'.join(key_words)), text_string)

Explanation

*

*(?:{0}) Is getting your key_words list and creating a non-capturing group with all the words inside this list.

*\s+? Add a lazy quantifier so it will get all spaces after any of the former occurrences up to the next character which isn't a space

*([^\s]+) Will capture the text right after your key_words until a next space is found

Note: in case you're running this too many times, inside a loop i.e, you ought to use re.compile on the regex string before in order to improve performance.

A: We will use re module of Python to split your strings based on whitespaces.
Then, the idea is to go over each word, and look if that word is part of your keywords. If yes, we set take_it to True, so that next time the loop is processed, the word will be added to taken which stores all the words you're looking for.
import re

def find_next_words(text, keywords):
  take_it = False
  taken = []
  for word in re.split(r'\s+', text):
    if take_it == True:
      taken.append(word)
    take_it = word in keywords
  return taken

print(find_next_words("happy yes_no!?.  why coding      without      paus happy yes", ["happy", "coding"]))

results in ['yes_no!?.', 'without', 'yes']


text:
Q: How to export functions from a custom hook The basic structure of my hook:

const useMyHook = () => {
  const func1 = (): boolean => { ... }
  const func2 = (type: "type1" | "type2"): boolean => { ... }
  const func3 = (): boolean => { ... }

  return {
    func1, func2, func3
  }
}

export default useMyHook

I'm currently using it like this, which works in dev, but breaks my build.
import useMyHook from "../hooks/useMyHook";

const { func1 } = useMyHook()

const handleSubmit = (e: React.FormEvent) => {
  e.preventDefault();
  const isValid = func1();

  if (isValid) {
  // do more things
  }
}

return (
  <form>...</form>
)

When running yarn build, I am faced with this error:
Objects are not valid as a React child (found: object with keys {func1, func2, func3}). If you meant to render a collection of children, use an array instead.
My attempt at solving this was to export my custom hook functions in an array, as the error seemed to suggest.
  return [
    func1, func2, func3
  ]

And using it like this:
  const [ func1 ] = useMyHook();
  const isValid = func1();

TypeScript is not happy with this:
An argument for 'type' was not provided.

But this is confusing, because func1 does not accept a type argument as func2 does.
Questions

*

*Is there some way I work around this build-time error and export the { } of functions? This feels like the cleanest approach.

*If there is no way to achieve 1, how can I properly use the exported array of functions without my types being misread?


text:
Q: How to write a tab.gz file using pyspark dataframe I have a Pyspark dataframe and I want my output files to be in tab.gz extensions.
df.write\
        .option("delimiter", "\t")\
        .option("codec", "org.apache.hadoop.io.compress.GzipCodec")\
        .save(
            s3_directory,
            format='csv',
            header=True,
            emptyValue='',
            compression="gzip"
    )

this creates the output files as
part-xyz.csv.gz
how can I change the config to make it save as  part-xyz.tab.gz please?

A: As much as "tab.gz" looks like a typo, have you tried to specify "path" argument:
file_path = s3_directory + "part-xyz.tab.gz"
df.write\
    .option("delimiter", "\t")\
    .option("codec", "org.apache.hadoop.io.compress.GzipCodec")\
    .save(
        path=file_path,
        format='csv',
        header=True,
        emptyValue='',
        compression="gzip"
)


text:
Q: Is there a way in TS to autocomplete all the properties of unknow object structure returned from a Promise? I am new in TS world and I was wondering if it's possible to make a request to an API end point which returns an object with a structure which I don't know.
Can TS help me with the properties in advance with autocompletion?

A: If you don't know what the response object structure will be, you can use unknown as a basis and afterwards check the type of the result.
const result = (await response.json()) as unknown;

You will need a list of all the possible types you expect the response to be if you want autocompletion to work, because TS needs some definition of what the object could be.
Let's say I expect one of two types:
interface Person {
  id: number
  name: string;
  age: number;
}

and
interface Message {
  id: number
  text: string;
  sender: string;
  receiver: string;
}

You can use type guards to check what the actual result is. First you have to create your custom type guards, like this:
const isPerson = (person: Person | unknown): person is Person =>
  !!(person as Person)?.id || !!(person as Person)?.name || !!(person as Person)?.age;

and
const isMessage = (message: Message | unknown): message is Message =>
  !!(message as Message)?.id || !!(message as Message)?.text || !!(message as Message)?.sender || !!(message as Message)?.receiver;

Now you can use these type guards to know if the result is one of these defined types:
if (!!isPerson(result)) {
  // result is of type Person and autocompletion will work with properties of type Person
} else if (!!isMessage(result)) {
  // result is of type Message and autocompletion will work with properties of type Message
} else {
  // result is of type unknown and further checks will need to done
}


text:
Q: Do function calls within a function's argument list deepen the stack? When calling F(argument_expression), is argument_expression evaluated before pushing the stack for F?
For example, when calling F(G(H(arg))), does the compiler first push the stack for H, evaluate H, pop, then push the stack for G, etc? Or does it first push the stack for F, then for G, then for H, then pop back up 3 layers?
Also, is one way any faster than the other?

A: You've actually asked two orthogonal questions.
The concept of evaluation is pitched at the programmer's vantage point, and in this case, is well-defined by the C++ standard.  Yes, the argument to a function is always evaluated before that function is called.
However, the standard does not specify how the stack should be managed.  The compiler is free to take either of the approaches that you've suggested.  Of course, it may take a third option, which is to directly inline one or more of your nested functions.  There are probably other alternatives.

A: The parameters are fully evaluated before the called function can run, per spec.
I.e.: In your example, H(arg) will be fully evaluated before G(result of H(arg)) can run, etc.
At any given time you'll have one-level depth of the stack.

A: No, they are evaluated sequentially (only one frame-deep in this case).

A: It depends what do you mean by pushing H,G,F
Essential it happens this way
The return value of F is pushed and a temp variable then G is pushed (its return value and a temp variable ) finally all H is pushed, evaluated and poped. then G and finally F.
for performance if you use argument expression it should be faster. since it should not contain any jumps.


text:
Q: in clojure why isn't x identified if defined as [x] argument and then referenced as x? in code block? (defn boolean [x]
  (if (x? nil or false)
    (false)
    (true)))

I get

Unable to resolve symbol: x? in this context

x is an argument to the function and I just reference it, what did I miss?

A: Because x and x? are two different names. Your function could be simply written as
(defn boolean [x]
  (if x true false))

A: In clojure x? is the name of a symbol, not a symbol x and an operator ?. The compiler is telling you that you didn't define any variable or binding named x?.
In addition (false) and (true) call the boolean values as a function. That will throw a run time error. Use false and true instead.

A: I am not sure what is your problem (you didn't ever defined x?) but you could implement it in Clojure like this
(defn boolean [x]
  (not
    (or
      (nil? x)
      (false? x))))

(boolean 1)
#=> true
(boolean nil)
#=> false
(boolean false)
#=> false
(boolean [])
#=> true

Or more implicit solution
(defn boolean [x]
  (if x
    true
    false))

Or your approach:
(defn boolean [x]
  (if (or (nil? x) (false? x))
    false
    true))


text:
Q: WiFi adapter over serial port? I just recently came into possession of a old AST Premium Exec notebook computer. The only ports it has are a serial port and a parallel port and it runs DOS. I thought that with the serial port I could get WiFi working with a Serial-to-USB adapter or something and write some software on the DOS end to communicate with the adapter. Anybody know of any WiFi adapters that go over a serial port / work over a serial port?
Note: I have a USB WiFi adapter anyway so if that could work that would be good.
Thanks,
Isaac

A: I remember the first time I woke up from a 20 year sleep. :)  Anyway, there are several RS232 to Wifi adapters out there (another).  I've never tied one tho!


text:
Q: Close activity after successful user login (WebView) I'm making an Android mobile application which uses 3rd party login page for authentication loaded in WebView. When user enters username/pass and submits the form it saves cookie on user's device and redirects user to the next page.
What I want to do here is to prevent that redirection, close login activity after the cookie has been saved to user's device and display main activity to the user.
Any advice? Thanks.

A: Thanks for quick answers. I figured out solution that worked for me.
As I explained in the question, after user enters credentials and successfully login next page is loaded in WebView. What I did is to catch that redirection and close the activity. Something like this:
myWebView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.contains("https://www.someservice/nextpage")) {
            Intent i = new Intent(LogInActivity.this,MainActivity.class);
            startActivity(i);
            finish();
        }
        return true;
    }
}

I'm not sure if this is the most elegant solution but it's short and it work for me :)

A: Use a seperate activity for WebView..
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
    if (url.contains("http://redirectingurl")
        finish();  // close activity
    else
        view.loadUrl(url);

    return true;
}

I didnt try, but i think this will work.
For refernce

A: I'm not able to post all codes right now but I'll give you the idea.
in onPageFinished(Webview view, STring url) method you can inject a javascript file that controls login button in that 3rd party web page, something like this:
@Override
public void onPageFinished(WebView view, String url) {
    view.loadUrl("javascript:/injection.js content will be here/")

}

injection.js
document.getElementById("loginButton").addEventListener("click", function(){
    //login process copy paste without redirection
    loginMethod()
});

And add a JavaScriptInterface to webView:
mWebView.addJavascriptInterface(new JsInterfaceLogin(this.getContext()), "MY_APP");

JsInterfaceLogin:
public class JsInterfaceLogin {

    private final Context context;

    public JsInterfaceLogin(Context context) {
       this.context = context;
    }

    @JavascriptInterface
    public void ___loggedIn___(String toast) {
       Toast.makeText(context, ""+toast, Toast.LENGTH_SHORT).show();
       //When user logged in, you can detect it in here
    }
}

And in loginMethod() function in injection.js, call this after login process:
window.MY_APP.___loggedIn___("test")

A: After successful user login will close login activity and start a new activity
It is working Smoothly.... and I applied.
package com.loginsql.afterloginmove;

import android.content.Intent;
import android.os.Bundle;

import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private WebView webViewLogin;
    private TextView loginTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webViewLogin = findViewById(R.id.myWebView);
        loginTextView = findViewById(R.id.logintext);

        webViewLogin.setWebViewClient(new WebViewClient());
        webViewLogin.setWebChromeClient(new WebChromeClient());

        webViewLogin.getSettings().setJavaScriptEnabled(true);

        webViewLogin.loadUrl("https://myweblogin.com/auth/index");

        webViewLogin.setWebViewClient(new WebViewClient()
        {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains(url)) {
                    Intent i = new Intent(MainActivity.this, DashboardActivityActivity.class);
                    startActivity(i);
                    finish();

                }
                return true;
            }
        });
    }
}


text:
Q: Question about the infinite products of formal power series I need a proof for this:

Let $(F_j)_{j\ge 0}$ be a sequence of formal power series.
The infinite product $\prod_{j\geq0}(1+F_j(x))$, where $F_j(0)=0$, converges if and only if $\lim_{j\to\infty}\deg F_j(x)=\infty$.
In this case, the series $G_I(x)=\prod_{i\in I}F_i$, with $|I|< \infty $ is summable and $\prod_{j\geq0}(1+F_j(x))= \lim_{n \to \infty} \prod_{j=0}^n (1+F_j(x)) = \sum_{|I| \leq 0}G_I(x)$.

I don't even know where to begin. Thanks in advance.

A: It's just a matter of thinking of things systematically. You have your infinite product, let's think of it as $(1+F_1)(1+F_2)(1+F_3)\cdots\,$, but let's write the factors beneath each other, one per line. Now: what does the infinite product look like if it's expanded? You certainly have one factor that's gotten by running down the left-hand column, all $1$'s. This is your $\sum_{|I|=0}G_I$. Then look at how many ways there are of going all the way down that left column, but taking just one "monomial" $F_i$ from the second column. Of course the totality of these is $F_1+F_2+F_3+\cdots\,$. This is your $\sum_{|I|=1}G_I$. Now how many ways can you get a contribution where you take two factors from the second column? You'll have all possible $F_iF_j$'s, added up, to get something like $F_1F_2+F_1F_3+F_1F_4+F_2F_3+\cdots\,$. This will be your $\sum_{|I|=2}G_I$. And so it goes. All you need to do is fill in the details. It may help to think about what the full expansion is when there are only finitely many of the $F$'s.


text:
Q: Cannot find module that is defined in tsconfig `paths` I am trying to setup aliases for my mock server. Whenever I try to compile ts files, it returns error that it couldn't find proper modules even though those are defined in tsconfig,json->paths
Folder structure:
├── server
│   └── src
│       └──/json
├── src
│   └──/modules
├── tsconfig.json

Here is my tsconfig.json
{
    "compilerOptions": {
        "baseUrl": "./src",
        "experimentalDecorators": true,
        "jsx": "react",
        "lib": [
            "dom",
            "es2015",
            "es2015.promise"
        ],
        "module": "commonjs",
        "moduleResolution": "node",
        "noImplicitAny": true,
        "noUnusedLocals": true,
        "esModuleInterop": true,
        "paths": {
            "@project/app/modules/*": [
                "modules/*"
            ],
            "@project/server/data/*": [
                "../server/src/json/*"
            ]
        },
        "sourceMap": true,
        "target": "es5"
    },
    "exclude": [
        "node_modules",
        "tools"
    ]
}

Error:
Error: Cannot find module '@project/server/data/accounts/accountsList'

A: The following tsconfig.json worked for me, allowing import { foo } from '@models' etc for the associated index.ts barrel exports:
{
    "baseUrl": "./",
    "paths": {
      "@environment": ["./src/environments/environment.ts"],
      "@models": ["./src/app/shared/models/index.ts"],
      "@services": ["./src/app/shared/services/index.ts"]
    },
}

A: TypeScript path properties can reliably resolve typings-based URLs such as an interface.
The intended behaviour is to allow TypeScript to resolve type information[1]
Most us seem to be experiencing that a path pointing to an actual dependency wont always compile as we expect. This is apparently by design despite what the doc says:
{
  "compilerOptions": {
    "baseUrl": ".", // This must be specified if "paths" is.
    "paths": {
      "jquery": ["node_modules/jquery/dist/jquery"] // This mapping is relative to "baseUrl"
    }
  }
}

Read this great breakdown by Mitchell Simoens - Why TypeScript Paths Failed Me
Found this after setting up @paths to my shared folders throughout the app.
During compilation TS paths where breaking and actual builds were missing all sorts of modules. On a personal note this is a huge disappointment that TS can't reliably resolve dependencies this way.

A: TLDR;
npm i -D module-alias
and add the mappings from your tsconfig.json paths to _moduleAliases in your package.json
"_moduleAliases": {
  "foo": "dist"
}

As for the reasoning behind it, using "jsx": "react" in conjunction with "module": "commonjs" prevents you from being able to use absolute imports even though baseUrl and paths are configured correctly. A detailed discussion can be found in this issue.

A: well, after suffering a few hours, I got a solution,
I am using the ts-node package, and I got the same error Error: Cannot find module '@modules/logger'
You need to add ts-node configuration in the tsconfig.json file.
You can get more infor at ts-node
Here is my tsconfig.json file look like
{
    "ts-node": {
        // Do not forget to `npm i -D tsconfig-paths`
        "require": ["tsconfig-paths/register"]
    },
    "compilerOptions": {
        "lib": ["es5", "es6", "es7"],
        "target": "es2017",
        "module": "commonjs",
        "moduleResolution": "node",
        "rootDir": "src",
        "outDir": "build",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "esModuleInterop": true,
        "noImplicitAny": true,
        "strict": true,
        "resolveJsonModule": true,
        "allowJs": true,
        "sourceMap": true,

        "baseUrl": ".",
        "paths": {
            "@modules/*": ["src/modules/*"],
            "*": ["node_modules/*"]
        },

    },
    "include": ["src/**/*"]
}

and here is my package.json
"_moduleAliases": {
        "@modules": "build/modules",
        "@core": "build/core"
    }

You need to install this package as a dependency of module alias npm i module-alias

A: I put it both in webpack resolve alias and the tsconfig paths and it worked that way :)

module.exports = {   //...   resolve: {
    alias: {
      Utilities: path.resolve(__dirname, 'src/utilities/'),
      Templates: path.resolve(__dirname, 'src/templates/'),
    },   }, };

A: You can easily define simple path resolver like this:
loader.js
const Module = require("module");
const originalResolveFilename = Module._resolveFilename;
const tsConfig = require("./tsconfig.json");
const Path = require("path");
const fs = require('fs');
if (!tsConfig.compilerOptions || !tsConfig.compilerOptions.baseUrl)
    throw "Compiler options Base URL (compilerOptions.baseUrl) is required in tsconfig.json.";
const basePath = Path.resolve(tsConfig.compilerOptions.baseUrl, tsConfig.compilerOptions.outDir);

//Inspired by https://github.com/dividab/tsconfig-paths but that one does not work with VS Code
Module._resolveFilename = function (request) {
    if (tsConfig.compilerOptions && tsConfig.compilerOptions.paths[request] instanceof Array) { //Supports only without wildchars, but enough for our use
        const pathsTried = [];
        for (const reqPath of tsConfig.compilerOptions.paths[request]) {
            const modPath = Path.resolve(basePath, reqPath) + ".js";
            if (fs.existsSync(modPath)) return modPath;
            pathsTried.push(reqPath);
        }
        throw "Module " + request + " not found, paths tried: " + pathsTried.join(", ");
    }
    const ret = originalResolveFilename.apply(this, arguments);
    return ret;
};

and than reference it from VS Code's launch.json like this:
"configurations": [
{
  "type": "node",
  "request": "launch",
  "name": "Node.js",
  "runtimeArgs": ["-r", "./loader.js"],
  "program": "${workspaceFolder}/run.ts",
  "preLaunchTask": "tsc: build - tsconfig.json",
  "outFiles": [
    "${workspaceFolder}/out/**/*.js"
  ]
}]

It does not support patterns in paths but with this stub it can be added.
tsconfig.json should look like this:
"compilerOptions": {
    "outDir": "out", //required
    "moduleResolution": "node",
    "baseUrl": "./", //required
    "paths": {
        "InjectableStub": [ //requires 2
            "myapp/myfolder/mymodule", //used in runtime
            "./myfolder/mymodule //used in compile-time
        ]
    }
}

at least for me tsc creates sub-folder in name of the root folder in out that's why the 2 registrations.

A: When u use the bare variant with just tsconfig.json ("typescript": "^4.4.4") without any third party libraries:

*

*Add baseUrl.

"baseUrl": ".",

*Add paths.

"paths": {
      "@app/assets/*": ["src/assets/*"],
      "@app/components/*": ["src/components/*"],
      "@app/features/*": ["src/features/*"],
      "@app/hooks/*": ["src/hooks/*"],
      "@app/navigation/*": ["src/navigation/*"],
      "@app/services/*": ["src/services/*"],
      "@app/utils/*": ["src/utils/*"]
}

*Add package.json with a name of alias for each path inside the destination folder.

// src/assets/package.json
{
  "name": "@app/assets"
}

A: I faced the same issue. I tried many things and now i got a solution which works for me. I have an app and a library in my angular project. I want to use a library alias in my app.
I have following structure:
├── projects
│   └── lib
│       └── src
│           └── lib
│               └── lib-service.ts
│           └── index.ts
│   └── app
│       └──tsconfig.app.json
├── tsconfig.json

In the tsconfig.json file in the root folder I have following paths defined:
"paths": {
  "my-lib": [
    "projects/lib/src/index.ts"
  ]
}

There I access an index.ts file where I define the things I want to export. In my case the index.ts file has the following entry:
export * from './lib/lib-service';

Now I can access the LibService in components of the app with the help of the alias:
import {LibService} from 'my-lib';

It is important to mention that this soloution don't work if I add this entry to the tsconfig.app.json file. I think the IDE (in my case WebStorm) searches for aliases in the tsconfig.json file which is close to the root folder. So I extend the tsconfig.json in my tsconfig.app.json
"extends": "../../tsconfig",

Maybe you have to restart you IDE to remove the red underline of the import line.
I hope this solution works for you. You have to to a little bit more of setup work because you have to define the classes you want to export in the index.ts file. But in case of using libraries it make sense because you don't want to make everything visible for other app.

A: After battling it for some time I figured it out you need to include all directories using tsconfig-paths in your main tsconfig.json. Working version of your tsconfig.json file could be
{
    "compilerOptions": {
        "baseUrl": ".",
...
        "paths": {
            "@project/app/modules/*": [
                "src/modules/*"
            ],
            "@project/server/data/*": [
                "server/src/json/*"
            ]
        },
    },

    "include": [
        "./src",
        "./server"
    ],
}

A: My issue was that my tsconfig.app.json which extended my tsconfig.json was overriding the "baseUrl" option incorrectly. I removed it from the tsconfig.app.json so it did not have a "baseUrl" or "paths". In the end, my tsconfig.json had the following compiler options:
"baseUrl": "src/",
"paths": {
    "@shared/*": ["shared/*"],
    "@client/*": ["client/*"],
    "@server/*": ["server/*"]
}

A: If your having this issue with Jest then you can edit your jest.config to include a moduleNameMapper that would looks something like this:
{

  "moduleNameMapper": {
    "^@project/server(|/.*)$": "<rootDir>/server/$1"
  }
}

So this uses a regex to map the import @project/server... to the path "<rootDir>/server/$1"

A: Check angular.json file if its "build" -> "options" config has "tsConfig" option set as your changed tsconfig file.
"architect": {
  "build": {
    "builder": "@angular-devkit/build-angular:browser",
    "options": {
      "outputPath": "dist",
      "tsConfig": "src/tsconfig.app.json",
      "polyfills": "src/polyfills.ts",
      "stylePreprocessorOptions": {
        "includePaths": [
          "src/assets/styles"
        ]
      },
............

The above one is my angular.json file, and I configured it to use tsconfig.app.json.
In this case, "paths" should be added in tsconfig.app.json file.

A: There are some issues with path, for example if you set the path to the root let us say:
@root/src and in src there is no index.ts that has a default, then this might fail...
It's a bit tricky per what I found.

A: just add  "moduleResolution" : "Node",  on tsConfig

A: Just Use this in your tsconfig.json
"moduleResolution": "node",


text:
Q: Make a graph in pydot from decision tree in sklearn Python I expected this code to create a PDF graph of the tree.
from sklearn import datasets,tree
import StringIO
import pydot
from sklearn.externals.six import StringIO

iris = datasets.load_iris()

clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris['data'],iris['target'])

dot_data = StringIO.StringIO()
tree.export_graphviz(clf, out_file=dot_data)
graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph.write_pdf("iris.pdf")

Is there a way to do what I want though pydot? This way is a dead end.
Explaining the problem further, the code fails in the last statement. graph.write_pdf() is looking for Graphviz in graph.progs() but there are no entries there. The error message says Graphviz executable not found.
Anyhow I was able to pdf file by invoking the dot.exe command in a DOS terminal, but it would be better to use pydot to do this step.

A: After you add the PATH variable it looks like you are importing StringIO then calling StringIO.StringIO()
try just calling:
dot_data = StringIO()

Works for my python 2.7.6 Win7 x64 environment with the pydot and graphviz error: Couldn't import dot_parser, loading of dot files will not be possible fix.

A: The problem appears to be that your PATH statement does not include a reference to GraphViz - so your pydot module can't find it.  To verify that this is the problem, type "PATH" from your Windows cmd window.

C:\Users\Ron Fredericks>path PATH=C:\Program
  Files\CollabNet\Subversion Client;C:\Program Files
  (x86)\Graphviz2.34\bin

The simplified path output above shows that my system includes Graphviz in my PATH. If you don't have Graphviz in your PATH, look for the answer on how to get Graphviz installed into your user path here at SO searching on this string "Graphviz executable not found"


text:
Q: Custom user model can't login after creation I'm trying to login with an account with my new custom user model. My superuser I created with my user model logs in just fine. However when I create non superuser account through the admin panel and try to login with exact credentials it fails.
Here is my code:
accounts/models.py
from django.db import models
from django.contrib.auth.models import (
    AbstractBaseUser,
    BaseUserManager,
    PermissionsMixin,
)

# Create your models here.

class UserManager(BaseUserManager):
    def create_user(self, email, first_name, last_name, company, phone, is_active=True, is_admin=False, is_staff=False, is_dealer=False, password=None):
        if not email:
            raise ValueError("Users must have an email address")
        if not password:
            raise ValueError("Users must have a password")
        if not first_name:
            raise ValueError("Users must have a first name")
        if not last_name:
            raise ValueError("Users must have a last name")
        if not company:
            raise ValueError("Users must have a company")
        if not phone:
            raise ValueError("Users must have a phone number")
        user_obj = self.model(
            email = self.normalize_email(email)
        )
        user_obj.set_password(password)
        user_obj.first_name = first_name
        user_obj.last_name = last_name
        user_obj.company = company
        user_obj.phone = phone
        user_obj.admin = is_admin
        user_obj.staff = is_staff
        user_obj.dealer = is_dealer
        user_obj.active = is_active
        user_obj.save(using=self._db)
        return user_obj

    def create_superuser(self, email, first_name, last_name, company, phone, password=None):
        user = self.create_user(
            email,
            first_name,
            last_name,
            company,
            phone,
            password=password,
            is_admin=True,
            is_staff=True
        )
        return user

    def create_staff_user(self, email, first_name, last_name, company, phone, password=None):
        user = self.create_user(
            email,
            first_name,
            last_name,
            company,
            phone,
            password=password,
            is_staff=True
        )
        return user

    def create_dealer_user(self, email, first_name, last_name, company, phone, password=None):
        user = self.create_user(
            email,
            first_name,
            last_name,
            company,
            phone,
            password=password,
            is_dealer=True
        )
        return user

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=255, unique=True)
    first_name = models.CharField(max_length=255, blank=True, null=True)
    last_name = models.CharField(max_length=255, blank=True, null=True)
    company = models.CharField(max_length=255, blank=True, null=True)
    phone = models.CharField(max_length=255, blank=True, null=True)
    active = models.BooleanField(default=True) # can login
    online = models.BooleanField(default=False)
    admin = models.BooleanField(default=False)
    staff = models.BooleanField(default=False)
    dealer = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)

    USERNAME_FIELD = 'email'
    # USERNAME_FIELD and password are required by default
    REQUIRED_FIELDS = ['first_name', 'last_name', 'company', 'phone']

    objects = UserManager()

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

    def get_full_name(self):
        return f"{self.first_name} {self.last_name}"

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_admin(self):
        return self.admin

    @property
    def is_staff(self):
        return self.staff

    @property
    def is_dealer(self):
        return self.dealer

    @property
    def is_active(self):
        return self.active

    @property
    def is_online(self):
        return self.online

Also if you see anything else wrong with my model please let me know.


text:
Q: Reloading view after search crashes the app I'm making an app that has a view with UITableView with UISearchDisplayController. Data comes from NSFetchedResultsController. All is working fine: I get the data, table view is being populated, search works great. The only problem is that if I search and then click on "Cancel"(without deleting the text from the UISearchBar) and then go back to previous view controller and then go to that same view with UITableView and UISearchDisplayController it crashes with this being written to the log:

2012-01-06 16:46:37.559 MyApp[9586:207] *** -[SomeRandomViewController
  controllerWillChangeContent:]: message sent to deallocated instance
  0x778d060

I've googled and stackoverflowed for that error, tried to release NSFetchedResultsController variable, did set it and its' delegate to nil, but nothing helps.
And if I do some search, then delete the text from the search bar and then tap on "Back" and go back to that view it works just fine.
A bit of the code:
- (void)viewDidUnload {
  [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
  [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];

  self.fetchedResultsController = nil;
  self.searchFetchedRC = nil;
  [super viewDidUnload];
}

- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller {

  self.fetchedResultsController = nil;
  [self fetchedResultsController];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
  self.searchDisplayController.searchBar.text = @"";
  self.searchDisplayController.active = NO;
  [self searchDisplayControllerWillEndSearch:self.searchDisplayController];
  return YES;
}

Any help will be appreciated
Update
Without zombies the output to the log is:

2012-01-09 09:25:48.128 Butane[17325:207]
  -[UITextMagnifierTimeWeightedPoint controllerWillChangeContent:]: unrecognized selector sent to instance 0x8251dc0

Update 2
Dealloc method:
- (void)dealloc {
  [self.mySearchDisplayController release];
  self.mySearchDisplayController.delegate = nil;
  self.mySearchDisplayController = nil;
  [self.fetchedResultsController release];
  self.fetchedResultsController.delegate = nil;
  self.fetchedResultsController = nil;
  [self.searchFetchedRC release];
  self.searchFetchedRC.delegate = nil;
  self.searchFetchedRC = nil;
  [self.tableView release];
  [textView release];
  self.tableView = nil;
  self.tableView.delegate = nil;
  [super dealloc];
}

mySearchDisplayController = UISearchDisplayController

fetchedResultsController and searchFetchedRC = NSFetchedResultsControllers

tableView = UITableView

textView = [HPGrowingTextView][1]

Update 3
Inspired by the answer of Tia I've set FRCs and their delegates to nil in searchDisplayControllerWillEndSearch method. Works so far so good
- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller {

  self.fetchedResultsController.delegate = nil;
  self.fetchedResultsController = nil;
  self.searchFetchedRC.delegate = nil;
  self.searchFetchedRC = nil;
  [self fetchedResultsController];
}

A: - (void)dealloc {
  //[self.mySearchDisplayController release];
  self.mySearchDisplayController.delegate = nil;
  self.mySearchDisplayController = nil;
  //[self.fetchedResultsController release];
  self.fetchedResultsController.delegate = nil;
  self.fetchedResultsController = nil;
  //[self.searchFetchedRC release];
  self.searchFetchedRC.delegate = nil;
  self.searchFetchedRC = nil;
  //[self.tableView release];
  [textView release];
  self.tableView.delegate = nil;
  self.tableView = nil;
  [super dealloc];
}

You are over-releasing your properties, as setting it to nil already release it for retained properties. I tried to remove extra releasing code by commenting them out, so please try to replace your dealloc with my code above and see.

A: I had a similar problem as my VC implemented the UISearchBarDelegate protocol and searchBarTextDidEndEditing: was being called after I'd dismissed the VC in the tableView:didSelectRowAtIndexPath: method.
I fixed it with:
self.searchDisplayController.delegate=nil;
self.searchDisplayController.searchBar.delegate=nil;

before the
[self dismissModalViewControllerAnimated:YES];


text:
Q: vegas.js plugin not working with overlay Recently I came across vegas.js plugin
  not sure how to use it...  Read the documentation but did not get a clear idea. http://vegas.jaysalvat.com/documentation/setup/
    Did the steps accordingly but no images are showing.

A: Could you try using firebug/inspector, click on console, and paste in what is going on. There will be errors in there. Also could you post how you're including the file? Post with your html if possible.

A: As you can se in the settings section the overlay property goes inside of the vegas function.

$(document).ready(function() {
  var imagecollection = [{
      src: 'https://i.stack.imgur.com/oURrw.png'
    },
    {
      src: 'http://i.imgur.com/SZPjHwz.jpg'
    },
    {
      src: 'http://www.boyter.org/wp-content/uploads/2016/08/ChJzv9lUYAA9D5E.jpg'
    },
    {
      src: 'https://pbs.twimg.com/media/Cg0x8vnXEAEB2Le.jpg'
    }
    /* Slideshow not working? Check your image links. */
  ];

  $("#ShowSlideShowHere").vegas({
    slides: imagecollection,
    transition: 'fade',
    preloadImage: true,
    timer: true,
    shuffle: true,
    delay: 5000,
    animation: 'kenburns',
    cover: true,
    overlay: 'https://media.istockphoto.com/vectors/isolated-christmas-falling-snow-overlay-on-transparent-background-vector-id628152000'
  });
});
<!DOCTYPE html>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/vegas/2.4.0/vegas.min.css">

sadasdasdas


text:
Q: Bug in TensorFlow reduce_max for negative infinity? Using tf.maximum with negative inf inputs as follows:
tf.maximum(-math.inf, -math.inf).eval()

gives the expected result -inf
However, tf.reduce_max, on the same inputs:
tf.reduce_max([-math.inf, -math.inf]).eval()

gives: -3.40282e+38 which is the min float32.
For positive infinity inputs, both functions result in inf. Is this a bug?

A: This turned out to be a bug in Eigen which has already been fixed and pushed out to TensorFlow.
The issue can be tracked here:
https://github.com/tensorflow/tensorflow/issues/4131


text:
Q: jQuery Mapster with dynamic data from php We are building a website and for that we need to include an image map from a country and when you highlight a provence it needs to show some content below the map.
For this we are using jquery mapster (I'm not really a jquery programmer, so maybe you could help).
All works with the code below, but only when the content is on 1 line.
For example groningen: "
Groningen

test</test>", <-- This works
For example
groningen: "
Groningen

test</test>",

This does not work.
Below you will find my jquery code

Output
var data = {
    groningen: "
Groningen

test</test>",
    friesland: "
Scholen in de regio Groningen

    \n

    \n
AOC Terra, Groene school
Adres
Winsum
Telefoonnummer
Naam directeur

    \n
De Bolster
Adres
Groningen
Telefoonnummer
Naam directeur

    \n
De Catamaran, School voor Praktijkonderwijs
Adres
Stadskanaal
telefoonnummer
Naam directeur

    \n
Dollard College locatie De Flint

    \n
",
    };

A: Javascript  and by extension jQuery strings cannot go over a line boundry, you need to either add 2 strings together with a + or replace newlines with \n
Do some manipulation of your php array so each newline is replaced with \n
$UpdatedString = str_replace("\n", '\\n', $FieldValue);


text:
Q: Dynamic access to Mongodb field The problem is how to access to fiels value in .find() request.
I tried to access with this.cteatedAt, but it not working.
const bestJobs = await Job.find({
  $and: [
    {category: 'Programming'},
    {status: 'best'},
    {8 : {$lte: moment().utc().diff(this.cteatedAt, 'minutes')}}
  ]
}).sort({createdAt: -1});

Have no results.
My collection:
bestJobs
{
    "_id": "5d455d85232b540b1c05dcaf",
    "jobTitle": "new",
    "category": "Programming",
    "jobType": "Full-Time",
    "tags": "Гейм-дизайн, левел-дизайн",
    "headOffice": "Moscow",
    "region": "Moscow",
    "applyLink": "sdfsdfds",
    "jobDescription": "dsffdsfdsfsd",
    "name": "ARKPlay",
    "companyStatement": "вааццауцуа",
    "logo": "logo\9-08-03T10-10-13.351Z6mnO8wnjYwQ.jpg",
    "websiteURL": "выаоывадоывадыавод",
    "email": "arkhannanov@gmail.com",
    "aboutCompany": "wfwfewfejl",
    "status": "best",
    "payment": false,
    "createdAt": "2019-08-03T10:10:13.389Z",
    "updatedAt": "2019-08-03T10:10:13.389Z",
    "__v": 0
}

A: You did not mention that, but I assumed you are trying to find jobs which where created 8 minutes ago or later. If createdAt type is Date you can do it using the following code:
const _8minutesAgo = moment().utc().subtract(8, 'minutes').toDate()
const bestJobs = await Job.find({
  category: 'Programming',
  status: 'best',
  createdAt : {$gt: _8minutesAgo}
}).sort({createdAt: -1})


text:
Q: Mapping an array within an array with Reactjs I'm trying to get some map over some data and render it as a card style component.
The data structure is as follows within my user array (all fake data)

and this is the code...
import React from "react";
import OverlayContent from "./OverlayContent";
import { onCountryClick } from "../Scene3D/AppSignals";
import Portal from "./Portal";
import "./style.scss";

class Overlay extends React.Component {
  constructor(props) {
    super(props);
    this.state = { overlay: false, users: [], country: [] };
    this.openOverlay = this.openOverlay.bind(this);
    this.closeOverlay = this.closeOverlay.bind(this);
  }

  openOverlay() {
    this.setState({ overlay: true });
  }

  closeOverlay() {
    this.setState({ overlay: false });
  }

  onCountryClick = (country, users) => {
    this.openOverlay();
    this.setState({ users: [users], country });
  };

  componentDidMount() {
    this.onCountrySignal = onCountryClick.add(this.onCountryClick);
  }

  componentWillUnmount() {
    this.onCountrySignal.detach();
  }

  render() {
    const country = this.state.country;
    const users = this.state.users;

    console.log(users);
    return (

        {this.state.overlay && (
          <Portal>

{country}

              {users &&
                users.map(user => (

                      {user.favouriteQuote}

                ))}
              <button className="btn" onClick={this.closeOverlay}>
                Close
              </button>

          </Portal>
        )}

    );
  }
}

export default Overlay;

When mapping on this user array it doesn't appear to give me access to the actual user data I need. Is it because I have an array within an array?

A:  onCountryClick = (country, users) => {
  this.openOverlay();
  this.setState({ users: [users], country });
 };

Is users an array? If so remove the brackets here or map through the first element. users[0].map()


text:
Q: trying to move colums .very new to html and css

body {
  text-align:center;
}
hi{
  font-family:arial;
  font-size:50px;
  background-color:blue;

}

h2{
  color:#ff0000;
  font-size:20px;
}

#image{
  height:300px

}

#image-caption{
  font-family:Algerian;
}

#tribute-link{
  font-size:20px;
}

#tribute-info{
  line-height:23px;
  text-align:left;
  column-count:3;

}

  <hi id= "title">kobe bryant
  </hi>

Famous basketball player

    <img id="image" src="data:image/jpeg;base64,[encoded data, 13544 characters]"  alt ="kobe bryant"

Former Basketball player with several awards

 Kobe Bean Bryant (/ˈkoʊbiː/ KOH-bee; August 23, 1978 – January 26, 2020) was an American professional basketball player. A shooting guard, Bryant entered the National Basketball Association (NBA) directly from high school, and played his entire 20-season professional career in the league with the Los Angeles Lakers. Bryant won five NBA championships, was an 18-time All-Star, 15-time member of the All-NBA Team, 12-time member of the All-Defensive Team, was named the 2008 NBA Most Valuable Player (MVP), and was a two-time NBA Finals MVP winner. Widely regarded as one of the greatest players of all time,[3][4][5][6] he led the NBA in scoring during two seasons, ranks fourth on the league's all-time regular season scoring and all-time postseason scoring lists.

Bryant was the son of former NBA player Joe Bryant. He attended Lower Merion High School in Pennsylvania, where he was recognized as the top high-school basketball player in the country.
 Upon graduation, he declared for the 1996 NBA draft and was selected by the Charlotte Hornets with the 13th overall pick; the Hornets then traded him to the Lakers. As a rookie, Bryant earned himself a reputation as a high-flyer and a fan favorite by winning the 1997 Slam Dunk Contest, and he was named an All-Star by his second season. Despite a feud with teammate Shaquille O'Neal, the pair led the Lakers to three consecutive NBA championships from 2000 to 2002.In 2003, Bryant was accused of sexual assault. Criminal charges were brought and then dropped after the accuser refused to testify, with a civil suit later settled out of court. Bryant denied the assault charge but admitted to a sexual encounter, and issued a public apology, but the allegations were considered to have harmed his public profile and led to the loss of several sponsorships.

After the Lakers lost the 2004 NBA Finals, O'Neal was traded and Bryant became the cornerstone of the Lakers. He led the NBA in scoring during the 2005–06 and 2006–07 seasons. In 2006, he scored a career-high 81 points; the second most points scored in a single game in league history, behind Wilt Chamberlain's 100-point game in 1962. Bryant led the team to two consecutive championships in 2009 and 2010, and was named NBA Finals MVP on both occasions. He continued to be among the top players in the league through 2013, when he suffered a torn Achilles tendon at age 34. Although he recovered from that injury, he suffered season-ending injuries to his knee and shoulder, respectively, in the following two seasons. Citing his physical decline, Bryant retired after the 2015–16 season.

At 34 years and 104 days of age, Bryant became the youngest player in league history to reach 30,000 career points. He became the all-time leading scorer in Lakers franchise history on February 1, 2010, surpassing Jerry West. Bryant was also the first guard in NBA history to play at least 20 seasons. His 18 All-Star designations are the second most all time, while it is the record for most consecutive appearances as a starter. Bryant's four All-Star MVP Awards are tied with Bob Pettit for the most in NBA history. At the 2008 and 2012 Summer Olympics, he won two gold medals as a member of the U.S. national team. In 2018, he won the Academy Award for Best Animated Short Film for his 2017 film</>

       Click Here For more Information

thats  what ihave done so far

thast what i have done so far. i have been trying to edit and try new things like creating separate divs for the column before i edit but wont work.i still very new to this.like 2days into html and css

The image below is that of a tribute page of a pic and 3 columns. I tried to wrap the columns in divs in  order to move them separately but it is not working. I tried position as well but still won't resolve my issue.


text: Q: How to create collapsible menu ,with menu icon in wpf mvvm I need collapsible menu in wpf mvvm,where onclick of menu icon the menu should be shown and again onclick menu should be hidden. The icon should be in one view and the menu displaying should be in another view. Can anyone help me in this...


text:
Q: yii2 после генирации gii crud нет доступа к сгенерированному коду? yii2 после генирации  gii crud нет доступа  к сгенерированному коду.
Создание CRUD:
"Model Class": app\models\Comment
"Controller Class": app\controllers\CommentController

перехожу на адрес
http://myblog.loc/comment

и браузер показывает "Not Found"
(ubuntu, apache2, права на все папки в myblog.loc - 777)
пример отсюда: http://rgblog.ru/page/sozdanie-sajta-na-yii-framework-20-chast-2
В чем может быть причина, почему оно не работает?


text:
Q: Firestore pagination and Vue I am trying to create Infinite scrolling pagination with Vuejs and Firestore.
So far I have been able to get the code to work in the sense that it is fetching and showing the data as intended. However when the new query is constructed after scrolling down to the bottom, the original query with the same values loads again.
It seems that I am doing something wrong with the startAfter() method, which is supposed to get the next values in the firestore query.
This is my setup:
  setup() {
    const latestDoc = ref(null);
    const getFoods = ref([]);

    onMounted(() => {
      runQuery(latestDoc.value);
    });

    const runQuery = async (doc) => {
      let q = query(collection(db, "foods"), orderBy("title"), startAfter(doc), limit(5));

      const querySnapshot = await getDocs(q);

      querySnapshot.forEach((doc) => {
        getFoods.value.push({ ...doc.data(), id: doc.id });
      });
    };

    const loadData = (InfiniteScrollCustomEvent) => {
      InfiniteScrollCustomEvent.target.complete();

      latestDoc.value = getFoods.value.length - 1;

      runQuery(latestDoc.value);
    };

    return { getFoods, optionsOutline, loadData, latestDoc, runQuery };
  },

Can anyone tell me what I am doing wrong?


text:
Q: PHPunit ignoring Laravel's .env database config I am building an API with Laravel 5.4 and writing integration tests using PHPunit, all within a Vagrant vm. The tests are working fine and is connecting to the database via credentials defined in .env.testing which is being called via line $app->loadEnvironmentFrom('.env.testing'); in tests/TestCase.php.
This is all fine, but when I try to run this on the staging server, PHPunit is not calling the environment file and therefore cannot run the tests. I have found that the tests work when populating the variables into phpunit.xml, however I don't like this approach because the values are hardcoded into this file.
Can anyone help me determine what may be different between these two environments for them to behave differently?


text:
Q: CRC lookup table generated in C always gives different results I'm trying to create a function that generates a CRC lookup table. I'm working with an 8051 micro-controller, and I'd rather do the table lookup method but at the same time, I'd rather have my computer generate the values which then I can load directly into the micro-controller. Most of this source code has been borrowed from: http://www.rajivchakravorty.com/source-code/uncertainty/multimedia-sim/html/crc8_8c-source.html
I only added in the "main" function
#include <stdio.h>
#define GP  0x107
#define DI  0x07

static unsigned char crc8_table[256];
static int made_table=0;

static void init_crc8()
{
  int i,j;
  unsigned char crc;
  if (!made_table) {
    for (i=0; i<256; i++) {
      crc = i;
      for (j=0; j<8; j++)
        crc = (crc << 1) ^ ((crc & 0x80) ? DI : 0);
      crc8_table[i] = crc & 0xFF;
    }
    made_table=1;
  }
}

void crc8(unsigned char *crc, unsigned char m)
{
  if (!made_table)
    init_crc8();
  *crc = crc8_table[(*crc) ^ m];
  *crc &= 0xFF;
}

int main()
{
  unsigned char crc[1];
  crc8(crc,'S');
  printf("S=%x\n",crc[0]); //different hex code almost every time
  crc8(crc,'T');
  printf("T=%x\n",crc[0]); //different hex code almost every time
  return 0;
}

When I execute the program, I expected the same values on the screen but the hex codes after the printed equals signs changed on nearly every program execution.
What can I do to correct that issue? I don't want to be collecting incorrect CRC values.

A: *

*crc[0] is not initialized. You need crc[0] = 0; or *crc = 0; before calling crc8() with crc. Then you won't get random answers coming from the random initial contents of crc[0].

*You don't need the *crc &= 0xff; in crc8(). If char is eight bits, then it does nothing. If you have an odd architecture where char is more than eight bits, then you need to do *crc = crc8_table[((*crc) ^ m) & 0xff]; to assure that you don't go outside the bounds of the table. (Only the low eight bits of m will be used in the CRC calculation.) The contents of the table have already been limited to eight bits, so in any case you don't need a final & 0xff.

*You may need a different initial value than zero, and you may need to exclusive-or the final CRC value with something, depending on the definition of the CRC-8 that you want. In the RevEng catalog of CRC's, there are two 8-bit CRCs with that polynomial that are not reflected. Both happen to start with an initial value of zero, but one is exclusive-ored with 0x55 at the end. Also the CRC definition you need may be reflected, in which case the shift direction changes and the polynomial is flipped. If your CRC-8 needs to be interoperable with some other software, then you need to find out the full definition of the CRC being used.

*Passing a pointer seems like an odd choice here. It would be more efficient to just pass and return the CRC value directly. E.g. unsigned crc8(unsigned crc, unsigned ch) {, which would apply the eight bits in ch to the CRC crc, and return the new value. Note that you do not need to make the CRC value a char. unsigned is generally what C routines most efficiently take as an argument and return. In fact usually the first argument is passed in a register and returned in the same register.

*Usually one computes a CRC on a message consisting of a series of bytes. It would be more efficient to have a routine that does the whole message with a loop, so that you don't need to check to see if the table has been built yet for every single byte of the message.

A: In the main, crc[0] has not been initialized.  As a result, in crc8, *crc in the expression (*crc) ^ m is uninitialized, hence your random values.
Fix: initialize crc[0].  Something like
unsigned char crc[1] = { 0 };


text:
Q: How do I add a list of figures/tables for Latex/PDF output? I trying to add a list of figures and a list of tables into a PDF document generated by Sphinx+Latex. So far I found nothing useful..
Would somebody know how to do it? Thanks

A: To whom it may interest, I found out that Sphinx can pass native commands to Latex.
Thus the following Sphinx source code snippet does what I was looking for:
..raw:: latex

  \listoffigures
  \listoftables

A: When rendering with the sphinx document class manual, adding raw LaTeX commands
..raw:: latex

  \listofequations
  \listoffigures
  \listoftables
  \listof{literalblock}{List of Code Blocks}

puts the lists onto pages with arabic numerals instead of pages with roman numerals.
Here is a LaTeX snippet, which goes into the LaTeX preamble setup in conf.py. It redefines the  command sequence \sphinxtableofcontents:
latex_elements['preamble'] = r'''
%% --------------------------------------------------
%% |:sec:| add list of figures, list of tables, list of code blocks to TOC
%% --------------------------------------------------
\makeatletter
\renewcommand{\sphinxtableofcontents}{%
  %
  % before resetting page counter, let's do the right thing.
  \if@openright\cleardoublepage\else\clearpage\fi
  \pagenumbering{roman}%
  \begingroup
    \parskip \z@skip
    \tableofcontents
  \endgroup
  %
  %% addtional lists
  \if@openright\cleardoublepage\else\clearpage\fi
  \addcontentsline{toc}{chapter}{List of Figures}%
  \listoffigures
  %
  \if@openright\cleardoublepage\else\clearpage\fi
  \addcontentsline{toc}{chapter}{List of Tables}%
  \listoftables
  %
  \if@openright\cleardoublepage\else\clearpage\fi
  \addcontentsline{toc}{chapter}{List of Code Blocks}%
  \listof{literalblock}{List of Code Blocks}%
  %
  \if@openright\cleardoublepage\else\clearpage\fi
  \pagenumbering{arabic}%
}
\makeatother
'''

If there should not be any entries in the table of contents for the lists, remove the \addcontentsline commands.


text:
Q: iOS Swift Buttons Not Responding In View I have written a class where a view is displayed that has a UITextView and a couple of buttons.  Everything works except the buttons don't respond to a tap.  Below is what I think is the relevant code in my class:
class FullPrompt:UIViewController {
    var canceledPressedCallback:(()->()?)?=nil
    var okPressedCallback:((_ txt: String)->()?)? = nil
    var popupView = UIView()
    var field = UITextView()
    var parentView = UIView()

    func prompt(_ message:String,view: UIViewController,numberInput: Bool, callback: @escaping (_ txt: String)->()) {
        prompt(message, view: view, numberInput: numberInput, callback: callback,cancelCallback: nil,defaultText: "")
    }

    func prompt(_ prompt:String,view: UIViewController,numberInput: Bool, callback: @escaping (_ txt: String)->(), cancelCallback: (()->())?,defaultText: String) {
        canceledPressedCallback=cancelCallback
        okPressedCallback=callback

        let cancelButton=UIButton(frame: CGRect(x: 10, y: y, width: 70, height: 32))
        cancelButton.setTitle("Cancel", for: .normal)
        cancelButton.addTarget(self, action: #selector(cancelButtonPressed(_:)), for: .touchUpInside)
        popupView.addSubview(cancelButton)
        let okButton=UIButton(frame: CGRect(x: 210, y: y, width: 70, height: 32))
        okButton.setTitle("Ok", for: .normal)
        okButton.setTitleColor(UIColor.blue, for: .normal)
        okButton.addTarget(self, action: #selector(okButtonPressed(_:)), for: .touchUpInside)
        popupView.addSubview(okButton)
        view.view.addSubview(popupView)
    }

    func cancelButtonPressed(_ sender: UIButton ) {
        popupView.removeFromSuperview()
        if canceledPressedCallback != nil {
            canceledPressedCallback!()
        }
    }

    func okButtonPressed(_ sender: UIButton) {
        popupView.removeFromSuperview()
        okPressedCallback!(field.text)
    }
}

What am I doing wrong?

A: I got it figured out.  My mistake was adding a view property (popupView) within my class.  Since my class was a subclass of UIViewController, I needed to add my subviews to the view property of the class, not create another view.  So, basically, wherever I add adding something to popupView, I just replaced it with self.view.  They the buttons worked fine.


text:
Q: How to make Xcode create xib files as file.xib instead of sourcecode.xib? My xcode start to cracking up and now it always open xib files with XML source editor instead of in interface builder.
I know how to fix this problem for specific file by changing file type at the "Get Info" of the file.
My question is how can i solve the root of the problem and make xcode to make xib files as file.xib by default?
Thanks!

A: In XCode preferences under "File Types" make sure xib files are opened using "External Editor (Currently Interface Builder)"


text:
Q: AWK compare two files, match first field, paste data, and more I have this script, it is used to compare the first field from two files,
I want it to ignore cases, tried to add a line IGNORECASE = 1; but doesn't seem to work,
can you tell how to ignore cases?
BEGIN {
   FS=OFS=";"
}

FNR==NR {
   array[$1]=$2
   next
}

{
   if ($1 in array) {
      print $1";" array[$1]";" $2
   }

   else {
      if ($2 in values) {
         print  $1";" "only_at_" FILENAME ";" $0 " same path    as " values[$2]
      }
      else {
         print  $1";" "only_at_" FILENAME ";" $0 " no path  found"
      }
   }
   values[$2]=$1
}

Let's say I have
File1
\\FILE48\bucan-CFAN_Subcommittees;\\SERVER24\dfs\Shared\can\CFAN Subcommittees

File2
\\file48\bucan-CFAN_Subcommittees;/fs8_100g/FILE48/BU/can/CFAN Subcommittees
\\FILE58\userhome_e;/fs1_100g/FILE58/userhome

Expected output
\\FILE48\bucan-CFAN_Subcommittees;\\SERVER24\dfs\Shared\can\CFAN Subcommittees;/fs8_100g/FILE48/BU/can/CFAN Subcommittees
\\MLISFILE58\userhome_e;only_at_file2;\\MLISFILE58\userhome_e;/fs1_100g/MLISFILE58/userhome no path found

A: Pretty simple with the join command
join -t';' -i -j 1 -o 1.1,1.2,2.2 File1 File2

Using ";" as a field separator, case-insensitively join the two files on field 1, and output the first and second fields from file1 and the 2nd field from file2.
If you really want awk, this will do the same thing:
awk '
   BEGIN {FS=OFS=";"}
   NR==FNR {key[tolower($1)] = $0; next}
   tolower($1) in key {print key[tolower($1)], $2}
 ' file1 file2


text:
Q: node distance=6mm and 25mm? In Brent Longboroughs TikZ-based Easy-maintenance flowchart, somewhere one can read:
node distance=6mm and 25mm

What does and 25mm mean here?

A: When positioning a node  e.g. below right of another node, the first value is the vertical shift, and the second value is the horizontal shift. See section 17.5.3 Advanced Placement Options in the manual.
A small example:
\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{positioning}

\begin{document}

\begin{tikzpicture}
\draw (0,0) grid (3,3);
\node (a) at (0,0) {A};

\node [above right=of a] {B};

\begin{scope}[node distance=2cm and 1cm] %default is 1cm and 1cm
\node [above right=of a] {C};
\end{scope}
\end{tikzpicture}
\end{document}

A: They are spaces for rows and columns. See what happens when we change it to node distance=2mm and 20mm.


text:
Q: how to make many buttons on box with shadow I want to know how to make box with non sharm edges with colorful shodows, in box many colors without borders. please help me. I am new in programing.
I want you to give me some examples to how to do it . In this its your and mine both benifit if you forgot something than it might help you to recap. Thank you

A: is this what you want to achieve

body{
  display:flex;
  justify-content:center;
  align-items:center;
  height:100vh;
}

.box{
  height:100px;
  width:100px;
  background-color:red;
  border-radius:20px;
  box-shadow: 0 0 20px rgba(0,255,0);
}


text:
Q: Are there any inflection points? $$
F(x) =
\begin{cases}
x^2 & x \le 0 \\
0 & 0 \le x \le 3 \\
-(x-3)^2 & x>3
\end{cases}
$$
My question is does this function have any points of inflection? Double Derivative at $x=0,3$.Thus the necessary condition is satisfied for all points such that $0 \le x \le 3$.
But, i have also read that the third derivative at x is not equal to 0 is also regarded as a sufficient condition, which is fulfilled at $x=0,3$. Thus, which sufficient condition should hold and which points should be regarded as inflection points?

A: An inflection point occurs at points of the domain at which the function changes concavity. The second derivative at an inflection point may be zero but it also may be undefined. If we look at the second derivative for your function
$$
F''(x) =
\begin{cases}
2 & x < 0 \\
0 & 0 \le x \le 3 \\
-2 & x>3
\end{cases}
$$
then $F''(x) > 0$ when $x < 0$ and $F''(x)<0$ when $x>3$. We know that the function $F(x)$ is concave up when $F''(x) > 0$ and concave down when $F''(x) < 0$. Therefore, it is clear that $F(x)$ is concave up on $(-\infty,0)$ and concave down on $(3,\infty)$.
But, what about the interval $[0,3]$? Since $F(x)\equiv 0$ when $0\le x \le 3$, the second derivative is also zero. As $F(x)$ changes concavity at the end points we know that there must be at least one inflection point. Therefore, we must decide whether there is one inflection point or two inflection points.
Suppose that we assume that there are two inflection points. Then, we would need to show that the function changes concavity twice - there would be two intervals where it was concave up and one interval where it is concave down. Alternatively, the function could be concave down on two intervals and then concave up on one interval.
Your function is concave up on one interval and then concave down on another interval. In the interval between these two intervals, the function is neither concave up nor concave down. Hence, your function only changes concavity once.
So, $F(x)$ has one inflection point. If we plot the function on Desmos, then we see that this point of inflection occurs in the middle of the interval $[0,3]$.

Interestingly, the function $f(x)=x^3$ exhibits similar behavior. This function is concave up on $(0,\infty)$ and concave down on $(-\infty,0)$. It has one inflection point at $(0,0)$.


text:
Q: Introducing a new event to a conditional probability? How is this equation derived? I am trying to figure out how the first problem in the following document is produced.
http://www.stanford.edu/class/ee178/hw4sol.pdf
Problem 1

Note that each letter in the genome sequence is independent and uniformly choosen from (A,T,G,C}. To show that 2 is equivalent to 2', we must verify that the conditional probability of the next letter given the previous letter is the same in both cases.  By symmetry we only have to check the conditional probabilities $p(A\mid A)$ and $p(C \mid C)$ in each case.
Let $M$ be the event that their is a mutation. Then  $p(M)=p, p(M^c)=1-p$ For 2:
$$\begin{align}p(A\mid A) & = p(A\mid A,M)p(M) + p(A\mid A,M^c)p(M^c) \\ &= (0)p + (1)(1-p)\\ & = (1-p) \end{align}$$

$$\begin{align}p(C\mid A) & = p(C\mid A,M)p(M) + p(C\mid A,M^c)p(M^c) \\ &= (1/3)p + (0)(1-p)\\ & = p/3 \end{align}$$

I am not sure how this equation is derived.

A: Okay.  What we are talking about here is the probability of the next letter, $A_{n+1}$, given the previous letter, $A_n$ when a mutation event may or may not have taken place.  The author is just being lazy with notation (leaving off index).
It's basically:
$\begin{align} \operatorname{P}(A_{n+1} \mid A_n) & = \operatorname{P}(A_{n+1}\cap (M \cup M^c)\mid A_n) & \text{since } M, M^c\text{ are exhaustive} \\ & = \operatorname{P}(A_{n+1}\cap M\mid A_n)+ \operatorname{P}(A_{n+1}\cap M^c\mid A_n) & \text{since } M, M^c\text{ are mutually exclusive} \\ &= \operatorname{P}(A_{n+1}\mid M\cap A_n)\operatorname{P}(M) + \operatorname{P}(A_{n+1}\mid M^c\cap A_n)\operatorname{P}(M^c) & \text{by Conditional Probability}\end{align}$
Thus:
$\therefore \operatorname{P}(A_{n+1}\mid A_n) = \operatorname{P}(A_{n+1} \mid A, M)\operatorname{P}(M) + \operatorname{P}(A_{n+1}\mid A_n, M^c)\operatorname{P}(M^c)$
And likewise:
$\therefore \operatorname{P}(C_{n+1}\mid A_n) = \operatorname{P}(C_{n+1} \mid A, M)\operatorname{P}(M) + \operatorname{P}(C_{n+1}\mid A_n, M^c)\operatorname{P}(M^c)$


text:
Q: search for the presence of two strings in oracle database in a clob column? I have a clob column with a long string.
like "great job done today. good "
I want to retrieve all the records which has both the words great and good .
both the position is not fixed.

A: It's not clear what "which has both the words great and good " actually means.
If you mean you want to check if the string has both patterns of words, then it is simple as
where lower(col) like '%good%' AND lower(col) like '%great%'

If you mean they should contain true words good and great, then for simpler cases  something like should do
where ' ' || lower(col) || ' ' LIKE '% good %' AND ' ' || lower(col) || ' ' LIKE '% great %'

However, this will not match a sentence ending with the word and having a full stop. It gets lengthy if you want to simply use  LIKE to handle such scenarios.
REGEXP functions give more flexibility, but could be less performant.
WHERE REGEXP_LIKE ( s, '(^|\W)good(\W|$|\.)') AND REGEXP_LIKE ( s, '(^|\W)great(\W|$|\.)')

This searches for word boundaries, i.e. the word surrounded by non-word characters and start and end including an ending dot. If you want to ignore case, add ,'i' as 3rd argument to it.

A: I think this is the basic logic you want:
where lower(col) like '%good%' and lower(col) like '%great%'

In clobs, you can't quite use like:
where dbms_lob.instr(col, 'good') and dbms_log.instr(col, 'great')

A: Try this and let me know if it works for you.
SELECT *
FROM clob_table
WHERE DBMS_LOB.INSTR(clob_text,'great')>0
      AND DBMS_LOB.INSTR(clob_text,'good')>0;

Remember put the names of your table and columns.
Here my results,


text:
Q: How do you add feature to a class that was originally designed wrong in the first place? I have a Surgeon class that is constantly changing
class Surgeon
{
   string name, discipline;
 public:
    Surgeon(string _name, string _discp) : name{_name}, discipline{_discp}{}
    void writeDir(string _dir);
    void readDir(string _dir);
}

Now I need to add recording settings to Surgeon. Keeping in mind SOLID principles this forces me to go back in Surgeon class add a recording settings and modify everything in surgeon class. Now, I'm also aware that the current implementation of software already adds value to the company. And refactor is not necessary, but in order to do this task right I need to refactor the whole class. If I just add the feature that works with the current design then I'm simply perpetuating bad design.
Where does the software engineer provide the most value? Should I produce code that shows results quickly but is prone to errors in the future or should I delay quick results to produce good code that is more robust? What would be the happy medium if there is any?

A:
And refactor is not necessary, but in order to do this task right I need to refactor the whole class.

This is contradictory. You cannot claim that refactoring is not necessary while specifying that the class should be refactored. You're in a situation where, in order to follow SOLID principles, you need to refactor existent code. The fact that "the current implementation of software already adds value to the company" is irrelevant: you don't refactor existent code because it doesn't have value; you refactor it because it doesn't match the new design.

Should I produce code that shows results quickly but is prone to errors in the future or should I delay quick results to produce good code that is more robust?

There is no general answer to that.
If it is essential to have visible results fast in order to show it to the business analyst and iterate quickly based on his feedback, you may do it. If you do it, make sure the business analyst (and possibly the project manager) understands the implications, i.e. that you're doing a prototype, that is code which will be thrown away in order for the production code to be written instead.
If it is not necessary to have visible results fast or if you know that people you're working with do not understand what prototypes mean and that as soon as they see any result, they'll consider that your job is finished, give an estimate based on how long would it take to write production code from the beginning. Writing production code includes refactoring and testing: you're not paid to type code, but to design working, reliable software.


text:
Q: Can I disable code folding in WebStorm? I want to disable code folding in WebStorm. It's possible to turn off the folding indicators, but the folding itself still works. I'd like to be rid of the whole thing, so it's impossible to activate it in any way. Is this possible?
(There aren't any obvious options, but I'm hopeful there's something I've missed...)

A: In the WebStorm preferences there is a section for folding. There you can enable/disable folding for all different types of code. Personally, I have all my folding disabled as well. Hope this helps!
FYI:
Preferences -> Editor -> General -> Code Folding


text:
Q: What does a non void C function without return statement actually return? Let's take this piece of code:
node_t* create_tree_node(void* data){
    node_t* node = (node_t*) malloc(sizeof(node_t));
    node->data = data ;
    node->left = NULL ;
    node->right = NULL ;
}

Now, If you noticed, there's no return statement, let's say we forgot to put one.
I actually tried a similar code (imagine node_t being the habitual structure for a node in a binary tree, ie, a field for the data, and pointers to the next left and right nodes), and, when I did this:
node_t* node = create_tree_node((void*) some_random_value) ;

I was able to create a node with the desired value , and save it in a binary tree, use it, and free it.
So two question:

*

*what does a non void function without any return statement actually return ?
Could it be the last allocated variable on the stack ?

*GCC raises a warning for that, but not an error. Wouldn't a compiler error be actually more pertinent for such a case instead of a compiler warning?

A:

*

*what does a non void function without any return statement actually return ? Could it be the last allocated variable on the stack ?

The C standard does not define the behavior if a function does not execute return with a value and the return value of the function is used.
(There is some evidence that, in some situations, GCC deliberately returns the value of the last full expression evaluated in the function, but that was discussed in comments some time ago, and I do not have a reference.)

GCC raises a warning for that , but not an error. Wouldn't a compiler error be actually more pertinent for such a case instead of a compiler warning ?

The C standard does not prohibit a function with a non-void return type from returning without returning a value (by allowing program control to flow to the terminating } of the function definition). So a conforming compiler should allow this in the function definition, meaning it can warn but should not produce an error. It is allowed to call such a function and not use its return value; that has behavior defined by the C standard.
If the compiler can see that a function call uses the return value of a function that does not return a value, the compiler could produce an error for that.
It is occasionally useful for a function with a non-void return type to return a value in some situations and not in others, such as a function that accepts a command to perform and returns a value when a "Get value of setting" command is performed and does not return a value when a "Set value of setting" command is performed.


text:
Q: Node.js REST webservice with wrong Content-Type I'm developing a REST webservice in Node.js, with fastify framework, designed to respond to a specific client.
This is how the client calls my webservice:
POST /myws/scan HTTP/1.1
Host: myhost.io
User-Agent: AGENT
Content-Length: 45
Accept: */*
Content-Type: application/x-www-form-urlencoded
X-Forwarded-For: xxx.xxx.xxx.xxx
X-Forwarded-Proto: http
Accept-Encoding: gzip

{"FIELD1":"testvalue","FIELD2":True,"FIELD3":90}

As you can see the Content-Type is "application/x-www-form-urlencoded" but the request payload is in "application/json" format.
I can't change the client, so I have to adapt my webservice to manage this kind of calls.
I tried with @fastify/formbody package but I receive an error because I think it expects the request body in "application/x-www-form-urlencoded" format.
I tried also with this code:
app.addContentTypeParser('application/x-www-form-urlencoded', function (req, body, done) {
    try {
      var json = JSON.parse(body)
      done(null, json)
    } catch (err) {
      err.statusCode = 400
      done(err, undefined)
    }
  })

but I have a JSON deserializing error.
How I can manage these kind of calls and which is the best way to do that?

A: body is a stream.
You need to add the parseAs option:
fastify.addContentTypeParser(
  'application/x-www-form-urlencoded',
  { parseAs: 'string' },
  function (req, body, done) {
    try {
      const json = JSON.parse(body)
      done(null, json)
    } catch (err) {
      err.statusCode = 400
      done(err, undefined)
    }
  }
)

I would check the first char before running the JSON.parse and I would use https://www.npmjs.com/package/secure-json-parse (as Fastify does under the hood)


text:
Q: mysql search by month and year as separate fields I want all sum of counts between these 2 month-year here month and year are 2 separate fields.
How can I do that ? Thanks for help.
SELECT *
FROM foo
JOIN
SELECT (SUM(`full_lead_count`)) AS `domainFullLeadCount`
FROM `abc`.`reports`
WHERE ((`month` >= 10)
       AND (`year` >= 2013))
  AND ((`month` <= 3)
       AND (`year` <= 2014)) LIMIT 1 bar ON val1 = val2
WHERE id = 123;

A: Think of this as a comment rather than a useful answer...
Untested and very incomplete:
The issue is that if there was a range of year such as 2012 to 2014 then not all rows would be selected with the given example.
Something like the following will correctly select all the rows in the date range required:
SELECT (SUM(`full_lead_count`)) AS `domainFullLeadCount`
FROM `abc`.`reports`
WHERE ((`year` * 100 + `month`) >= 201310)
  and ((`year` * 100 + `month`) <= 201403)

And, yes it isn't nice as indexes cannot be used etc.

A: These premises are definitely not ideal. If it is possible to change the database layout, then you should consider to use real date datatypes from MySQL. Otherwise you could use STR_TO_DATE in order to convert your two fields into a single DATETIME, which can then be handled more easily.


text:
Q: VelocityTemplate, generate list of dates between start and end date I am sending a batchGetItem API query to AWS DynamoDB which uses Velocity Template to build the query string dynamically. I fetch the startdate and enddate params. In the following query, I need to collect all the dates between startdate and enddate params.
I have reviewed the documentation and examples in here and here, ComparisonDateTool() provides to get years, months or days. But I guess the solution would be complicated with those options (i.e generating the list manually).. So looking for alternative (and possible quick) options..
#set($startDate = "$input.params('startdate')")  // ex. 2019-05-27
#set($endDate = "$input.params('enddate')")    // ex. 2019-06-02

... some script to get all dates between start and end date

#set($dates = ["date1", "date2", "date3", ...])

//DynamoDB batchGetItem query
{
    "RequestItems": {
        "tableName": {
            "Keys": [
                "dates": $util.toJson($dates)
             ]
         }
    }
}

A: Since you cannot use your own custom Java tools in the AWS environment, you have to resort to dates and calendars manipulations from within Velocity templates.
## parse input dates
#set($start = $date.toDate('yyyy-MM-dd', $startDate))
#set($end = $date.toDate('yyyy-MM-dd', $endDate))

## get calendars
#set($calendar = $date.toCalendar($start))
#set($endCal = $date.toCalendar($end))

## get the number of days
#set($diff = $date.difference($calendar, $endCal).days)

#set($dates = [])

## loop on days
#foreach($day in [0..$diff])
  #set($nextDate = $date.format('yyyy-MM-dd', $calendar))
  $dates.add($nextDate)
  $calendar.add(5, 1) ## '5' means 'days'
#end

...

Now $dates contains an array of string dates between wanted bounds.