text:
Q: What am I doing wrong here? Method Does not work So I'm trying to call methods and i want it to like go from one method to another. So I at first I tried calling the method with parameters but that kind of did not work because 1 method needed more and i got confused after some errors so i tried this... I read an answer on a post and it said to try declaring variable with static outside the main method but inside the class.. So i did it
public class RiskGame {
//Player 1 Win
static Boolean P1Qrehz=false;
static Boolean P1Mez=false;
static Boolean P1Flehst=false;
static Boolean P1Veiled=false;
static Boolean P1Sharktooth=false;
static Boolean P1Zicat=false;
//Player 2 Win
static Boolean P2Qrehz=false;
static Boolean P2Mez=false;
static Boolean P2Flehst=false;
static Boolean P2Veiled=false;
static Boolean P2Sharktooth=false;
static Boolean P2Zicat=false;
//Stock Market
static Random stock = new Random();
static int StockCorn = stock.nextInt(433 - 350) + 350;
static int StockCotton = stock.nextInt(100 - 65) + 63;
static int StockOrange = stock.nextInt(125 - 112) + 112;
static  int StockSilver = stock.nextInt(1350 - 1000) + 1000;
static int StockSugar = stock.nextInt(500 - 200) + 200;
static int StockCoffee = stock.nextInt(400 - 300) + 300;
static int StockRice = stock.nextInt(265 - 170) + 170;
static String NameP1;
static String NameP2;
static int MoneyCount;
static int MoneyCount2;
static int CitizenLoveNum2;
static int CitizenLoveNum;
static int SoldierCount1;
static int SoldierCount2;
static String Rules;
public static void main(String[] args) {

And this is inside the main method
public static void main(String[] args) {
    //Testing Area
    //Player 1 Win
    //This is the Give name phase
    JOptionPane.showMessageDialog(null, "Welcome To RiskGame 0.1.1, This game is in Early access So expect some bugs! :)", "RiskGame 0.1.1", JOptionPane.PLAIN_MESSAGE);
    JOptionPane.showMessageDialog(null, "This game was originally developed and released By Elias Ioannou", "A Game By Elias Ioannou", JOptionPane.INFORMATION_MESSAGE);
    String Name1 = JOptionPane.showInputDialog("What's your name Player 1?", "Player 1");
    String Name2 = JOptionPane.showInputDialog("What's your name Player 2?", "Player 2");
    Name1=NameP1;
    Name2=NameP2;
    //Money Setup
    String Money = JOptionPane.showInputDialog(NameP1 + ", How Much Money do you want to start with?", "1000");
    String Money2 = JOptionPane.showInputDialog(NameP2 + ", How Much Money do you want to start with?", "1000");
    int MoneyCountP1 = Integer.parseInt(Money);
    int MoneyCountP2 = Integer.parseInt(Money2);
    MoneyCount=MoneyCountP1;
    MoneyCount2=MoneyCountP2;
    //Rules
    String Rules1=JOptionPane.showInputDialog("This rules will add something more exciting in the game. (This rules must be done by the players). The system won't know anything so you need to play by your rules. \n Enter the custom rules you want to play with. If you want to just play the game leave it blank it won't affect anything!", "Default. No Special Rules Added");
    Rules1=Rules;
    //Soldier Count
    int SoldierCountP1 = 3;
    int SoldierCountP2 = 3;
    SoldierCount1=SoldierCountP1;
    SoldierCount2=SoldierCountP2;
    JOptionPane.showMessageDialog(null, "You will Both Start With " + SoldierCount1 + " Soldiers!", "Soldiers On Arms", JOptionPane.INFORMATION_MESSAGE);
    //Starting City
    Random city = new Random();
    int City = city.nextInt(3 - 1) + 1;
    Random city2 = new Random();
    int City2 = city2.nextInt(3 - 1) + 1;
    int CityNum = 0;
    switch (City) {
        case 1:
            JOptionPane.showMessageDialog(null, NameP1 + ", Your Starting Island is Veiled Atoll");
            P1Veiled=true;
            CityNum = 1;
            break;
        case 2:
            JOptionPane.showMessageDialog(null, NameP1 + ", Your Starting Island is Skarktooth Isle");
            P1Sharktooth=true;
            CityNum = 2;
            break;
        case 3:
            JOptionPane.showMessageDialog(null, NameP1 + ", Your Starting Island is Zicat Peninsula");
            P1Zicat=true;
            CityNum = 3;
            break;
        default:
            JOptionPane.showMessageDialog(null, "Something went wrong... Try Restarting the program.");
            break;
    }
    int City2Num = 0;
    switch (City2) {
        case 1:
            JOptionPane.showMessageDialog(null, NameP2 + ", Your Starting Island is Mez Archipelago");
            P2Mez=true;
            City2Num = 1;
            break;
        case 2:
            JOptionPane.showMessageDialog(null, NameP2 + ", Your Starting Island is Flehst Archipelago");
            P2Flehst=true;
            City2Num = 2;
            break;
        case 3:
            JOptionPane.showMessageDialog(null, NameP2 + ", Your Starting Island is Qrehz Archipelago");
            P2Qrehz=true;
            City2Num = 3;
            break;
        default:
            JOptionPane.showMessageDialog(null, "Something went wrong... Try Restarting the program.");
            break;
    }
    //Citizen Happiness
    String CitizenLove = JOptionPane.showInputDialog(NameP1+", How Much Citizen Happiness do you want to start with?", "50");
    int CitizenLoveNumP1= Integer.parseInt(CitizenLove);
    String CitizenLove2 = JOptionPane.showInputDialog(NameP2+", How Much Citizen Happiness do you want to start with?", "50");
    int CitizenLoveNumP2= Integer.parseInt(CitizenLove2);
    CitizenLoveNum2=CitizenLoveNumP2;
    CitizenLoveNum=CitizenLoveNumP1;

    P2Menu();
}

And this is the method im trying to call but does not respond (The program exits)
public static void P2Menu(){
    //-CitizenLove
    Boolean Yes=true;
    while(Yes){
    CitizenLoveNum2-=15;
    }

What's wrong? Im new to java So please don't hate my probably bad coding skills :)

A: To call a static method outside of the class you are in, you need to do:
RiskGame.P2Menu();

You also need to make sure that you define the P2menu() method inside the RiskGame class, like so:
public class RiskGame {
   ....
public static void main(String[] args) {
    ...
   P2Menu();
 }
public static void P2Menu(){
...
}

Also, you have an issue with the P2Menu() method, as it is in an infinite loop. You never set the variable to false.


text:
Q: Lazy initialization error with parameter I am coding a MVC internet application and have a question in regards to lazy initialization.
Here is my working code before lazy initialization:
Declaration:
private ValidationService validationService;

Initialization:
validationService = new ValidationService(genericMultipleRepository);

Here is the code I am trying:
Declaration:
private Lazy<ValidationService> validationService;

Initialization:
validationService = new Lazy<ValidationService>(genericMultipleRepository);

Here is the error:

Error 125 The best overloaded method match for
  'System.Lazy.Lazy(System.Threading.LazyThreadSafetyMode)'
  has some invalid
  arguments

I have looked at the Lazy<T> constructor documentation, but I don't see what is wrong.

A: The constructor of lazy expects a Func that returns the ValidationService type specified:
validationService = new Lazy<ValidationService>
                    ( () => new ValidationService(genericMultipleRepository)
                    );

That would be equivalent to:
validationService = new Lazy<ValidationService>
                    ( SomeMethod
                    );

private ValidationService SomeMethod()
{
    return new ValidationService(this.genericMultipleRepository);
}

Note you can't pass the parameter genericMultipleRepository like it is inferred by using the lambda expression.

redpajama_set_name: RedPajamaStackExchange


text:
Q: A failure occurred attempting to install the .NET Framework 4 Client Profile I wrote an application in VS2015. I had to change the project properties to Framework 4 client profile since one of the customer has WinXP SP3. According to Microsoft, it is fine.
I have created a setup file from the publish tab in the project properties.
I checked in Prerequisites:

*

*Component Microsoft .NET Framework 4 Client Profile (x86 and x64) and Update for .NET Framework 4 (KB2468871)

*Window Installer 4.5

I select "Download prerequisites from the component vendor's website".
I clicked on Publish and I get the setup file and all its dependencies.
I ran the setup file on the Window XP OS, it took a lot of time to install the .Net Framework and once finished, I got the following message:
Component Microsoft .NET Framework 4 Client Profile (x86 and x64) and Update
for .NET Framework 4 (KB2468871) has failed to install with the following
error message:
"A failure occurred attempting to install the .NET Framework 4 Client
Profile."

The following components failed to install:
- Microsoft .NET Framework 4 Client Profile (x86 and x64) and Update for
.NET Framework 4 (KB2468871)

See the setup log file located at
'C:\DOCUME~1\eric_h\LOCALS~1\Temp\VSD9.tmp\install.log' for more information.

I am not clear what is wrong, please advise.


text:
Q: SQL Server select rows from, to I am trying to select rows in SQL Server 2012, I want to select from row x to row y.
Is there an option in SQL Server to select rows from-to like in mysql limit 10,20?

A: You are looking for the offset/fetch functionality.
The documentation is here.enter link description here
This is new in SQL Server 2012, so you need other methods in earlier versions of SQL Server, such as using row_number() or using nested queries with top.

A: SELECT * FROM TableName
OFFSET 0 ROWS -- Starting Row Number
FETCH NEXT 10 ROWS ONLY; -- Number of rows you want


text:
Q: split() in perl How to divide text into sentences. In my opinion, I should use split() and print them, but I donˇt now have.
I am just started learning Perl.
My text
A block of text is a stack of line boxes.  In the case of 'left',
'right' and 'center', this property specifies how the inline-level
boxes within each line box align with respect to the line box's left
and right sides; alignment is not with respect to the viewport.  In
the case of 'justify', this property specifies that the inline-level
boxes are to be made flush with both sides of the line box if
possible, by expanding or contracting the contents of inline boxes,
else aligned as for the initial value. See also 'letter-spacing' and
'word-spacing'.

A: If this isn't actually homework, I would just use one of the CPAN modules which handle this, say Lingua::Sentence which seems to be under active development.

A: One way to do it is using split in combination with look-behind.
 perl -nlwe 'print for split /(?<=\S[.!?])\s+/' < data.txt

This works for your sample data.
What you want to do here is eliminate the space separating sentences. An end of sentence is defined as one of .!? preceded by a non-whitespace character. Tweak as desired.

A: try
$paragraph = "Text. Text";
@sentences = split(/\./, $paragraph);
print @sentences;


text:
Q: Docker backing filesystem as AWS efs I am mounting an AWS efs filesystem on /var/lib/docker and using it as the default docker backing filesystem. Storage driver is overlay2. I see in the docs that overlay2 only supports xfs and ext. My aim is to mount this backing filesystem on multiple machines so that all those machines have the image data but multiple mount is not supported by aws ebs(being a ext4 and a supported backing fs by overlay2). One way could by that is pull the images on an ext4 fs and cp the image data into the efs but it would be too time taking. What could be another way to go about this?

A: The short answer is "don't do that" because /var/lib/docker is not designed to be shared by multiple daemons. You'll find race conditions, erroneous output about networks and containers that don't exist locally, and other errors that won't be fixed/supported.
Instead, put a registry near your cluster, in the same VPC/AZ, and have your nodes pull from that cluster. Or have a look at the work done to support estargz in runtimes like containerd which can start running a container before the layers are completely pulled.


text:
Q: Unable to launch Skyrim: The Elder Scrolls with PlayOnLinux Hello fellow from stack exchange!
I've been trying to run Skyrim on ubuntu using playonlinux with no success.
After several installation error's, i've found myself stuck in this error message:
wine: Call from 0x7f295cd001da to unimplemented function VCRUNTIME140.dll.__C_specific_handler, aborting
err:seh:setup_exception stack overflow 4416 bytes in thread 0022 eip 00007f295cd384dd esp 00000000001404c0 stack 0x140000-0x141000-0x240000

Any hints on solving it? Thank's for your attention!
Note: Im using Codex .iso Skyrim, 64bit version.


text:
Q: How to get MVVM Light Messenger working with a PCL I am currently reorganizing my WP8 project in order to have a Portable Class Library, which could result in a W8 app.
I am using MVVMLight and have the following code:
In the Portable Class Library:
namespace MyApp.Shared.Messages
{
    public class MyItemSelectedMessage : MessageBase
    {
        public MyItemSelectedMessage(MyItem item)
        {
            Item = item;
        }
        public MyItem Item { get; set; }
    }
}

In my WP8 app, I still do have the ViewModels (because of Telerik and some other stuff which I cannot outsource to the PCL), where I use the following code to register for the message:
Messenger.Default.Register<MyItemSelectedMessage>(this, msg => SelectedItem = msg.Item);

The code worked fine before but now VS gives me the following error in the WP8 app at the given line:
The type 'GalaSoft.MvvmLight.Messaging.MessageBase' is defined in an assembly that is not referenced. You must add a reference to assembly 'GalaSoft.MvvmLight, Version=4.2.30.16997, Culture=neutral, PublicKeyToken=null'

In my WP8 project, I have installed MvvmLight (v4.2.30.23483) and in my PCL there are the MvvmLight Libraries for PCL (v4.2.30.16997), both up-to-date from Nuget. Do I need to downgrade a package to get the same build number, add the libraries manually or what can I do in order to make it work?
Thanks in advance!

A: You should reference the Portable.MvvmLightLibs NuGet package from both projects, and not any of the non-portable MvvmLight packages.  The Portable.MvvmLightLibs package includes support for both PCLs and platform-specific libraries.


text:
Q: Using regex to remove HTML tags I need to convert
$text = 'We had fun. Look at this photo of Joe';

[Edit] There could be multiple links in the text.
to
$text = 'We had fun. Look at this photo (http://example.com) of Joe';

All HTML tags are to be removed and the href value from  tags needs to be added like above.
What would be an efficient way to solve this with regex? Any code snippet would be great.

A: First do a preg_replace to keep the link. You could use:
preg_replace('(.*?)', '$\2 ($\1)', $str);

Then use strip_tags which will finish off the rest of the tags.

A: try an xml parser to replace any tag with it's inner html and the a tags with its href attribute.
http://www.php.net/manual/en/book.domxml.php

A: The DOM solution:
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
foreach($xpath->query('//a[@href]') as $node) {
    $textNode = new DOMText(sprintf('%s (%s)',
        $node->nodeValue, $node->getAttribute('href')));
    $node->parentNode->replaceChild($textNode, $node);
}
echo strip_tags($dom->saveHTML());

and the same without XPath:
$dom = new DOMDocument;
$dom->loadHTML($html);
foreach($dom->getElementsByTagName('a') as $node) {
    if($node->hasAttribute('href')) {
        $textNode = new DOMText(sprintf('%s (%s)',
            $node->nodeValue, $node->getAttribute('href')));
        $node->parentNode->replaceChild($textNode, $node);
    }
}
echo strip_tags($dom->saveHTML());

All it does is load any HTML into a DomDocument instance. In the first case it uses an XPath expression, which is kinda like SQL for XML, and gets all links with an href attribute. It then creates a text node element from the innerHTML and the href attribute and replaces the link. The second version just uses the DOM API and no Xpath.
Yes, it's a few lines more than Regex but this is clean and easy to understand and it won't give you any headaches when you need to add additional logic.

A: I've done things like this using variations of substring and replace. I'd probably use regex today but you wanted an alternative so:
For the  tags, I'd do something like:
$text = replace($text, "", "");
$text = replace($text, "", "");

(My php is really rusty, so replace may not be the right function name -- but the idea is what I'm sharing.)
The  tag is a bit more tricky. But, it can be done. You need to find the point that  ends with. Then you extract the entire length and replace the closing
That might go something like:
$start = strrpos( $text, "<a" );
$end = strrpos( $text, "", $start );
$text = substr( $text,  $start, $end );
$text = replace($text, "", "");

(I don't know if this will work, again the idea is what I want to communicate. I hope the code fragments help but they probably don't work "out of the box". There are also a lot of possible bugs in the code snippets depending on your exact implementation and environment)
Reference:

*

*strrpos - http://www.php.net/manual/en/function.strrpos.php

*replace - http://www.php.net/manual/en/function.str-replace.php

*substr - http://php.net/manual/en/function.substr.php

A: It's also very easy to do with a parser:
# available from http://simplehtmldom.sourceforge.net
include('simple_html_dom.php');

# parse and echo
$html = str_get_html('We had fun. Look at this photo of Joe');

$a = $html->find('a');
$a[0]->outertext = "{$a[0]->innertext} ( {$a[0]->href} )";

echo strip_tags($html);

And that produces the code you want in your test case.


text:
Q: Hot tablets problem possible when using App Engine auto-generated IDs? The hot tablets problem is described here:
http://ikaisays.com/2011/01/25/app-engine-datastore-tip-monotonically-increasing-values-are-bad/
I think I've read before that auto-generated IDs can suffer from this, I assume it's still the case?
If so, would a simple trick like inserting a random letter in front or reversing the order of the digits would help with this ? (I'm searching for a way to work around this problem while keeping keys as short as possible...)

A: The ID numbers generated when you put a model in the datastore don't increase monotonically when deployed to App Engine (they do in dev_appserver).  You may see short ranges, but the numbers bounce around quite a bit.  I'm not sure if they do this specifically to defeat monotonically increasing indexes, but that's a side effect.
If you don't trust that, what I often do is create a key name using uuid.uuid4() (assuming you are using Python).


text:
Q: All the section titles showing in one section I have a grouped tableview and for some reason all the section titles display only in one section. So the result is that the titles are all on top of each other in section = 0. All of the other sections are blank.
I tried debugging and see that when section == 1, the headerLabel is nil.
I am using a custom view as the header, here is that code:
class HeaderView: UIView {

let headerLabel =  UILabel()

override init(frame: CGRect) {
    super.init(frame: frame)
    self.translatesAutoresizingMaskIntoConstraints = false
    addCustomView()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func addCustomView() {
    self.addSubview(headerLabel)
    NSLayoutConstraint.activate(headerLabelConstraints())
}

private func headerLabelConstraints() -> [NSLayoutConstraint] {
    let leadingAnchor = headerLabel.leadingAnchor.constraint(equalTo: self.layoutMarginsGuide.leadingAnchor)
    let trailingAnchor = headerLabel.trailingAnchor.constraint(equalTo: self.layoutMarginsGuide.trailingAnchor)
    let topAnchor = headerLabel.topAnchor.constraint(equalTo: self.layoutMarginsGuide.topAnchor)
    let heightAnchor = headerLabel.heightAnchor.constraint(equalToConstant: 44)
    headerLabel.translatesAutoresizingMaskIntoConstraints = false
    return [leadingAnchor, trailingAnchor, topAnchor, heightAnchor]
}

}
Here is how I am calling it in the tableView:
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    let header = view as! HeaderView
}

//for reference: sectionHeaderHeight = 44
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return tableView.sectionHeaderHeight
}

//for reference: sectionTitles = ["title1", "title2", "title3"]
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = HeaderView(frame: CGRect.zero)
    headerView.layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
    headerView.headerLabel.text = sectionTitles[section]
    headerView.headerLabel.textColor = UIColor.black
    return headerView
}

Thanks!

A: Update:
I noticed a couple of other issues. Here's how to resolve them:
In your HeaderView implementation:

*

*Remove self.translatesAutoresizingMaskIntoConstraints = false from the init(frame:) method.

(A UITableView always needs fixed row heights for both cells and header / footer views. If you're using Auto Layout to determine the row's height the system first computes the necessary height, then sets the corresponding bounds for the respective view and then adds a fixed width and a fixed height constraint that "simulate" these bounds. If you deactivate translatesAutoresizingMaskIntoConstraints on the view you also deactivate that last step and the view never gets its correct height set.)

*Add a bottom constraint:
let bottomAnchor = headerLabel.bottomAnchor.constraint(equalTo: self.layoutMarginsGuide.bottomAnchor)
// ...
return [leadingAnchor, trailingAnchor, topAnchor, bottomAnchor, heightAnchor]

(If you only connect the top, left and right layout anchors of the label with those of its superview the superview's height is not bound to the label's height. Its height will actually be 0. This is why all your labels are stacked on top of each other.)
In your view controller implementation that contains a reference to the table view:

*Add the following lines to its viewDidLoad() method:
tableView.sectionHeaderHeight = UITableViewAutomaticDimension
tableView.estimatedSectionHeaderHeight = 44

(This is how you tell the table view that you do not want to use a fixed header view height but you want the table view to automatically compute the height by resolving the Auto Layout constraints you added to the view. The estimated height doesn't need to be exactly 44. It should only be close to the average value of your header view heights.)

Original Answer:
Seems like you haven't "told" your table view how many sections it should have. Simply implement
func numberOfSections(in tableView: UITableView) -> Int {
    return sectionTitles.count
}

in your table view's data source. (If omitted the number of sections defaults to 1.)

By the way:
Your implementation
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    let header = view as! HeaderView
}

doesn't really make sense. It simply creates a constant and doesn't do anything with the constant. The compiler should actually show a yellow warning for this line. So unless you need to do something right before a header view is displayed just remove the whole method.


text:
Q: editMessageReplyMarkup in Telegraf.js deletes all markup I have this:
await ctx.editMessageReplyMarkup(ctx.chat_id, ctx.message_id, await keyboard.getPostInline(await db.getLikesCount(ctx.wizard.state.post.id), 1))

getPostInline:
async function getPostInline(likes_count, comments_count) {
    return Markup.inlineKeyboard([
        Markup.button.callback(`❤ ${likes_count}`, 'like'), Markup.button.callback(` ${comments_count}`, 'comment')
    ]).oneTime().resize()
}

When editMessageReplyMarkup runs, all markup just disappears from message. I tried JSON.stringify, nothing works.


text:
Q: Access parent view from a chid UIView I have a UIViewController with an xib and using Interface Builder I've added a child UIView.
Within the child UIView, when I click on an object within that view, I want to be able to alter the title of the whole window.
Now I'd normally do that setting
self.title = @"hi";

on the parent UIViewController. But is there any way I can access the parent title from within the child?
I've tried
self.superview.title = @"i";
self.parentViewController.title = @"hi";

but neither work.
Any help much appreciated
thanks

A: self.superview.title = @"i"; evaluates to an object of type UIView, and UIView has no title property. UIViewControllers have a parentViewController property but UIViews don't.
So the fundamental problem is that you're not properly separating your controller and your view classes. What you'd normally do is make the view you want to catch taps on a subclass of UIControl (which things like UIButton already are, but if it's a custom UIView subclass then you can just change it into a UIControl subclass since UIControl is itself a subclass of UIView), then in your controller add something like:
- (void)viewDidLoad
{
    [super viewDidLoad];

    // we'll want to know if the view we care about is tapped;
    // we've probably set up an IBOutlet to it but any way of
    // getting to it is fine
    [interestingView
               addTarget:self
               action:@selector(viewTapped:)
               forControlEvents:UIControlEventTouchDown];

     // UIButtons use UIControlEventTouchUpInside rather than
     // touch down if wired up in the interface builder. Pick
     // one based on the sort of interaction you want
}

// so now this is exactly like an IBAction
- (void)viewTapped:(id)sender
{
    self.title = @"My new title";
}

So you explicitly don't invest the view with any knowledge about its position within the view hierarchy or how your view controllers intend to act. You just tell it to give you a shout out if it receives a user interaction.


text:
Q: Let a, b ∈ Z, where Z is the set of integers. Define a relation S on Z as aSb is even for some number n. Prove that S is an equivalence relation. So, I am new to this relations. I have tried to attempt this question by supposing for values but that would not get me anywhere in a formal proof. The question is as follows:
Q. Let a, b ∈ Z, where Z is the set of integers. Define a relation S on Z as aSb
a) iff an + bn is even for some number n
b) iff a^n + b^n is even for some number n
Prove that S is an equivalence relation.
So, I need to prove both of these statements and I am not sure how can I check the properties with it?
To prove a relation we need to check the properties of reflexive, symmetric, and transitive. How can we prove the properties of variables?
NOTE: a and b are 2 different parts. The question is the same though.


text:
Q: What is meant by coordinate time? Isn't it time measured on a clock? If not then what does it measure? In this question-
Is proper time equal to the Invariant Interval or the time elapsed in the Rest Frame?
@Dale in the comments says-

no $dt$ is never physical time. It is always coordinate time. The equation $d\tau=dt'$ needs to be interpreted carefully. It is not a general fact, but instead it is only true along the worldline of the clock and only in the (primed) rest frame of said clock. But even then, the physical time is $d\tau$ and the coordinate time $dt'$ is designed to match it. That is what makes the primed coordinates the rest frame of the clock [...]

What is coordinate time?
What does one mean by coordinate time? Isn't it a time measured on the clock ( any clock)?
@Dale says no.
Then what is meant coordinate time?

A: In relativity we deal with spacetime which is a 4-dimensional structure called a (pseudo-Riemannian) manifold. It includes space and time together. Meaning that time is just another direction in spacetime, perpendicular to the three dimensions of space.
In the manifold we have a metric which describes all of the geometric properties of spacetime. It describes physically measured distances and durations and angles and speeds. You can use it to identify straight or curved lines and so forth. Straight lines in this sense are technically called geodesics.
A point particle forms a line in the spacetime manifold, called its worldline. An extended object forms a worldsheet or a worldtube, but we will stick with worldlines for now. A physically measured duration is called proper time, $d\tau$, and is measured by a physical clock on a specified worldline. An inertial object (in free-fall, no real forces acting on it) moves in a straight line at constant speed according to Newton's first law. In other words, an inertial object's worldline is straight.
Now, spacetime does not come with any physical labels or grid lines on it, but often we find it convenient to add labels/gridlines. These are called coordinates. Coordinates are ordered set of four numbers that label each event in spacetime. They must have some nice mathematical properties like being smooth and invertible. Everything else is a matter of convenience.
One approach that is often convenient is to use the first coordinate for time and the last three coordinates for space $(t,x,y,z)$. A further convenience is to use straight lines and planes. A further convenience is to choose an inertial object as a reference and orient those lines so that the time coordinate axis is parallel with the reference object's worldline and so that the space axes remain fixed and don't rotate. A final convenience is to scale the coordinates so that on the reference object's worldline the physically measured proper time matches the coordinate time and so that coordinate distances match measured physical distances. Such coordinates are called the inertial reference object's rest frame. In the absence of gravity such coordinates can extend to cover all of spacetime, but with gravity they can only be local, near the path of the inertial object.
Importantly, in these coordinates the metric can be written as $ds^2 = -c^2 d\tau^2 = -c^2 dt^2 + dx^2 + dy^2 + dz^2$. The physical time measured on any clock can be obtained by integrating the above expression for $d\tau$ along the worldline of that clock. The coordinate time is merely a convention for assigning the labels as described above. This convention is chosen to match the physical time on the reference object's clock, but not necessarily on other clocks. Elsewhere, $dt$ is merely a label.

A: In special relativity one traditionally imagines that spacetime is filled with a network of clocks that are Einstein synchronized. The clocks define an inertial reference frame, and the time coordinate of an event is the reading on the nearest clock.
When dealing with curved spacetime you usually can't Einstein synchronize clocks, and it's usually not convenient to use clock readings (however synchronized) directly as a coordinate, so coordinates are treated more abstractly. The same is true when dealing with ordinary curved surfaces like the surface of the Earth. We use latitude and longitude to measure global position, but there are no rulers that measure latitude and longitude; measurements are done locally with metersticks. In general relativity, the metric tells you how to convert between local measurements of clocks and metersticks and the global coordinates that you're using.

A: Mathematically Space-Time is a 4-dimensional Lorentzian manifold $L$. Coordinates of an event,
i.e. $(x_{\mu})=(ct, x, y, z)$ only make sense when you define an Atlas $\mathcal{A}={(\mathcal{U}_{\alpha}, \phi_{\alpha})}$ on $L$ where
$\mathcal{U}_{\alpha}\subset L$ and $\phi_{\alpha}:L\rightarrow\mathbb{R}^4$  is a homeomorphism (i.e. continus functions between the topological Spaces $M$ and $\mathbb{R}^4$). The coordinates of a point $p\in U_{\alpha}\subset L$ are then given by $\phi_{\alpha}(p)=(x_1, x_2, x_3, x_4)$.
There are a few restrictions on the $\phi_{\alpha}$ in order for the math to make sense, but other than that you're more or less free to choose any parametrization you want. The main idea is now, that physical quantities and laws should in a sense be independent of this choice. $\tau$ is such a quantity, the coordinates $x_i=\phi_{\alpha}(p)_i$ are obviously not.

A: $d\tau$ is an invariant of the metric. $dt$ is the time measured by a clock in a particular frame, as $dx$ is the length measured in this frame.
It is like saying that in 2D spatial cartesian coordinates, $ds^2 = dx^2 + dy^2$. $ds$ here is invariant by rotation. And we can also say that for any orientation of $ds$, there is a particular frame so that $ds^2 = dx^2$ (or $ds^2 = dy^2$).
But for 2D polar coordinates it is different. $ds^2 = dr^2 + r^2 d\theta^2$. $ds$ is also invariant by rotation. But there is no angle of rotation that leads to $ds^2 = d\theta^2$. It only happens in the case of $r = 1$. It corresponds to the example of $d\tau = dt$ for a static observer in the Schwartschild metric, that is only valid at $r = \infty$.
The Minkowski metric can be compared to the example of cartesian coordinates, and $d\tau$ can be understood as the time for a clock at rest of an inertial frame.
But in GR, similar to the example of polar coordinates, it is not generally true.


text:
Q: bash prompt wrapping to start of line I was trying to add some color and the time to my PS1 prompt on Debian 10 in my ~/.bashrc file. It initially looks right, but if I type a line that's more than about 40 characters the cursor moves to the beginning of the line (the first character of the prompt itself) and typing continues from there. I think something isn't escaped correctly, but I can't see what it is.
SH_OFF='\[\033[00m\]'

SH_BLACK='\[\033[1;30m\]'
SH_BLUE='\[\033[1;34m\]'
SH_GREEN='\[\033[1;32m\]'
SH_CYAN='\[\033[1;36m\]'
SH_RED='\[\033[1;31m\]'
SH_PURPLE='\[\033[1;35m\]'
SH_BROWN='\[\033[1;33m\]'
SH_YELLOW='\[\033[1;33m\]'

PS1="${debian_chroot:+($debian_chroot)}$SH_GREEN\u@\h \t$SH_OFF $SH_YELLOW\w$SH_OFF \$ "

A: Well, it looks like I had to use double-quotes. This appears to have fixed it:
SH_OFF="\[\033[00m\]"

SH_BLACK="\[\033[1;30m\]"
SH_BLUE="\[\033[1;34m\]"
SH_GREEN="\[\033[1;32m\]"
SH_CYAN="\[\033[1;36m\]"
SH_RED="\[\033[1;31m\]"
SH_PURPLE="\[\033[1;35m\]"
SH_BROWN="\[\033[1;33m\]"
SH_YELLOW="\[\033[1;33m\]"


text:
Q: Mapping where clause generic type (of SelectConditionStep) to my own class in jooq So I have an abstract class that prepares my query up to after where clause. It looks something like this:
SelectConditionStep<Record2<Integer, String>> whereQuery = dslContext.select(FOO.DIGITS, FOO.WORD)
                                                                .from(FOO)
                                                                .where(/*some conditions*/);

It then returns whereQuery and that instance is used by concrete implementations to add stuff onto it.
Is it possible to make this call return SelectConditionStep<MyClass> so that I don't have to write all Record types in method signature (note that this is a simplified version, imagine having Record10). MyClass would, in this example, have two fields, Integer and String fields.
Or if not that, is there any other way to do it.
I am using Postgres as a db

A: Assuming you have an immutable POJO MyClass, e.g. a Java 16 record:
record MyClass(int digits, String word) {}

You could use a nested record to achieve something similar:
Select<Record1<MyClass>> whereQuery =
ctx.select(row(FOO.DIGITS, FOO.WORD).mapping(MyClass::new))
   .from(FOO)
   .where(...)


text:
Q: resque-web with rails api only mode 1. What is the best way I can use resque-web with rails API-only mode?
My application uses resque with four separate job servers fur running the queues. I have mounted resque-web and I run it on local machine. it works fine only to show me the information about workers and queues. However,
    if I try to 'retry failed' jobs or 'delete a queue', it gives me
    routing error.
2. Is there any readymade way to expose all the routes used by resque-web as a json API?
So that I can design my own JS front end for job monitoring

A: In an Rails "API-only" app, you can fix the routing errors when retrying failed jobs or deleting queues by adding these lines to application.rb:
config.middleware.use Rack::MethodOverride
config.middleware.use ActionDispatch::Flash

See this GitHub issue for more details.


text:
Q: NGINX match multiple paths with proxy pass I'm trying to pass multiple locations to a proxy, though, I can simply not make it work. Can anybody point me in the right direction?
This is what I have so far:
    location / {
            try_files $uri $uri/ /index.html =404
            gzip on;
    }

    location ~* ^/(login|callback|ph|ch|th) {
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-Host $host;
            proxy_cache_bypass $http_upgrade;

            proxy_pass http://127.0.0.1:4002;
    }

As you probably can tell, I'm trying to pass

*

*/login

*/callback

*/ph

*/ch

*/th
to localhost on port 4002, but it's not passing them?
EDIT: If it's of any help. I think my front-end it hijacking the path-location? Not sure though.

A: All requests are starts from /, so your location should look like this:
location ~* ^/(login|callback|ph|ch|th) {

if you use start string symbol.


text:
Q: could not find function "%n%" function "%n%" not working even though I've loaded package dplyr.
mutate(category = ifelse(Year.Last.Used %n% c("2015", "2016"),"baseline","treatment"))
Caused by error in Year.Last.Used %n% c("2015", "2016"):
! could not find function "%n%"
How to fix the error?

A: I think that you probably want to use %in%..


text:
Q: How can i get the user's current voice channel ID? I am trying to get the channel ID that a certain user, target from a command is connect and then use it to move to a channel
This is my current test code:
@client.command(aliases=['teste'])
async def test(ctx, target: discord.Member):
    channel_return = (target.voice)
    await ctx.send (channel_return['VoiceChannel id'])

it returns on the discord text chat the value:
<VoiceState self_mute=True self_deaf=False self_stream=False suppress=False requested_to_speak_at=None channel=<VoiceChannel id=734512711748157471 name=':eyes: :regional_indicator_s: :regional_indicator_a: :regional_indicator_l: :regional_indicator_a:' rtc_region=<VoiceRegion.us_central: 'us-central'> position=4 bitrate=64000 user_limit=0 category_id=703115313884954624>>
which have the channel_id, but i can't acess without getting the error:
TypeError: 'VoiceState' object is not subscriptable
How can i access the value of VoiceChannel id from a target user?

A: @client.command(aliases=['teste'])
async def test(ctx, target: discord.Member):
    if target.voice:
        channel_return = target.voice.channel
    else:
        return

member.voice returns the voice_state of the member which basically means is current voice status (channel, speaking ect)
what I have done was checking if he is actually in a voice because if he isn't voice is going to return None and then you wouldn't be able to access the channel because none doesn't have a channel attribute.
you've to take the channel like it is a dict but what you saw was an object so all of the values there were attributes or properties that the voice_state object had


text:
Q: How to move content from activity to fragment My application had a single activity and I decided to put the main content inside a fragment, so I can continue using my drawer with other activities. However I can't make the buttons work:
 Button profile= findViewById(R.id.button1);
    profile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplication(),"Sürücüler",Toast.LENGTH_SHORT).show();
        }
    });

    Button education= findViewById(R.id.button2);
    education.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplication(),"Takımlar ve arabalar",Toast.LENGTH_SHORT).show();
        }
    });

    Button health= findViewById(R.id.button3);
    health.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplication(),"Pistler",Toast.LENGTH_SHORT).show();
        }
    });

    Button goals= findViewById(R.id.button4);
    goals.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplication(),"Sıralama",Toast.LENGTH_SHORT).show();
        }
    });

    Button finance= findViewById(R.id.button5);
    finance.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplication(),"Grand Prix Tarihi",Toast.LENGTH_SHORT).show();
        }
    });

    Button comfort= findViewById(R.id.button6);
    comfort.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplication(),"GP kart oyunu",Toast.LENGTH_SHORT).show();
        }
    });

