text:
Q: What is the nature of, and syntactic distinction between, modifier and complement? I am struggling to understand the syntactic relevance of the distinction between complement and modifier in theories such as the one presented in the Cambridge Grammar of the English Language by Huddleston and Pullum (henceforth CaGel).
Specifically, I'd like to know
(i) Is there a concise, precise definition of each of these functions, saying exactly what it means to be a modifier and a complement respectively (according to the theory presented in CaGel)? There are obviously lots of examples with extensive discussion, but no matter how much I've searched, I haven't been able to find actual, concise definitions.
(ii) What is the syntactic relevance of the distinction between complement and modifier? That is, what general syntactic phenomenon or phenomena does this distinction explain?
(iii) Are there any reliable syntactic tests for making the distinction, and, if so: what are they? I know of two tests:

*

*the substitution test, which involves substituting the head of a phrase containing a dependent with a head that unequivocally doesn't license complements, to see if the dependent still "works" – in which case it would be a modifier

*the omission test, which involves omitting a dependent to see if the result is still grammatical – which may imply that the dependent in question is a modifier.

However, neither of these tests seem reliable to me – the substitution test seems unreliable for reasons discussed here, and the omission test is unreliable because complements can sometimes be omitted without rendering the result ungrammatical – as in e.g. She stayed in her room/She stayed) – which means that it only works in cases where omission renders the result ungrammatical.
Finally, I'm asking you please not to mark this as a duplicate of this question, because it's not. In that other question I'm asking specific questions about the substitution test; here I'm asking whether there are any other tests to distinguish between complements and modifiers, and this is furthermore just one of the questions I pose here.
Thank you!

A: Here is an extract from another post of mine, slightly modified:
1.0 Complements versus Modifiers
1.1 Complements
OK, so let´s have a look at what Modifiers and Complements actually are. Well, roughly speaking, a Complement is a phrase which fills a special slot set up by another word or phrase in the sentence. So for example, the verb TEACH sets up a slot for the thing being taught, the Direct Object, and the people being taught, the so-called Indirect Object. These terms such as Direct Object, Indirect Object, Locative Complement and so forth are just more specific names for Complements of a verb. Prepositions take Complements too, often noun phrases which we can also sometimes describe as Predicative Complements or Objects. Adverbs can sometimes take Complements either directly or indirectly as well. So for example, the infinitival clause to eat in one go fills a special slot set up by the adverb too in It was too big to eat in one go. Adjectives can take their own various sorts of Complements too; consider on chess in keen on chess or to leave in keen to leave.
So, all sort of words and phrases can set up these slots, and all sorts of words and phrases can fill them too. Sometimes Complements are obligatory and sometimes they aren't. Of course, it's nice and handy when Complements are obligatory, because it's easy to identify them. It is also, in such cases, easy to demonstrate how that word or phrase has a special relationship with the Head of the phrase. So, unfortunately, Complements are often construed as obligatory essential accompaniments to other words or phrases when we first start to learn about them. This isn't always the case. Let's revisit the verb TEACH:

*

*I teach.

*I teach English.

*I teach students.

*I teach students English.

*I teach English to students.

Here we see this verb taking no Complements, taking one Object, taking two Objects and taking an Object and  a preposition phrase Complement. These different Complements are Complements because this verb sets up a special slot for them, not because they are obligatory.
Complements, of course, have other features. For example, they are usually selected by the word they are the Complements of. These Heads will allow certain types of Complements but not others. So for example, the adjective keen will select preposition phrases headed by the preposition on, but not ones headed by the preposition of:

*

*keen on spiders

**keen of spiders (ungrammatical)

The verb inquire can take interrogative clauses as Complements, but not declarative ones:

*

*I inquired whether the elephants had left.

**I inquired that the elephants had left. (ungrammatical)

Complements are thought of as being more tightly integrated into the phrases they occur in than Modifiers are. Whereas Complements are often required to be adjacent to the words that license them, Modifiers can often be moved further away from the phrases they modify or appear on either side of them. So if we see both Complements and Modifiers in the same phrase, as a rule of thumb, all other things being equal, we expect the Complements to be closer to the Head word than the Modifiers:

*

*Put it on the shop floor on Thursday.

**Put it on Thursday on the shop floor. (awkward if not ungrammatical)

A sentence or phrase will often sound marked, awkward or ungrammatical if this does not occur. In the sentence above the Complement on the shop floor will ideally come closer to the verb put than the Modifier on Thursday.
Because Complements are more tightly integrated into the phrases they occur in than Modifiers, they are often obligatorily replaced when we use a proform, whereas Modifiers may be repeated or addended to such phrases:

*

**I put my beer in the fridge and Bob did so in the cupboard. (ungrammatical)

*I drank my beer in the kitchen but Bob did so in the living room.

**I am counting on their help, but I don't want you to do so on their help. (ungrammatical)

*I am counting on their help, but I don't want you to do so.

In the first sentence in the fridge is a Locative Complement. As the anaphoric proform do so includes the Locative Complement in the second clause in that example, we cannot then add a second Locative Complement, in the cupboard. In the second sentence, where in the kitchen is a Locative Adjunct (a Modifier), we can freely add another Locative Adjunct in the second clause, in the living room. In the last pair we see that the sentence is grammatical if we omit the Complement on their help after do so, and ungrammatical if we repeat it.
Lastly, semantically, Complements usually have a close relationship with the words that license them. Words inherently describe semantic relations between different things. So the verb PUT brings to mind a putter, a thing being put, and a location. It doesn't inherently involve any idea of time. So in Put it in the fridge tonight, we would not expect tonight to be a Complement of the verb put, but we would expect both it and in the fridge to be Complements, which as we have seen above, they are. The thing being put and the destination of that thing are suggested by the very use of the verb PUT. Similarly the noun collector also inherently implies that there are things which are collected and someone who collects them. The noun resignation implies a resigner. So in a collector of antique books, we would expect of antique books to be a Complement, and we would expect of the President to be a Complement in the resignation of the President. But we would not expect in the corner to be a Complement in the collector in the corner, because the noun collector does not inherently imply a location.
Because of semantic factors above we also expect Heads to impose semantic, as well as syntactic, selectional restrictions on their Complements. We can annoy elephants but not tables, unless we ascribe some sort of animacy to our tables for some reason. We don't expect such tight restrictions with Modifiers. One can do almost anything on Wednesday and almost anything pointlessly. And whereas the number of possible Complements is specified by the Head both semantically and syntactically, the number of Modifiers is not.
1.2 Modifiers
Modifiers are never obligatory. We can characterise them as syntactically extra elements. They are usually semantically extra too, in the sense that they are not automatically implied by the words or phrases that they modify. Unlike Complements, Modifiers are usually only loosely integrated into the larger phrases they occur in. Their position is often only loosely determined:

*

*I play foot ball [in the park][on Fridays][with my friends]

*I play football [with my friends][on Fridays][in the park]

*I play football [on Fridays][in the park][with my friends]

*[On Fridays] I play football [with my friends] [in the park]

As shown further above unlike Complements, modifiers are not obligatorily relaced when we use proforms to refer back to a larger phrase.
We can use various forms of cycle as an analogy for phrases here: unicycles, bicycles, tricycles, tandems and so forth. If we regard the frame of the cycle as the Head of a phrase or clause, then the Complements are all the things that fit into the different slots in the frame. So the frame dictates the size and number of wheels, saddles, handlebars and so forth (some of which may be optional, for example in the case of tandems) that the frame can take. These things are all Complements. You can't put the wrong Complements on the wrong frames. For example, a unicycle frame won't usually allow handlebars in the same way that an intransitive verb won't allow a Direct Object. Also you can't fit the wrong size parts into the wrong slots. So the stem of your handlebars must fit into the frame, for example. It cannot be too big or too small. So the frame puts restrictions on what can be slotted into it. In contrast, any lights, bells, mudguards, panniers, stickers and so forth are always optional extras. They are, to extend the metaphor, Modifiers. You can't ride your unicycle without a wheel, but a light is definitely an optional extra. Notice as well, that the bicylce frame puts very few selectional restrictions on the Modifiers available. You can stick lights, bells or horns on any cycle you want to, and any number of each as well—although admittedly things might get awkward if you do decide to use very many.

A: When X is appended to Y to make a constituent of category Y, X is a modifier; otherwise it isn't.
Notice that it follows (in a CF language) that modifiers are always optional, and that if one modifier is permitted, then any number of them are also permitted.
(This might not always work.)


text:
Q: PowerBI Filter on multiple fields across multiple data sources I have work in Tableau for years, but my new employer uses PowerBI and I can not wrap my head around the one relationship only thing.
I have a 2 fields from 5 different datasources I need to be able to filter by.  I have a "main" datasource with the bulk of my datapoints that I have merged in PowerQuery with the other four datasources using a Date field as the 1 relation and a Text field with only two options as the 2 relation.  The Text field contains the names of our company's two business units.
I have set up a PBI report that filters fine on Date, but I need the report to filter on both Date and Business Unit and have the datapoints from all five datasources filter to data only for records that contain the selected Date and Business Unit.  I can not add a Date filter and then add five identical Business Unit filters and present this to my C-suite.
I understand how calculate() works (SQL where).  I understand how filter() works (LOD calc, sorta).  I am using them in some of my measures in the table pictured below.
If this were Tableau, I would probably join on the Date field and blend on the Business Unit field, or blend both fields, or create Parameters and filter on T/F calculated fields.  I tried to figure out the PBI Parameter, but all it looks like is a series of numbers from 1 to 20?  WTF am I supposed to do with that?

A: In Power BI, you need to create a dimensional model. You will have an Organization dimension (table) that has the Business Unit field, and a Date dimension that has dates. Then the keys from the dimension tables are related to the Fact (data) tables. More than likely, if the columns are the same between your five datasources, they might be best combined into a single fact table.
You model should look like this, with you fact table in the middle, and dimension tables in a "star" around them. They call this a "star schema."

A good model is essential in a Power BI report. Here is a good reference to get started with dimensional modeling in Power BI:
https://learn.microsoft.com/en-us/power-bi/create-reports/desktop-dimensional-model-report

redpajama_set_name: RedPajamaStackExchange


text:
Q: using React Native with Laravel I need help regarding how to create an react native app of a project which is already made in the Laravel framework.
As I am going to make a Laravel website. So I also want to create an IOS and Android app for it.
Can anyone suggest me something for it?

A: In a layman's terms:
Laravel is a backend framework, react-native is a frontend framework - they will only be interacting through API's.
You will be creating API's (laravel controllers that return json objects instead of websites) and then call them from the react-native app.
lastly, you will write code in js and have it execute around the json objects that you received from the API to create app elements.
User's interaction within the app will use a similar set of API's to send the data back to your laravel framework (works quite similar to forms)

A: Basically laravel is a backend programming language framework and its PHP so definately laravel most important thing is to build API's.
And the another side we have react which is the latest framework of javascript which is made up of Facebook for front end side.
So React developer + laravel developer = Full Stack developer
so basically you have two sides web or App
you build API's for the help of controllers and that controllers gives the response in
JSON's format when the App developer call the controllers
your controllers are attached your module and your your module are connected to your
database.
you write a code of javascript inside of Json's


