text:
Q: IE11 in IE7mode not triggering mousewheel event I've not found the IE7 mode version of this specifically addressed. I've tried various versions of this, working fine in Chrome, FF, IE9+, but not in IE11 in forced IE7 mode, a client server-set requirement :-(.
IE7 mode alerts "mousewheel" as the wheelEvent , but never even calls first alert line of scrollHandler() on mouse wheel, so doesn't seem to be attaching the event/handler via window.attachEvent?
        var wheelEvent = "onwheel" in document.createElement("div") ? "wheel" : // Modern browsers support "wheel"
          document.onmousewheel !== undefined ? "mousewheel" : // Webkit and IE support at least "mousewheel"
          "DOMMouseScroll"; // let's assume that remaining browsers are older Firefox

    function scrollHandler(wheelEvent) {
        alert("scrollHandler "+wheelEvent);
        //upDown = -1 on scroll-down, = 1 on scroll up

            if (wheelEvent.wheelDelta) {//chrome
                upDown = (wheelEvent.wheelDelta % 120 - 0) == -0 ? wheelEvent.wheelDelta / 120 : wheelEvent.wheelDelta / 12;
            } else {//FF
                var rawAmmount = wheelEvent.deltaY ? wheelEvent.deltaY : wheelEvent.detail;
                upDown = -(rawAmmount % 3 ? rawAmmount * 10 : rawAmmount / 3);
            }
            scroller(upDown);
    }

    if (window.addEventListener) {//most browsers
        window.addEventListener(wheelEvent, scrollHandler );
    }else if (window.attachEvent){//IE7...
        alert("IE7 - window.attachEvent: " + wheelEvent);
        window.attachEvent(wheelEvent, scrollHandler);
    }

A: attachEvent uses the "on" prefix for events, so you need to change your code to, and you need to attach the event to the document instead of window.
else if (window.attachEvent){//IE7...
   alert("IE7 - window.attachEvent: " + wheelEvent);
   document.attachEvent("on"+wheelEvent, scrollHandler);
}


text:
Q: Mongodb find contains, startswith, endswith, and exact string with java driver I'm trying to do a find on my database for strings. These strings contain a wildcard for contains, startswith, and endswith; otherwise I just search for the exact value. I've looked at many examples of doing search with java but they all seem to be outdated with the current java driver and use BasicDBobjects which I cant get to work. I believe the code below will work
I just need to know how I need to change some of the strings to search the database:
Let's say my database looks like this
{State:Ohio}
{State:Iowa}
{State:Texas}

containsString: returns any document that contains it. ie "io" would return Ohio and Iowa documents
beginString: returns any documents that start with it. ie "io" would retun Iowa document
endString: returns  any documents that end with it. ie "io" would return Ohio document
else it will look for the exact value. ie "texas" would return Texas document
MongoDatabase db = mongoClient.getDatabase("database1");
MongoCollection collection = db.getCollection("collection1");
BasicDBList list = new BasicDBList();
for(int i=0; i < data.length; i++){
     String[] queries = data[i].split(":", 2);
     String column = queries[0];
     String query = queries[1];
     if (query.startsWith("*") && query.endsWith("*")) {
        String containsString = query.replace("*", "");
        MongoCursor<Document> cursor = collection.find(new Document(column, containsString)).iterator();
       while (cursor.hasNext()) {
          list.add(cursor.next());
       }
     } else if (query.startsWith("*")) {
       String beginString = query.replace("*", "");
       MongoCursor<Document> cursor = collecton.find(new Document(column, beginString)).iterator();
       while (cursor.hasNext()) {
          list.add(cursor.next());
       }
     } else if (query.endsWith("*")) {
       String endString = query.replace("*", "");
       MongoCursor<Document> cursor = collection.find(new Document(column, endString)).iterator();
       while (cursor.hasNext()) {
          list.add(cursor.next());
       }
     } else {
       MongoCursor<Document> cursor = collection.find(new Document(column, query)).iterator();
       while (cursor.hasNext()) {
          list.add(cursor.next());
       }
     }
}

A: So I figured I might have to do regex for this but I didn't how I would using the java driver. However, I've now found that the java driver has filters(more documentation on them). So I guess this has now turned into a how do I transform my strings into regex question.
And so after some learing of the regex ways, this is what I did.
For contains
Pattern pattern = Pattern.compile(".*"+Pattern.quote(anyString)+".*", Pattern.CASE_INSENSITIVE);
MongoCursor<Document> cursor = collecton.find(regex(column, pattern)).iterator();

For startswith
Pattern pattern = Pattern.compile("^"+Pattern.quote(beginString), Pattern.CASE_INSENSITIVE);
MongoCursor<Document> cursor = collection.find(regex(column, pattern)).iterator();

For endswith
Pattern pattern = Pattern.compile(Pattern.quote(endString)+"$", Pattern.CASE_INSENSITIVE);
MongoCursor<Document> cursor = collection.find(regex(column, pattern)).iterator();

For exact
Pattern pattern = Pattern.compile("(?i)(?<=\\s|^)"+Pattern.quote(query)+"(?=\\s|$)", Pattern.CASE_INSENSITIVE);
MongoCursor<Document> cursor = collection.find(regex(queryCol, pattern)).iterator();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Terminology for smoothing methods: kernel density estimation, kernel smoothing, etc I'm using what I have been referring to as 'kernel density estimation' to estimate the rates of a series of variables a, b, c from noisy observations distributed in 1-, 2- and 3-dimensional space. The variables being estimated are relative proportions - a+b+c=1 at every point. The approach boils down to taking a weighted average of all the values where the weights are a function of distance from the point of interest to each observation. That function is usually a static Gaussian function, but I've also used a square kernel (all points within distance k are weighted 1, all others are weighted 0), k-nearest neighbours (the nearest k points are weighted 1, all other points are weighted 0), or a dynamic Gaussian kernel (weights are determined with a Gaussian function but σ is set for each estimate such that the sum of weights is always k).
My question is about terminology -

*

*Can I reasonably refer to all of these as kernel density estimation, regardless of the kernel function?

*Is it okay to refer to these as kde when I'm working with relative proportions?

*I see a range of other terms around - kernel smoother, kernel smoothing, kernel density smoothing, weighted moving averages, nearest neighbour smoothing, etc. - are there really differences here, or are some of these different names for the same methods?


text:
Q: Access Form Bring Text Box in Front of Listbox? This application is Access 2010, with a SQL backend.
I have a form, which has a tab control, with 2 pages.  1 page has 1 listbox and the other has 2 listboxes.  I use some code, on change of the tab control, to determine the active page, and set the listbox(es) row source(s) for the one(s) on the active page, and clear it out on the inactive page.  This takes a sec and the listboxes look yucky while this is happening.
To prevent the user from seeing this, I made a text box, with a colored background and the control source ="Please Wait One Moment..."
with like 48 font.  On load of the form, this textbox is visible = false.  On click of the tab control, the text box is to be made visible, and it is big enough to cover then entire tab control. It does cover the tab control, but I can still see the listboxes through the text box.  The text box has a back color and is not transparent. I tried right-clicking the listboxes in design view and choosing Position - Send to Back, and right-clicking the textbox and choosing Position - Send to Front.
This doesn't seem to work.  Is anyone familiar with this issue? Figuring someone has tried a trick like this.
The meat of my code is all functioning properly, for this on change of the tab control.  I have this code at the beginning:
DoCmd.Hourglass True
Me.txtPleaseWait.Visible = True
Me.Repaint
Application.Echo False
Debug.Print Me.txtPleaseWait.Visible

and this at the end:
Application.Echo True
Me.txtPleaseWait.Visible = False
Me.Repaint
Debug.Print Me.txtPleaseWait.Visible
DoCmd.Hourglass False
Debug.Print "got to end of resting form state"

Does that make sense?
Should I handle this differently?
Thank you.
Edit
I found that listboxes have a higher zorder than textboxes, so I changed my textbox to a listbox.  I still see the listboxes from the tab control, through the listbox I'm using to cover them up.
Is there a control that would better cover these and could have this "intermission" type message show, while the listboxes are being set and unset?

A: I researched different aspects of this, and found the listbox has a higher zorder than text boxes, which is position front or back relative to other objects.  I tried just doing this onload of the form, and there wasn't time to hide anything. It just waited to load the form, until the rowsources were set.
Since the find tab is the default one, and quicker to load, I just load that on load.  Then, if someone clicks on the other tab, I will load the add listboxes. I also set an integer variable to 0 on load of the form. When I click on the tab to go to the add page (add page is active), I check that variable, and if it is 0, I set the row source, and then +1 to the variable.  Next time I click on it, I don't re-order it.
This way, I'm not using resources to load and unload the listboxes, and I only load 2 of them, if the user even goes to that tab. Many times, they might just be looking for one in the system, and going to view it.
Here is the full code, in case this method helps someone else.  You could also make the variable boolean, and just set it to true, and then false.
Option Compare Database
Option Explicit
Dim AddLoaded As Integer

Property Get ActivePage() As Access.Page
    'PROPERTY TO IDENTIFY WHICH TAB WE ARE ON, FOR FILTERING AND IDENTIFYING WHICH ACTIVE LISTBOX TO LOOK AT, FOR VALUES AND ACTIONS
    With Me.tbAddFind
        Set ActivePage = .Pages(.Value)
    End With
End Property

Private Sub Form_Load()
    Dim Listctrl As Control
    Dim cmd As ADODB.Command
    Set cmd = New ADODB.Command
    Dim cSQL As String

    AddLoaded = 0

    For Each Listctrl In Form.Controls
        If (Listctrl.ControlType = acListBox) Then
            With Listctrl
                .RowSource = ""
            End With
        End If
    Next Listctrl

    Me.tbAddFind.Value = 0

    cSQL = "SELECT vw_CMP_Projects.CM_CID, [vw_CMP_Projects]![ProjectName] &" & Chr$(34) & " (" & Chr$(34) & "& [vw_CMP_Projects]![ProjectNo] &" & Chr$(34) & ") " & Chr$(34) & " AS Projects FROM vw_CMP_Projects ORDER BY [vw_CMP_Projects]![ProjectName] &" & Chr$(34) & " (" & Chr$(34) & "& [vw_CMP_Projects]![ProjectNo] &" & Chr$(34) & ")" & Chr$(34)
    Me.lstProjects.RowSource = cSQL
    Me.lstProjects.Requery

End Sub

Private Sub tbAddFind_Change()
    Dim cmd As ADODB.Command
    Set cmd = New ADODB.Command
    Select Case Me.ActivePage.Name
        Case "pgAddProjects"
            If AddLoaded = 0 Then
                cmd.ActiveConnection = GetCatalog()
                cmd.CommandType = adCmdStoredProc
                cmd.CommandText = "sp_RefreshProjectsAdd"
                cmd.Execute

                Me.lstAllProjects.RowSource = "Select * From qryAddProjectsYes"
                Me.lstAllProjects.Requery
                Me.lstAddProjects.RowSource = "Select * From qryAddProjectsNo"
                Me.lstAddProjects.Requery

                AddLoaded = AddLoaded + 1
            End If
    End Select
End Sub

Thanks for the discussion. It was helpful, as it gave me things to research.


text:
Q: How to find similarity percentage for multiple alligned sequence My question is related to protein sequence alignment. When I use ClustalW for alignmnet I can see the identity percentage, strongly similar and weekly similar. But I want to find similarity percentage of all aligned sequence not Identity.
I goggled for software's which will help to find out algorithms to solve it, but I am unable to download them ex:MStatX this sounds promising to solve my problem but somehow I can not find the information to download it.
I even read about similarity Matrix which looks like one solution to calculate the percentage similarity of the sequence. Even for this I don't know where to find information to download any software's if any exist.
Can any one please help me in finding out proper tool or method to calculate the similarity percentage in multiple aligned sequence.
Thank you,
pavithra.

A: Have you heard about Smith-Waterman? Smith-Waterman can help you to calculate the similarity of a sequence (in fact it started with the DNA..) but once you will learn how to calculate the intermediate matrix, you can use it to find many other important and useful information (such as partial matching)

A: Levenshtein Distance algorithm
Link to wikimedia:
http://en.wikipedia.org/wiki/Levenshtein_distance
You can find a implement for you specific language


text:
Q: Multi-Day All Day Events with Event Kit not at top of calendar All-day events that span multiple days in Event Kit are appearing at the bottom of the list of events for that day.
For example if I have a multi-day all day event from 1 January to 3 January and then look at the calendar for 2 January.
2 January

*

*8-10am Meeting

*12pm - 1pm Lunch

*All-Day Event*

Code
    let startDate = NSCalendar.currentCalendar().startOfDayForDate(Dates.dateObject)
    let endDate = startDate.dateByAddingTimeInterval(Double((60 * 60 * 24))

    let calendars = eventStore.calendarsForEntityType(.Event)
    var selectedCalendars = [EKCalendar]()

    for cal in calendars {
        if (NSUserDefaults.standardUserDefaults().boolForKey(cal.calendarIdentifier) != false) {
            selectedCalendars.append(cal)
        }
    }

    let eventsPredicate = eventStore.predicateForEventsWithStartDate(startDate, endDate: endDate, calendars: selectedCalendars)

    events = eventStore.eventsMatchingPredicate(eventsPredicate)

A: To solve this, the start date and end date for the predicate has to be 00:00:00 to 23:59:59 (rather than 00:00:00 to 00:00:00).
The code was modified as below.
    let startDate = NSCalendar.currentCalendar().startOfDayForDate(Dates.dateObject)
let endDate = startDate.dateByAddingTimeInterval(Double(((60 * 60 * 24) - 1))

let calendars = eventStore.calendarsForEntityType(.Event)
var selectedCalendars = [EKCalendar]()

for cal in calendars {
    if (NSUserDefaults.standardUserDefaults().boolForKey(cal.calendarIdentifier) != false) {
        selectedCalendars.append(cal)
    }
}

let eventsPredicate = eventStore.predicateForEventsWithStartDate(startDate, endDate: endDate, calendars: selectedCalendars)

events = eventStore.eventsMatchingPredicate(eventsPredicate)


text:
Q: php multiply int values seperated by comma and dot In my current application a user can have a "prepaid" amount of money on his account. The value is stored in cents. Now in case of a user tries to transfer money from one account to another he should be able to use values like: "1,53", "1.53" and "1". Now I need to check if the entered amount is below the amount he's able to transfer.
 if (($request->amount * 100) <= $user->calculateAmount())

The function $user->calculateAmount() returns values like for example "351" which stands for 3,51€ (saved in cents).
I know the problem is the ",", using a "." works fine, but user should be able to use both. Is there a better way or did I need to use str_replace()?

A: You can use this:
http://codepad.org/NW4e9hQH
Currently there are no other method to parse this to float.


text:
Q: Flow no-weak-types warning: optional argument of weak type with default value Having this Flow'ed code
export default (resource: string, init?: Object = {}) =>

I'm getting following warning

warning  Unexpected use of weak type "Object"  flowtype/no-weak-types

The thing is the init argument is exactly native' fetch second argument (see MDN) which is optional and which is an object that might have more than 10 complicated properties, so I don't want to specify its type rather than generic "Object" or "any".
What is the right way to avoid this warning in my situation?

A: The warning you are seeing is from ESLint, specifically the eslint-plugin-flowtype plugin, and not from Flow itself.
However, it's warning you about something valid. Object is an unsafe type in Flow. It is equivalent to any (it used to have some subtle differences, but no longer does). In general it is probably worthwhile to spell out the properties explicitly, even if they are complicated, with something like this:
type Init = {
  someProp: string,
  someOtherProp: number;
}

export default (resource: string, init?: Init = {}) => {}

(try)
You may also want to consider the mixed type, which is safe but inconvenient to use.
If you are sure that you want to accept the unsafe behavior of Object or any, you can turn off the ESLint rule for that line.


text:
Q: SQLite insert query giving error after 246 records I am trying to insert 1916 records in sqlite database in iphone, but after inserting 246 records I am getting an error

"Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error while inserting data. 'unable to open database file'' "

is there any setting regarding insert cache or something?

A: There could be a memory limit constraint, you might want to run this is a couple of transactions, say insert 245 records at a time then the next 245 until your finished.
Some more details would help out as well, like Query, sqLITE version, how much data is passed in each field, the table structure, constraints, etc...

A: For that many INSERTs, you'll want to wrap your write operation in a transaction.  I've found that doing otherwise can cause your memory usage to shoot up on the device and lead to overall bad performance.  I've provided some code in this answer as an example of how to do this.


text:
Q: Python hosts file entries in memory i have some scripts that use a hardcoded FQDN. I am not allowed to change the scripts because of very specific reasons that i can not elaborate on.
These scripts rely on an entry in the hosts file in windows.
However, i want to be able to control multiple devices with those scripts without having to change the IP value of that FQDN in the hosts file each time.
So i wrote a python script to visualize the commands that those scripts implement.
Via that python script i want to be able to change the ip value for that FQDN by specifying the ip address in a textfield in the python program.
Instead of running the python program with administrative rights and parsing/updating the hosts file each time, can't i change the FQDN ip in memory?
I would like your thoughts.
Please don't suggest to change the underlying scripts because that is no option.
the scripts also don't take ip parameters.
i hope this makes sence.
so:
-- hosts file
---- business logic scripts that rely on hosts file
------ Python program that wraps a visual layer over the business logic scripts. Here i want to specify the ip address via a textbox.


text:
Q: Using JSweet to Transpile Java->JS, 'matches' error I'm new to JS. I've written two large Java classes that I want to turn into JS using JSweet. The first smaller one transpiled without issue. With the second, I've hit a wall. It throws this error twice, and no others:
Line 55: property 'matches' does not exist on type 'string'. Did you mean 'match'?

Line 55 in my class is as follows:
private String name;

name is at the class level, and given a value later by an object constructor, by which I mean it is contained within no other brackets besides the class. (It happens to be line 55 due to some previous skeleton classes I added before the class I'm transpiling to define dependancies)
My one theory was that the following line was causing the issues:
if(pointer.content.equals(sub_table.get_name()))

So I changed it to this:
if(pointer.content.compareTo(sub_table.get_name())==0)

The idea being that these are two different ways to compare strings, and matches vs. match in JS are also different ways to compare data, and that perhaps I was trying to transpile a method that JS doesn't like. However, the error has not changed. Any clues?

A: The problem was line 350:
if((words[i - 2].matches("\\d*") && words[i-1].equals("+")) && words[i].matches("\\d*"))

I changed it to:
if((isNumeric(words[i - 2]) && words[i-1].equals("+")) && isNumeric(words[i]))

and I added isNumeric as a method:
public static boolean isNumeric(String strNum) {
    if (strNum == null) {
        return false;
    }
    try {
        int i = Integer.parseInt(strNum);
    } catch (NumberFormatException nfe) {
        return false;
    }
    return true;
}

Still don't understand why the error was showing on line 55. Matches works as intended in java, so js or jsweet just doesn't like it used like that.


text:
Q: How search sentence with match sql I need to seek a sentence in my database.
I use "LIKE" :
SELECT * FROM `TABLE` WHERE `TEXT` LIKE '%toto tata titi%';

but, i need to use "MATCH" :
SELECT * FROM `TABLE` WHERE match(`TEXT`) AGAINST ('+toto +tata +titi' IN BOOLEAN MODE)

or
SELECT * FROM `TABLE` WHERE match(`TEXT`) AGAINST ('+toto tata titi' IN BOOLEAN MODE)

But the query with "MATCH" does not return the same number of records with a "LIKE".
So How to search a sentence with match ?

A: These two statements are very different:
WHERE `TEXT` LIKE '%toto tata titi%'
WHERE match(`TEXT`) AGAINST ('+toto +tata +titi' IN BOOLEAN MODE)

The first looks for a string that has 14 characters 'toto tata titi' that look just like that.  It will not match 'tata titi toto'.
The second does a search word by word, so it will match 'tata titi toto' and 'toto and xxx tata yyy titi' as well.
The equivalent like logic would be more like:
WHERE `TEXT` LIKE '%toto%' and
      `TEXT` LIKE '%tata%' and
      `TEXT` LIKE '%titi%'

This isn't exactly the same, because this will match 'tototatatiti' which the match version will not.  But it is probably close enough for what you want.


text:
Q: A bit confused about the "agenda" of a Chrome extension So, I wrote a few extensions, most disposable and one hopefully viable.
I'm still a bit confused about the "agenda", of "schedule" or whatchacallit, i.e. the order in which things happen, and the places where they live.
For example, I am writing a new one that shall do the following :

*

*a browser action presents the user with a menu of 3 items

*two of those items trigger actions to be executed immediately, while the third lauches a process that is to run undercover for an extended period (namely polling a certain web page at an interval, said web page needing not to be loaded in any visible tab or window).

Naturally I'd be tempted to assume that the long-term is to live in the background.js.
Now, I understand that the pop-up menu is an HTML document in its own right, living its life in its own bubble. It shall disappear right after the user cliked on an item, thereby taking its context with it to its grave. Right now I'm at a bit of a loss trying to figure out how it can trigger a background process.
Notwithstanding, I don't quite grasp what brings the background.js to life, even less so when it is specified as non persistent as is recommended.
Naturally, I'll RTFM again, but if you fellows could dumb this down to my poor level of understanding, I'd be so happy ...

A: Maybe as you said, you would need to RTFM again..
Background Page runs in the extension process and exists for the lifetime of your extension, until your extension is removed or the browser process terminates.
While Event Page, what chrome has recommended to use, is loaded only when they are needed. Take a look at Lifetime part, the following are some example that will cause the event page to load:

*

*The app or extension is first installed or is updated to a new version (in order to register for events).

*The event page was listening for an event, and the event is dispatched.

*A content script or other extension sends a message.

*Another view in the extension (for example, a popup) calls runtime.getBackgroundPage.

As for your question, 'how it can trigger a background process', if there are no events to catch or message to pass, you can just call runtime.getBackgroundPage to load the event page.


text:
Q: How do I get syntax highlighting of source code files within Quick Look back in Lion? Source code files viewed using Quick Look on Snow Leopard had syntax highlighting. Unfortunately the syntax highlighting has disappeared on OS X Lion. Is there a way to get it back?

A: I don't think Snow Leopard did that by default, you most likely had a QuickLook plugin installed, such as qlcolorcode or colorqc2. You can simply install this again in Lion.

A: Actually, Xcode 3.x included a Quicklook plugin for source codes. With the intruduction of Xcode 4.x, such plugin has disappeared.
I have personallly tried to use qlcolorcode and colorqc2 on Lion, but both are not stable/reliable enough (slow response, sometimes missing quicklook). An updated version of the plugins would be welcome.

A: The Xcode 3 plugin was found at /Developer/Applications/Xcode.app/Contents/Library/QuickLook/SourceCode.qlgenerator
Unfortunately I don't think this can be made to work now. :(

A: Guys you can do this procedure bellow:
To fix this, open a new Terminal window and enter these commands to open vim's configuration file:
$ cd /usr/share/vim
$ sudo vim vimrc

Press the i key to switch vim to Insertion Mode, then enter these lines below the set backspace=2 line:
set ai                  " auto indenting
set history=100         " keep 100 lines of history
set ruler               " show the cursor position
syntax on               " syntax highlighting
set hlsearch            " highlight the last searched term
filetype plugin on      " use the file type plugins

" When editing a file, always jump to the last cursor position
autocmd BufReadPost *
\ if ! exists("g:leave_my_cursor_position_alone") |
\ if line("'\"") > 0 && line ("'\"") <= line("$") |
\ exe "normal g'\"" |
\ endif |
\ endif

Press the ⎋ esc key to take vim out of Insertion Mode, then press : (colon) followed by x to save the file and exit.
It worked for me thanks.


text:
Q: Classification with Convolutional Neural Networks I am trying to classify samples into two classes, positive and negative.
I have 500 positive samples and 100 negative. examples:
http://imgur.com/a/3XDAP
(I dont have enough reputation to post images or multiple links)
I am using a convolutional neural network to do the classification. For negative samples which have an obvious distortion, the network works fine. The problem is with negative samples that have a small distortion, they are classified as positive.
Does anyone have any suggestions ? Maybe pre-processing steps or completely another methode rather than CNN ?
Thank you


text:
Q: Experiential have and let's? Can let us (or let's) be used with have in such a way?

Let's just have you stop being so mean to me, I'd really appreciate it.

A: This usage is sometimes called the first person imperative, and it's marked by let us or let's, and it is so called because it includes the speaker. What you really are saying is

Stop being so mean to me.

By including yourself, you soften the command somewhat while maintaining a wry tone. After all, taken literally you yourself are asking someone to enter an agreement with yourself not to be mean to yourself.
The complement of let is the bare infinitive [to] have, familiar in a sentence like

Let's have dinner.

A: There's two constructions combined here.
One is the let's VP-inf impositive construction:

*

*Let's go to the movies tonight. (an offer to accompany the addressee)

*Let's ask Fred whether he knows. (a suggestion about what to do)

It must contain an infinitive VP, without to, like go to the movies tonight.
The other is the causative or experiential have VP constructions, like

*

*I had my tires rotated.

*I had my tires slashed.

*We had him sit next to his wife.

*They have us signed up for monthly payments.
The two together act as a combined impositive, intended to command, but ameliorated by using a light 'suggestion' morpheme, and an indirect causative to spread the responsibility.

*

*Let's have no more of this, please.

*Let's have everybody stand up when the Queen enters, OK?

*Let's not have everybody talking at once.


text:
Q: Skip all the test instead of decorating each test function with @pytest.mark.skipif()? I have a pytest file which requires environment being set. So I add the following decorator on every function.
@pytest.mark.skipif('password' not in os.environ,
                    reason='Environment variable "password" not set.')
def test_1(mock):
    ....

@pytest.mark.skipif('password' not in os.environ,
                    reason='Environment variable "password" not set.')
def test_2(mock):
    ....

@pytest.mark.skipif('password' not in os.environ,
                    reason='Environment variable "password" not set.')
def test_3(mock):
    ....

Is it a way to skip all the test instead of decorating each test function?
BTW, it just skip the tests with the following message. Is it a way to display a warning information of missing environment variable?
====== 25 skipped in 5.96s =======

A: You can use a fixture with autouse=True that does the skipping for you:
@pytest.fixture(autouse=True)
def skip_if_no_password():
    if 'password' in os.environ:
        yield
    else:
        pytest.skip('Environment variable "password" not set.')

Another possibility is to put the tests into a class and put the marker on the class instead, as mentioned by Luke Nelson in the comments.


text:
Q: Adding body class when post contains a specific shortcode Simple shortcode function :
function my_shortcode_function($atts,$content=null){
  // Do something
  return $content;
}
add_shortcode('my_shortcode','my_shortcode_function');

I wonder how to add more extra body class when user use this shortcode in contents.
I can't do something like :
function my_shortcode_function($atts,$content=null){
  // Do something
  add_filter('body_class','my_body_class');
  return $content;
}
function my_body_class($classes) {
   $classes[] = 'foo';
   return $classes;
}
add_shortcode('my_shortcode','my_shortcode_function');

Any idea ?

A: I am doing something like this in one of my plugins:
function my_body_class( $c ) {

    global $post;

    if( isset($post->post_content) && has_shortcode( $post->post_content, 'your-shortcode' ) ) {
        $c[] = 'your-class';
    }
    return $c;
}
add_filter( 'body_class', 'my_body_class' );

I'm not sure it was really necessary, but I probably can't remove it now either. TheDeadMedic is right, you should think about whether you really need to do this.


text:
Q: Outlook to excel VBA stops searching body after first match I wrote a code to pull data from outlook to excel, And its 80% working :) It does pull info but not from the whole email.
I receive emails in the same format with pricing and other info on them. These are for purchase orders what have more than 1 line usually. They are in this format:
Item Number             : 00001
Vendor Sales Order Number :
Vendor Material Number  :
SAP Material Number     :
Vendor Description      :
SAP Description         :
Vendor Quantity         : 30.000 EA
SAP Quantity            : 30.000 EA
Quantity UOM            : EA
Vendor Delivery Date    : 20.09.2014
SAP Delivery Date       : 20.09.2014
Action Request          :
Following details does not match for PO line item 00001
Vendor Price            : USD 0.00 for 1 EA
SAP Price               : USD 0.01 for 1 EA
Item Number             : 00002
Vendor Sales Order Number :
Vendor Material Number  :
SAP Material Number     :
Vendor Description      :
SAP Description         :
Vendor Quantity         : 70.000 EA
SAP Quantity            : 70.000 EA
Quantity UOM            : EA
Vendor Price            : USD 3.90 for 1 EA
SAP Price               : USD 3.90 for 1 EA
Vendor Delivery Date    : 20.09.2014
SAP Delivery Date       : 20.09.2014
Action Request          :
Quantity and Requested Date all matched with PO. Item 00002
As you can see from the code i am pulling multiple things from these emails that have the same beginning string. After it pulls line 1, the code moves to the next email without searching the entire body of the email for further matches. How can i fix this? Stuck :)
Option Explicit

Sub CopyToExcel()
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim olItem As Outlook.MailItem
Dim vText As Variant
Dim sText As String
Dim vItem As Variant
Dim i As Long
Dim rCount As Long
Dim bXStarted As Boolean
Const strPath As String = "Excel filepath here" 'the path of the     workbook

If Application.ActiveExplorer.Selection.Count = 0 Then
MsgBox "No Items selected!", vbCritical, "Error"
Exit Sub
End If
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Application.StatusBar = "Please wait while Excel source is opened ... "
Set xlApp = CreateObject("Excel.Application")
bXStarted = True
End If
On Error GoTo 0
'Open the workbook to input the data
Set xlWB = xlApp.Workbooks.Open(strPath)
Set xlSheet = xlWB.Sheets("Sheet1")

'Process each selected record
 For Each olItem In Application.ActiveWindow.Selection
sText = olItem.Body
vText = Split(sText, Chr(13))
'Find the next empty line of the worksheet
 rCount = xlSheet.UsedRange.Rows.Count + 1

'Check each line of text in the message body
For i = UBound(vText) To 0 Step -1
  rCount = rCount
  If InStr(1, vText(i), "Purchase Order          :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("A" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Vendor                  :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("B" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Item Number             :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("C" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Vendor Quantity         :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("D" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "SAP Quantity            :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("E" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Quantity UOM            :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("F" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Vendor Price            :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("G" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "SAP Price               :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("H" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Vendor Delivery Date    :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("I" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "SAP Delivery Date       :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("J" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Text here:") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("K" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Text here:") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("L" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Text here:") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("M" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Text here") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("N" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Text here") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("O" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Text here") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("P" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Text here") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("Q" & rCount) = Trim(vItem(1))
    End If
Next i
xlWB.Save
Next olItem
xlWB.Close SaveChanges:=True
If bXStarted Then
End If
Set xlApp = Nothing
Set xlWB = Nothing
Set xlSheet = Nothing
Set olItem = Nothing
End Sub

A: Code:
Option Explicit

Sub CopyToExcel()
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim olItem As Object
Dim vText As Variant
Dim sText As String
Dim vItem As Variant
Dim i As Long
Dim j As Long
Dim rCount As Long
Dim bXStarted As Boolean
Const strPath As String = "Excel filepath here" 'the path of the     workbook

If Application.ActiveExplorer.Selection.Count = 0 Then
MsgBox "No Items selected!", vbCritical, "Error"
Exit Sub
End If
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Application.StatusBar = "Please wait while Excel source is opened ... "
Set xlApp = CreateObject("Excel.Application")
bXStarted = True
End If
On Error GoTo 0
'Open the workbook to input the data
Set xlWB = xlApp.Workbooks.Open(strPath)
Set xlSheet = xlWB.Sheets("Sheet1")

'Process each selected record
 For j = 1 To Application.ActiveExplorer.Selection.Count
 Set olItem = Application.ActiveExplorer.Selection.Item(j)

 If olItem.Class = 43 Then
sText = olItem.Body
vText = Split(sText, Chr(13))
'Find the next empty line of the worksheet
 rCount = xlSheet.UsedRange.Rows.Count + 1

'Check each line of text in the message body
For i = UBound(vText) To 0 Step -1
  If InStr(1, vText(i), "Purchase Order          :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("A" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Vendor                  :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("B" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Item Number             :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("C" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Vendor Quantity         :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("D" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "SAP Quantity            :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("E" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Quantity UOM            :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("F" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Vendor Price            :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("G" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "SAP Price               :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("H" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Vendor Delivery Date    :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("I" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "SAP Delivery Date       :") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("J" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Text here:") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("K" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Text here:") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("L" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Text here:") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("M" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Text here") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("N" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Text here") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("O" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Text here") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("P" & rCount) = Trim(vItem(1))
    End If

    If InStr(1, vText(i), "Text here") > 0 Then
        vItem = Split(vText(i), Chr(58))
        xlSheet.Range("Q" & rCount) = Trim(vItem(1))
    End If
Next i
xlWB.Save
rCount = rCount + 1

End If
Next j
xlWB.Close SaveChanges:=True
If bXStarted Then
End If
Set xlApp = Nothing
Set xlWB = Nothing
Set xlSheet = Nothing
Set olItem = Nothing
End Sub

This should work.  For some reason Outlook will simply stop execution without error if it encounters a non-mail item in your selection.
Copy and Paste the whole thing (even the Dim statements).


text:
Q: Is it possible to set all JPanes the same background color at once? I'm creating a little game. I know how to set a background color to a JPanel.
pane.setBackground(Color.RED);

My problem is, I've a BorderPane as layout and if I want to place something in the south I need to create a new JPane. Foreach pane I create i need to set the background color again. My Question is, is it possible to set the background color for every pane at once?

A: You can always set color of the main container to the red, and then make all your panels transparent with setOpaque(false);

A: Besides the nice idea from Antiossss, you could do one of these two, too:

*

*typically, any UI container knows about its children. So you can write some generic code that (probably recursively) fetches the children of some UI component, and if it is a JPanel, set the background

*probably easier to do: your code simply remembers all JPanels you care about itself

In other words: when you want to treat a number of "things" in similar ways, then easiest solution is to have a field
Set<JPanel> myPanels = new HashSet<>();

in some of your "root" classes, and every time you create a panel ... you add it to that set, so that when you need them you can go:
for(JPanel aPanel : myPanels) { aPanel.setBackground(...


text:
Q: Is jquery append working wrong when using in a loop? I have got this:
arr = []
        $(function () {
            for (let i = 0; i < 4; i++) {
                arr[i] = $('
Hello
')
                $('body').append(arr)
                console.log(arr)
            }
        })

and the result is 4 different (arr) in the console but just 4 x "Hello" on the screen.
Anyone know why?

A: Is this what you're trying to do?

var arr = [];
for(x = 0; x < 4; x++) {
    var h2 = $('
Hello
');
    arr.push(h2);
    $('body').append(arr);
}


text:
Q: Conversion of highlighted text pdf to postscript I am using ghostscript to convert PDF to postscript.
If I am converting pdf having hightlight and comment i.e., pdf containing simple text then it converts text properly in postscript.
But when pdf has highlighted or commented text then it converts that pdf page to image.
I am using following command.
gswin64c -o sample.ps -sDEVICE=ps2write sample.pdf
Thanks

A: Without seeing the PDF file, which you have not supplied, my guess would be that the highlight, or comment, is using transparency.
The PDF transparency model is not supported in the PostScript imaging model, at all.
So there is no way to take a transparent PDF file and produce from it a transparent PostScript file. While certain minimal transparency features could be replicated with clever PostScript programming, the general case simply cannot be reproduced.
So when the ps2write devcie encounters input which involves transparency it renders the page to an image, and uses that as the page contents in the output PostScript program.


text:
Q: Trying to Print Array without Repeating Numbers I have a programming assignment where I am tasked with the following:
I am taking two int values (x and y) and creating two different arrays: the first (size x) will print an array starting from x and descending down to 1. The second (size y) will take random values from the first array (size x) and store it in its own array. I will then print out the second array. However, the second array cannot have any repeating values. For example, if the array was size 10, it could not have two of the same digit within its 10 individual indexes. I am attempting to store unique elements in my second array by creating two arrays, one boolean to check for unique elements and another one to store those unique elements. Here is my code:
/*
* user will enter desired size x for first array labeled arr_1
* arr_1 will contain values descending from x down to 1
* user will enter desired size y for second array labeled arr_2
* arr_2 will contain random values taken from arr_1 w/o repeating numbers
*/

import java.util.Arrays;
// import java.util.Arrays;
import java.util.Random;
// import java.util.Scanner;
public class Prog1B
{
    public static void main(String[] args)
    {
        System.out.println("Program 1B, Christopher Moussa, masc1574");
        // Scanner scnr = new Scanner(System.in);
        int x = 20;
        int v = x;
        int[] arr_1 = new int[x];

        for (int i = x-1; i >= 0; i--)
        {
            arr_1[i] = v;   // System.out.print(i+1 + " "); prints 20, 19, ... , 1
            v--;            // System.out.print(arr_1[i] + " "); prints 20, 19, ... , 1
        }
        // int[] b = unique(arr_1);
        System.out.println(Arrays.toString(unique(arr_1)));
    }

    public static int[] unique (int[] n)
    {
        boolean[] seen = new boolean[n.length];
        int[] unique = new int[n.length];
        Random rand = new Random(123L);
        for (int i = 0; i < n.length; i++)
        {
            int index = rand.nextInt(n.length);
            while (seen[index])
            {
                index = rand.nextInt(n.length);
            }
            unique[i] = n[index];
        }
        return unique;
    }

}

The code compiles and runs, but it still prints out an array with repeating values. I am trying to write the program so that it does not print out an array with repeating values, only unique values. Do you have any suggestions as to where the problem lies? I am pretty sure it lies within the "unique" method, more specifically when the boolean array is checking for unique values (I noticed while trying to debug that even if the random index it generated was not unique, it still skipped the while condition and printed it out). I am a beginning programmer (a freshman at San Diego State studying computer science) and any feedback/advice will be greatly appreciated. Thanks you very much.

A: You need to even set your array seen[index] = true;
public static int[] unique (int[] n)
    {
        boolean[] seen = new boolean[n.length];
        int[] unique = new int[n.length];
        Random rand = new Random(123L);
        for (int i = 0; i < n.length; i++)
        {
            int index = rand.nextInt(n.length);
            while (seen[index])
            {
                index = rand.nextInt(n.length);
            }
            unique[i] = n[index];
            seen[index] = true;
        }
        return unique;
    }

A: I found the problem in your code. You never update your "seen" Boolean array. See the code below for fix:
public static int[] unique (int[] n){
 boolean[] seen = new boolean[n.length];
 int[] unique = new int[n.length];
 Random rand = new Random(123L);
 for (int i = 0; i < n.length; i++)
 {
     int index = rand.nextInt(n.length);
     while (seen[index])
     {
         index = rand.nextInt(n.length);
     }
     seen[index] = true; //boolean array updated
     unique[i] = n[index];
 }
 return unique;

}
Using this fix, I was able to get the output below (which has no repeats):
[3, 11, 17, 10, 16, 18, 15, 6, 14, 20, 7, 13, 1, 19, 9, 2, 5, 4, 12, 8]

A: Unless you specifically have to do it this way, I suggest you take a step back and try a totally different approach, something like this:
Set<int> mySet = new HashSet<int>(Arrays.asList(someArray));

NOTE: You will want to adjust the return type of unique() to be Set
The rest of the implementation is left as an excercise for the reader. Basically you take the array and convert it to a set as the example above.
(Credit where credit is due)
I just wanted to steer you in the right direction per https://meta.stackexchange.com/questions/10811/how-do-i-ask-and-answer-homework-questions
Good luck, I would say the biggest lesson here is how to walk away from code that has become inefficient when a better solution exists. Good luck!

A: Heres is how to do this using java8 lambdas
    ArrayList<Integer> arrayli = new ArrayList<Integer>(Arrays.asList(arr_1));//converted array to list
    System.out.println();
    List<Integer> distinctIntegers = arrayli.stream().
    .distinct()
    .boxed()
    .collect(Collectors.toList());
 distinctIntegers.foreach(System.out::println);


text:
Q: Are all the commas and semicolons really necessary in 'My mother, Martha; my father, Jesse; and my daughter, Amy, will be there'? Are all the commas and semicolons really needed in:
'My mother, Martha; my father, Jesse; and my daughter, Amy, will be there'?
In this sentence I have only one father, only one mother and only one sister; hence I believe the sentence is correctly punctuated – but it is a trainwreck and an eyesore.
I think that we could simply render the exact sentence thus (with only one comma):
REVISION
'My mother Martha, my father Jesse and my daughter Amy will be there.'
Does anyone agree with my revision?
Many, many thanks.

A: I'm late to the party; I still hope you're here, though! Okay, let me start of my saying that if you were to write your sentence like so:

"My mother Martha, my father Jesse and my daughter Amy will be there."

You're leaving your readers to know that you have more than one mother, father, and daughter, and I'll exmplain why.
I'll use a good example: If you were to write, "My friend, Lia," with a comma, this makes the word "Lia" non-restrictive; therefore, it would signify that Lia is your ONLY friend. Now, if you were to write it without the comma before "Lia" as so: "My friend Lia," this makes "Lia" restrictive, showing you have more than one friend.
Now that you understand how the comma can make a difference, you need to add commas before their names; otherwise, it'll signify that you have more than one mother, father, and daughter. Since you do have a list (a list contains THREE items), and that list contains commas that describe a list item (for example, Martha describes "my mother"), it is ABSOLUTELY necessary to add the semicolons as you had it in your example. If you think the semicolon looks horrible on the eyes, you can simply put the names around parenthesis, and that'll fix your problem.

"My mother (Martha), my father (Jesse), and my daughter (Amy) will be there."

As for the comma before "and," that is optional, though I would recommend adding it to not confuse your readers. Also, keep in mind that if you're going to use the semicolons, you need one before "and." I hope this helps! :)


text:
Q: wget to download dynamic website which uses aspx I m trying to download entire website using wget for offline learning.
wget --recursive --no-clobber --page-requisites
--html-extension --convert-links
--restrict-file-names=windows  --domains scmhrd.edu
--no-parent  http://elearning.scmhrd.edu/frmSet.aspx

All the static content gets downloaded but not the dynamic contents . Is there a way to do that ?

A: There is no way to download server side code from HTTP. That's why asp.net rules!


text:
Q: AngularJS : Add the same component to several modules I'm using https://coreui.io/demo/#main.html core ui bootstrap template .
I have got several modules + controller  .like this for example :
mypartapp1.js :
 angular
    .module("app", [])
    .controller('ComptesController', ComptesController)
   // etc ...

mypartapp2.js :
    angular
    .module("app", [])
   .controller('EnseignesController', EnseignesController)
    // etc ...

I've built a very large component compatible with each of my controllers (reusable), do i have to rewrite it inside each files (mypartapp1.js, my partapp2.js ...) , because i would like it to be unique, and dont know how to do .
How could i simply call it from the same path ?
This is my large component for info :
.component('filtresDyn', {
    templateUrl:'_crm/views/include/filtres_dyn.html',
    controller : [ '$http','$scope','$rootScope','toastr',function control($http,$scope,$rootScope,toastr){

         const table = 'crm_comptes';

         this.filtres = [];

        $http.post("./_crm/backend/backend.php?action=GetColumnsNames", {'table':table}).then(function(response) {
            this.table = response.data;
        }.bind(this))

         this.operateurs = [
            {'nom':'LIKE','traduction':'Contient'},
            {'nom':'NOT LIKE','traduction':'Ne Contient Pas'},
            {'nom':'=','traduction':'Est'},
            {'nom':'!=','traduction':'N\'est pas'},
            {'nom':'NULL','traduction':'Est vierge'},
            {'nom':'NOT NULL','traduction':'N\'est pas vierge'},
            {'nom':'>','traduction':'Est supérieur à'},
            {'nom':'<','traduction':'N\'est pas supérieur à '}
        ];

        this.Get_filtered_data = function(){

            $scope.$parent.Get_filtered_data(this.filtres);
        }

        this.addElement = function(){
            this.filtres.push({'champs':'','operateur':'','critere':'','table':table});

        }

        this.spliceElement = function(){
            this.filtres.splice(-1,1);

        }

        this.verify_data_type = function(champs,parent){

            switch(champs.data_type) {
                case 'integer':
                    parent.showInteger = true;
                    parent.showDate = false;
                    parent.showText = false;
                    break;
                case 'date':
                    parent.showInteger = false;
                    parent.showDate = true;
                    parent.showText = false;
                    break;
                case 'character varying':
                    parent.showInteger = false;
                    parent.showDate = false;
                    parent.showText = true;
                    break;
                default:
                    parent.showInteger = false;
                    parent.showDate = false;
                    parent.showText = true;
            }

        }

        this.nomF = '';

        this.ChargeFiltresPersos = function(){
                $http.post("./_crm/backend/backend.php?action=GetFiltresDynamique",{'id'    : $rootScope.user.id})
                    .then(function(response) {

                        angular.forEach(response.data,function(value,key){
                                angular.forEach(value.filtres,function(value,key){
                                    if(value.showDate == true){
                                         value.critere = new Date(value.critere);
                                    }
                                 });
                        });

                        this.listeFiltresUser = response.data;

                }.bind(this))
        }

        this.sauverFiltre = function(){

                $http.post("./_crm/backend/backend.php?action=SetFiltresDynamique",
                    {
                    'id_liseo_utilisateurs' :   $rootScope.user.id_liseo_utilisateurs,
                    'filtres'               :   this.filtres,
                    'nom_filtre'            :   this.nomF
                    })
                    .then(function(response) {
                         toastr.success('Bien Joué !', 'Votre filtre a bien été enregistré.');

                        $http.post("./_crm/backend/backend.php?action=GetFiltresDynamique",{'id'    : $rootScope.user.id})
                            .then(function(response) {
                                this.listeFiltresUser = response.data;
                        }.bind(this));

                    }.bind(this))

        }

            this.chargerMonFiltrePersonnel = function(array){

                    this.filtres = angular.copy(array.filtres);

                    this.Get_filtered_data();

            }

        this.filtres.push({'champs':'','operateur':'','critere':'','table':table});

        this.ChargeFiltresPersos();

    }]
  })

DO i have to rewrite this in each of my files modules ? It wont look good and it is supposed to be unique

A: While creating component inject other modules in dependency to avail the component in multiple modules.
angular.module("app1", []);

angular.module("app2", ["app1"])
.component("myComponent",{}); //component can used in multiple modules

Check the link, I have added a common structure of shared component:
https://next.plnkr.co/edit/MlktyFgTYCgHXBo9?preview


text:
Q: Framework for UI management - Design improvement I am in the middle of writing a small structure to serve as a framework for handling the 2D GUI of a Unity3d project. I have one empty gameobject called "UIManager" with "UIManager" script on it. UIManager is a Singleton with DontDestroyOnLoad. Now here is a problem, it works for all practical purposes but design wise, i am openly revealing my implementation (that it is a singleton) to the rest of the world/project. I need suggestion on how it could be improved such that it is better encapsulated.
For a better design of the problem, I stumbled upon Service Locator Pattern. Now I am even more confused. If i am understanding it correctly, I still declare my UIManager as singleton, but instead of getting it's reference via something like UIManager.GetInstance()... I create another Singleton of "ServiceLocator" and ask it for an instance of UIManager. I don't see how it improves the encapsulation of my UIManager class, whose implementation still remains public. And I don't see how it helps with decoupling.
Any insight into the issue? How do you prefer to do it?

A: If you want to preserve the access, then remove the public static reference. If you need it because your framework depends on it then maybe it is meant to be public.
You can also make your project a full assembly so your public member can be internal and only accessible from within the assembly.
You could also have your object to use interface to minimize the content accessible.
public interface IFirst{ void GetFirstThing(); }
public interface ISecond { void GetSecondThing(); }
public class MyClass:MonoBehaviour, IFirst, ISecond
{
    public void GetFirstThing(){}
    public void GetSecondThing(){}
}

public class ConsumerForFirstOnly
{
    private IFirst first = null;
    public ConsumerForFirstOnly(IFirst first)
    {
        this.first = first;
    }
}

Now your ConsumerForFirstOnly is not aware of the ISecond part of the class.


text:
Q: merge two google forms data into the one spreadsheet I want to create application which takes two different google forms data into the one spreadsheet and having two different sheets there on a single spreadsheet with the help of google apps script.
I've searched over a lot but hadn't find any satisfactory solution. Can anyone tell me that is that possible to acheive with google-apps-scripts?
Sorry, I don't have any piece of code this time.

A: It is impossible to insert data of two Google Forms directly to a single spreadsheet using GAS without involving another two spreadsheets, because now the Forms are able to deploy data only to own spreadsheet and GAS has no any service to access to the Forms.
There is a workaround which merges the Forms spreadsheets to a single spreadsheet using the ImportRange function (see bellow paragraph) but seems it is not suitable for you.
The spreadsheets have the ImportRange function which permits to import a source spreadsheet range to a destination spreadsheet, for instance, there is a task to import spreadsheet_1 columns A, B, C of Sheet1 and spreadsheet_2 columns B, C of the Sheet2 to spreadsheet_0 columns F, G, H, I and J. To achieve it is necessary to place to the spreadsheet_0 cell F1 the =ImportRange("spreadsheet_1_key", "Sheet1!A:C") formula and the cell I1 should contain the =ImportRange("spreadsheet_2_key", "Sheet2!B:C") formula.

A: For anyone who ends up at this question, looking for some general knowledge, you can change the form destination.  In the form editor, choose RESPONSES, CHANGE RESPONSE DESTINATION.  The form responses can be sent to another spreadsheet.  I'm not sure if this is a capability that didn't exist when this question was first asked, but for anyone doing a general search, you might end up here.


text:
Q: Enrutador de angular 10 no puedo compartir el link de una ruta estoy usando angular 10 con firebase lo que pasa es que al hacer deploy de la aplicacion con firebase, trato de acceder a una ruta que hice desde app-routing.module.ts la cual se accede por medio del id del post la cual es post/:id.
he intentado almacenar esa misma ruta en otra constante y aun asi me sigue dando el 404, el deploy me funciona bien pero cuando intento compartir el link del post me tira el not found.
const routes: Routes =

[

{path:'',component:ContainerAppComponent,children:

[
{ path: '', loadChildren: () => import('./components/pages/home/home.module').then(m => m.HomeModule) },
**{path:'post/:id',component:DetailsPostComponent}**,
{ path: 'about', loadChildren: () => import('./components/pages/about/about.module').then(m => m.AboutModule) },
{path:'',redirectTo:'',pathMatch:'full'}
]

},
{ path: 'admin', loadChildren: () => import('./components/admin/admin.module').then(m => m.AdminModule) },
{ path: 'login', loadChildren: () => import('./components/auth/login/login.module').then(m => m.LoginModule) },
{ path: 'stat', loadChildren: () => import('./components/posts/estadisticas/estadisticas.module').then(m => m.EstadisticasModule) },

]

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

el proposito de poder acceder a la ruta es poderla copiar y compartir en otras partes sin que me tire este error en el firebase

A: Éste es un problema recurrente con las SPA (Single Page Application, aplicación de una única página):
Estas aplicaciones tienen la siguiente estructura:

*

*Un único fichero HTML, generalmente llamado index.html.

*Uno o varios ficheros Javascript y/o CSS, importados por el fichero anterior.

*Resto de recursos (imágenes, vídeo, audio, ficheros JSON... etc), quizá en una carpeta assets o con un nombre similar.

Cuando un usuario carga tu aplicación, generalmente pone la URL "base", digamos algo como www.midominio.com. Lo que hace el servidor web es buscar por defecto un fichero llamado index.html que esté en la carpeta base y servirlo. Hasta aquí todo como esperamos.
El problema es que cuando navegas dentro de esta SPA, la SPA juega con el API del historial del navegador para cambiar la URL, sin realmente cargar ninguna página nueva. Pasas de www.midominio.com a www.midominio.com/post/1, lo que Angular usa para indicar que tiene que cargar cierto componente y mostrar los datos obtenidos al buscar el post con ID 1.
Y aquí viene el pero: el servidor web no ha recibido nunca una petición a la URL www.midominio.com/post/1, si haces una petición real a esa URL obtienes un 404 porque el servidor va a buscar primero un fichero llamado 1.html y, en su defecto, un fichero index.htmlen la carpeta /post/1/, que no existe.
¿Cómo se soluciona esto? En realidad es sencillo: diciendo al servidor web que si no encuentra algo, actúe como si en realidad le estuvieran pidiendo el index.html del directorio raíz. De ese modo tu SPA se carga, detecta que la URL con la que se ha cargado contiene /post/1, y actúa en consecuencia.
Por tanto no es un problema de la aplicación, sino de la configuración del servidor.
En el caso de Firebase hay bastante documentación al respecto, por ejemplo [aquí1. La solución propuesta es añadir, en el fichero de configuración de Firebase, lo siguiente:
"hosting": {
    ... ,
    "rewrites": [{
      "source": "**",
      "destination": "/index.html"
    }]
  },


text:
Q: Where to create accounts in a multi OU AWS Organization I have a multi OU AWS setup with a number of member accounts, a management account and a root account. My goal here is to have a central repository of users and not create accounts across all of the member accounts.
I understand that I need to have a trust relationship between the two member accounts for cross account access. But according to best practice where is the best place to create the actual IAM groups and accounts? Should the users be created in the management account in this setup?
Any help is appreciated.

A: I would say yes, if you can avoid have load in the master account you should use a management account. But it could be an ide to create a new IAM-account.
Another solution that I like is to use is AWS SSO.


text:
Q: JSON Root Name in Serialized Entity I'm using FOSRestBundle and JMSSerializerBundle to output JSON data to be consumed by an ember application.  I would like to use the built-in adapters of ember-data and the JSON format that is expected has to have a root name.  My current JSON is as follows:
{
     "user_id": 1
     "first": "Dan"
     "email": "dan@email.com"
 }

Ember expects, and what I want is:
{
 "user":
   {
     "user_id": 1
     "first": "Dan"
     "email": "dan@email.com"
    }
}

User is the name of the entity.  I'm pretty sure this is just a configuration thing, but looking through the documentation I can't seem to find what to set.  I have tried @XmlRoot, but that doesn't seem to have an affect on the resulting JSON (expected).

A: Personally I'd think it's the API consumers job to bend to the API, not the other way around.
I'd suggest taking a look at this example of massaging the payload into a shape ember likes:
Transform JSON to an appropriate format for RESTAdapter EmberJS

A: You can do it in the controller which extends FOSRestController by sending an array as the view data, I couldn't find a way to do this in the configuration, but I agree a root node setting would be nice.:
$fooThing = $em->getRepository('Foo')->find($id);
$view = $this->view(array('foo' => $fooThing), 200);
return $this->handleView($view);

I'm pretty sure this is going to mess with my XML, but I'm just starting work on the API so I haven't gotten that far yet.


text:
Q: Manually save full fragment back stack state in Android fragment activity I currently have an activity with 2 panels and a stack of fragments on each panel with also nested fragments inside. Everything is nicely saved and restored by FragmentActivity (support library) however, since i need to do some heavy task during onCreate() this create some lag.
The fragments in the task depend on the heavy task so i cannot create the fragments before doing the task. So, question is, is there any smart way to save the entire back stack and restore it after onCreate is called? I know i can save a single fragment state but i need to store the entire stack and restore it as it is on the correct view containers.
Full back stack means all the Fragments i have in FragmentManager.backStack()
Heavy Task means something i cannot do on the onCreate() method because it takes more than 5 seconds.


text:
Q: Insert value into jk-rating-stars element using angularJS Hello I would like to know how to put a value into rating="ctrl.rating" with $scope angular js.
<jk-rating-stars max-rating="5" rating="ctrl.rating"
    read-only="ctrl.readOnly" on-rating="ctrl.onRating(rating)">
</jk-rating-stars>

Thanks

A:

    <jk-rating-stars max-rating="5" rating="ctrl.rating"
        read-only="ctrl.readOnly" on-rating="ctrl.onRating(rating)">
    </jk-rating-stars>

angular.module('myApp', ['ngMaterial', 'jkAngularRatingStars'])

.controller('MyCtrl', function() {
    this.rating = 3;
    this.readOnly = false;
    this.onRating = function(rating){
      alert('On Rating: ' + rating);
    };
});

The DEMO

angular.module('myApp', ['ngMaterial', 'jkAngularRatingStars'])

.controller('MyCtrl', function() {
    this.rating = 3;
    this.readOnly = false;
    this.onRating = function(rating){
      console.log('On Rating: ' + rating);
    };
});

<link rel="stylesheet" href="https://unpkg.com/angular-material/angular-material.css" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://unpkg.com/angular-jk-rating-stars/dist/jk-rating-stars.css" />

    <jk-rating-stars max-rating="5" rating="ctrl.rating"
        read-only="ctrl.readOnly" on-rating="ctrl.onRating(rating)">
    </jk-rating-stars>

    <input type="number" ng-model="ctrl.rating" />


text:
Q: java.io.IOException: Failed to bind to port [7003] on host [VM_IP1] I have two Virtual Machines running cloudify-manager-1 (with VM_IP1) and cloudify-manager-2 (with VM_IP2).
After some days, the VMs goes down. Into the "2015-04-16~10.33-gigaspaces-esm_3-VM_IP1-20855.log" log file of the cloudify-manager-1 I can see the errors reported at the following link:
2015-04-16~10.33-gigaspaces-esm_3-VM_IP1-20855.log
Moreover, il I can to conenct to the cloudify-manager-1 by the cloudify shell, I obtain the following error:
cloudify@default> connect 212.189.205.246

Failed to locate a lookup service in the cloud endpoint with discovery groups:[localcloud] and locators:[jini://VM_IP1:4174/, jini://VM_IP2:4174/]
Operation failed.

whereas if I try to connect to the cloudify-manager-2, it works
cloudify@default> connect VM_IP2
Connected successfully

Can someone help me to understand where is the problem?

A: Its not entirely clear what you mean by "the VMs goes down". The ESM error log indicates that this ESM instance tried to start but the port is opens (7003) is already in use.
This could indicate that there was an older instance of the ESM running on the same machine, and it is somehow stuck. This would cause Cloudify to try and start a new agent, assuming the old one is dead, but the old one is still holding the required port. Try checking for another instance of the ESM running on the same machine (or for whatever process that is holding the port).
As for the CLI errors, it seems like one of the VMs (VM_1) is suffering some sort of communication problem - it is not able to find the other services of the cloudify manager. The Manager VM_2 seems to be functioning, and still find the running services (which should be available on both manager).
Please be aware the Cloudify 2 has reached end-of-life. You may want to check out Cloudify 3.

A: Some days ago, I have only ran the following commands to restart the Cloudify processes and save the applications state:
cloudify@default> shutdown-managers -timeout 10 --verbose

cloudify@default> bootstrap-cloud --verbose -use-existing <openstack-cloud-driver-name>

To solve the error od the ESM, I have executed:

*

*ssh in both the cloudify-manager VMs

*killing of all the java processes (returned by pgrep java)

*/root/gigaspaces/tools/cli/cloudify.sh

*cloudify@default> start-management -timeout 30 --verbose -cloud-file /root/gs-files/<openstack-cloud-driver-name>.groovy
Now the cloudify-managers work, and the applications previously deployed work, too.


text:
Q: QAction aware of the item where the context menu containing it is triggered in a QTableView I have a QTableView/QAbstractTableModel framework where I implemented a context menu, with at most 2 actions, depending on the index where the menu was requested. For one of those two actions, once triggered I would like to emit the index where the context menu was requested. I have a solution that works but I don't like it.
The code:
class MyModel(QAbstractTableModel):

    ...

    def _restore_all(self):
        print('restore all')

    def _restore_index(self, index):
        print('restore index at: row = ' , index.row(), ', column = ', index.column())
    ...

class _ItemAwareAction(QAction):

    _mytriggered = pyqtSignal('QModelIndex')

    def __init__(self, *args, index=None, **kwargs):
        super().__init__(*args, **kwargs)
        self._index = index
        self.triggered.connect(self._emit_index)

    def _emit_index(self):
        self._mytriggered.emit(self._index)

class MyTableView(QTableView):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        model = MyModel(self)
        self.setModel(model)
        # Attributes
        restore_all_action = QAction('Restore all values', self)
        self._restore_all_action = restore_all_action
        self._menu = QMenu(self)
        # Connexions
        self.customContextMenuRequested.connect(self._item_context_menu)
        restore_all_action.triggered.connect(model._restore_all)

    def _item_context_menu(self, pos):
        menu = self._menu
        menu.clear()
        index = self.indexAt(pos)
        model = self.model()
        originals = model._originals
        if not originals:
            return
        menu.addAction(self._restore_all_action)
        references = model._index_to_references(index)
        if references in originals:
            action = _ItemAwareAction(
                'Restore this value', parent=self, index=index
            )
            action._mytriggered.connect(model._restore_index)
            menu.addAction(action)
        menu.popup(self.viewport().mapToGlobal(pos))
    ...

I find my _ItemAwareAction class to be an unnecessary loop. Maybe you can point me to a simpler and more straightforward solution.

A: The simpler solution would be to use lambda or partials:
    def _item_context_menu(self, pos):
        # ...
        if references in originals:
            action = QAction('Restore this value', parent=self)
            action.triggered.connect(lambda: model._restore_index(index))
        # ...

Since you're not doing cycles of sort, you could even just check if the triggered action is the one that should reset, and that's accomplished by using exec() (which blocks until the menu is triggered/closed) instead of returning immediately:
    def _item_context_menu(self, pos):
        # ...
        if references in originals:
            restoreAction = QAction('Restore this value', parent=self)
        else:
            # cancelled menu returns None, we need to compare with something else
            restoreAction = -1
        if menu.exec_(self.viewport().mapToGlobal(pos)) == restoreAction:
            model._restore_index(index)

Another alternative is to use the data() of the action, and then you either connect to the menu triggered action.
class MyTableView(QTableView):
    def __init__(self, *args, **kwargs):
        # ...
        self._menu = QMenu(self)
        self._menu.triggered.connect(self._menu_triggered)

    def _menu_triggered(self, action):
        if isinstance(action.data(), QtCore.QModelIndex):
            self.model()._restore_index(action.data())

    def _item_context_menu(self, pos):
        # ...
        if references in originals:
            action = QAction('Restore this value', parent=self)
            action.setData(index)
        # ...


text:
Q: How to change index.html reference using Grunt? When using grunt is it possible to alter the references within a html file.
I am altering the filename from abc.html to abc.0bf5.html
What I would like to do is within my index.html file alter the reference to the html template to use the latest html template.

A: I see at least 2 ways of doing it:

*

*use grunt-contrib-copy to copy index.html to your build directory and set its process option: https://github.com/gruntjs/grunt-contrib-copy#process

*use grunt-template to generate your index.html


text:
Q: f is continuous at uncountably many points of $[0,1]$ and discontinuous at uncountably many points of $[0,1].$
Justify: Let $K\subset [0,1]$ be the cantor set. Then the function $$f:[0,1]\to\mathbb R:x\mapsto \begin{cases}1,~\text{if}~~x\in K\\0,~\text{if}~~x\notin K\end{cases}$$ is continuous at uncountably many points of $[0,1]$ and discontinuous at uncountably many points of $[0,1].$

Please help me. I'm clueless.

A: HINT: Let $U=[0,1]\setminus K$; then $U$ is a dense open subset of $[0,1]$, so every point of $[0,1]$ is a limit of points of $U$. Give this some thought, but if it isn't enough, I've added a bigger hint in the spoiler-protected field below; mouse-over to see it.

 Show that $f$ is continuous at points of $U$ and discontinuous at points of $K$.

A: Since $[0, 1]\setminus K$ contains intervals it is clearly continuous on uncountably many points. Show that it is discountinuous on $K$, which is uncountable, and you are done. For this you should use the fact that $K$ is nowhere dense.


text:
Q: How to access the request object in a fetch then/response function I have a JavaScript loop iterating over an array. For every item, I perform a fetch request to insert the object. If the server response indicates it is an already inserted object, I try an update operation with another fetch call.
As the requests are asynchronous, the loop sets the request object to the next insert item before I try the update operation, so I end up requesting an update for an object it's not yet inserted.
Is there any way I can access the request object used for this fetch operation, so I can use that object instead of the loop var?
I've tried with this within the promise method, but it returns a reference to the window object: console.log(this) ==> > Window http://localhost
My code:
for (var i = 0; i < expectedRows; i++) {
    var row = myArray[i];
    customerCode = row['customer_code'];
    customerName = row['customer_name'];
    customerBalance = row['customer_balance'];
    // Build body call
    var callBody = {
        user: 'USER',
        code: customerCode,
        name: customerName,
        balance: customerBalance
    };
    var fetchOptions = {
        method: "POST",
        cache: "no-cache",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        redirect: "error",
        referrer: "ux-import",
        body: JSON.stringify(callBody),
    };
    // Call
    var epurl = baseEP + '/customer/create';
    fetch(epurl, fetchOptions)
    .then(response => response.json())
    .then(response => {
        console.log(this) // <== Window object reference
        if (response.error === 0) {
            console.log('insert ok');
            insertRows++;
        } else {
            if (response.error == 2) {
                console.log('insert error => update');
                var updateEP = baseEP + '/customer/update';
                fetch(updateEP, fetchOptions) // <== Not what you expect
                .then(updResponse => updResponse.json())
                .then(updResponse => {
                    if (updResponse.error === 0) {
                        console.log('update ok.')
                        updateRows++;
                    } else {
                        console.log('update error: ' + updResponse.msg)
                        errorMessages.push(updResponse.msg);
                    }
                })
                .catch(error => {
                    console.log('update failure');
                    errorMessages.push(error);
                });
            } else {
                console.log('insert error.');
                errorMessages.push(response.msg);
            }
        }
    })
    .catch(error => {
        console.log('insert failure.');
        errorMessages.push(error);
    });
}

I need some way to access this fetch call request object to achieve something like this:
var updFetchOptions = {
    method: "POST",
    cache: "no-cache",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
    },
    redirect: "error",
    referrer: "ux-import",
    body: this.request.body, // this as a reference to this fetch's request
}
fetch(updateEP, updFetchOptions)...
:
:

A: Can you try this.
for (let i = 0; i < expectedRows; i++) {
    let row = myArray[i];
    customerCode = row['customer_code'];
    customerName = row['customer_name'];
    customerBalance = row['customer_balance'];
    // Build body call
    let callBody = {
        user: 'USER',
        code: customerCode,
        name: customerName,
        balance: customerBalance
    };
    let fetchOptions = {
        method: "POST",
        cache: "no-cache",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        redirect: "error",
        referrer: "ux-import",
        body: JSON.stringify(callBody),
    };
    // Call
    let epurl = baseEP + '/customer/create';
    fetch(epurl, fetchOptions)
    .then(response => response.json())
    .then(response => {
        console.log(this) // <== Window object reference
        if (response.error === 0) {
            console.log('insert ok');
            insertRows++;
        } else {
            if (response.error == 2) {
                console.log('insert error => update');
                let updateEP = baseEP + '/customer/update';
                fetch(updateEP, fetchOptions) // <== Not what you expect
                .then(updResponse => updResponse.json())
                .then(updResponse => {
                    if (updResponse.error === 0) {
                        console.log('update ok.')
                        updateRows++;
                    } else {
                        console.log('update error: ' + updResponse.msg)
                        errorMessages.push(updResponse.msg);
                    }
                })
                .catch(error => {
                    console.log('update failure');
                    errorMessages.push(error);
                });
            } else {
                console.log('insert error.');
                errorMessages.push(response.msg);
            }
        }
    })
    .catch(error => {
        console.log('insert failure.');
        errorMessages.push(error);
    });
}

Basically, defining variables with var is not a good method as it doesn't maintain its state with each iteration of loop. But using let maintains the variable state for each iteration and you can use the variable even after doing some async task like fetch in your case.

A: You can achieve this by explicitly creating the RequestInit-Object and wrapping your handler functions like this:
const initObject = {
    method: 'POST',
    something: 1234
};
fetch('/test.json', initObject)
    .then(r => r.json())
    .then(((initObject) => {
        return json => {
            console.log({json, initObject})
        }
    })(initObject));


text:
Q: How to create a Average measure on a aggregated table of both rows and columns in Power BI So I have this
Dataset
My wanted result is to create a measure that is a Average of the Value 1 + value 2, split by date and Type
I have created a legit solution with a calculated table
consolidateTable =
SUMMARIZE('Blad2';Blad2[Type];Blad2[Date];"summarized";sum(Blad2[value 1]) + sum(Blad2[Value 2]))

and the result looks like this:
SummarizedTable
with the measure
measure = AVERAGE(consolidateTable[summarized])

I get the wanted
Result
I want to create the whole process in a measure
I'm happy for any input in how to create this measure piece by piece with first filtering the table.


text:
Q: Unable to modify file after creation I created a file using
sudo vim filename

but I can't modify it after creating.
How can I make it possible to modify this file?

A: By executing this command
sudo vim filename

you create new file, whose owner is the root user. You can confirm that by executing ls -al. From the output you can see that the owner and the group to which the file belongs are set to root.
If you try to edit it with your normal user, you wont be able, because the file does not belongs to your user. Again you are able to read the file but not write to it, because of the permissions. You can check them to from the command line with ls -al command. It should be something like:
-rw-r--r-- 1 root   root       4 Apr  9 07:40 filename

the first part -rw-r--r-- means that only owner can read and write to file, users from the same group and other user can only read the file.
Here is a good diagram that describes the meaning of permissions:

If you wish to be able to edit the file, you must do so as the root user - this is almost always the best way:
sudo vim filename

If you wish to edit it as normal user you can assign additional permissions to it, (but you should not do this to system files outside your home directory - use sudo to edit them instead):
sudo chmod 777 filename

This way the file will be readable, writable and executable from every user. This is rarely a good idea.
To give ONLY write permissions to all other users:
sudo chmod o+w filename

Otherwise if you want the file to be writable only by you, you can change the owner to you:
sudo chown yourusername:root filename


text:
Q: Control with play/stop/pause e.t.c. buttons for media playing does somebody know if there is a free control or somebody is selling a control with buttons play/stop/pause e.t.c. (like the ones of windows media player)
that can be used for media playing.
I do not want that the control plays the media but i want only the buttons and the play progress bar.
Also do you know of a control where the user can select segments of the media file ?
Thanks !

A: Something like this?
As for buttons, you could search for some pretty PNGs and embed them in buttons. Easy, free, and quick to do.

If you simply want to get it done, see this beast. I have not used it, but it looks like it could handle the media hassle for you.


text:
Q: My program works in ModelSim, but doesn't work on real FPGA board There is my VHDL code, and there is BDF desing.
When I simulate my VHDL code in ModelSim, it's working fine, but when I simulate it in Quartus or upload to FPGA Cyclone board, LED have no signal. IDK, in what way I suppose to look at.

A: I had a quick look at your code, and while it seems syntactically correct, it doesn't really look synthesizable (even though it may be).
For example:
led_size : process(clk, size)
begin
  if size = '1' then
    led_size_f <= led_size_f +1;
  end if;
  if  led_size_f > 4 then
    led_size_f <=1;
  end if;
end process;

It doesn't even use clk, and it will also generate a latch (generally a bad thing, unless you're absolutely certain what you're doing), which will most probably give you problems when trying to run it in an FPGA.
I can post more examples, but if I were you, I'd try looking at the list of warnings that you're most probably getting from your synthesis tool.
Also, see if your IDE comes with some templates for synchronous design, and then try to adhere to them, to make sure that you are actually inferring the hardware that you want.


text:
Q: Iphone SQLite initializing and closing I'm new to working with iphone and SQLite i have my app working fine with SQLite but i would like to know what you all think is the correct / best way of opening an sqlite connection and closing it..
Would you

*

*Initialise a DB connection on app load and close on app close..

*Open and close connections when is needed..

Also is it good practise to constantly update db entries as you go or store all information  in an object and write out at the end when needed..
There is not to much information on this via google just some useful small tutorials that cover delete / insert / update but not as a general overview of the best practise in using SQLite with iphone..
Thanks guys

A: Keep the connection open.
Whenever you execute a SQL query, it has to be compiled into a prepared statement.  Once it's compiled, you can use it over and over and it doesn't have to be compiled again.
However, the query is compiled against the database pointer, so if you close your connection, you have to release all of your prepared statements.  When you re-open your connection, you then have to re-prepare each statement as you use it again.
Save an object whenever you make a set of changes.  If you are changing several things on an object (name, address, etc.) make all the changes first, then save it.  Don't wait to commit several unrelated changes all at once, though (i.e. at the termination of the app).  Related changes can be delayed until they are all made, before saving them.


text:
Q: encountered the symbol create oracle stored procedure the below oracel procedure keeps showing me "pls-00103 encountered the symbol create" and i am not ablt to figure out why.. please help
create or replace procedure myproc
    (
    otherdate in varchar2
    )
    as
    mystringdate varchar2(20);

    begin
    create or replace function checkdate(givdate in varchar2) return number
    as
    givedate1 date;
    begin
    givedate1 := todate(givdate);
    return1;
    exception
    when others then
    return 0;
    end;

    mystringdate := ltrim(rtrim(otherdate));

    if checkdate(mystringdate,'dd-mm-yyyy')= 1 then
     DBMS_OUTPUT.PUT_LINE('it is a date format');
    else
     DBMS_OUTPUT.PUT_LINE('it is not a date format');
    endif
    end myproc;

i tried more like \ symbol and all but not working. please help

A: This is weird, you started creating a proc and then inside begin you started creating function, you need to remove create function from there. Why you want to do that?
Remove this:
create or replace function checkdate(givdate in varchar2) return number
    as
    givedate1 date;
    begin
    givedate1 := todate(givdate);
    return1;
    exception
    when others then
    return 0;
    end;


text:
Q: standard deviation for a sample from a uniform distribution? Let $X_1,X_2,...,X_n$ be a random sample from $U(0,1)$. I need to find the standard deviation of $max${$X_1,X_2,...,X_n$}. I am not sure how to begin with this problem?

A: You begin the problem by identifying the distribution's CDF.
$$\mathsf P(\max\limits_{i=1}^n \{X_i\} \leq x) = \mathsf P(\bigcap_{i=1}^n (X_i\leq x))$$
Then you use the fact that for any surely non-negative continuous random variable $$\mathsf E(Y)=\int_0^\infty \mathsf P(Y>y)\operatorname d y$$
To find $\mathsf{Var}(\max \{X_i\}) = \mathsf E\Big(\big(\max \{X_i\}\big)^2\Big)-\Big(\mathsf E\big(\max \{X_i\}\big)\Big)^2$


text:
Q: How to find period of this periodic function? How can I find a period of this function?
$$2\sin{3x} + 3\sin{2x}$$
Is here any way how to sum both sinuses?

A: One has period $\pi$ and the other has period $2\pi /3$. What you want now is to see when they "match up". This is obtained in $2\pi$. Basically, this is $3\times 2\pi/3$ and $2\times \pi$. We're just cross multiplying periods.

A: To find a period is no problem, note that $2\pi$ is a period of both parts.

A: You can always go the hard way analyzing, for arbitrary $T$:
$$
    2 \sin(3 (x+T) ) + 3 \sin(2(x+T)) = \\ 2 \sin(3x) \cos(3T) + 2 \cos(3x) \sin(3T) + 3 \sin(2x) \cos(2T) + 2 \cos(2x) \sin(2T)
$$
When $T$ equals a period you should have
$$
   \sin(3T) = 0, \quad \sin(2T) = 0, \quad \cos(3T) = 1, \quad \cos(2T) = 1
$$
Since $\sin(3T) = \sin(T+2T) = \sin(T) \underbrace{\cos(2T)}_1 + \cos(T) \underbrace{\sin(2T)}_0 = \sin(T)$, and $\cos(3T) = \cos(T) \cos(2T) - \sin(T) \sin(2T) = \cos(T)$. We have:
$$
    \sin(T) = 0, \quad \sin(2T) = 0, \quad \cos(T) = 1, \quad \cos(2T) = 1
$$
Repeating the exercise we see that $\sin(2T) = 0, cos(2T)=1$ is implied by $\sin(T)=0$ and $\cos(T) = 1$. Solving $\sin(T)=0$ and $\cos(T)=1$ is easy. There are infinitely many solutions:
$$
    T = 2 \pi n, \quad n \in \mathbb{Z}
$$
The minimal solution is $T = 2\pi$.

A: The (smallest) period can be shown to be $2\pi$ by yet another method. Note that
$$f(x)=2\sin(3x)+3\sin(2x)=2\sin x(\cos x+1)(4 \cos x-1).$$
So the zeros of $f(x)$ in $[0,2\pi]$ occur at $0, \pi, 2\pi$ and at two other points obtained from $4 \cos x-1=0$ which are $\cos^{-1}(1/4)$ and $2\pi-\cos^{-1}(1/4).$
In any period of $f(x)$ this pattern of zeros would have to repeat. However the numeric estimates $$0.00,\ 1.318,\ 3.141,\ 4.965,\ 6,28$$ are not evenly spaced, in fact the spacings are
$$1.318,\ 1.823,\ 1.823,\ 1.318.$$
It seems clear this uneven spacing of the zeros makes it impossible for $f(x)$ to repeat before a full $2\pi$ goes by.
EDIT: It is because this spacing pattern is of the form ABBA(where lengths A,B different) that the period must be $2\pi$ and not smaller. A different function with zero spacing pattern ABAB might have period $\pi$. If extended, the ABBA pattern is ABBAABBAABBA.., and there are no periods of less than four letters length in this pattern. The repeated pattern ABABABAB.. has a period of two letters, hence zero spacing of that form might have period $\pi$ rather than $2\pi$.

A: The fundamental period of sin function is $2\pi$.
Now,Add the period of $2\pi$ in each sin function of given equation.
$y=2\sin(3x) + 3\sin(2x)$
$y=2\sin(3x+2\pi) + 3\sin(2x+2\pi)$
taking $3$ common from 1st sin fun. and $2$ from 2nd sin fun.
$y=2\sin[3(x+2\pi/3)] + 3\sin[2(x+2\pi/2)] $
so, the period of 1st sin fun. is  $\frac{2\pi}{3}$
and the peiod of 2nd sin fun. is ${\pi}{}$
Finally, find the lowest common multiple of these two periods
which is = $2{\pi}$ Answer.

A: The period of the first is $2 \pi/3$, that of the second is $\pi$. When we take the  sum, the resulting period is the least common multiple of the two, which is $2 \pi$.

A: the correct ans will be $2\pi$, as the period of first is $2\pi$ by $3$ and second is $2\pi$ by $4$.

A: given f(x) = 2sin3x+3sin2x
we know sinx fundamental period (fp) is 2pi.
Also, fp of sin(ax+b)=2pi/modulus a.
Therefore fp of sin3x=2pi/3 & fp of sin2x=2pi/2=pi
cosider LCM of {2/3 ,1}     (the LCM of fp of sin3x&sin2x)
         =LCM{2,1}/HCF{3,1}=2/3
hence given f(x) is periodic with fp=2pi/3


text:
Q: Adding colors for an particular event day in jquery full calendar
I'm using a jQuery full calendar to show leaves taken by people which are coming from one of my database tables.
There are different types of leaves. I need to show each leave type in different colors in the particular day.
Suppose I took an Annual leave on 1st of November and a Casual leave on 3rd of November.
So I need to show these two different leave types in two different colors in the same calendar.
Could you please help me.
Thanks.

A: Try using the className parameter in the events. That should help.
Example json
{
    title     : 'Some title',
    start     : '2012-11-05',
    className : 'casual_leave',
}

Example css
.casual_leave{
    background-color: #F00;
    color: #FFF;
}

Similarly, you can have many different classes and assign background-color, color and (if I am not mistaken) border details in css


text:
Q: I'm trying list comprehensions for printing 0's and 1's but it gives an error So basically I'm trying to print an 8x8 grid witch has 0's and 1's like this:
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1

I need it in a nested loop.
And I'm using this code but it Isn't working:
def print_board(board):
    board = [1 for i in range(8)] + board[3:]
    board = board[::-1] #reverse
    board = [1 for i in range(8)] + board[3:]
    for i in range(len(board)):
        print(board[i])
        print(" ".join([str(x) for x in board[i]]))
board=[]
for i in range(8):
        board.append([0] * 8)
print_board(board)

the error is:
001 | 1
002 | Traceback (most recent call last):
003 |   File "<string>", line 11, in <module>
004 |   File "<string>", line 7, in print_board
005 | TypeError: 'int' object is not iterable

Using latest version (3.10) of python

A: Not sure if this is really what you're looking for but:
a = []

for i in range(8):
    match i:
        case 3 | 4:
            r = [0] * 8
        case _:
            r = [1] * 8
    a.append(r)

for r in a:
    print(*r)

Output:
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1


text:
Q: How can I find most recent time from a datetime object in string format so I have this nested dictionary consisting of either twitter or reddit posts, with each posts id or url as the inner key, and the datetime in string format in the value.
{'reddit': {'my6vne': '2021-04-25 16:00:02',
        'my7uar': '2021-04-25 17:00:02',
        'my9i47': '2021-04-25 18:34:09',
        'myhq5w': '2021-04-26 01:10:37',
        'myioia': '2021-04-26 01:57:58',
        'myiout': '2021-04-26 01:58:25',
        'myjhtj': '2021-04-26 02:38:51',
        'myndga': '2021-04-26 06:16:45',
        'myo6x3': '2021-04-26 07:04:48'},
 'twitter': {'https://twitter.com/twitter/statuses/1386540140068102146': '2021-04-26 '
                                                                     '04:38:24',
         'https://twitter.com/twitter/statuses/1386541987210223618': '2021-04-26 '
                                                                     '04:45:45',
         'https://twitter.com/twitter/statuses/1386542478656827394': '2021-04-26 '
                                                                     '04:47:42',
         'https://twitter.com/twitter/statuses/1386544375086321674': '2021-04-26 '
                                                                     '04:55:14',
         'https://twitter.com/twitter/statuses/1386544515964571648': '2021-04-26 '
                                                                     '04:55:48'}}

Basically, I want to loop through the dictionary, check all the datetime values (which again are strings), and fetch the most recent one, relative to the current time. How would I go about doing this, as the datetime values are strings?

A: Check this out for converting string to a datetime object
https://www.educative.io/edpresso/how-to-convert-a-string-to-a-date-in-python
How about you create an object of the current datetime and using the delta method find the difference and choose the minimum value?
More here: Finding Min/Max Date with List Comprehension in Python