If I leave this code at MainActivity it doesn't work (because the buttons aren't created yet?) but when I move them into the fragment, findViewById and getApplicationContext doesn't work. How can make Toast messages compatible with fragments and how can I make sure my fragment can use findviewbyid?
I am beginner so I am sorry if this is simple.
Any help would be appreciated.

A: Based on your comment,
return inflater.inflate(R.layout.fragment_home, container, false);

should actually be:
View root = inflater.inflate(R.layout.fragment_home, container, false);
Button profile =(Button)root.findViewById(R.id.button1);
profile.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Toast.makeText(getApplication(),"Sürücüler",Toast.LENGTH_SHORT).show();
    }
});

//similarly for other buttons

return root;

A: if the button in the fragment XML
you can use
 Button profile= v.findViewById(R.id.button1);

so v is your fragment view in the method "onCreateView"
View v=inflater.inflate(R.layout.fragment_home, container, false);

and in the last of the method
return v;

A: A fragment is usually used as part of an activity's user interface and contributes its own layout to the activity.
 So first you need to create a layout for the fragment with all the button in it.
To provide a layout that we created to the  fragment, you must implement the onCreateView() callback method in the fragment class, which the Android system calls when it's time for the fragment to draw its layout. Your implementation of this method must return a View that is the root of your fragment's layout.
public  class ExampleFragment extends Fragment {