text:
Q: google.com search suggestions not showing in chrome I am experiencing an weird problem in Chrome. When I go to www.google.com, I search something, but I don't get any auto search suggestions / autocomplete suggestions. I tried with both google.no and google.com. None works. But I get this feature in all other browsers even in Chrome in my PC. It only doesn't work in Chrome in my Macbook pro. I have uninstalled Chrome, cleared all application data and re-installed the latest version, but no luck. This is so annoying. It started before a month ago, and I cannot solve this problem. Also it works fine in a incognito window. Is there a solution?
Thanks in advance.
Note: I am not talking about the chrome addressbar. I am talking about when you go to www.google.com and search something in there.


text:
Q: iOS playing audio in iOS 13 throws C++ exception, freezes app TL;DR:
The code below (all ten lines of it, apart from debugging)

*

*fails (UI freezes)  on iOS 13.x (Simulator)

*succeeds (audio plays) on 14.x  (Simulator and devices)

I don't have any devices with iOS 13.x. But...analytics from live apps suggest it is failing in the field on both iOS 13 and 14 devices. False positives? (See line of code commented with $$$.)
Steps To Reproduce
Create a new SwiftUI project that can run in iOS 13. Replace the text in ContentView.swift with the code below. Add an audio resource named clip.mp3. Build and run.
I am using Xcode 12.4, macOS 11.1, Swift 5.
See Also

*

*Apple Dev Forum 1   // Unresolved

*Apple Dev Forum 2   // Attributed to beta iOS/Xcode

*Stackoverflow 1    // Unresolved

*Stackoverflow 2   // Refers to next link

*Apple Dev Forum 3   // Claims fixed in Xcode 12b5
[...and many more...]

Code
import SwiftUI
import AVKit

struct ContentView: View {
    var body: some View {
        Text("Boo!").onAppear { playClip() }
    }
}

var clipDelegate: AudioTimerDelegate!   // Hold onto it to forestall GC.
var player      : AVAudioPlayer!        // Ditto.

func playClip() {
    let u = Bundle.main.url(forResource: "clip", withExtension: "mp3")!
    player = try! AVAudioPlayer(contentsOf: u)
    clipDelegate = AudioTimerDelegate()  // Wait till now to instantiate, for correct timing.
    player.delegate = clipDelegate
    player.prepareToPlay()
    NSLog("*** Starting clip play")    // NSLog so we get timestamp.
    player.play()

    // Wait 5 seconds and see if audioPlayerDidFinishPlaying.
    DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
        if let d = clipDelegate.clipDuration {
            NSLog("*** Caller   clip duration = \(d)")
        } else {
            NSLog("!!! Caller found nil clip duration")
            // $$$ In live app, post audio-freeze event to analytics.
        }
    }
}

class AudioTimerDelegate: NSObject, AVAudioPlayerDelegate {
    private var startTime : Double
    var clipDuration: Double?
    override init() {
        self.startTime = CFAbsoluteTimeGetCurrent()
        super.init()
    }
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        clipDuration = CFAbsoluteTimeGetCurrent() - startTime
        NSLog("*** Delegate clip duration = \(clipDuration!)")
    }
}

Console Output
Simulator iOS 14.4
The audio plays and the Console (edited for brevity) reads:
14:33:17  [plugin] AddInstanceForFactory: No factory registered for ... F8BB1C28-...
14:33:17  *** Starting clip play
14:33:19  *** Delegate clip duration = 1.692...
14:33:22  *** Caller   clip duration = 1.692...

I gather that the first line is innocuous and related to the Simulator's sound drivers.
Is anyone else getting this console message with AVAudioPlayer in Xcode 11 (and 11.1)?
Device 14.4
Results are the same, without the AddInstanceForFactory complaint.
Simulator 13.6
Audio never sounds, the delegate callback never runs, and in the Console I get:
14:30:10  [plugin] AddInstanceForFactory: No factory registered for ... F8BB1C28-...
14:30:11  HALB_IOBufferManager_Client::GetIOBuffer: the stream index is out of range
14:30:11  HALB_IOBufferManager_Client::GetIOBuffer: the stream index is out of range
14:30:11  [aqme] AQME.h:254:IOProcFailure: AQDefaultDevice (1): output stream 0: null buffer
14:30:11  [aqme] AQMEIO_HAL.cpp:1774:IOProc: EXCEPTION thrown (-50): error != 0

14:30:26  [aqme] AQMEIO.cpp:179:AwaitIOCycle: timed out after 15.000s (0 1); suspension count=0 (IOSuspensions: )
14:30:26  CA_UISoundClient.cpp:241:StartPlaying_block_invoke: CA_UISoundClientBase::StartPlaying: AddRunningClient failed (status = -66681).
14:30:26  *** Starting clip play
14:30:26  HALB_IOBufferManager_Client::GetIOBuffer: the stream index is out of range
14:30:26  HALB_IOBufferManager_Client::GetIOBuffer: the stream index is out of range
14:30:26  [aqme] AQME.h:254:IOProcFailure: AQDefaultDevice (1): output stream 0: null buffer
14:30:26  [aqme] AQMEIO_HAL.cpp:1774:IOProc: EXCEPTION thrown (-50): error != 0

14:30:41  [aqme] AQMEIO.cpp:179:AwaitIOCycle: timed out after 15.000s (1 2); suspension count=0 (IOSuspensions: )
14:30:46  !!! Caller found nil clip duration

Remarks
It seems that there are two fifteen-second delays going on in the failure case.


text:
Q: webapi - Custom value Provider to capture request header In ASP.NET Web-API, i am trying to read the Http request header information with the help of custom value provider technique mentioned in this article
https://www.c-sharpcorner.com/article/fetch-header-information-using-customvalueprovider-in-asp-ne/
Now this technique is working fine and it is giving me the value for the desired header key. But i want to modify the API controller action method signature to get the entire dictionary object of header.
My API controller method is looking like this :-
   [HttpPost]
   [Route("user-documents")]
  public async Task<IHttpActionResult> GetUserDocuments([ValueProvider(typeof(CustomHeaderProviderFactory))] string Client, SearchCriteria incomingObj)
        {    .... Logic ...... }

And here are the classes for the CustomHeaderProviderFactory.
  public class CustomHeaderProviderFactory : ValueProviderFactory
    {
        public override IValueProvider GetValueProvider(HttpActionContext actionContext)
        {
            return new CustomHeaderValueProvider(actionContext);
        }
    }

    public class CustomHeaderValueProvider : IValueProvider
    {

        public Dictionary<string, string> objCollection;
        public CustomHeaderValueProvider(HttpActionContext context)
        {
            objCollection = new Dictionary<string, string>();

            foreach (var item in context.Request.Headers)
            {
                objCollection.Add(item.Key, string.Join(string.Empty, item.Value));
            }
        }

        public bool ContainsPrefix(string prefix)
        {
            return objCollection.Keys.Contains(prefix);
        }

        public ValueProviderResult GetValue(string key)
        {
            if (key == null)
                throw new Exception("NullReferenceException");

            if (objCollection.TryGetValue(key, out string resultValue))
            {
                return new ValueProviderResult(resultValue, resultValue, System.Globalization.CultureInfo.InvariantCulture);
            }

            return null;
        }

    }

I want to change the signature of the API method, so that i can access the full request header object inside the body of the API method. It would be great, if i can access the full objCollection inside the API method.  Because i would to use other header values as well inside the method.
Please suggest how to make this code change.

A: Create a custom attribute and set a key in Request.Properties[].  You will be able to access that from your controller action
public class MyNewAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        actionContext.Request.Properties[<yourkey] = <your value>;
    }
}

However, why do you need this information in your controller action?  If it's information you need in your request, why not include it in the payload of the call instead of the header?


text:
Q: c# console application unassigned local variable         int ValueOne, ValueTwo, Numchar, Total;
    Console.WriteLine("This Is A Program For doing any Of the four mathematical Proccesses");
    Console.WriteLine("You can Add , substract , Divide And Multiply");
    Console.WriteLine("When Asked Please Type The Values Or The Proccesses You Want.");
    Console.WriteLine("Please Type The First Value");
    ValueOne = Convert.ToInt32((Console.ReadLine()));
    Console.WriteLine("Please Type The Second Value");
    ValueTwo = Convert.ToInt32((Console.ReadLine()));
    Console.WriteLine("Please Enter The Number Of The Proccess/Character You Want Meaning That (1 = +) , (2 = -) , (3 = *) , (4 = /)");
    Numchar = Convert.ToInt32((Console.ReadLine()));
    if (Numchar == 1)
        Total = ValueOne + ValueTwo;
    if (Numchar == 2)
        Total = ValueOne + ValueTwo;
    if (Numchar == 3)
        Total = ValueOne * ValueTwo;
    if (Numchar == 4)
        Total = ValueOne / ValueTwo;
    Console.WriteLine("The Total Is :");
    Console.WriteLine(Total);
    Console.ReadLine();

the Console.WriteLine(Total);
at the end is apparently an unassigned local variable , though it should be assigned from the Lines beneath the "If" lines, also note that I'm new in visual studio and i just started taking The Courses , also , i don't think this is a duplicate because the other post's fix Didn't Work for me.

A: Let's say that your code didn't produce an error, and compiled and ran. What do you think would happen if NumChar wasn't 1, 2, 3, or 4?
Your code would never reach any of the statements in your ifs there, and would never assign an initial value to Total. Since this is entirely possible given your program (and would be impossible to check for in general -- see the Halting Problem), the error is substantiated and necessary.


text:
Q: Close by or nearby?
The cops traced residential address of his relatives who lived close
  by.

Close up/down, close off, close in are terms well understood, I have not seen such usage of close + by.
Would it be better to write:

The cops traced residential address of his relatives who lived nearby.

A:
Close by/nearby in the sentence implies "close at hand or adjacent".

near – close: talking about short distances
If something is near, near to, or close to a place or thing, it is a short distance from it.
When near and close have this meaning, don't use them immediately in front of a noun. Instead use nearby.

*

*He was taken to a nearby hospital.

*He threw the bag into some nearby bushes.
Nearby, definitely, is more idiomatic than close by.

A: Usually, 'Close' is used when the sentence mentions a relationship of some sorts. And 'Near' is usually used in other notions. Although, in most cases these two are interchangeable.
EDIT:
Close By and Nearby however is completely interchangeable.


text:
Q: Fill array inside each loop jquery I would like to get values from the array created inside the each loop
var arr = [];

$.each([52, 97], function(index, value) {

    var arr = [value];

});

console.log(arr);

But the logged array has no entry.

A: The error what you did is var arr = [ value]; reinitialized variable, test this:
var arr =[];
$.each([ 52, 97 ], function( index, value ) {
 arr.push(value);
});
console.log(arr);

A: The error what you did is var arr = [ value]; reinitialized variable & wrong setting of array index.

var arr = [];

$.each([52, 97], function(index, value) {

  arr[index] = value;

});

console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can also do this with push() as in other answer(@Boris Bresciani).

A: Your variable arr inside the function is not the same as the outside variable arr, but local to the function. To fix that, do not create a new local variable, but let the function refer to the outside variable instead (this is called a closure). This should work:
var arr =[];
$.each([ 52, 97 ], function( index, value ) {
  arr.push(value);
});
console.log(arr);

A: You can simply use spread syntax to get the array element copied without reference. This means that you can independently change the content of any array without affecting the content of other.

var arr1 = [ 52, 97 ];
var res = [...arr1];
console.log(res);

A: Add value in Array using each loop in js

var ProductTypeId = [];
$("input[name=ProductTypeId]").each(function() {
    if ($(this).prop('checked') == true) {
        ProductTypeId.push($(this).val());
    }
});
alert(ProductTypeId`enter code here`);
<input type="checkbox" class="custom-control-input" name="ProductTypeId" id="<?php echo $term['productTypeId']; ?>"  value="<?php echo $term['productTypeId']; ?>">


text:
Q: Extract block of numerical data using regec in python I am trying to parse a file that presents some sections of numerical data. The goal is to extract each block of data for further parsing. The fact is that these sections span multiple lines (ended by \n), possibly with spaces at the beginning and the last line of the section presents the keyword END :
1 2 3 4
 2 5 6 7
3 8 9 10
*END

1 11  12 13
2 14 15 16
3 17 18 19
*END

What I want to extract with regex is the list of strings:
['1 2 3 4\n 2 5 6 7\n3 8 9 10',
 '1 11  12 13\n2 14 15 16\n3 17 18 19']

I do :
import re
ifile = open('file.dat', 'r')
data = ifile.read()

Then the regex pattern I built for a line is :
line = r'^(\s*\d+(?:\s+\d+){3}\s*)$'
pattern = re.compile(line, re.MULTILINE)
pattern.findall(data)

Then I get:
['1 2 3 4',
 ' 2 5 6 7',
 '3 8 9 10',
 '\n\n1 11  12 13',
 '2 14 15 16',
 '3 17 18 19']

A first question would be why the '\n' are retained in the fourth string ?
The way I would do to extract the two sections is:
section = r'(?:(' + line + ')*)\*END'
pattern = re.compile(section, re.MULTILINE)
pattern.findall(data)

But I can't manage to make it work. Maybe something I don't understand with MULTILINE flag ?

Edit :
I would like to specify the structure of a line (1 integer followed by 3 other integers) inside my regex. The solution of vks works but I would like to be a bit more specific. I tried the following :
for a line :
^\s*\d+(?:\s+\d+){4}\s*$