 Button health;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.example_fragment, container, false);
    // bind views like this:-
    health= root.findViewById(R.id.button3);

    return  root;
  }
}

To manage the fragments in your activity, you need to use FragmentManager. To get it, call getSupportFragmentManager() from your activity.
Now the activity class add the following code to add fragment to activity , :-
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

 // Commit the transaction
 transaction.commit();

Where R.id.fragment_container is id of the container layout  where the fragments  are to be added in the activty layout , generally a framelayout.
How to use Fragments in android


text:
Q: Who knows this formula for polynomial interpolation? For my high school math project I studied polynomial interpolation: given a set of points $(x_0,y_0),...,(x_n,y_n)$, find the polynomial of degree $n$ that passes through all points. The solutions by Newton and Lagrange are well known, but I wanted to know the coefficients of the polynomial in standard form (powers of $x$). Using elementary algebra I solved the cases up to $n=3$ and generalized this to

$$
V(x) = \sum^n_{i=0}(-1)^{n-i}\sum^n_{j=0}y_j\frac{e_{n-i}(x_0,...,x_{j-1},x_{j+1},...,x_n)}{\prod^n_{k=0,k\neq j}(x_j-x_k)}x^i
$$

where $e_k(S)$ is the elementary symmetric polynomial (ESP). I also proved this. Later, I found out that V(x) is equivalent to the solution using Vandermonde's matrix, see the answer to exercise 40 in Knuth's The Art of Computer Programming, vol. 1, section 1.2.3. Sums and products. The only difference is that Vandermonde doesn't use the ESP. Lagrange's solution is expressed in elementary algebra, Newton's solution uses the divided differences (DD) $[y_0,...,y_n]$, and Vandermonde's solution can be expressed using ESP. So I wondered whether there is a solution using both DD and ESP. And there is. My solution is