It works well (http://regex101.com/r/qZ6sE3/6)
For a section :
((?:^\s*\d+(?:\s+\d+){4}\s*$)*)(?=\s*\*END)

The idea here is to duplicate the line to form a multiline block and matching it only if it is followed by a line with *END.
http://regex101.com/r/qZ6sE3/7
However, the result is not that expected. It matches the last line but also some void strings... Any help in understanding ?
Regards,
François.

A: To answer to your question why the newline characters where present before the character 1 is because there where two empty lines before it.
As the data block is split based on '*END' text we can use it as delimiter and divide the file content into list. And then we can traverse the list and the use regex to process the data and collect the numbers.
#!/usr/bin/env python3

import re

data = open('file').read().split('*END')

items = []

for x in data:
    items.append(re.findall('(\d+)\s+', x))

print(items)

Output
[['1', '2', '3', '4', '2', '5', '6', '7', '3', '8', '9', '10'],
['1', '11', '12', '13', '2', '14', '15', '16', '3', '17', '18', '19'], []]

Here the list items has the contents of each block within a separate list.

A:
A first question would be why the '\n' are retained in the fourth string ?

Because they are matched by the first \s*.
In general, I would suggest to "parse" the file line by line, skipping empty lines and regex-parsing non-empty lines. Something like
data = []
block = []
for line in ifile.readlines():
  if not line.strip():
    continue
  elif line.startswith("*END"):
    data.append(block)
    block = []
  elif:
    m = re.match(r"(\d+)\s*(\d+)\s*(\d+)\s*(\d+)", line)
    block.append(m.groups())

A: I suggest that you split the text with '*END', then clean up the resulting pieces. This should be faster than going line by line or using regular expressions. I think it also captures the essence of the task, which is to find things separated by '*END'.
raw_parts = data.split('*END')
parts = []
for part in raw_parts:
    part = part.strip()
    if len(part) != 0:
        parts.append(part)

print(parts)

In response to your comment about the possibility of other types of data mingled with the numerical blocks, let me suggest this solution using a regular expression. The key idea is to use re.DOTALL to make the period match across multiple lines. That may be the behavior you were expecting from re.MULTILINE.
import re

pattern = re.compile('(\d.*?)\*END', re.DOTALL)
blocks = list(map(lambda s: s.strip(), pattern.findall(data)))
print(blocks)

A: ([\d\s]+)(?=\*END)

Try this.Grab the capture.See demo.
http://regex101.com/r/qZ6sE3/3
import re
p = re.compile(ur'([\d\s]+)(?=\*END)')
test_str = u"1 2 3 4\n 2 5 6 7\n3 8 9 10\n*END\n\n\n1 11 12 13\n2 14 15 16\n3 17 18 19\n*END"

re.findall(p, test_str)

Edit:
For new requiremnt try
((?:\s*\d+(?:\s+\d+){4}\s*)*)(?=\s*\*END)

See demo.
http://regex101.com/r/qZ6sE3/9

A: This would work for you,
import re
import sys
with open('file.txt', 'r') as f:
    file = f.read()
    file = re.sub(r'(?s)\n\*END$', r'', file)
    print(re.split(r'\n\*END\n+', file))

Output:
['1 2 3 4\n 2 5 6 7\n3 8 9 10', '1 11  12 13\n2 14 15 16\n3 17 18 19\n']


text:
Q: Unicenta password encryption i'm trying to develop i new version of Unicenta opos _ it's an Openbravo open source project _ working on android platforme, i'm almost done with, but i'm still have some problems with password part.
my problem is:
the Unicenta opos save the password in a mysql database using Sha1 encryption, so when i tried to do the same in my android application it does not gave me the same Encryption for the same password, then what i did; i looked for the Unicenta code source and i picked up the Encryption code and i put it as it is in my App;
Encryption function from unicenta code source:
public static String hashString(String sPassword) {

      if (sPassword == null || sPassword.equals("")) {
          return "empty:";
      } else {
          try {
              MessageDigest md = MessageDigest.getInstance("SHA-1");
              md.update(sPassword.getBytes("UTF-8"));
              byte[] res = md.digest();
              return "sha1:" + StringUtils.byte2hex(res);
          } catch (NoSuchAlgorithmException e) {
              return "plain:" + sPassword;
          } catch (UnsupportedEncodingException e) {
              return "plain:" + sPassword;
          }
      }
    }

so it's so clear that this function take a String as parametre (the Password) and return the (password encrypted)
but the problem is when i try to encrypt a password for example (0000) with unicenta opos it gaves me: (sha1:B6589FC6AB0DC82CF12099D1C2D40AB994E8410C) and with my android app using the same methode used by unicenta it gaves me another Hash (sha1:39dfa55283318d31afe5a3ff4a0e3253e2045e43)
sorry for being long, i hope if someone intersted!
thank u

A: Unicenta does not directly encrypt/hash passwords. Look at byte2hex and JEditorText.java for how it manipulates the input password before encryption. So 9802 is changed into 'Wt a' without quote and then hashed.
First function to hash:
MessageDigest md = MessageDigest.getInstance("SHA-1");
                    md.update(sPassword.getBytes("UTF-8"));
                    byte[] res = md.digest();
                    return "sha1:" + StringUtils.byte2hex(res);

byte2hex:
StringUtils.java
public static String byte2hex(byte[] binput) {

        StringBuilder sb = new StringBuilder(binput.length * 2);
        for (int i = 0; i < binput.length; i++) {
            int high = ((binput[i] & 0xF0) >> 4);
            int low = (binput[i] & 0x0F);
            sb.append(hexchars[high]);
            sb.append(hexchars[low]);
        }
//sb : 56E048B73E9B3EFF42C509B772AF6941FF0B5BA5
        return sb.toString();
    }

Finally look into JEditorText.java:
    private static final char[] CHAR_abc1_1 = {'.', '?', '!', ',', '1', ';', ':'};
    private static final char[] CHAR_abc1_2 = {'a', 'b', 'c', '2', '\u00a0'};
    private static final char[] CHAR_abc1_3 = {'d', 'e', 'f', '3', '\u201a'};
    private static final char[] CHAR_abc1_4 = {'g', 'h', 'i', '4', '\u00a1'};
    private static final char[] CHAR_abc1_5 = {'j', 'k', 'l', '5'};
    private static final char[] CHAR_abc1_6 = {'m', 'n', 'o', '6', '\u00a4', '\u00a2'};
    private static final char[] CHAR_abc1_7 = {'p', 'q', 'r', 's', '7'};
    private static final char[] CHAR_abc1_8 = {'t', 'u', 'v', '8', '\u00a3', '\ufffd'};
    private static final char[] CHAR_abc1_9 = {'w', 'x', 'y', 'z', '9'};
    private static final char[] CHAR_abc1_0 = {' ', '0'};

    private static final char[] CHAR_ABC1_1 = {'.', '?', '!', ',', '1', ';', ':'};
    private static final char[] CHAR_ABC1_2 = {'A', 'B', 'C', '2', '\u00b5'};
    private static final char[] CHAR_ABC1_3 = {'D', 'E', 'F', '3', '\u00c9'};
    private static final char[] CHAR_ABC1_4 = {'G', 'H', 'I', '4', '\u00cd'};
    private static final char[] CHAR_ABC1_5 = {'J', 'K', 'L', '5'};
    private static final char[] CHAR_ABC1_6 = {'M', 'N', 'O', '6', '\u00d1', '\u00d3'};
    private static final char[] CHAR_ABC1_7 = {'P', 'Q', 'R', 'S', '7'};
    private static final char[] CHAR_ABC1_8 = {'T', 'U', 'V', '8', '\u00da', '\u00dc'};
    private static final char[] CHAR_ABC1_9 = {'W', 'X', 'Y', 'Z', '9'};
    private static final char[] CHAR_ABC1_0 = {' ', '0'};

A: Try this may help you
private String hashString(String s) {
        try {
            // Create SHA-1 Hash
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
            digest.update(s.getBytes("UTF-8"));
            byte messageDigest[] = digest.digest();

            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++)
                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


text:
Q: Search detected faces from a database OpenCV I am working with this Code:
Program sample
the above link has been programmed with the help of this page:
Servo Magazine
This Code can do Extract face, learn face and save the learn face in a database with a label(example: chris_laughing.bmp or chris_sad.bmp). It can be recognize the face that the User saved in a Database.
My Project is send a E-Mail to user if the Person not in the database.

*

*i included a function to send a E-Mail to the user.

So i have saved 2 different Images from 2 Stars chris and john. When i click recognize they show me the correctly star with label(example: chris_laughing.bmp) from the database.
The Problem is if i Extract(detect) a face from a other star or person (also not chris not john) the Code show me the NEAREST star from the database.
What i want is that the Program give me a Messagebox that say: this Person is not in the database.
Is it possible with this Program(code)??

A: That program works by assuming that face images for each person lie in a subspace different to that for other people. This idea can work really well in some situations. The program learns a subspace for each person and when you input a new image it measures the distance to all subspaces it has previously learned and chooses the nearest one.
The program doesn't seem to have any sort of check that the image is too far from all learned subspaces. However, it would be an interesting exercise to try to add that feature.
Here is a some info about the main idea in the software: http://en.wikipedia.org/wiki/Eigenface


text:
Q: Double checking if contours are correct Since
$$ |z| = 1 $$
is the unit circle centered at (0,0) which is used as a contour for a lot of integration problems, would
$$ |z - i| = 1,   |z + 3| = 1 $$
simply be translations of the unit circle, with the first one centered at (0,-i) and the next one at (3,0)?


text:
Q: Добавить картинку в  Собственно, в чём вопрос. Делаю Range Slider. Хочу вот добавить вместо обычного range (она же кнопка прокрутки) изображение. Как это сделать?)
введите сюда код

Ссылка

A: Посмотрите как реализовано на CSS изменение вида RANGE:

input[type=range] {
  -webkit-appearance: none;
  margin-top: 0.5rem;
  width: 100%;
  border: none !important;
  background: transparent;
  padding: 0; }
  input[type=range]:focus {
    outline: none; }
  input[type=range]::-webkit-slider-runnable-track {
    width: 100%;
    height: 0.3rem;
    cursor: pointer;
    animate: 0.2s;
    background: #eee;
    border-radius: 5px; }
  input[type=range]::-webkit-slider-thumb {
    height: 1rem;
    width: 1rem;
    border-radius: 0.5rem;
    background: #0275d8;
    cursor: pointer;
    -webkit-appearance: none;
    margin-top: -0.35rem; }
  input[type=range]::-moz-range-track {
    width: 100%;
    height: 0.3rem;
    cursor: pointer;
    animate: 0.2s;
    background: #eee;
    border-radius: 5px; }
  input[type=range]::-moz-range-thumb {
    height: 1rem;
    width: 1rem;
    border-radius: 0.5rem;
    background: #0275d8;
    cursor: pointer; }
  input[type=range]::-ms-track {
    width: 100%;
    height: 0.3rem;
    cursor: pointer;
    animate: 0.2s;
    background: transparent;
    color: transparent; }
  input[type=range]::-ms-fill-lower {
    background: #e1e1e1;
    border-radius: 10px; }
  input[type=range]::-ms-fill-upper {
    background: #eee;
    border-radius: 10px; }
  input[type=range]::-ms-thumb {
    height: 1rem;
    width: 1rem;
    border-radius: 0.5rem;
    background: #0275d8;
    cursor: pointer; }
  input[type=range]:focus::-ms-fill-lower {
    background: #eee; }

datalist {
  display: flex;
  justify-content: space-between;
  height: 6px;
  overflow: hidden;
  margin-top: -6px; }
  datalist option::before {
    content: '';
    display: block;
    width: 0;
    border-right: 1px solid #DDD;
    height: 10px;
    padding-left: 3px;
    text-indent: 0; }
<input type="range" id="size" name="size" class="form-control form-control-sm" min="1" max="5" step="1" list="range_list">
<datalist id="range_list">
 <option>1</option>
 <option>2</option>
 <option>3</option>
 <option>4</option>
  <option>5</option>
</datalist>


text:
Q: Error in using WHERE for search function in Ruby on Rails I made a controller to search something ,
but the result was weird:
My code:
  def create
    @word = searching_params[:word]
    @searching = current_user.searchings.build(word: @word)
    flash[:notice] = "New searching is performed!" if @searching.save
    @users = User.where("firstname LIKE ? OR lastname LIKE ?", "%#{@word}%", "%#{@word}%")
    @posts = Post.where("body LIKE ?", "%#{@word}%")
    render :index
  end

So, when i searched for a name: Mose Collins,
o, se, ose could get the result,
but m, c, co and others would give me nothing.

A: LIKE performs a case sensitive match. If you want to perform a case insensitive match in a somewhat polyglot fashion you can use the LOWER() SQL function:
@users = User.where("LOWER(firstname) LIKE ? OR LOWER(lastname) LIKE ?", "%#{@word.downcase}%", "%#{@word.downcase}%")

Postgres has a ILIKE function which is case insensitive:
@users = User.where("firstname ILIKE ? OR lastname ILIKE ?", "%#{@word.downcase}%", "%#{@word.downcase}%")

You can also use Arel to construct it instead of a SQL string:
class User < ApplicationRecord
  has_many :favorite_jobs

  def self.search(term)
    where(
      arel_table[:firstname].matches("#{name}").or(
        arel_table[:lastname].matches("#{name}")
      )
    )
  end
end

This approach is more portable and espcially shines if you want to built the query programatically.


text:
Q: How to Excel Copy from one Sheet to another with vba I need some help for my Excel sheet,
I have the first sheet and this is blank
and on the seconde sheet i have a list and in the column D i can change the value starts from 1.
And when i changed in the column a cell then it should copy the row to the first sheet.
thanks
Regards

A: It is not clear for me what you want to do. If you want VBA to copy the row automatically, you should go to the module of the corresponding Worksheet in the VBA editor (in the list of the Wroksheets on the left, just double-click the Worksheet to open up the module associated with it). After that, write an event handler:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column = 4 Then
        ActiveSheet.Rows(Target.Row).Copy Worksheets("Sheet1").Rows(whichRowYouNeed)
    End If
End Sub

you should also write a routine to determine the 'whichRowYouNeed'
It may be the end of the filled range on Worksheet1

A: Hey sorry for my bad statement, i try it again :)
The first sheet is blank,
The Second sheet is that:
When i add a number in column D then I want to copy this row, in that case row 8, copy to the first sheet starting from row 5.
I hope now it is better to understand


text:
Q: Different results statsmodels(python) vs. R autocorrelation Question: why are R and python's statsmodels giving such different results in the ACF?
I tried to replicate an example from a Time Series Analysis book in python and not only I don't get the same smooth shape but I see only erratic behavior. I have checked if I was coding something wrong (e.g. the parameters) but I don't seem to find any solution. Any hints?
R source
This is the example from R that I'm trying to replicate, extractred from Time Series Analysis, Chan and Cryer 2008:

Python source
My attempt with statsmodels:
import matplotlib.pyplot as plt
import statsmodels.api as sm

from statsmodels.graphics import tsaplots

fig, ax = plt.subplots(2,2, figsize=(10, 10), sharey=True, sharex=True)
for n, i in enumerate([[0.5,0.25], [1, -0.25], [1.5, -0.75], [1, -0.6]]):
    y = sm.tsa.arma_generate_sample(ar=[1]+[-j in i for j in i], ma=[1, 0], nsample=100)
    tsaplots.plot_acf(y, ax[n//2][n%2], lags=20, fft=True)#lags=len(y)//2)
    if n//2: ax[n//2][n%2].set_xlabel('Lag [t]')
    if n in [0,2]: ax[n//2][n%2].set_ylabel(r'Correlation [$\rho$]')
    ax[n//2][n%2].legend(['AR(2)={}'.format(i)])
plt.show()

The output:

A: Thanks to Josef, I found out my typo (see: here). Now that it is changed, the plots look way more similar:

Due to the random nature of the processes, I was not expecting to get exactly the same results but qualitative similar. Now that the typo is solved, they do look similar.
Checking the code with someone after having worked long on the same thing is my lesson learnt here.


text:
Q: Changing the default mod_policy in Hyperledger Fabric I have seen that default mod_policy is set to Admins policy at that level of configuration, however if I want to set it to MyPolicy (which may be any custom valid policy) then how to do that?
Can I achieve it in configtx.yaml itself?

A: Yes, this could be done. You can check the article which shows how to create a new custom policy and how to update the ACL from configtx.yaml only.

A: I could achieve this successfully by following the below steps:

*

*Started the fabric-samples/first-network.

*Perform docker exec into the cli container.

*Set the environment corresponding to peer0.org1.example.com and that organization's admin user: Admin@org1.example.com. Fetch the latest application channel (here mychannel) configuration block.

*Edit the decoded JSON block by changing the mod_policy value under the policies section for the Org1MSP under the Application group. Change it from Admins to Readers.

*Submit the channel update transaction by encoding and signing the delta block into a protobuf envelope.

Now, our task is to verify this new mod_policy is working fine or not. For this, do the following:

*

*Set the cli environment to peer0.org1.example.com and that organization's user: User1@org1.example.com. Fetch the latest application channel (here mychannel) configuration block.

*Edit the decoded JSON block by changing the Readers policy in the Org1MSP from "OR('Org1MSP.admin', 'Org1MSP.peer', 'Org1MSP.client')" to "OR('Org1MSP.admin', 'Org1MSP.peer')" by keeping the JSON syntax of policies in mind.

*Submit the channel update transaction. The successful update denotes that the Readers policy (the new mod_policy for that section) was satisfied as we submitted the channel update on behalf of the User1@org1.example.com (a client user). Note that while updating channel configuration at this moment, the Readers policy will be evaluated as "OR('Org1MSP.admin', 'Org1MSP.peer', 'Org1MSP.client')" as the update has not been processed.

*Now using the same cli environment, try to fetch the latest application channel configuration block. The following error appears:
2020-04-09 22:25:48.990 UTC [channelCmd] InitCmdFactory -> INFO 001 Endorser and orderer connections initialized
 2020-04-09 22:25:49.001 UTC [cli.common] readBlock -> INFO 002 Got status: &{FORBIDDEN}
This is because now to read the configuration block, User1@org1.example.com with client OU won't be able to satisfy the new Readers policy i.e. "OR('Org1MSP.admin', 'Org1MSP.peer')".


text:
Q: Response type "pass through" works as expected, but when I changed it to "XML" only GET requests works I have a MPG that, until now, the request and response were defined as "pass through", but now I want to ensure that the request is XML.
I defined the Request Type as "XML", and now only GET requests make it through to the server.
In the probe I see, what seems to me, a perfectly valid XML, but after the implied filter it drops it with error 'rejected'.
I'm sending the XML, to test, via curl as such curl -X POST -d '<note>value</note>' -H 'Content-Type: application/xml' http://1.2.3.4:5678


text:
Q: I'm trying to initialize a UIViewController to be pushed I began from a tutorial example that had a UIViewController connected to a nib, but now i've decided to do it all programmatically. Consequently, I deleted the nib but without knowing how to implement my controller.
I did something like this:
EventsDetailController *myChild = [[EventsDetailController alloc] init];
[self.navigationController pushViewController:myChild animated:YES];

However, it crashes when I click the specific cell.
Do I have to initWith something? Before when I had a nib it was initWithNib
#import <UIKit/UIKit.h>

@interface EventsDetailController : UIViewController {

    NSString *message;
}

@property (nonatomic, copy) NSString *message;

@end

#import "EventsDetailController.h"

@implementation EventsDetailController
@synthesize message;

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

}

-(void)viewDidLoad{

    UILabel *theMsg = [[UILabel alloc] initWithFrame:CGRectMake(0,0,200,30)];

    theMsg.text = @"hello";

    [theMsg release];
    [super viewDidLoad];
}

-(void)viewDidUnload{

    self.message = nil;
    [super viewDidUnload];

}

-(void)dealloc{

    [message release];
    [super dealloc];

}
@end

Perhaps, I'll start from scratch, I think it is still looking for the nib I deleted.

A: I'm assuming that you have the app delegate's window.rootViewController set to a NavigationController instance, and that instance was created with a initWithRootViewController, as you mentioned that you're getting to the point where it crashes when you click on a cell.
Looking at the added code, the only thing I see that's strange is in the 'veiwDidLoad' method - you alloc and release 'theMsg', but don't use it. I'm assuming you've cut out some code for brevity.
I ended up starting from scratch when I went away from .nib files (about 5 minutes after starting my first iPhone app). I would run with that, adding in your functionality a little at a time.


text:
Q: Join two regex or do the same inside the same regex Got this string:
26/02/2015	09:00	26/02/2015	12:00	3	I1/121	10074 codification	103126 Codification, Cooperation and development - 11	Walter Shelter, Mary; Johnson Smith, Robert; Dickinson Queen Patty	without group

And I want to extract the next information:
02 103126-11 Walter Johnson Dickinson

I can figure out how to get the 02 103126-11 Walter part with the regex:
$nodup_filtertoexec = preg_match('/\d{2}\/(\d{2})\/\d{4}.*?\d+\s.*?(\d+)\s.*?-\s(\d+).*?(?:.*?){1}([a-zA-ZñÑ]+).*/m', $filtered, $matches);

So the problem is I can't realize how to get the first surname value part of every second value before ;.
Here's the link to regex101 with the actual regex regex to get 02 103126-11 Walter values
The regex to get the three surnames is:
(?:(?<=^)|(?<=; ))\w+

Here's the regex101 example:
regex to get the Walter Johnson Dickinson values
So it would be good to know how to join the two regex expressions in one.
UPDATE:
Here is my latest try, not working as expected yet. Only need to know how to iterate the last part of the regex to get "Proof" and "Prooftwo" or "Proofthree" (if exist), etc... from the html. Any help will be appreciated.
I've been testing with (?<=;) and (?=;) without luck.
https://regex101.com/r/oQ1fJ1/4

A: I did some tests and this works if you have 3 words to get:
\d{2}\/(\d{2})\/\d{4}.*?\d+\s.*?(\d+)\s.*?-\s(\d+).*?(?:.*?){1}([a-zA-ZñÑ]+)[^;]+; ([a-zA-ZñÑ]+)[^;]+; ([a-zA-ZñÑ]+)

The key point is this to get the first word after ;:
{1}([a-zA-ZñÑ]+)[^;]+; ([a-zA-ZñÑ]+)[^;]+; ([a-zA-ZñÑ]+)

https://regex101.com/r/tM9nW3/1
You of course can group them (regex){2} if you think the number of elements won't be static.


text:
Q: Receiving unstructured data with Business Central web service/api? I want to expose an endpoint in Business Central which can receive HTTP POST/PUT request and save content of that request into Blob, without any validation. I need that so I can receive json or xml data from external custom services.
I'm not sure how to achieve that since both OData and SOAP expect data to be in specific format and trigger data validation before I can even access POST-ed data.
I've been trying to play with Bound/Unbound actions but still can't figure out a way to access the content of the request. WebServiceActionContext is not well documented and I have not idea what I can or can't do with it. More about that: Microsoft documentation, Tutorial.
Any idea how to read content of a HTTP POST/PUT request is appreciated!

A: You could create a codeunit with a global procedure and then publish that as your web service.
Something like this:
codeunit 50000 MyUnstructuredWebService
{
    procedure PostUnstructuredData(RequestId: Text; RequestContent: BigText);
    begin

    end;
}

Then you can handle the data directly or save it to a BLOB field in a table for later use.
The trick is to use BigText as the datatype for the parameter containing your actual content.


text:
Q: how to reload video in axVLCPlugin21 using C# How to reload video in axVLCPlugin21 using C# my code just working one time and just open one video although open another video this my code:
private void panel2Open_Click(object sender, EventArgs e)
{

      if (openFileDialog1.ShowDialog()==DialogResult.OK)
      {
          axVLCPlugin21.playlist.add(openFileDialog1.FileName);
          axVLCPlugin21.playlist.play();
          axVLCPlugin21.playlist.items.clear();
      }

}

A: It is working fine for me even I used it by getting video links for Datagridview:
 string videoSource=dataGridView1.Rows[e.RowIndex].Cells["Link"].Value.ToString();
 axVLCPlugin21.playlist.add(videoSource, "video", " ");
 axVLCPlugin21.playlist.next();
 axVLCPlugin21.playlist.play();


text:
Q: Linked Lists remove function in c++ I am trying to finish up an assignment regarding linked lists in c++ but my remove function seems to be crashing the app every time I try to use it. I've tried a few different things but I seriously don't know what's wrong. For example if I only have one item in the list and try to remove it it crushes same goes for any other case. If anyone knows what's wrong please help :)
template <class T>
Error_code List<T>::retrieve(string fn, T& item)
{
    if (empty()) return underflow;

    Node<T>* temp = head;

    while (temp->entry.FlightNO.compare(fn) != 0) {
        if (temp->next == NULL)
            return not_found;
        temp = temp->next;
    }

    item = temp->entry;

    return success;
}

template <class T>
Error_code List<T>::remove(T& item)
{
    Node<T>* current = head;
    Node<T>* search = new Node<T>(item);

    if (head == search) {
        head = head->next;
        return success;
    }

    else {
        Node<T>* previous = current;
        current = current->next;

        if (current->next == NULL) {
            delete current;
            return success;
        }

        while (current != search)
        {
            previous = current;
            current = current->next;
        }

        previous->next = current->next;
        return success;
    }
}

This is my code, the first function is to retrieve the item and check if it actually exists, then the second is the remove which doesn't work

A: Everything what was mentioned in the comments is on point. However you came here looking for an answer, so here you go:
template <class T>
Error_code List<T>::remove(T& item)
{
    Node<T>* current = head;
    Node<T>* search = new Node<T>(item); // <--- why?

    //if (head == search) {    //<-- always false
    //    head = head->next;
    //    return success;
    //}

    Node<T>* previous = current;
    current = current->next;

    if (current->next == NULL) {
        delete current;
        return success;
    }

    while (current != search) // <--- fails here, this is always true (you are comparing pointers, not objects)
    {
        previous = current;
        current = current->next; // <--- because this loop is always true and you have a nullptr terminated list then this will segfault with RAV
    }

    previous->next = current->next;
    return success;
    }
}

EDIT: Just to clarify what causes the segfault, at the "end of the loop" you eventually call
nullptr->next;


text:
Q: I have found on the Internet polynomial time algorithm for graph coloring, possibly proving P=NP I was searching for graph coloring algorithms, and I have found algorithm, which, how author states, runs in polynomial time.
Author gives also C++ program source code and demonstration program.
The suspicious thing is that decision problem whether graph is k-colorable, is NP-complete, so no polynomial time algorithm should exist until P=NP.
However, author doesn't claims, that algorithm works for all graphs, he only says, that he haven't found any graph, for which algorithm doesn't work.
So, the question: does that algorithm really works for every graph and that means actually P=NP, or there exist certain graphs/graph classes for which it doesn't work? Or maybe there is simply a mistake in complexity calculation?

A: I think you haven't read the abstract very carefully.
The author presents an algorithm which finds m-colorings of a graph, for some m less than the limit imposed by Brooks' theorem: https://en.wikipedia.org/wiki/Brooks'_theorem
(which is old and states that chi < delta + 1 as the author states in second sentence.)
The author is aware of the P vs NP question. The paper does not claim to resolve the question, he merely states:

For all known examples of graphs, the algorithm finds a proper m-coloring of the vertices of the graph G for m equal to the chromatic number χ(G)

Then he asks,

In view of the importance of the P versus NP question, we ask: does there exist a graph G for which this algorithm cannot find a proper m-coloring of the vertices of G with m equal to the chromatic number χ(G)?

Emphasis in original (!)
So it doesn't claim to resolve P vs NP, its just, as a matter of academic research, they ask "can anyone produce an example on which this algorithm fails to reach the chromatic number", which might be instructive to them for mathematical purposes. It is highly unlikely that the algorithm actually achieves the chromatic number for all graphs. (Although it is, scientifically speaking, unknown whether it does or doesn't.)


text:
Q: on touch of YouTube iFrame embed adds delay to clicks on iOS Safari I've an embedded YouTube video on a page as normal:
<iframe src="https://www.youtube.com/embed/dC0kYlHWrZ8" />

As you can see if you click the button it increments the count and feels normal and responsive. Now if you touch the video and scroll the page without playing it, it seems to add a delay to the button and it now feels sluggish/requires a hard press.
Once you play/pause the video using the native HTML 5 controls, the button becomes responsive again.
https://jsfiddle.net/qfxma8bj/2/embedded/result

I cannot seem to stop this behaviour! As our website is an SPA it delays all interactions with the site thereafter and really ruins the experience.


text:
Q: How could I write a get_categories_by_year() function? I need to write a function to get all the categories for a given year. Since the creation date of a taxonomy isn't stored in the database, I'm not really sure what to do. My initial thought was to get all posts for a given year and somehow find all categories associated with those posts, but I'm not sure how to do that and it sounds horrifically slow. Perhaps I could just write some SQL but I'm much more well versed in PHP. So again back to the function, I imagine it would like something like:
function get_categories_by_year($year) {
 // Do stuff...
 return $array_of_categories_in_year;
}

This is actually for a custom taxonomy but since categories are the default hierarchical taxonomy I decided to use it as an example. I'm happy to provide more info on what the output is supposed to look like if it's relevant. Thank's for the help!

A: I would do this with SQL query. Doing it in PHP will be a little bit slow, I guess.
This function should do the job:
function get_categories_from_year($year) {
    $sql = "select term.*
        from {$wpdb->terms} term
            inner join {$wpdb->term_taxonomy} tax on (term.term_id = tax.term_id)
            inner join {$wpdb->term_relationships} relation on (tax.term_taxonomy_id = relation.term_taxonomy_id)
            inner join {$wpdb->posts} post on (relation.object_id = post.ID)
        where tax.taxonomy = 'category' and YEAR(post.post_date) = %d";
    return $wpdb->get_results( $wpdb->prepare($sql, $year) );
}


text:
Q: Facing issue while appending dropdown object with string in Jquery I have to append dropdownlist in div with ul li. When I am append with whole ul li string then it is appearing like [object object] where as if I append only dropdown then it is coming as html dropdown control that is correct.
Is there any way to append dropdown with string?
My Html:
<select id='sel'>
  <option value='1'>Option 1</option>
  <option value='2'>Option 2</option>
  <option value='3'>Option 3</option>
  <option value='4'>Option 4</option>
</select>
Add

My jquery function:
 function createNewSelect(a) {
    var selVal = $(''+ a +'').val();
    var ddl = $(''+ a +'').clone();
    $('select').each(function() {
        $(ddl).find("option[value='"+ selVal +"']").remove();
    });
    var newId = 'sel' + $('select').length;
    $(ddl).attr('id',newId);
    $('#aselect').attr("onclick","createNewSelect('#"+ newId +"')");

    $("body").append("
Social Media
" + ddl + "
");
    $("body").append(ddl);
}

https://jsfiddle.net/4uqgmqzc/3/

A: You are trying to append whole object instead of html you need to update your code as shown below
function createNewSelect(a) {
        var selVal = $(''+ a +'').val();
        var ddl = $(''+ a +'').clone();
        $('select').each(function() {
            $(ddl).find("option[value='"+ selVal +"']").remove();
        });
        var newId = 'sel' + $('select').length;
        $(ddl).attr('id',newId);
        $('#aselect').attr("onclick","createNewSelect('#"+ newId +"')");

        $("body").append("
Social Media
" + ddl[0].outerHTML + "
");

        $(ddl).change(function() {
            createNewSelect(this);
        });
}

good luck !!

A: You need to change your snippet to simple callback. Your snippet would be
<select id='sel'>
    <option value='1'>Option 1</option>
    <option value='2'>Option 2</option>
    <option value='3'>Option 3</option>
    <option value='4'>Option 4</option>
</select>
Add

And your javascript code would be
function createNewSelect2 () {
    $("#out").append("
" + $("select#sel :selected").text() + "
");
    $("select#sel :selected").remove();
}

FIDDLE

A: try to append it like this $("body").append(ddl[0]);
What you are trying to append is a jquery object. Basically an array of all the select elements which in your case is just one. hence use the index accessor to get the select statement and append.


text:
Q: Applying impulse at angle based on touch location I'm currently developing a game with a cannon that shoots a projectile, I'm having trouble figuring out how to get the projectile to fire at the angle based on the touch location and how far away it is from the cannon. this is the code i'm using below.
let dx = cannon.position.x - (touchLocation.x)
        let dy = cannon.position.y - (touchLocation.y)
        let angle = atan2(dy, dx)

        bullet.zRotation = angle
        bulletspeed = Double.random(in: 1...6)

        //let angle1 = Double.random(in: 0.2...5); let angle2 = Double.random(in: 1...4)

        // dx must be somewhere between 0.2 to 5
        bullet.physicsBody?.applyImpulse(CGVector(dx: -angle , dy: -angle))

this doesn't seem to work and i've resorted to using the angle as my x and y values which works but not well.
I'm trying to get the cannon to fire based on the angle of the touch location and to change the speed/power of the projectile by how far way the touch location is from the cannon. How can I do this?

A: The vector you need to use takes in dx and dy as parameters. You already have these but you say the speed is too fast. That's because the length of the vector is the speed.
So in your example the speed can be calculated like...
sqrt(dx*dx+dy*dy)

What you need to do is calculate a 'unit vector' that is, a vector with length equal to one.
You can do this by dividing dx and dy by the length of the vector.
So...
touchDX = //your calculation
touchDY = //your calculation

touchLength = sqrt(touchDX*touchDX+touchDY*touchDY)

unitVectorDX = touchDX / touchLength
unitVectorDY = touchDY / touchLength

// now put the speed you want in...

speed = 10

vector = CGVector(dx: unitVectorDX * speed, dy: unitVectorDY * speed)

Now, if you use the vector in your impulse it will have the correct direction and speed.
Quick side note, I'm typing on my iPad so don't have access to code completion etc... you may be able to do this using APIs on CGVector. I think I remember a 'unitVector' property that returns a unit vector. But I may be mistaken.


text:
Q: How to update a progress bar so it increases smoothly? I'm using progress bar of WPF (C#) to describe the process's progress.
My algorithm is below:
DoSomethingCode1();
ProgressBar.SetPercent(10); // 10%
DoSomethingCode2();
ProgressBar.SetPercent(20); // 20%

...

DoSomethingCode10();
ProgressBar.SetPercent(100); // 100%

It's ok, but it will make the progress bar was not sequent.
Someone can tell me some suggestions that make the progress bar is updated softly?

A: You can use a behavior!
public class ProgressBarSmoother
{
    public static double GetSmoothValue(DependencyObject obj)
    {
        return (double)obj.GetValue(SmoothValueProperty);
    }

    public static void SetSmoothValue(DependencyObject obj, double value)
    {
        obj.SetValue(SmoothValueProperty, value);
    }

    public static readonly DependencyProperty SmoothValueProperty =
        DependencyProperty.RegisterAttached("SmoothValue", typeof(double), typeof(ProgressBarSmoother), new PropertyMetadata(0.0, changing));

    private static void changing(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var anim = new DoubleAnimation((double)e.OldValue, (double)e.NewValue, new TimeSpan(0,0,0,0,250));
        (d as ProgressBar).BeginAnimation(ProgressBar.ValueProperty, anim, HandoffBehavior.Compose);
    }
}

Your XAML would look like this:
<ProgressBar local:ProgressBarSmoother.SmoothValue="{Binding Progress}">

Whenever the Progress property you are binding to in the xaml changes, the code in the ProgressBarSmoother behavior will run, adding the animation to the progress bar for you with the appropriate values for To and From!

A: Check if you can modify the style of the progressbar and set an Easing function to it's storyboard that modifies the "filling" of the progressbar and by doing that it will have a smooth transition.

A: You could call the BeginAnimation method to animate the ProgressBar's Value property. In my example below, I used a DoubleAnimation.
I created an extension method that takes in the desired percentage:
public static class ProgressBarExtensions
{
    private static TimeSpan duration = TimeSpan.FromSeconds(2);

    public static void SetPercent(this ProgressBar progressBar, double percentage)
    {
        DoubleAnimation animation = new DoubleAnimation(percentage, duration);
        progressBar.BeginAnimation(ProgressBar.ValueProperty, animation);
    }
}

So in your code you could simply call:
myProgressBar.SetPercent(50);

Doing this simply smooths out the transition so it looks nicer. To quote another answer: "The idea is that a progress bar reports actual progress - not time elapsed. It's not intended to be an animation that just indicates something is happening." However, the default style of the progress bar does have a pulsating effect which can imply work is happening.

A: try this out.
private void updateProgressBar(int percent)
    {
        if (ProgressBar.InvokeRequired)
        {
            updateProgressBarCallback cb = new updateProgressBarCallback(updateProgressBar);
            this.Invoke(cb, new object[] { percent });
        }
        else
        {
            ProgressBar.Value = percent;
            ProgressBar.Update();
            ProgressBar.Refresh();
            ProgressBar.Invalidate();
        }


text:
Q: Jupyter R crashes when plotting in docker container I am trying to set up Jupyter using Docker. I would like to provide multiple languages kernels (python, scala, R etc.) Now it seems work for others but R.
Everytime I execute a 'plot' function, the browser will tell me "The kernel appears to have died. It will restart automatically"
And the error message in log is:
 ***caught segfault ***
 address 0x35da0, cause 'memory not mapped'
 Traceback:
 1: png(tf, width, height, "in", pointsize, bg, res, antialias = antialias)
 2: dev.cb(tf)
 3: repr_recordedplot_generic(obj, ".png", TRUE, function(tf) png(tf, width, height, "in", pointsize, bg, res, antialias = antialias))
 4: repr_png.recordedplot(plotobj)
 5: mime2repr[mime]
 6: doTryCatch(return(expr), name, parentenv, handler)
 7: tryCatchOne(expr, names, parentenv, handlers[[1L]])
 8: tryCatchList(expr, classes, parentenv, handlers)
 9: tryCatch({ formats[[mime]] <- mime2repr[mime]}, error = handle_error)
 10: send_plot(last_recorded_plot)
 11: executor$execute(msg)
 12: handle_shell()
 13: kernel$run()
 14: IRkernel::main()
 aborting ...
 [I 2016-06-08 19:41:02.360 XX restarter:103] KernelRestarter: restarting kernel (1/5)
 WARNING:root:kernel XXXXXXXXXXXXXXXXXX restarted

If I execute a function of png() or jpeg() from the browser (Google Chrome) first, then plot() function could be executed successfully. I don't know why this happens, what will be changed after running png() or jpeg(). Has anyone met similar issues in either Jupyter or R?

A: This ended up avoiding using conda while downloading/installing the R packages. Instead, CRAN is used. It seems something is wrong with the compiled packages in conda.


text:
Q: CombGuid differents in C# and SQL Server I'm trying to generate a CombGuid with my own seed, and I need that code be generated equals both in C# and SQL Server.
I'm following the idea of CombGuid generation as stated in this site:
http://www.informit.com/articles/article.aspx?p=25862&seqNum=7
I'm also borrowing C# code from:
https://github.com/richardtallent/RT.Comb
The problem I can't make the last group of the Guids be generated equal in both languages. In SQL Server I know it's working, because I can reverse the Guid to Bigint again.
But in C#, when I try reverse it, the value is returned lower than the original.
What am I doing wrong?
Here is the code:
C#:
        //create a Guid and convert it to byte
        var gbytes = Guid.NewGuid().ToByteArray();

        //create the last part of a Guid with a big seed
        var ms = 281474967000000 +  Math.Floor(DateTime.Now.Subtract(new DateTime(2018,2,21)).TotalMinutes / 10.0);
        var msBytes = BitConverter.GetBytes(ms);
        if (BitConverter.IsLittleEndian) Array.Reverse(msBytes);

        //copy bytes for later use
        var byteLen = 6;
        var dbytes = new byte[byteLen];
        var index = msBytes.GetUpperBound(0) + 1 - byteLen;
        Array.Copy(msBytes, index, dbytes, 0, byteLen);

        //replace the last part of the guid with my seed
        Array.Copy(dbytes, 0, gbytes, 10, 6);
        var guid = new Guid(gbytes);
        //results: 6e07bc10-20d6-4cee-aefe-**ffffed7a8ec0**

T-SQL (SQL Server):
--this is how I generate the Guid part
    SELECT
        CAST(CAST(NEWID() AS BINARY(10)) +
        CAST(cast((floor(DATEDIFF(MINUTE, '2018-02-21', getdate())/10) + 281474967000000) as bigint) as BINARY(6)) AS UNIQUEIDENTIFIER)
        --results: 2E2FC4CC-CA45-4C6B-81D2-**FFFFFF6BD45D**

--this is how I check its working
select format(convert(bigint, convert(binary(6), '0x' + 'FFFFFF6BD45D', 1)), '#,0')

Notes:
In C#, it generated:
6e07bc10-20d6-4cee-aefe-ffffed7a8ec0

In T-SQL, it generated:
2E2FC4CC-CA45-4C6B-81D2-FFFFFF6BD45D

Note the last group of the guids only. They would be the same as I'm changing it only at next 10 minutes.
In T-SQL, I can reverse the "FFFFFF6BD45D" back to BigInt with no problems.
In C#, the reversed number is a lower value.
I think that the problem should be in the byte[6] (the size?), but I can't understand why in SQL it works fine and in C# not.

A: Problem is Math.Floor return type is double in your case, so type of ms is double. Floating point numbers are represented differently in memory, so  BitConverter.GetBytes(double) produces not the same result as BitConverter.GetBytes(long), even if values are the same. So to fix, cast the result to long, just as you do in your SQL query (with as bigint):
var ms = 281474967000000 + (long)Math.Floor(DateTime.Now.Subtract(new DateTime(2018, 2, 21)).TotalMinutes / 10);


text:
Q: Allowing Empty Cells in a datagrid WPF I am currently using a datagrid where I leave the value empty for a few weeks until I need to fill it. My datagrid will not allow the value to be empty and shows a red box. How can I allow a null value in this column?
I have tried to remove all row validation with Validation.ErrorTemplate="{x:Null}" in xaml but that hasn't changed anything either.

A: I assume that cell is displaying a value of type DateTime, which is a non-nullable type. Therefore you have to have a value for it.
You could either use a string property to display the scrap date, or make the DateTime nullable using DateTime? dateTime = null;


text:
Q: Подключение данных из Postgres BD к OBIEE 12c Хочу подключить к OBIEE 12c данные из Postgres DB. Есть ли официальная документации и возможность не использовать сторонние драйверы, как например от CData?
OBIEE развернут на Linux.
U.P.D. нужен ODBC драйвер, вопрос в том как его сейчас установить

A: https://docs.oracle.com/middleware/12213/biee/BIEMG/GUID-914424A9-D431-43DB-A951-1C7996A3B61A.htm#datadirect_sql_srvr

*

*официальная документация по установке от Oracle

https://www.postgresql.org/ftp/odbc/versions/src/

*

*драйвер для скачки

https://odbc.postgresql.org/docs/unix-compilation.html

*

*компилятор для драйвера

Надеюсь кому-нибудь пригодится


text:
Q: Clear password text field in Jquery I want to clear the password text field each time the pop-up is shown. The pop-up contains the password field
I'm using below function in jquery to reset:
function resetPopupFormErrors() {
    $("div.errors").closest("tr").remove();
     ....
}

And I'm calling this function in fancybox on startup. How can I reset the password text in above function so that if the user has typed something in text field & closed the pop-up & then if user opens it again, I don't want that password to reappear....How can I do it using jquery in above function?
EDIT: If I look at the html view source after typing the password, the value is empty for that password field. How can we clear something that's not appearing in value field?
Thanks!

A: Wouldnt you do it the same as clearing a normal text box?
$("#yourTextBox").val('');

A: Why not just set the textbox's value to ''?
$('input[type="password"]').val('');

Note that this resets all password textboxes. Use an id if you want to target a specific one.

A: Clearing a field is easy:
$('selector').val('');

The tricky part is going to be detecting that they close the window and that it's not the first time it has been opened.

A: Just make use of this function everytime while closing the popup !!
$('#myModal').on('hidden', function () {
    $('#id').closest('form').find("input[type=text]").val("");
});


text:
Q: How to extract multiple entries from Windows "configuration manager trace log tool"? seems like you can only use "copy to clipboard" for individual line items.
How can I copy or extract a few hundred lines?


text:
Q: Drop column in MySqlWorkbench taking a long time I started a 'DROP COLUMN' operation in MySQLWorkbench yesterday and it still hasn't finished.  It's now about 16 hours later.  The table only has about 52000 records.
Should I let it run, or should I assume something has gone wrong and stop the process?
Is there any way to know the status of the operation, or if it has hung in some way?
Thanks.
Update:
Here are the results from 'desc websvc_userprofile' and 'show processlist'
The processlist seems to indicate that the only processes are coming from my webserver instance, not MySqlWorkbench that is running on my desktop.  Also, the column that I was trying to drop, is not displayed in the results of the 'desc websvc_userprofile' command.


text:
Q: I can't use multiple jquery versions I want use two different jquery version on one page it is my codes:
    <!----- mobile menu Starts ----->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="style/mobile_menu.css">
    <script type="text/javascript">
        var jQuery_1_11_0 = $.noConflict(true);
    </script>
    <!----- mobile menu  Ended ----->
    <!------ The Post slide starts ------>
    <link rel="stylesheet" type="text/css" href="./style/post_slide_style.css">
    <script src="js/jquery.v1.5.1.min.js"></script>
    <script type="text/javascript">
        var jQuery_1_5_1 = $.noConflict(true);
    </script>
    <script type="text/javascript" src="./js/jquery.colorbox.js"></script>
    <script>
        jQuery_1_5_1(document).ready(function(){
         jQuery_1_5_1("a.gallery").colorbox({rel:'gallery'});
         jQuery_1_5_1("a.dbox").colorbox({iframe:true, width:"480", height:"580"});
         });
    </script>
    <!------ The Post slide Ended ------->

The Mobile Menu is work but The Post slide isn't work thanks for helping

A: You should not have 2 different JQuery Versions.
You should use the latest version of JQuery. If you need to support some legacy JQuery API, you addiotnaly need to use the jQuery Migrate Plugin
From the documentation:

We have created the jQuery Migrate plugin to simplify the transition
from older versions of jQuery. The plugin restores deprecated features
and behaviors so that older code will still run properly on newer
versions of jQuery. Use the uncompressed development version to
diagnose compatibility issues, it will generate warnings on the
console that you can use to identify and fix problems. Use the
compressed production version to simply fix compatibility issues
without generating console warnings.
There are two versions of Migrate.
The first will help you update your
pre-1.9 jQuery code to jQuery 1.9 up to 3.0. You can get that version
here:
The second version helps you update code to run on jQuery 3.0 or
higher, once you have used Migrate 1.x and upgraded to jQuery 1.9 or
higher:

A: The main problem is that you are passing true to both noConflict calls.

jQuery.noConflict( [removeAll ] )
removeAll
Type: Boolean
  A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself).

So after those calls you code has not access to $ nor jQuery so you should be getting some errors in your console.
If you want to use the second version of jquery then remove the true from that noConflict call.

In general, though, it is a bad sign when you must use two versions of jQuery in the same page.


text:
Q: Degree of a separable extension of a Dedekind ring's quotient field I'm studying "Algebraic number theory" written by S. Lang. In proposition 21 of chapter 1.7 it says if $A$ is a Dedekind ring and $K$ its quotient field, for a separable extension $L/K$, $[L:K]=\sum_{P|p} e_P f_P$ where $p$ is a prime ideal in $A$ and $e_P, f_P$ are ramification indexes and residue class degrees.
My problem is a part of its proof; It says if $B$ is $A$'s integral closure in $L$ then $B/pB$ is an $A/p$-vector space of dimension $[L:K]$. I don't see why this holds. I tried to show if $a_1,...,a_n$ are basis of $L$ as a $K$-vector space then $a_i$s are integral over $A$ hence a generator for $B$ as an $A$-module so that from $[B/pB:A/p]=[B:A]$ the result can be obtained. But the leading coefficient wouldn't remain unity over $A$

A: I'd say that we need to look at $A_p=(A-p)^{-1}A$ which is a PID (and DVR). The separability of $L/K$ gives that $A_p B$ is a finitely generated $A_p$-module

(I don't recall the exact argument here, I think it is based on that $L\cong K[x]/(f)$ with $f\in A_p[x]_{monic}$ and $0\ne Disc(f)=\det(Tr(x^i x^j))$ so we'd get $\sum_{i=0}^{[L:K]-1} x^i A_p \subset A_p B\subset \frac1{Disc(f)} \sum_{i=0}^{[L:K]-1} x^i A_p$).

Then we use a general linear algebra theorem that finitely generated $R$-modules are free whenever they are contained in a $Frac(R)$-vector space and $R$ is a PID.
Since $K B = L$ is a $[L:K]$-dimensional $K$-vector space it gives that $A_pB$ is a free $A_p$-module of rank $[L:K]$, so that $[B/pB:A/pA]=[A_pB/pA_pB:A_p/pA_p]=[L:K]$.


text:
Q: generic class with superclass class Program
{
    static void Main(string[] args)
    {
        //GrandFather gf = new Son();
        IGF<Father> igf = new MyClass();
    }
}
public class Father
{

}
public class Son : Father
{
}
public class MyClass : IGF<Son>
{
    public void Method()
    {
        //DoSomething
    }
}
public interface IGF<T> where T : Father
{
    void Method();
}

Hello everyone,I meet a question when I using generic class with superclass.
Can anyone tell me that why line 6 is wrong ,as when we using list,we always say that IList ss=new List();

A: If you're using C# 4.0, you can add the out keyword to the IGF implementation to make it a covariant interface.  This allows you to have a generic with a base class (here Father) and have it point to an instance of that same interface with a derived generic type (Son).


text:
Q: ASP.NET + IIS6: whitelist users via authorization section in web.config Consider an IIS6 Application under a web site:

*

*Windows authentication is enabled.

*anonymous is off

This is an ASP.NET MVC application with Areas. The root web.config has the authentication and authorization nodes as follows:
<authentication mode="Windows"></authentication>

<authorization>
    <allow users="domain\abc, domain\xyz, domain\foo, domain\bar"/>
</authorization>

My identity is NOT in the list of allowed users. Entering the URL in the browser, I can view and navigate to all the pages within. I know I am being authorized properly, as my Active Directory name is displayed on the site.
Problem: I am given access to the site.
Question: Using the web.config, how can I restrict users based on their Windows credentials to this IIS6 Application?

A: Try this:
<authorization>
    <allow users="domain\abc, domain\xyz, domain\foo, domain\bar"/>
    <deny users="*"/>
</authorization>

A: How about adding a deny section behind the allow one?
<deny users="*" />


text:
Q: iOS Keyboard show event handling I am working on a chat app wherein I have a textview (not textfield) and when I click on it, the keyboard should show and everything should move up.
Till now, I have managed to shift the frame of the table view and textview up and show the keyboard using the below code.
- (void)keyboardWasShown:(NSNotification *)notification {

    NSDictionary* info = [notification userInfo];

    keyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    CGPoint contentViewOrigin = self.contentView.frame.origin;

    CGFloat contentViewHeight = self.contentView.frame.size.height;

    CGRect visibleRect = self.view.frame;

    visibleRect.size.height -= keyboardSize.height;
    BOOL up = CGRectContainsPoint(visibleRect, contentViewOrigin);

    if (!up){

    self.tableView.frame = CGRectMake(self.tableView.frame.origin.x,self.tableView.frame.origin.y,self.tableView.frame.size.width,280.0f);

    self.contentView.frame = CGRectOffset(self.contentView.frame, 0, 0 - keyboardSize.height);

    if([self.tableView numberOfRowsInSection:0]!=0)
    {
        NSIndexPath* ip = [NSIndexPath indexPathForRow:[self.tableView numberOfRowsInSection:0]-1 inSection:0];
        [self.tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionBottom animated:UITableViewRowAnimationLeft];
    }

}

}

- (void)keyboardWillBeHidden:(NSNotification *)notification {

self.contentView.frame = originalContentView;
self.tableView.frame = originalTable;
}

- (void)registerForKeyboardNotifications {

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWasShown:)
                                             name:UIKeyboardDidShowNotification
                                           object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillBeHidden:)
                                             name:UIKeyboardWillHideNotification
                                           object:nil];

}

- (void)deregisterFromKeyboardNotifications {

[[NSNotificationCenter defaultCenter] removeObserver:self
                                                name:UIKeyboardDidHideNotification
                                              object:nil];

[[NSNotificationCenter defaultCenter] removeObserver:self
                                                name:UIKeyboardWillHideNotification
                                              object:nil];

}

But when I saw how whatsapp does it, mine looked like a hack. Whatsapp's keyboard moves up together with all the elements while mine works like this: First the keyboard is shown, a notification is sent to the app, notification is received, the code calculates the height of keyboard and moves up the elements according to the height.
I have searched and found the solution that I have implemented.
Can someone help??

A: I use this trick a lot in my apps. You want to listen to UIKeyboardWillShowNotification and UIKeyboardWillHideNotification.
The best way to handle animation in my opinion is using autolayout. When you call [self.view layoutIfNeeded]; your views will move along with the keyboard animation. No animation block needed.
I've set up a simple project for anyone to try and see how it works!
- (void)addKeyboardNotificationsObserver {

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleKeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

}

- (void)handleKeyboardWillShow:(NSNotification *)paramNotification

{

    NSDictionary* info = [paramNotification userInfo];

    //when switching languages keyboard might change its height (emoji keyboard is higher than most keyboards).
    //You can get both sizes of the previous keyboard and the new one from info dictionary.

    // size of the keyb that is about to disappear
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    // size of the keyb that is about to appear
    CGSize kbSizeNew = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

    //make adjustments to constraints here...

    //and here where's magick happen!

    [self.view layoutIfNeeded];

}

- (void)handleKeyboardWillHide:(NSNotification *)paramNotification

{
    //adjust constraints

    [self.view layoutIfNeeded];

}

A: *

*You can use UIKeyboardWillShowNotification and UIKeyboardWillHideNotification

*Try TPKeyboardAvoidingScrollView from here: https://github.com/michaeltyson/TPKeyboardAvoiding (my choice)


text:
Q: How can I know if browser notifications are blocked by Windows My web app sends browser notifications, and I know how to check the browser permission for the notifications, and how to request permissions if they are not granted.
However, even if the user granted permission for my site to send notifications, she might still not get the notifications, because they might be disabled (either globally on Windows, or for the current browser).
Is there a way for me to detect this and let the user know that notifications won't be displayed unless she enables them in Windows Settings?

A: There's no way to do it!
There's no way to do this, JavaScript doesn't have direct access to Windows to detect settings, or to change Windows settings.
I am pretty sure it's made to protect users' privacy.
The only affected browsers by Windows settings are Chromium-built browsers.
If you turn notifications settings off in Windows, Google Chrome and Microsoft Edge (aka Chromium browsers) won't be able to send notifications while other browsers like Firefox that are built on different engines will be able to send notifications.
This means that Google Chrome and Microsoft Edge uses a different way to send notifications:
Google Chrome:

Microsoft Edge:

While Firefox has a completely different way and UI:

Summarize:
JavaScript can't detect whether notification settings are enabled or not in Windows settings. And if notification settings are disabled, browsers like Firefox can still send notifications.


text:
Q: Modelling user created Resource-level permissions in keycloak This is more of an early stage question around idiomatic approaches for modelling permissions/roles for user created resources in Keycloak. For this use case I'm not sure if I should just use Keycloak for identity management and leave access management to the application.
Proposed use case: In the application, resources belong to a company, A company can have multiple users. Some users are admin users, and are responsible for setting up roles/permissions for other users. These permissions may grant global access (eg User can view all files) or resource specific access (Eg User can view/modify files in the marketing folder).
A more concrete example is AWS IAM. Multiple users can be on a single AWS account, but access can be controlled at varying levels. For example, a role might be set up which grants S3 Read permissions, and a different role might have S3 Delete permission on a marketing bucket.
Because these resources/roles are user created and managed, I imagine my application would need to provide its own UI and then use the REST API to communicate with Keycloak. Because these are all user generated and there could be many companies that are using the application, I could foresee a very large amount of resource related data being persisted in Keycloak.
I'm not sure if this is a good idea - I imagine I would need to communicate with the Keycloak servers frequently to verify a given user has access to the resources they are trying to request/modify. It seems like Keycloak is more suitable for scopes/permissions that are not tied to specific user created resources? If it is a standard use case, is there any documentation around approaches like this (I haven't been able to find anything)?

A: The Keycloak is able to manage very smoothly the roles of users which you can use next in Java code with annotations like:
@Secured("ROLE_ADMIN")

Or
@RolesAllowed({"ROLE_USER", "ROLE_ADMIN"})

inside the Controller, together with HTTP methods' mapping or inside the HTML code like
sec:authorize="hasRole('ADMIN')"

It means you are able to manage access to view/modify files in the marketing folder. To go further on User access level, you can use token authorisation; please read e.g. this article.


text:
Q: Joining 2 Tables with Non-Unique Values - Comparing Legacy to Current Data I am looking to compare some transaction data from our legacy system with the current system. This is being used as a means for comparison. The problem is that certain transactions are listed multiple times, often due to needing to report it in all the corresponding reporting agencies.
So let me just give a quick Example:
Current System Transaction Data
Transaction#| ReportCode |
:---------- | ---------: |
 123        | 3          |
 123        | 4          |
 1234       | 3          |
 1235       | 4          |
 1255       | 6          |

Legacy System Transaction Data
Transaction#| ReportCode |
:---------- | ---------: |
 123        | 3          |
 123        | 4          |
 1234       | 6          |
 1235       | 6          |

I am trying to make a query that would result in the following based on comparing the two systems:
Transaction#| ReportCode |
:---------- | ---------: |
 123        | 3          |  Match with Legacy
 123        | 4          |  Match with Legacy
 1234       | 3          |  MisMatch Legacy Reports 6
 1235       | 4          |  Mismatch Legacy Reports 6
 1255       | 6          |  Not in Legacy System