$$H(x) = \sum^n_{i=0}\sum^n_{j=i}[y_0,...,y_j](-1)^{j-i}e_{j-i}(x_0,...,x_{j-1})x^i$$

It can be derived from Newton's solution and from Vandermonde's solution. After finding the solution tried to find it in (online) literature but I couldn't. I asked my math teacher and a university math professor and both did not know where it can be found. (Question) Who knows where to find the solution $H(x)$ in math literature?

A: Hint:
By Cramer, the coefficient of the $n^{th}$ power is the ratio of the Vandermonde determinant dividing a modified determinant where the $n^{th}$ column is replaced by the RHS. The latter can be expanded using the modified column and corresponding minors, which are of a quasi-Vandermonde type (there is a discontinuity in the exponents). These minors are still factored with the differences between two $x$'s, but there is an extra factor.

A: Note that you can pass from Newton or Lagrange , expressed in terms of products
in $(x-x_k)$ to $x^k$ through the Vieta's formulas.
That is, if given the vector $\bf x_h$  indexed $0 \cdots h$ (the abscissas of the $h+1$ interpolating points)
 we construct the square matrix $ {\bf A}_{\,h} ({\bf x})$ according to Vieta's formulas as below
$$
\begin{array}{l}
 {\bf A}_{\,h} ({\bf x}) = \left\| {\;a_{\,n,\,m} ({\bf x})\;} \right\|_{\,h}  =  \\
  = \left\| {\;\left[ {m \le n} \right]\left( { - 1} \right)^{\,n - m} \sum\limits_{\begin{array}{*{20}c}
   {}  \\
   {0\, \le \,k_{\,0} \, < \,k_{\,1} \, < \, \cdots \, < \,k_{\,n - m - 1} \, \le \,n - 1}  \\
\end{array}} {\prod\limits_{0\, \le \,j\, \le \,n - m - 1} {x_{\,k_{\,j} } } } \;} \right\|_{\,h}  \\
 \end{array}
$$
and if you accept the following notation (nothing standard, it's just my personal elaboration)
$$
\begin{array}{l}
 z^{\,{\bf x}_{\,h} }  = \left\| {\;\prod\limits_{0\, \le \,k\, \le \,n - 1} {\left( {z - x_{\,k} } \right)} \;} \right\|_{\,h,0} \quad  \Rightarrow  \\
  \Rightarrow \quad z^{\,{\bf o}_{\,h} }  = \left\| {\;\prod\limits_{0\, \le \,k\, \le \,n - 1} {\left( {z - 0} \right)} \;} \right\|_{\,h,0}  = \left\| {\;z^{\,n} \;} \right\|_{\,h,0}  \\
  \Rightarrow \quad z^{\,{\bf n}_{\,h} }  = \left\| {\;\prod\limits_{0\, \le \,k\, \le \,n - 1} {\left( {z - k} \right)} \;} \right\|_{\,h,0}  = \left\| {\;z^{\,\underline {\,n\,} } \;} \right\|_{\,h,0}  \\
 \end{array}
$$
where $ z^{\,{\bf x}_{\,h} } $ is thus the Newton basis polynomial
and where $x^{\,\underline {\,k\,} }$
represents the Falling Factorial
then
$$ \bbox[lightyellow] {
z^{\,{\bf x}_{\,h} }  = {\bf A}_{\,h} ({\bf x})\;z^{\,{\bf o}_{\,h} }
}$$
Since
$$
z^{\,{\bf n}_{\,h} }  = \left\| {\;z^{\,\underline {\,n\,} } \;} \right\|_{\,h,0}  = {\bf A}_{\,h} ({\bf n})\;z^{\,{\bf o}_{\,h} }
  = {\bf A}_{\,h} ({\bf n})\left\| {\;z^{\,n} \;} \right\|_{\,h,0}
$$
and, representing in square brackets the (unsigned) Stirling N. of 1st kind and in curly brackets those of 2nd kind, it is
$$
x^{\,\underline {\,n\,} }  = \sum\limits_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)} {\left( { - 1} \right)^{\,n - k} \left[ \matrix{
  n \cr
  k \cr}  \right]x^{\,k} }
$$
then
$$
\begin{array}{l}
 {\bf A}_{\,h} ({\bf n}) = \left\| {\;\left[ {m \le n} \right]\left( { - 1} \right)^{\,n - m} \sum\limits_{\begin{array}{*{20}c}
   {}  \\
   {0\, \le \,k_{\,0} \, < \,k_{\,1} \, < \, \cdots \, < \,k_{\,n - m - 1} \, \le \,n - 1}  \\
\end{array}} {\prod\limits_{0\, \le \,j\, \le \,n - m - 1} {\,k_{\,j} } } \;} \right\|_{\,h}  =  \\
  = \left\| {\;\left( { - 1} \right)^{\,n - m} \left[ \begin{array}{c}
 n \\
 m \\
 \end{array} \right]\;} \right\|_{\,h}  = {\left\| {\;\left\{ \begin{array}{c}
 n \\
 m \\
 \end{array} \right\}\;} \right\|_{\,h}} ^{\; - \,{\bf 1}}  = {\bf S}_{{{\bf t2}} _h} ^{ - \,{\bf 1}}  \\
 \end{array}
$$
so that the Vieta' formulas provide a generalization of the Stirling Numbers.
Some references you may find interesting to start are this related post and this paper.


text:
Q: jQuery/JavaScript Undefined Function Error I am using a script for my slider called Camera. Unfortunately it keeps loading and gives me the following error:

TypeError: undefined is not a function (evaluating '$('#camera_wrap').camera')

The piece of code where that is involved is as following:
$(document).ready(function () {
    $('#camera_wrap').camera({
        loader: true,
        pagination: false,
        minHeight: '',
        thumbnails: false,
        height: '54.6875%',
        caption: true,
        navigation: true,
        fx: 'simpleFade'
    });
});

A: One of the functions you call isn't actually a function.
There are only two or three (relevant) function calls: $(..) and .camera(...) and maybe .ready(...).
.
So either:

*

*You don't have jQuery loaded before this script is executed. In that case $(...) does not exist. You should load the jQuery library before (higher up in the code of the page) before this script is executed.

*You have jQuery loaded in compatibility mode, so it doesn't register $(...). In that case, you can replace the shorthand $ with jQuery, so you can call jQuery.ready(....).

*You didn't load the camera plugin. It doesn't matter much where you load it, since the code that calls the function is only called when the whole page has loaded, but you need to include that library in your page as well.

*You didn't include any of the other libraries, or you included them in the wrong order. The website says:

As you can see in the examples themselves, before the Camera plugin,
  you must call jQuery in the head [sic]*) of your document: without jQuery the
  slideshow doesn't work.
Then you must call jQuery Easing plugin and jQuery Mobile plugin.
  After that you must call Camera plugin and initialize the function
  camera with the simply method jQuery('YOUR_TARGET').camera();

*) (As Sparky mentioned in comments, you don't strictly need to load jQuery in the head, as long as you load it before the script is executed).

A: Given that the error occurs while evaluating $('#camera_wrap').camera, we can assume you have loaded jQuery correctly as this is called inside $(document).ready().
So the problem must be that jQuery can't 'see' your plugin script at the time when it needs to.
Make sure you include the Camera plugin script after jQuery and before your code which uses it. If you don't know how to do this please edit your question and include all of the HTML for the page you are working on.


text:
Q: Globing with linux How do you list only files that have two numbers in the name?
I did ls *[0-9]*[0-9]* but it appears that this is not the right one as it shows other files that have 4 digits in their name.
How do you list only files are two-letter-named txt files?
for this I did ls ??.txt but I do not know how to list only letter named files.
I am using bash.

A: In *[0-9]*[0-9]*, the asterisks can match anything, so even more letters. Something like 1234.txt does have two digits in it, even if that's not how it would be usually phrased in English.
You'd need something that matches "any number of characters that are not digits" to replace the asterisks, and that's harder to do with regular globs. You could do it with ksh-style extended globs, though. In e.g. Bash:
#!/bin/bash
shopt -s extglob
ls *([^0-9])[0-9]*([^0-9])[0-9]*([^0-9])

(An alternative would be to loop over the list of filenames matching *[0-9]*[0-9]*, and filter out the ones that also match *[0-9]*[0-9]*[0-9]*. Either way, it's not very pretty.)
Any two letters (only), followed by .txt would be [[:alpha:]][[:alpha:]].txt.


text:
Q: error while joining tables using nesting in SQL My query looks like this
SELECT level1_idnt, day_dt, avg(sls_price) as avg_rp
FROM (SELECT * FROM (SELECT DISTINCT level1_idnt,day_dt,sls_price
                     FROM (SELECT a.level1_idnt,a.day_dt,a.sls_price,b.op
                           FROM (SELECT level1_idnt,day_dt,sls_price
                           FROM md1.loc_sku_dy_act_pos_full_v2
                           WHERE seasn_cd =2 and day_dt >= '2015-03-01 00:00:00' and day_dt <= '2015-09-30 00:00:00'
                                )l0
                           a left join (SELECT level1_idnt, AVG(org_sales_price) as op
                                        FROM (SELECT DISTINCT level1_idnt, org_sales_price
                                        FROM md1.item_lv1_org_price_m
                                        WHERE fr_cntry_cde = '01' AND org_sales_price IS NOT NULL
                                        ) l
                                        GROUP BY level1_idnt)l_op
                           b
                           ON a.level1_idnt = b.level1_idnt
                           )l1
            WHERE sls_price <= op
      )l2
      WHERE sls_price is not null
     ) l3
GROUP BY level1_idnt,day_dt;

for this I am getting an error
syntax error at or near "a"

Any help on this will be greatly appreciated

A: Check this;) it looks like a alias mistake in subquery.
SELECT level1_idnt, day_dt, avg(sls_price) as avg_rp
FROM (SELECT * FROM (SELECT DISTINCT level1_idnt,day_dt,sls_price
                     FROM (SELECT a.level1_idnt,a.day_dt,a.sls_price,b.op
                           FROM (SELECT level1_idnt,day_dt,sls_price
                                 FROM md1.loc_sku_dy_act_pos_full_v2
                                 WHERE seasn_cd =2 and day_dt >= '2015-03-01 00:00:00' and day_dt <= '2015-09-30 00:00:00'
                                )
                          a left join (SELECT level1_idnt, AVG(org_sales_price) as op
                                       FROM (SELECT DISTINCT level1_idnt, org_sales_price
                                             FROM md1.item_lv1_org_price_m
                                             WHERE fr_cntry_cde = '01' AND org_sales_price IS NOT NULL
                                            ) l
                                       GROUP BY level1_idnt)
                    b
ON a.level1_idnt = b.level1_idnt
)l1
WHERE sls_price <= op
)l2
WHERE sls_price is not null
) l3
GROUP BY level1_idnt,day_dt;

Before a there is a string l0 and before b a string l_op

A: It looks like you're trying to give two names to the same subquery:
(SELECT level1_idnt,day_dt,sls_price
 FROM md1.loc_sku_dy_act_pos_full_v2
 WHERE seasn_cd =2 and day_dt >= '2015-03-01 00:00:00'
 and day_dt <= '2015-09-30 00:00:00')l0 a

or call the subquery "l0" or "a"
and the same situation with "b":
(SELECT level1_idnt, AVG(org_sales_price) as op
 FROM (SELECT DISTINCT level1_idnt, org_sales_price
       FROM md1.item_lv1_org_price_m
       WHERE fr_cntry_cde = '01' AND org_sales_price IS NOT NULL) l
 GROUP BY level1_idnt) l_op b

or you call the subquery "l_op" or "b"
From what I can see I think you can replace "a" with "l0" and "b" with "l_op" in this line
SELECT a.level1_idnt,a.day_dt,a.sls_price,b.op

and remove the names "a" and "b" from the subquery


text:
Q: linux - headphones and speaker works only AFTER resume from sleep Good day all
For quite some time I have had this issue, not distro specific, I assume it is a kernel related issue.
aplay -l
**** List of PLAYBACK Hardware Devices ****
card 0: PCH [HDA Intel PCH], device 0: VT1802 Analog [VT1802 Analog]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: PCH [HDA Intel PCH], device 2: VT1802 Alt Analog [VT1802 Alt Analog]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: PCH [HDA Intel PCH], device 3: HDMI 0 [HDMI 0]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 1: Headset [Logitech G930 Headset], device 0: USB Audio [USB Audio]
  Subdevices: 0/1
  Subdevice #0: subdevice #0

lspci -v | grep Audio
00:1b.0 Audio device: Intel Corporation 7 Series/C210 Series Chipset Family High Definition Audio Controller (rev 04)

My USB Logitech headset always functions, no matter cold or hot boot, and I recently got this, so the USB headset is not the issue.
All sound configurations were left stock, except of course for volume changes
This occured since I started using Linux with Linux Mint 14, with Mint 15, Ubuntu 15.04 and Ubuntu 15.10, I am not sure about others since I haven't used them
For some reason, either my card is not properly detected/configured on a cold boot but runs this script/procedure when resuming

A: On my desktop with Linux Mint 17.3 I also had a problem with sound that would only work after resuming from suspend. That has proved not to be consistent way to make sound work. I tried lately to unplug replug the phono plug to the computer and on the other end the phono plug to the speaker. That somehow made my sound work again. The plugs were not lose or improperly plugged.


text:
Q: Read path and compression offset map I'm trying to understand Cassandra read path and can't get why do we need a
compression offset map.
https://docs.datastax.com/en/cassandra/3.0/cassandra/dml/dmlAboutReads.html

The partition index resides on disk and stores an index of all partition keys mapped to their offset.
The compression offset map stores pointers to the exact location on disk that the desired partition data will be found.

Why do we need both of them? Why can't partition index store pointers to exact location on disk?
I'm sorry for a stupid title, but that's what stackoverflow asked me, I couldn't use "Why do we need a compression offset map if we have a partition index?"

A: The file is compressed in chunks. By default 64k of data is compressed, then next 64k etc. The offsets written in index file are that of the uncompressed data. This is because as its writing, it knows how many bytes have been written so far so uses that to mark whenever starting new partition. The compression offsets maps the compressed offsets and their uncompressed positions so it knows which chunk to start decompressing to get to the partition at some uncompressed offset from the index.
If a partition exists in the middle of a 64k compressed chunk, you need do decompress that entire chunk. You cannot start reading in the middle of it due to how the compression algorithms work. This is why in some situations it makes sense to decrease the chunk size as it would reduce the overhead of reading a tiny partition.


text:
Q: POST request to Django Model Formset with Vuejs front-end I am using Django to build a back-end of my project and Vuejs to build the front-end.
I have defined my models in Django and have used Django forms to save data to the models. For a single form, I just pass a JSON object in the body of the POST request. This works perfectly fine.
But now I need to save multiple records at the same time. I found that Django model formsets can do this. However, I am not able to figure out how to format the POST request. The Django documentation assumes that I'll be using Django templates (which is quite annoying), and therefore says nothing about the format of the request itself.
The application is an API documentation tool and I need to allow the user to define the params of the API. As of now, I have the following:
from django.forms import modelformset_factory
from docs.models import ApiParams

ParamsFormSet = modelformset_factory(ApiParams, exclude=('param_id',))

def create_params(request):
    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)
    formset = ParamsFormSet(body)
    instaces = formset.save()
    return HttpResponse(instances)