So the main problem I am having is when the same transaction is reported on multiple schedules. Since it is a JOIN, it simply grabs whichever first Reportcode that it sees, so I will often see results like this:
Transaction#| ReportCode |
:---------- | ---------: |
 123        | 3          |  MisMatch Legacy Reports 4
 123        | 4          |  MisMatch Legacy Reports 3

Does anyone know of a good way around this issue I am experiencing? Below is my current code
SELECT DISTINCT
                     a.ReportCode AS LegacyReportCode b.ReportCode AS CurrentReportCode CASE WHEN a.Reportcode= b.ReportCode THEN 'ReportCode Matched' WHEN a.ReportCode IS NULL
                     THEN 'In Current not in Legacy' WHEN b.ReportCode IS NULL THEN 'In Legacy not in Current' ELSE 'Mismatch' END AS ReportCodeMatchResult, a.TransactionID AS LegacyTransactionID,
                     b.TransactionID AS CurrentTransactionID

FROM                dbo.LegacySystem AS a FULL OUTER JOIN
                     dbo.CurrentSystem AS b ON a.TransactionID = b.TransactionID

A: First, I would get all the ones that do match by joining CurrentSystem to LegacySystem on both TransactionID AND ReportCode. Then, write a separate query to get the ones that do not match
Select c.TransactionNum, c.ReportCode, (Select top 1 ReportCode From Legacy Where TransactionNum = c.TransactionNum) as mismatch
From Current c
Where Not Exists
(
    Select 1 From Legacy l
    Where c.TransactionNum = l.TransactionNum and c.ReportCode = l.ReportCode
)

You can UNION ALL them together if you need them in one result set.

A: FULL OUTER JOIN is pretty much the right way to go.  However, you can't really specify the ReportCode that doesn't match.
However, you can get the information you want by including ReportCode in the ON conditions:
SELECT a.ReportCode AS LegacyReportCode b.ReportCode AS CurrentReportCode,
       (CASE WHEN a.Reportcode = b.ReportCode THEN 'ReportCode Matched'
             WHEN a.ReportCode IS NULL THEN 'In Current not in Legacy'
             WHEN b.ReportCode IS NULL THEN 'In Legacy not in Current'
             ELSE 'Mismatch'
        END) AS ReportCodeMatchResult,
       a.TransactionID AS LegacyTransactionID,
       b.TransactionID AS CurrentTransactionID
FROM dbo.LegacySystem a FULL OUTER JOIN
     dbo.CurrentSystem b
     ON a.TransactionID = b.TransactionID AND a.ReportCode = b.ReportCode;


text:
Q: Make sure the back cover of a book ends on a even page I'm trying to create a back cover for a book, and I don't want to manually have to make sure it ends on a even page. However since I have different sections with different numbering (think preamble, appendix, etc)  I have a hard time finding out if the current page is currently even or odd.
\cleardoublepage forces the next page to be an odd page, so it SHOULD be a simple matter to just do a \newpage and that new page would be an even page. But I can't get it to work.
The below is a minimum example that works in an environment where numbering isn't reset. But as the last numbering may not start on an odd page in my case, it doesn't seem to work all the time.
\documentclass[10pt,twoside,twocolumn,openany]{book}
\usepackage[utf8]{inputenc}
\usepackage[pages=all]{background}
\usepackage[english]{babel}
\usepackage{blindtext}