I called this API with the following data:
[
    {
        "api": 2,
        "param_name": "param1",
        "param_type": "string",
        "param_required": true,
        "param_sample": "param"
    },
    {
        "api": 2,
        "param_name": "param2",
        "param_type": "numeric",
        "param_required": false,
        "param_sample": "3"
    }
]

But this results in the following error:
Internal Server Error: /create-params/
Traceback (most recent call last):
  File "D:\Documents\django\api-docs\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "D:\Documents\django\api-docs\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "D:\Documents\django\api-docs\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\Documents\django\api-docs\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "D:\Documents\django\api-docs\docs\views.py", line 47, in create_api_params
    if formset.is_valid():
  File "D:\Documents\django\api-docs\venv\lib\site-packages\django\forms\formsets.py", line 308, in is_valid
    self.errors
  File "D:\Documents\django\api-docs\venv\lib\site-packages\django\forms\formsets.py", line 288, in errors
    self.full_clean()
  File "D:\Documents\django\api-docs\venv\lib\site-packages\django\forms\formsets.py", line 329, in full_clean
    for i in range(0, self.total_form_count()):
  File "D:\Documents\django\api-docs\venv\lib\site-packages\django\forms\formsets.py", line 112, in total_form_count
    return min(self.management_form.cleaned_data[TOTAL_FORM_COUNT], self.absolute_max)
  File "D:\Documents\django\api-docs\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:\Documents\django\api-docs\venv\lib\site-packages\django\forms\formsets.py", line 91, in management_form
    if not form.is_valid():
  File "D:\Documents\django\api-docs\venv\lib\site-packages\django\forms\forms.py", line 180, in is_valid
    return self.is_bound and not self.errors
  File "D:\Documents\django\api-docs\venv\lib\site-packages\django\forms\forms.py", line 175, in errors
    self.full_clean()
  File "D:\Documents\django\api-docs\venv\lib\site-packages\django\forms\forms.py", line 376, in full_clean
    self._clean_fields()
  File "D:\Documents\django\api-docs\venv\lib\site-packages\django\forms\forms.py", line 388, in _clean_fields
    value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
  File "D:\Documents\django\api-docs\venv\lib\site-packages\django\forms\widgets.py", line 258, in value_from_datadict
    return data.get(name)
AttributeError: 'list' object has no attribute 'get'

P.S. My question doesn't have anything to do with Vuejs, that was mentioned only so that people don't suggest Django template solutions. I made the above POST request with Postman, haven't even integrated theh API with my front end.

A: So let's see if we do this in DRF. I'm assuming your ApiParam model is this:
_param_types = ["string", "integer", "array", "object"]
PARAM_TYPE_CHOICES = [(t, t) for t in _param_types]

class ApiParam(models.Model):
    api = models.ForeignKey(Api, on_delete=models.CASCADE, related_name="parameters")
    param_name = models.CharField(max_length=100)
    param_type = models.CharField(max_length=10, choices=PARAM_TYPE_CHOICES)
    param_required = models.BooleanField(default=False)
    param_sample = models.TextField()

The serialization would be:
class ApiParamSerializer(serializers.ModelSerializer):
    class Meta:
        model = ApiParam
        fields = [  # Explicit > Implicit
            "param_name",
            "param_type",
            "param_required",
            "param_sample"
        ]

Judging from the formset in the title, what your intention with the payload seems to be is to update an Api model with additional parameters, which is a reverse foreign key or perhaps even a ManyToMany.
In this case, it's better to structure the payload as:
{
    "api": 2,
    "parameters": [
        {
            "param_name": "param1",
            "param_type": "string",
            "param_required": true,
            "param_sample": "param"
        },
        {
            "param_name": "param2",
            "param_type": "numeric",
            "param_required": false,
            "param_sample": "3"
        }
    ]
}

Your ApiSerializer would be:
class ApiSerializer(serializers.ModelSerializer):
    api = serializers.IntegerField(source='api_id')
    parameters = ApiParamSerializer(many=True)
    class Meta:
        model = Api
        fields = ["api", "parameters"]

And your view:
class ApiUpdateView(generics.UpdateAPIView):
    serializer_class = ApiSerializer

And we should be done. As you can see this is all declarative. And the heavy lifting is done by Django / DRF. It takes a bit to get used to, but it's pretty straight forward once the quarter drops.


text:
Q: Application of Desargues' theorem for constructions I found this interesting document (german) on the internet. On page 8 it says:
"Draw a line segment between two given points only using compass and ruler, while the distance between the two points is larger then the length of the ruler"
Now I have two questions:

*

*Has someone heard about this problem and can give an other source?

*I know there are two versions of Desargues' Theorem, an affine and a projective one. Is the problem stated above an application of the affine or of a projective version?

Any help is appreciated and if more translation is necessary please let me know.

A: I. No, I haven't heard of this problem, and can give no other source, sorry.
II. According to page 2, the Desargues theorem used in the document is the projective version in the wiki page. (The author of the interesting document employs of the theorem to prove that the point $C$ in the construction actually lies on the line $AB,$ so as to reduce the distance from $\overline{AB}$ to one of $\overline{AC}$ and $\overline{BC}.$)
P.S. Have you read the references in the document? Especially the Reelle projektive Geometrie der Ebene of Coxeter might be quite interesting.
Hope this answers the doubt, at least partially.


text:
Q: Assign char value 'B' to byte datatype in soapUI I have created a web service , Now i am trying to test my web service using SaopUI tool which takes WSDL file(xml file) as input
Here ,one of parameter is of byte datatype,it's value can be 'C' , 'S' , 'B'
I tried by pass value 'C' but it gives below error
java.lang.NumberFormatException: For input string: "C"
I tried to pass ASCII value of 'C' as 67 but it gives below error
The mandatory field of entityType either unassigned or NULL
Please suggest how can I pass char value
Thanks


text:
Q: Ajax not sending PHP POST data I'm using the following ajax script to POST data back after re-sorting the rows (which works fine). I'm not getting anything in the alert(data) that is being shown once I drag-and-drop the row. It should show me what it's trying to pass to the 'refresh_order.php' file.
I am NOT a jQuery or ajax expert -- I found this bit of code online and the first part works for me (the dragging and dropping) but I don't know what's wrong with the ajax that posts the data back to MySQL.
What do I need to do to fix this?
$('tbody').sortable({
    cancel: ":input,button,[contenteditable]",
    axis: "y",
    update: function (event, ui) {
        var data = $(this).sortable('serialize');

         alert(data);  // Sent to server

        $.ajax({
            data: data,
            type: 'POST',
            url: 'refresh_order.php',
            success: function(response) {
             //    alert(response);   // Server response
            }
        });
    }
});