\begin{document}

\blindtext[5]

\cleardoublepage
\ifodd\value{page}
    \hbox{}\newpage
\fi

\begin{titlepage}
    \hbox{}
    \backgroundsetup{
    scale=1,
    opacity=1.0,
    angle=0,
    color=black,
    contents={%
        \includegraphics[width=1.1\paperwidth]{bgcover.jpg}
        }
    }
\end{titlepage}

\end{document}

The lastpage package doesn't seem to work to find the total number of pages either, \pageref{LastPage} gives me the numbering of the last numbersection (e.g. III when using roman numbering). Since the appendix at that time was 3 pages long, even though the entire document was 50 pages long at the time.
This due to using \setcounter{page}{1}.
Should I just try to create a counter or something that remembers, and adds together the pages before each \setcounter{page}{1} ? If then, what is the cleanest way to do that?

A: To solve, I had to get rid of the titlepage environment, since it seems to put its contents always onto an odd page. To mimic the titlepage environments proper centering, I'm using the geometry package and set negative margins just before adding the backcover (see comments in code).
I always move to a fresh page, and then check if its even/odd using the ifodd command. Only if I'm on an odd page, to I issue another clearpage (note the protected space adding invisible content to the page, thus forcing the compiler to move to a new page).

edit following cfr's comment: you can use the nextpage package to take care of the manual checking for even and odd pages.
\documentclass[10pt,twoside,twocolumn,openany]{book}
\usepackage[utf8]{inputenc}
\usepackage[pages=all]{background}
\usepackage[english]{babel}
\usepackage{blindtext}
\usepackage{geometry}
\usepackage{nextpage}

\begin{document}
    \blindtext[10]
    \cleartoevenpage% this line replaces the next 5 lines
%   \clearpage% move to the next empty page
%   \ifodd\thepage% if that page is odd,
%       \thispagestyle{empty}% supress page numbering and headers for the page to be left empty
%       \ \clearpage% add a protected space to force tex to move to the next page
%   \else% do nothing
%   \fi
    \newgeometry{margin=-.05\paperwidth} % setting a negative margin to make sure the figure will be centered left/right (taken care of in your MWE by the titlepage environment). Make sure the number corresponds with the width of the figure you set below
    \thispagestyle{empty} % supress page numbering and headers for the back cover
    \begin{figure}[p] % float environment placing the float on its own page will center top/bottom. Will go on this page, since you emptied the float queues before using the \cleardoublepage commands
        \includegraphics[width=1.1\paperwidth]{example-image}
    \end{figure}
\end{document}