[I have looked through most of the posts here on Stack Overflow and seen nothing that helps my situation. I even tried to reach out to the person who I got the code from but haven't received a response.]

A: From the documentation:
Note: If serialize returns an empty string, make sure the id attributes include an underscore. They must be in the form: "set_number" For example, a 3 element list with id attributes "foo_1", "foo_5", "foo_2" will serialize to "foo[]=1&foo[]=5&foo[]=2". You can use an underscore, equal sign or hyphen to separate the set and number. For example "foo=1", "foo-1", and "foo_1" all serialize to "foo[]=1".
I assume your tr elements are missing the id attributes in the appropriate format. Here's a working example:

      r1c1
      r1c2

      r2c1
      r2c2

$('tbody').sortable({
  cancel: ":input,button,[contenteditable]",
  axis: "y",
  update: function(event, ui) {
    var data = $(this).sortable('serialize');
    console.log(data);
  }
});

https://jsfiddle.net/bwxmfzs5/


text:
Q: Arithmetic series in Ruby I am trying to write a function in ruby that returns "Arithmetic" when the input is an arithmetic series array(the delta between a number and the consecutive number in the array is the same across the array). Here's what I have for so far:
array = [1,3,5,7,9] #arithmetic series input example
array.each_cons(2).map {|x,y| y - x == array[2] - array[1]}

This returns the following
[true,true,true,true,true]

My goal is to write a function that identifies what kind of series the array is, if there is one at all. Here's what I am trying to build
def isarithemetic(array)
if array.each_cons(2).map {|x,y| y - x == array[2] - array[1]} == true
    return "arithmetic"

I am open to new suggestions as well.

A: You should be able to do this using all?:
array.each_cons(2).map {|x,y| y - x == array[2] - array[1]}.all?

or perhaps
array.each_cons(2).all? {|x,y| y - x == array[2] - array[1]}

A: If an array arr contains integer values, those (ordered) values comprise at most one arithmetic expression.  If the average interval is integer-valued (i.e.,
  ((arr.last-arr.first) % (arr.size-1).zero?

is true), a unique progression is given by the values of arr.first, arr.last and arr.size, namely:
  avg_interval = (arr.last-arr.first)/(arr.size-1)
  (arr.first..arr.last).step(avg_interval).to_a

If the average interval is not integer-valued, it cannot be an arithmetic progression, but we don't need to check that condition.  That's because by using integer arithmetic to compute avg_interval, the resulting arithmetic progression cannot equal arr if the average interval is not integer-valued.
Hence, rather than check if all the intervals are equal, we could just check to see if the above arithmetic progression equals arr.
Code
def arithmetic_progression?(arr)
  return true if arr.size < 2
  (arr.first..arr.last).step((arr.last-arr.first)/(arr.size-1)).to_a == arr
end

Examples
arithmetic_progression?([1,3,5,7,9]) #=> true
arithmetic_progression?([1,3,5,7,8]) #=> false

In the first example:
arr = [1,3,5,7,9]
avg_interval = (arr.last-arr.first)/(arr.size-1) #=> 2
(arr.first..arr.last).step(avg_interval).to_a    #=> [1, 3, 5, 7, 9]

In the second:
arr = [1,3,5,7,8]
avg_interval = (arr.last-arr.first)/(arr.size-1) #=> 1
(arr.first..arr.last).step(avg_interval).to_a    #=> [1, 2, 3, 4, 5, 6, 7, 8]

You could then write, for example:
arithmetic_progression?([1,3,5,7,9]) ? "Arithmetic progression" :
  "Not arithmetic progression" #=> "Arithmetic progression"

Variant
The method could probably be made slightly more efficient by inserting the following line after the first line of the method:
return false unless ((arr.last-arr.first) % (arr.size-1)).zero?


text:
Q: Python PIL/imagemagick merge gradient over the base image I already know how to get a gradient image but how can I merge the gradient image and the base image so that it looks something like this:
link
convert -size 1327x1327 xc:transparent gradient: grad_image.png

or another approach has been suggested here
Base image is
The output should the gradient at the bottom like this: https://1drv.ms/i/s!Aoi-6MWkMNN4kGLYNmqN9dm1nrOD

A: I can only guess what you are trying to do, so my first attempt would be this:
convert jelly.jpg \( -size 1140x100! gradient:none-black \) -gravity south -composite -pointsize 36 -fill white -annotate +0+20 "Title Treatment" result.png

The important parts are that the gradient goes from black to transparent rather than black to white, else you will get white on your background which I am guessing you don't want.
The -gravity south places the gradient at the bottom and also sets the initial position of the title, but that is then shifted 20 pixels up from the bottom with -annotate +0+20.
Hope that helps.
Update 1
If you want to control the gradient, you can alter the start and end of it using rgb() constants, like this:
convert jelly.jpg \( -size 1140x100! gradient:"rgba(0,0,0,0.25)"-"rgb(50,50,50)" \) -gravity south -composite -pointsize 36 -fill white -annotate +0+20 "Title Treatment" result.png

Or you can make it go from one colour to another:
convert jelly.jpg \( -size 1140x100! gradient:"rgba(0,0,0,0.25)"-"rgba(255,255,0,0.75)" \) -gravity south -composite -pointsize 36 -fill white -annotate +0+20 "Title Treatment" result.png

Or you can change the blending mode, so here I use colorBurn:
convert jelly.jpg \( -size 1140x100! gradient:"rgba(0,0,0,0.25)"-"rgba(255,255,0,0.75)" \) -gravity south -compose colorburn -composite -pointsize 36 -fill white -annotate +0+20 "Title Treatment" result.png

If you want to try some other blending modes, you can get a list with:
identify -list compose:

Atop
Blend
Blur
Bumpmap
ChangeMask
Clear
ColorBurn
ColorDodge
Colorize
CopyAlpha
CopyBlack
CopyBlue
CopyCyan
CopyGreen
Copy
CopyMagenta
CopyRed
CopyYellow
Darken
DarkenIntensity
DivideDst
DivideSrc
Dst
Difference
Displace
Dissolve
Distort
DstAtop
DstIn
DstOut
DstOver
Exclusion
HardLight
HardMix
Hue
In
Intensity
Lighten
LightenIntensity
LinearBurn
LinearDodge
LinearLight
Luminize
Mathematics
MinusDst
MinusSrc
Modulate
ModulusAdd
ModulusSubtract
Multiply
None
Out
Overlay
Over
PegtopLight
PinLight
Plus
Replace
Saturate
Screen
SoftLight
Src
SrcAtop
SrcIn
SrcOut
SrcOver
VividLight
Xor

Update 2
If you want to blur the text, it is easier to create that first, blur it, and then underlay the background like this:
convert -size 1140x100! gradient:none-black     \
   -pointsize 36 -fill white -gravity south     \
   -annotate +5+25 "Title Treatment" -blur 0x4  \
   -annotate +0+20 "Title Treatment" jelly.jpg +swap -composite result.png

Update 3
If you want to shadow your text, and control your gradient and do a load of other things, you may be better off doing one thing at a time. So, let's try and make your text with a drop-shadow first, then put a gradient on your image then put the shadowed text on top of that - and hope we are getting close!
string="Funky Main Title\nSub-title"
convert -size 1200x400 xc:none -pointsize 72 -gravity center   \
       -fill white  -stroke black  -annotate +25+65 "$string"  \
       \( +clone -background black  -shadow 70x4+5+5 \) +swap  \
       -background none -flatten  -trim +repage shadowed.png

Now put gradient on main image and title top of that:
convert jelly.jpg                                                   \
  \( -size 1140x100! gradient:"rgba(0,0,0,0.25)"-"rgb(50,50,50)" \) \
  -gravity south -composite                                         \
  shadowed.png -composite result.png


text:
Q: Accordion JQuery Search I have an accordion set up on a website i am building however i have been trying to implement a search function.
Potentially as you type, to hide & display each accordion based on the search.
here is my HTML code for two cards which are part of the accordion:

            <input class="input-medium search-query" id="searcher" placeholder="Search">
            <button class="btn">Search</button>

                    Why should I use Imperial Claims Consultants?

                    Imperial Claims are industry experts in dealing with commercial, industrial, homeowners and landlords insurance claims and we have, and continue to provide our clients with a truly personal and bespoke service. With over 80 years combined in-house claims handling experience there isn't any type of disaster that we haven't already managed. From small claims to the largest of claims, we can truly assist.

                    Loss assessors are typically professional companies and individuals that will negotiate on the policyholder's behalf to progress a claim to resolution. It could be said that they offer a claims management service for the policyholder, meaning the policyholder doesn't have to spend time dealing with the insurer – the loss assessor will typically do this.

                    A Loss Assessor, like Imperial Claims Consultants, will look at the damage, assess the costs involved and they may then take the lead in all discussions on the claim with the insurers or loss adjusters concerned. Loss Assessors are employed by the policyholder, they are acting exclusively to protect the policyholders best interests.

                    Imperial Claims Consultants are a Financial Conduct Authority registered firm. We are authorised to assist clients with their insurance claims. We work for the policyholder only, never the insurer. Our service will not cost the insured anything provided they use our panel of contractors.

                    We help clients who have suffered from the insurance covered perils relating to building and/or contents such as:

 - Fire

 - Flood

 - Explosion

 - Storm

 - Impact Damage

 - Subsidence

 - Theft

 - Burglary

 - Contents

 - Business Loss

 - Liability Claims

 - Professional Indemnity

 - Loss Of Licence

                    Which insurance claims can Imperial Claims Consultants help me with?

                    We help clients who have suffered from the insurance covered perils relating to building and/or contents such as:

 - Fire

 - Flood

 - Explosion

 - Storm

 - Impact Damage

 - Subsidence

 - Theft

 - Burglary

 - Contents

 - Business Loss

 - Liability Claims

 - Professional Indemnity

 - Loss Of Licence

                    So, before you contact the insurers, contact Imperial Claims Consultants for a very personal and bespoke service.

                    Don't forget, If our sister company, Imperial Maintenance and/or its sub-contractors are used for managing the entire reinstatement works process, then you truly will not have a single penny to pay at all as our fee would be paid by our sister company.

This also includes my search bar.
However I need to display a card based on an on text search.
I tried the following however it didn't work even with a button:
 $("#searcher").on("keyup click input", function () {
    var val = $(this).val();
    if(val.length) {
        $(".accordion .card.m-b-0").hide().filter(function () {
            return $('input', this).val().toLowerCase().indexOf(val.toLowerCase()) !== -1;
        }).show();
    }
    else {
        $(".accordion .card.m-b-0").show();
    }
});

Can someone point me in the correct direction?

A:

$(document).ready(function(){
  $("#searcher").on("keypress click input", function () {
      var val = $(this).val();
      if(val.length) {
          $(".accordion .card.m-b-0").hide().filter(function () {
              return $('.card-title', this).text().toLowerCase().indexOf(val.toLowerCase()) > -1;
          }).show();
      }
      else {
          $(".accordion .card.m-b-0").show();
      }
  });

  //for test
  //$("#searcher").val('us').keyup();
});

            <input class="input-medium search-query" id="searcher" placeholder="Search">
            <button class="btn">Search</button>

                    Why should I use Imperial Claims Consultants?

                      We help them clients who have suffered from the insurance covered perils relating to building and/or

                    We help clients  who have suffered from the insurance covered perils relating to building and/or contents such as:

                    Which insurance claims can Imperial Claims Consultants help me with?

                    We help clients who have suffered from the insurance covered perils relating to building and/or contents such as:

                    So, before you contact the insurers, contact Imperial Claims Consultants for a very personal and bespoke service.

On Your Request I have updated The answer

$(document).ready(function(){
  $("#searcher").on("keypress click input", function () {
      var val = $(this).val();
      if(val.length) {
          $(".accordion .card.m-b-0 .collapsed").hide().filter(function () {
              return $('.card-block', this).text().toLowerCase().indexOf(val.toLowerCase()) > -1;
          }).show();
      }
      else {
          $(".accordion .card.m-b-0 .collapsed").show();
      }
  });

  //for test
  //$("#searcher").val('us').keyup();
});

            <input class="input-medium search-query" id="searcher" placeholder="Search">
            <button class="btn">Search</button>

                    Why should I use Imperial Claims Consultants?

                      We help them clients who have suffered from the insurance covered perils relating to building and/or

                    We help clients  who have suffered from the insurance covered perils relating to building and/or contents such as:

                    Which insurance claims can Imperial Claims Consultants help me with?

                    We help clients who have suffered from the insurance covered perils relating to building and/or contents such as:

                    So, before you contact the insurers, contact Imperial Claims Consultants for a very personal and bespoke service.


text:
Q: Proving that $MA + MB > CA + CB$ in the given figure On the extension of side $BC$ of the triangle $ABC$ consider the point D such that $C$ is between $B$ and $D$ and $AC = CD.$ Let M be an arbitrary point on the angle bisector of $\angle ACD$. Prove that $MA + MB > CA + CB.$
I am completely stuck on this question. I don't know how to approach it. Any help would be greatly appreciated.

A: Join $MD$. Here I have assumed that $\triangle MBD$ is not degenerate.
Here's a proof $$\triangle AMC \cong \triangle DMC$$
By $SAS$ congruence criterion.
So
$$AM=MD$$
Triangle inequality in $\triangle MBD$ gives
$$MB+MD>BC+CD$$
which gives using previous equality and the fact $AC=CD$
$$MB+MA>CA+CB$$
$QED$

A: Connect $M$ to $D$ to form the line $MD$.
In triangles $ACM$  and $CDM$,
1) $\angle ACM = \angle MCD$ (because $CM$ is the angle bisector of $\angle ACD$).
2) The side $CM$ is common.
3) $AC=CD$ (They were chosen that way)
Now, we have that the given triangles are congruent (I think it's called the $SAS$ criteria), so that $AM=MD$.
Now, simply note that $BM+MD > BD$ using triangle inequality, and $BD = BC+CD = BC + AC$, while $DM=AM$, so this gives $BM + AM > BC + AC$.


text:
Q: Why are ram timings in DDR4 ram so much slower than DDR3? I've been looking over RAM timings today, and one thing I noticed is that, even when considering very high-end DDR4 RAM, the timings are absolutely massive compared to DDR3 - I can buy very cheap DDR3 RAM with 9-9-9-24 timing, but DDR4 RAM (at nearly ten times the cost) might have a timing of 19-24-24-46. I have two questions about this:

*

*Why are the timings so much higher in DDR4?

*Does the speed of DDR4 ram overcome the massive timing increases?

A: 1600MHz  9-9-9-24       1.25e-9 seconds per clock tick
CL = (1.25e-9 * 9)   =  1.125e-8 seconds
RtC = (1.25e-9 * 9)  =  1.125e-8 seconds
RtP = (1.25e-9 * 9)  =  1.125e-8 seconds
tRAS =(1.25e-9 * 24) =  3.0e-8 seconds

4266MHz 19-24-24-46     4.688e-10 seconds per clock tick
CL =  (4.688e-10 * 19)  = 8.907e-9 seconds
RtC = (4.688e-10 * 24)  = 1.125e-8 seconds
RtP = (4.688e-10 * 24)  = 1.125e-8 seconds
tRAS = (4.688e-10 * 46) = 2.156e-8 seconds

So on timings, the DDR4 is the clear winner, being at worst equal to the DDR3 latencies, and at best is in an different order of magnitude.


text:
Q: My navbar brand is taking a whole lot of space I was writing an html page with bootstrap and then I come across some sort of kind of error the navbrand is too long. It takes up a whole lot of space in my navbar at the point when I view it on mobile It takes up a whole line and the hamburger icon goes to the bottom. This problem doesn't occur with text only with images.
{% load static %}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Urci</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

    <link rel='stylesheet' href="{% static 'home/css/custom.css' %}">

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Lato&family=Oswald:wght@300&family=Roboto+Condensed&display=swap" rel="stylesheet">

    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">

          </button>

                        Board of Directors
                        Events
                        {% if user.is_authenticated %}

                            Create Announcement
                            Create Events

                        {% endif %}

        {% block content %}

    {% endblock  %}

enter image description here

A: In your home/css/custom.css add the following...
.urci-brand{
   width: fit-content !important;
}

This would mean that the width of the anchor tag would be the width of the content within it.
And the !important is used to overwrite some bootstrap styling.


text:
Q: Reuse jQuery ready code by passing parameters I am using the following piece of jQuery code:
    $('div#addMenu1').click(function(){
    if (!menuSet1){
        menuSet1 = true;
                    $('div#sliderOne').slideDown('slow');
                    $('img', this).attr('src', 'Green_Up.png');
                    $('img', this).attr('title', 'Collapse');
                    $('div#sliderOne').css("background-color", "#cee8ff");
    }
    else {
        menuSet1 = false;
                    $('div#sliderOne').slideUp('slow');
                    $('img', this).attr('src', 'Green_Down.png');
                    $('img', this).attr('title', 'Create a top menu item');
    }
});

The thing is though, I would like to reuse the same bit of code but be able to also check for div#addMenu[1234] as well as set menuSet[1234] and change img title.
Any idea how I can reuse this code but based on the div section the user clicks on, pass the section number, say 3 and new title for img, to this code, so it would be using:
        $('div#addMenu3').click(function(){
    if (!menuSet1){
        menuSet3 = true;
                    $('div#sliderOne').slideDown('slow');
                    $('img', this).attr('src', 'Green_Up.png');
                    $('img', this).attr('title', 'Collapse');
                    $('div#sliderOne').css("background-color", "#cee8ff");
    }
    else {
        menuSet3 = false;
                    $('div#sliderOne').slideUp('slow');
                    $('img', this).attr('src', 'Green_Down.png');
                    $('img', this).attr('title', 'Create a Level 3 menu item');
    }
});

A: I'm not sure if this covers the scope of your question, but jQuery UI provides an accordion control which covers what you seem to want to do.

A: you can pass data to an event handler if you use the bind() flavor...  http://docs.jquery.com/Events/bind

A: You could whip up a little plugin.  There may be problems in this as it was "air coded".
$.fn.dropper = function(args) {
 // some default options - extended by args
 var opts = $.extend({
   sliderElem: null,
   sliderBg: '#cee8ff',
   imgOpen: 'Green_Up.png',
   imgClosed: 'Green_Down.png',
   titleOpen: 'Collapse',
   titleClosed: 'Open',
   openClass: 'open',
 }, args);

 this.click(function() {
   // using a "hasClass" instead of your boolean logic
   if ($(this).hasClass(opts.openClass)) {
     $(this).removeClass(opts.openClass);

     // the opts will be passed in when you call the plugin
     $(opts.sliderElem).slideUp('slow');
     $('img', this).attr('src', opts.imgClosed).attr('title', opts.titleClosed);
   } else {
     $(this).addClass(opts.openClass);

     $(opts.sliderElem).slideDown('slow').css('background-color', opts.sliderBg);
     $('img', this).attr('src', opts.imgOpen).attr('title', opts.titleOpen);
   }
 });
 return this;
}

$('div#addMenu1').dropper({sliderElem: 'div#sliderOne'});
$('div#addMenu3').dropper({sliderElem: 'div#sliderThree', titleClosed: 'Create a Level 3 menu Item'});


text:
Q: C++ Event template class I would like to write a C#-like C++ event class like this :
template< typename ListenerType >
class Event
{
private:

    std::vector< ListenerType * > m_aListeners;

public:

    void operator += ( ListenerType * pListener )
    {
        m_aListeners.push_back( pListener );
    }

    void operator -= ( ListenerType * pListener )
    {
        std::vector< ListenerType * >::reverse_iterator revIter = m_aListeners.rbegin();
        for( ; revIter != m_aListeners.rend(); ++revIter )
            if( revIter == pListener )
            {
                m_aListeners.remove( revIter );
                break;
            }
    }
};

class DataReceivedEvent : public Event< DataReceivedListener >
{
public:

    void Trigger( const byte_t * pData )
    {
        for( size_t nI = 0; nI < m_aListeners.size(); ++nI )
            m_aListeners[ nI ]->OnDataReceived( pData );
    }
}

The problem is that it forces me to write a Trigger method that always does the same thing (iterate and call handlers) for each event type since different events can have a different list of parameter, and for each event, the associated handler type has a mehod with a specific name.
I don't know much about C++11, but i have the feeling that it would be possible to avoid rewritting the Trigger method for each event type using templates.
But i can't use C++11, so i wonder if there is a way, using older C++ version, to do that, in a type safe way.
EDIT : I thought about creating a hierarchy of event data classes, i.e template< typename ListenerType >::Data and DataReceivedEvent::Data : public template< typename ListenerType >::Data so that i can have a Trigger method always taking a single argument, i.e virtual void Trigger( const Data * pData ). But I still have the problem that it needs to call a specific method in the event listener.

A: You can use templates and operator overloading for this as well. When you assume that the ListenerType implements the operator() you can implement it like this (the example also uses variadic templates. You can use arbitrary amount of arguments):
#include <vector>
#include <iostream>

template< typename ListenerType >
class Event
{
private:

    std::vector< ListenerType * > m_aListeners;

public:

    void operator += ( ListenerType * pListener )
    {
        m_aListeners.push_back( pListener );
    }

    void operator -= ( ListenerType * pListener )
    {
        auto revIter = m_aListeners.rbegin();
        for( ; revIter != m_aListeners.rend(); ++revIter )
            if( revIter == pListener )
            {
                m_aListeners.remove( revIter );
                break;
            }
    }

    template<typename... Params>
    void operator()(Params... data) {
        for (auto l : m_aListeners) {
            (*l)(data...);
        }
    }
};

class DataReceivedListener {
public:

    void operator()(const char* pData) {
        std::cout << pData << std::endl;
    }

};

class DataReceivedEvent : public Event< DataReceivedListener >
{
public:
};

int main() {

    DataReceivedEvent e;
    DataReceivedListener l1;
    DataReceivedListener l2;
    e += &l1;
    e += &l2;

    e("Hello");
}

Unfortunately, C++11 does not introduces Concepts. If you had this (constraints in C#) you would get some more help by the compiler.


text:
Q: passing placeholder value to dependency jar bean configuration Hi I am developing a spring boot application which has a dependency on another project say B. The dependency jar of B has config file for all the bean injections. Now when I am creating a bean of class in project B in my project the definitions of dependent beans has to be added to hence repeating the configuration in project B in my configuration file. To avoid that I just added the project B configuration file to my classpath.
Project B has a class say ClassEX which has contructor arguments as argA and argB. When i am trying to pass the value to these using my placeholder configuration it is failing to read it and throwing exception as .
Cannot cast null to int type

So basically the value is coming null.
I tried creating the bean of same class by putting it in in my project and it is working fine and reading the placeholder values.
For below example projectAbean is getting created but projectBbean is failing.
Can anyone tell what could be the reason.Below are my configurations:
    project A config.xml
<context:property-placeholder location="classpath:/ce.env.properties" />
<import resource="classpath:/projectB-config.xml" />
<bean id="projectAbean" class="com.ex.projecta.ClassEX">
<constructor-arg type="String" value="${argA}" />
<constructor-arg type="String" value="${argB}" />
</bean>
properties file:
argA=20
argB=10

projectB-config.xml
<bean id="projectBbean" class="com.ex.projectb.ClassEX">
<constructor-arg type="String" value="${argA}" />
<constructor-arg type="String" value="${argB}" />
</bean>
exception:
Unsatisfied dependency expressed through constructor parameter 0:
Could not convert argument value of type [null] to required type [int]:
Failed to convert value of type [null] to required type [int]; nested
exception is java.lang.IllegalArgumentException: Cannot convert value of
type [null] to required type [int]: PropertyEditor
[org.springframework.beans.propertyeditors.CustomNumberEditor] returned
inappropriate value of type [null] at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]


text:
Q: How can i get the length of this itertools.product() immediately, because len(list()) will take infinitely long to do this? from itertools import product

p = np.random.randint(1,2,2)
p = product(p, repeat=50)

I don't know how to get length of P immediately

A: This is simple combinatorics, not really programming. There are a**n ways to select any of a values n times (repetition is allowed). In your case, a is len(p) (the original p, the array), or 2 (since you've generated an array with two values), and n is 50, so will get 2**50 or 1125899906842624 results from your product if you have a whole lot of time to iterate over them all.
Now, if you're looking for how many distinct values you get, the answer is even easier (though subtly so). There's only one distinct value ever generated, a tuple with 50 ones. That's because you're taking products from an array that contains only the value 1, never anything else, since numpy.random.randint(1, 2) only ever gives you 1 (the upper bound is excluded).

A: The product iterator will have as many items as the lengths of all iterables you pass in multiplied with each other.
You're passing in one iterable but repeating it 50 times. Therefore you have to multiply the length of p 50 times with each other. That's basically   len(p)**50.