text:
Q: this program rotates a 2d array 90 degrees to the right - can i apply the values of the old array into a new array according to [col] and [row] index? I want to take the values in 2d array 'arr' and place them in a different order in 'arrRotated' using for loop differentiating column and row indexes each iteration.
I tried this:
for (int i = 6; i >= 0; i--)
{
    for (int count = 0; count <= 6; count++)
    {
        arrRotated[count][i] = arr[i][count];
    }

But I get an error:

expression must be a pointer to a complete object type

This is the whole code:
#include <stdio.h>

void DisplayArray2D(char arr[][7]);
void RotateArray2D(char arr[][], char arrRotated[][]);

int main()
{
    char arrRotated[7][7];
    char arr[7][7] =
{
{ '*',' ',' ',' ',' ',' ',' '},
{ '*','*',' ',' ',' ',' ',' '},
{ '*','*','*',' ',' ',' ',' '},
{ '*','*','*','*','*','*','*'},
{ '*','*','*',' ',' ',' ',' '},
{ '*','*',' ',' ',' ',' ',' '},
{ '*',' ',' ',' ',' ',' ',' '},
};

    RotateArray2D(arrRotated, arr);
    DisplayArray2D(arrRotated[7][7]);
}

void DisplayArray2D(char arr[][7])
{
    int i, count;
    for (i = 0; i < 7; i++)
    {
        for (count = 0; count < 7; count++)
            printf("%c", arr[i][count]);
        printf("\n");
    }
}

void RotateArray2D(char arr[][], char arrRotated[][])
{
    for (int i = 6; i >= 0; i--)
    {
        for (int count = 0; count <= 6; count++)
        {
            arrRotated[count][i] = arr[i][count];
        }
    }
}

A: When you declare void RotateArray2D(char arr[][], char arrRotated[][]), you must specify the size if the first dimension. You do it correctly for DisplayArray2D. Here's the corrected line:
void RotateArray2D(char arr[][7], char arrRotated[][7])

You are also calling RotateArray2D with the arguments swapped.
RotateArray2D(arrRotated, arr);

should be
RotateArray2D(arr, arrRotated);

Demo


text:
Q: ios - How to find people using my app within a wifi network Hi I  want to  find all people using my app within a same network, say if its a wifi network then i want to get all people using my app in that particular network.
their profile data existing in my database (mySQL) with their location. I can get the users As per location But my Question is to find them as per network. Any ideas how to start to do that?

A: Im not saying using Bonjour (Zeroconf) is the best way to achieve what you want - but you can certainly achieve your goal using it.
Bonjour is used in two ways:
- publishing a service
- detecting (browsing for) available services
For your task you'd have to do both.
One basic description can be found here: Bonjour Overview and its application in iOS
If you decide to use Bonjour then you'll find a lot of documentation on Bonjour for Developers
Basically, you need to publish a service: Bonjour Programming > Section 18.2. Publishing a Service
The publishing class (usually appDelegate) should be also a NSNetService delegate.
NSNetService *netService; //an ivar or a property

//creating and publishing a service
netService = [[NSNetService alloc] initWithDomain:@""
                                             type:@"_yourservicename._tcp."
                                             name:@""
                                             port:9876];
//if your app actually acts as a server port: should be it's port,
//otherwise it could be any free port

netService.delegate = self;
[netService publish];

You should also handle delegate methods (and some appDelegate methods):
-(void)netService:(NSNetService *)aNetService
    didNotPublish:(NSDictionary *)dict
{
    NSLog(@"Service did not publish: %@", dict);
}

- (void)applicationWillTerminate:(UIApplication *)application {
    //---stop the service when the application is terminated---
    [netService stop];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    //---stop the service when the application is paused---
    [netService stop];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [netService publish];
}

And browse for existing services: Bonjour! (cocoanetics)
(you'll only need the bottom part of the page)
serviceBrowser = [[NSNetServiceBrowser alloc] init];
serviceBrowser.delegate = self;
[serviceBrowser searchForServicesOfType:@"_yourservicename._tcp." inDomain:@""];

- (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser
    didFindService:(NSNetService *)aNetService moreComing:(BOOL)moreComing
{
    [self willChangeValueForKey:@"foundServices"];
    [_foundServices addObject:aNetService];
    [self didChangeValueForKey:@"foundServices"];

    NSLog(@"found: %@", aNetService);
}

- (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser
    didRemoveService:(NSNetService *)aNetService moreComing:(BOOL)moreComing
{
    [self willChangeValueForKey:@"foundServices"];
    [_foundServices removeObject:aNetService];
    [self didChangeValueForKey:@"foundServices"];

    NSLog(@"removed: %@", aNetService);
}

PS: Bonjour might be tricky to start with but it is certainly a useful knowledge.
Depends on what user experience exactly you want. A good alternative to Bonjour would most certainly
be GameKit (GKPeerPickerController) where user can actually
select to which devices (peers he wants to connect to).
This should work in Wi-Fi or via BlueTooth.

A: One way of doing service discovery is to have your program listen on a port and then doing a broadcast on that port when you want to be discovered or poll for other entities.
Something along these lines.
 socket = listen_and_stuff()
 others = do_broadcast()
 while(run)
     if time to update
         others = do_broadcast
     if received request
         reply with info about self

But, broadcast depends a bit on router settings, subnetworks and so on so it might not work in all cases.

redpajama_set_name: RedPajamaStackExchange


text:
Q: matching certain keywords in a string that are not delimited by certain characters In a Java program, I want to find out all the occurrences in a given String of these substrings: $$, or $\d (the symbol '$' followed by an integer).
My problem started when I added an additional constraint stating that a match occurs only if the matched string is not part of a substring limited by certain sequence of characters.
For example, I want to ignore the matches if they are part of a substring surrounded by "/{" and "/}".
The following example brings all the occurrences of $$, or $\d, but does not considere the additional constraint of ignoring the match if it is inside "/{" and "/}".
public static final String PARAMETERS_PREFIX = "$";
public static final String ALL_PARAMS_SUFFIX = "$";
public static final String BEGIN_JAVA_EXPRESSION = "/{";
public static final String END_JAVA_EXPRESSION = "/}";
...
String test = "$1 xxx $$ " //$1 and $$ are matches
  + BEGIN_JAVA_EXPRESSION + "xxx $2 xxx" + END_JAVA_EXPRESSION; //$2 SHOULD NOT be a match
Set<String> symbolsSet = new LinkedHashSet<String>();
Pattern pattern = Pattern.compile(Pattern.quote(PARAMETERS_PREFIX)+"(\\d+|"+Pattern.quote(ALL_PARAMS_SUFFIX)+")");
Matcher findingMatcher = pattern.matcher(test);
while(findingMatcher.find()) {
  String match = findingMatcher.group();
  symbolsSet.add(match);
}
return new ArrayList<String>(symbolsSet);

In addition to find the keywords that are not part of certain substring, I want to be able to replace afterwards only those keywords by certain values.
Then, the option of just removing everything between the delimited characters before doing the match probably will not help, since afterwards I need to be able to get the original string with the matched tokens replaced by certain values, and the tokens inside the delimited region should be left without modifications.
This should be easy if I found the right regex.
Does someone could give me a hint about how to write the right regex for this problem ?.

A: Is it permissible to use more than 1 regex? It might be less sexy, but you could do this with 3 regex's pretty easily.
(these are not the actual regex's)
1. For getting the string you are looking for ($$ | ${num})
2. For '/{'
3. For '/}'
It should be fairly easy to match up the invalid areas in 2 and 3. You can then use those spans to eliminate results in 1

A: I recommend using multiple regular expressions for this. Trying to do it all at once – though enticing – seems to be pretty messy.

*

*Remove your "Java Expressions" from the String: /{.*?/}

*Run your matcher on the resulting String: \$(?:\d+)?
Note: I was lazy on the first expression, so it assumes that any occurrence of /{ will be followed eventually by /} and without nesting.

A: The first part that you need can be achieved using this regex:
(?<!/{)\($[$|\d])(?!}/)

So, after running this you'll get all your matches in groups - from now on you can get Java to do the hard work by evaluating the match in the group and finding an appropriate replacement.
You should be able to use backreference somehow to do the replacement bit but I guess you can figure it out.
UPDATE:
(?<!/{) - it's a negative lookbehind - it says: from the current position assert that the previous characters are not /{. If this evaluates to true the match for /{ is discarded and the real matching begins. Lookahead/lookbehind are zero-width assertions which don't participate in the match.
(?!}/) - similarly but in the other direction - from the current position assert that the following characters are not }/. These also don't participate in the match. So effectively if these conditions are met, your match will still be just the text within the assertions, i.e. $$ or $\d.
Btw: it's possible that you'd need to escape some characters - the ones I remember are { and $ outside character class
(?<!/\{)\(\$[$|\d])(?!}/)

see also:
How to escape text for regular expression in Java

A: I'm not sure you can do that with one regex. If no one can provide this ultimate regex I made a little workaround :
public static final String PARAMETERS_PREFIX = "$";
public static final String ALL_PARAMS_SUFFIX = "$";
public static final String BEGIN_JAVA_EXPRESSION = "/{";
public static final String END_JAVA_EXPRESSION = "/}";

    String test = "$1 xxx $$ " //$1 and $$ are matches
    + BEGIN_JAVA_EXPRESSION + "xxx $2 xxx" + END_JAVA_EXPRESSION; //$2 SHOULD NOT be a match
    Set<String> symbolsSet = new LinkedHashSet<String>();
    Pattern pattern = Pattern.compile(Pattern.quote(PARAMETERS_PREFIX)+"(\\d+|"+Pattern.quote(ALL_PARAMS_SUFFIX)+")");
    Matcher findingMatcher = pattern.matcher(test);
    while(findingMatcher.find()) {
        String match = findingMatcher.group(0);
        int idx= findingMatcher.start();
        int bexIdx = test.lastIndexOf(BEGIN_JAVA_EXPRESSION,idx);
        if(bexIdx!=-1){
            int endIdx = test.indexOf(END_JAVA_EXPRESSION,bexIdx);
            if(endIdx<idx){
                symbolsSet.add(match);
            }
        }
        else{
            symbolsSet.add(match);
        }
    }

A: You can use a Pattern with Lookaround:
(?<!\\{[^\\}]{0,100})\\$(\\d|\\$)(?![^\\{]*\\})

*

*(?<!\\{[^\\}]{0,100}): group used to restrict a predecessor value.
This use negative lookbehind: {?<!X}, where X is a regex expression that can't precede the main expression. In Java, you can't use negative lokbehind without a obvious maximum length, then you can't use \\{.*. You could use Integer.MAX_VALUE, ou testString.length(). Another thing: you must check if you found a end symbol before start symbol. Therefore the expression is [^\\}] instead of ..

*\\$(\\d|\\$): The main group sought.
The usually here.

*(?![^\\{]*\\}): group used to restrict a posterior value
This use negative lookahead: {?!X}, where X is a regex expression that can't succeed the main expression. Here, you can use no-fix length. Again, you must check if you found a start symbol of substring. Then, you use [^\\{]* instead of .*.
However, add more constraints will add more complexity in your regex.

String to test the pattern: "$1 xx3x $$ /{xxx $2 xxx/} $4"


text:
Q: Why does setting kinetic energy equal not work in inelastic collision? From my understanding, in an inelastic collision there is no loss of kinetic energy. So if we take the following problem:
A 7700kg car is traveling 18 m/s and strikes a second car. The two stick together and move off with a speed of 5.0 m/s. What is the mass of the second car?
And if we know that KE = 1/2mv^2 , why can we not just say:
1/2 ( 7700)(18^2) = 1/2(7700+x)(5)^2
If x is solved for, we get 92092 kg as the mass of the second car, but this answer is not correct. If there is no loss in kinetic energy, why does setting the previous kinetic energy to the combined kinetic energy not work out?
Thank you and I appreciate all help.

A: Momentum is conserved in all collisions, but kinetic energy of the bodies, considered as point masses, is only conserved in elastic ones. In an inelastic collision, some of the kinetic energy of motion is transformed into heat. Try again using momentum conservation
$$m_1v_1 = (m_1+m_2)v_2$$.


text:
Q: Can't seem to cast from NSString* to CFString* using ARC I am using the following code to obtain a file's file type in Objective-C (Mac OS X Cocoa Application):
NSString *kind = nil;
NSURL *url = [NSURL fileURLWithPath:[path stringByExpandingTildeInPath]];
LSCopyKindStringForURL((CFURLRef)url, (CFStringRef*)&kind);
return kind ? kind : @"";

However, the only error being produced is on the following line:
LSCopyKindStringForURL((CFURLRef)url, (CFStringRef*)&kind);

Saying:

C-style cast from 'NSString *__strong *' to 'CFStringRef *' (aka
  'const __CFString **') casts away qualifiers

After doing some research, I saw that the __bridge keyword is required to make the cast from NSString* to CFStringRef* valid in ARC. So I stuck in the keyword, producing:
LSCopyKindStringForURL((CFURLRef)url, (__bridge CFStringRef*)&kind);

Now, I am receiving the following error:

Incompatible types casting 'NSString *__strong *' to 'CFStringRef *'
  (aka 'const __CFString **') with a __bridge cast

It's starting to drive me crazy... no matter what I seem to try, I just can't make the error go away. Any ideas?

A: There's a simple workaround. Use an actual CFStringRef variable and cast it when it comes time to return it as an NSString:
NSURL *url = [NSURL fileURLWithPath:[path stringByExpandingTildeInPath]];
CFStringRef kind;
LSCopyKindStringForURL((CFURLRef)url, &kind);
return kind ? CFBridgingRelease(kind) : @"";

A: I use the following to get kind
    (NSURL *)path
    NSString *tempKind;
    [path getResourceValue:&tempKind forKey:NSURLLocalizedTypeDescriptionKey error:nil];


text:
Q: Android: Load/replace image from a thread I have an activity that needs to parse an XML from web, then read in images according to the XML info. To speed things along, I created AsyncTask to do the parsing and image fetching. However, I cannot put the images into the activity from within the thread due to "cannot update view objects from outside the view-creating thread..."
So I moved everything back to the main onCreate routine and it slows things down so much that it's not usable (UI not showing until everything is done (I guess when onCreate returns)) .
Any idea on how to tackle this problem (i.e. parsing/fetching using AsyncTask, then placing/updating images dynamically when each becomes available)? or where in the life-cycle should/can I update the UI?
Thanks in advance for all your help.

A: How are you using the AsyncTask? It's exactly for the purpose you mentioned: AsyncTask.doInBackground() is running in a separate thread and can be used to do the time-consuming task (loading the bitmap), and AsyncTask.onPostExecute() runs on the UI thread and can be used to perform quick operations that have to happen in the UI thread (i.e. replacing the bitmap in your View).

A: Try this:
runOnUiThread(Runnable action)
    //Runs the specified action on the UI thread.

I implemented this to update a ListView after getting data from the web and it works like a charm. If you download the source from this tutorial ( to the bottom ), you can see an implementation of how this works. :-)
Edit: see this rar file: ( Eclipse source code of an upcoming tutorial :-) )

A: The async task was the right route. Use the async task to do the work in the background then use onpostexecute.
private class DownloadFilesTask extends AsyncTask<URL, Integer, imageview> {
 protected imageView doInBackground(URL... urls) {
    //parse and load
 }

 protected void onProgressUpdate(Integer... progress) {
     //update progress if you have progress dialog
 }

 protected void onPostExecute(imageView result) {
    //load image into view.
 }

}
See Async task


text:
Q: SQL(ite) Remove (and keep some) duplicates in table Say I have a table, called tablex, as follows:
name|year
---------
Bob | 2010
Mary| 2011
Sam | 2012
Mary| 2012
Bob | 2013

Names appear at most twice. I want to remove from the table only those names that are repeated and have a difference of one year (in which case I want to keep the newer year).
name|year
---------
Bob | 2010
Sam | 2012
Mary| 2012
Bob | 2013

I have tried:
SELECT a.Name, a.Year, b.Year
FROM tablex AS a
LEFT JOIN tablex AS b
ON a.Name=b.Name AND (a.Year=b.Year OR b.Year-a.Year=1)
ORDER BY a.Name, a.Year

results in:
  Name YearA YearB
1  Bob  2010  2010
2  Bob  2013  2013
3 Mary  2011  2011
4 Mary  2011  2012
5 Mary  2012  2012
6  Sam  2012  2012

Bob's and Sam's entries are correct, how can I restrict it further to only include Mary 2012 2012?

A: This operation deletes rows from the table where the same name with a newer year also exist:
delete from tablex t1 where year < (select max(year) from tablex where name = t1.name)

A: DELETE FROM tablex t
WHERE year + 1 =
  (SELECT MAX(year)
   FROM tablex
   WHERE name = t.name)

Or, if you don't want to delete anything, but want a query to only give the desired results:
SELECT *
FROM tablex t
WHERE year + 1 !=
  (SELECT MAX(year)
   FROM tablex
   WHERE name = t.name)

A: From the question is not clear if you want to SELECT (suppressing the duplicates) or actually DELETE the "duplicates". The select case:
SELECT a.Name, a.Year
FROM tablex AS a
WHERE NOT EXISTS (
    SELECT * FROM tablex AS b
    WHERE b.Name = a.Name
    AND b.Year = a.Year +1
   );

And the delete case:
DELETE
FROM tablex AS a
WHERE EXISTS (
    SELECT * FROM tablex AS b
    WHERE b.Name = a.Name
    AND b.Year = a.Year +1
   );

A: you can use :
SELECT a.Name, a.Year, b.Year
FROM tablex AS a
LEFT JOIN tablex AS b
ON a.Name=b.Name AND (a.Year=b.Year )
ORDER BY a.Name, a.Year


text:
Q: Replacing regexp patterns with different values I have string like this:
text = "bla bla bla\n {panel:title=Realisation|borderStyle=dashed|borderColor=#cccccc|titleBGColor=#a39d9d}\n bla bla bla\n {panel:title=Definition of Done|borderStyle=dashed|borderColor=#cccccc|titleBGColor=#a39d9d} bla bla

and i need replace {panel:title=Realisation|borderStyle=dashed|borderColor=#cccccc|titleBGColor=#a39d9d} to Realisation and {panel:title=Definition of Done|borderStyle=dashed|borderColor=#cccccc|titleBGColor=#a39d9d} to Definition of Done
I tried to do it like this
def del_tags(text):
    if text:
        CLEANR = re.compile('{panel.*?}')
        try:
            TITLES = re.search('title\=(.+?)\|', text).group(1)
        except AttributeError:
            TITLES = ""
        cleantext = re.sub(CLEANR, TITLES, text)
        return cleantext
    else:
        return text

But they replace everything with Realisation.
How can I solve my problem?

A: Try:
import re

text = "bla bla bla\n{panel:title=Realisation|borderStyle=dashed|borderColor=#cccccc|titleBGColor=#a39d9d}\nbla bla bla\n{panel:title=Definition of Done|borderStyle=dashed|borderColor=#cccccc|titleBGColor=#a39d9d} bla bla"

text = re.sub(r"{panel:title=([^|}]+).*?}", r"\1", text)
print(text)

Prints:
bla bla bla
Realisation
bla bla bla
Definition of Done bla bla

{panel:title=([^|}]+).*?} will match title after the panel:title= and substitute the whole {...} - regex101


text:
Q: Basically, how would a person who knows nothing about coding copy the code of an entire website on a basic, school-provided Chromebook? I really need help finding out how to add the code for a Site to Google Sites.
I Google searched it and found something on this site, but it was too complicated. I need step-by-step instructions,not one whole lumpsome.


text:
Q: sqlalchemt---SAWarning: fully NULL primary key identity cannot load any object model:
'''任务工单'''
    __tablename__ = 'task'
    id = db.Column(db.Integer, primary_key=True, nullable=False, autoincrement=True)
    user_id = db.Column(db.Integer, index=True, nullable=False)
    dep_id = db.Column(db.Integer, index=True, nullable=False)
    title = db.Column(db.String(200), nullable=False, index=True)
    content = db.Column(db.Text, nullable=False)
    cate = db.Column(db.SmallInteger, default=1,`enter code here`)
    add_time = db.Column(db.Integer, default=int(time.time()), comment="添加时间")
    is_top = db.Column(db.SmallInteger, default=0, comment="是否加急 1--加急 0--不加急")
    desgin_id = db.Column(db.Integer,comment="设计人员的id")
    update_time = db.Column(db.Integer, comment="修改时间")
    review_time = db.Column(db.Integer, comment="审核时间")
    assignment_time = db.Column(db.Integer, comment='分配时间')
    fiannce_time = db.Column(db.Integer, comment='完成时间')
    invalid_time = db.Column(db.Integer, comment='无效时间')
    desgin_time = db.Column(db.Integer, comment="开始设计时间")
    state = db.Column(db.SmallInteger, default=1, comment="状态:1--初始化待分配 2--带设计 3--设计中 4--提交待审核(审核中) 5--驳回  7--完成 0--无效")

use:
 taskDicts = Task.query.filter_by(state=state).order_by(desc(Task.is_top),asc(Task.add_time)).offset(offset).limit(10).all()

venv/lib/python3.7/site-packages/sqlalchemy/orm/loading.py:246:
  SAWarning: fully NULL primary key identity cannot load any object.

This condition may raise an error in a future release.


text:
Q: Do away with default output directory completely - MapReduce I have a code for writing multiple outputs using org.apache.hadoop.mapreduce.lib.output.MultipleOutputs.
The Reducer writes the results to a pre-created location so I don't require the default o/p directory (which contains the _history and _SUCCESS  directories).
I have to delete them everytime before running my job again.
So I removed the TextOutputFormat.setOutputPath(job1,new Path(outputPath)); line. But, this gives me the
(expected) error org.apache.hadoop.mapred.InvalidJobConfException: Output directory not set
Driver Class:
MultipleOutputs.addNamedOutput(job1, "path1", TextOutputFormat.class, Text.class,LongWritable.class);
MultipleOutputs.addNamedOutput(job1, "path2", TextOutputFormat.class, Text.class,LongWritable.class);
LazyOutputFormat.setOutputFormatClass(job1,TextOutputFormat.class);

Reducer Class:
if(condition1)
    mos.write("path1", key, new LongWritable(value), path_list[0]);
else
    mos.write("path2", key, new LongWritable(value), path_list[1]);

Is, there a workaround to avoid specifying a default output directory?

A: I don't think _SUCCESS is a directory and the other history directory resides inside _logs directory.
First of all TextOutputFormat.setOutputPath(job1,new Path(outputPath)); is important because when the job is run this path is taken as a work directory by Hadoop to create temporary files and such for different tasks (_temporary dir). This _temporary directory and files eventually gets deleted at the end of the job. The file _SUCCESS and history directory is actually what remains under work directory and kept after the job has finished successfully. _SUCCESS file is kind of a flag saying the job actually ran successfully. Please look at this link.
The creation of your file _SUCCESS is done by  TextOutputFormat class, you are actually using, which in turn uses FileOutputComitter class. That FileOutputCommiter class defines a function such as this --
 public static final String SUCCEEDED_FILE_NAME = "_SUCCESS";
/**
   * Delete the temporary directory, including all of the work directories.
   * This is called for all jobs whose final run state is SUCCEEDED
   * @param context the job's context.
   */
  public void commitJob(JobContext context) throws IOException {
    // delete the _temporary folder
    cleanupJob(context);
    // check if the o/p dir should be marked
    if (shouldMarkOutputDir(context.getConfiguration())) {
      // create a _success file in the o/p folder
      markOutputDirSuccessful(context);
    }
  }

// Mark the output dir of the job for which the context is passed.
  private void markOutputDirSuccessful(JobContext context)
  throws IOException {
    if (outputPath != null) {
      FileSystem fileSys = outputPath.getFileSystem(context.getConfiguration());
      if (fileSys.exists(outputPath)) {
        // create a file in the folder to mark it
        Path filePath = new Path(outputPath, SUCCEEDED_FILE_NAME);
        fileSys.create(filePath).close();
      }
    }
  }

Since, markOutputDirSuccessful() is private, you have to instead override commitJob() to bypass the SUCCEEDED_FILE_NAME creation process and achieve what you want.
The next directory _logs is very important if you want to later use hadoop HistoryViewer to actually get a report of how the Job ran.
I think, when you use the same output directory as an input to another Job, the file *_SUCCESS* and directory *_logs* will get ignored due to Filter set in Hadoop.
Moreover, when you define a namedoutput for MultipleOutputs, you can instead write to a subdirectory inside the outpath you mentioned in the TextOutputFormat.setOutputPath() function and then use that path as input to the next job you'll be running.
I don't actually see how _SUCCESS and _logs will every bother you?
Thanks

A: Question is pretty old, still sharing an answer,
This answer suits good for the scenario in the question.
Define your OutputFormat to say you are not expecting any output. You can do it this way:
job.setOutputFormat(NullOutputFormat.class);

or
you could also probably use LazyOutputFormat
import org.apache.hadoop.mapreduce.lib.output.LazyOutputFormat;
LazyOutputFormat.setOutputFormatClass(job, TextOutputFormat.class);

Credits @charlesmenguy

A: What version of Hadoop are you running?
For a quick workaround you could set an output location programmatically and call FileSystem.delete to remove it on job completion.


text:
Q: Form validation with variable input list in Angular? Alright, so here's the problem. I have a list of questions that are either inputs, or mat selection lists. This is a child component to a parent that can spawn up multiple versions of this form with differing questions.
What I need to figure out is how to be able to validate every input or selection list is answered in some way before setting some variable to the parent that the form is complete.
<mat-horizontal-stepper>
  <mat-step *ngFor="let question of formQuestionsFormatted">
    <ng-template matStepLabel>{{ question.questionText}}</ng-template>
      <mat-label>{{ question.questionText }}</mat-label>

      <mat-form-field class="inputForm" *ngIf="!question.isSurveyOptionList">
        <input matInput placeholder="Answer" [(ngModel)]="question.responseInputText">
      </mat-form-field>

      <mat-radio-group *ngIf="question.isSurveyOptionList" [(ngModel)]="question.responseOptionSelected">
        <mat-radio-button class="example-radio-button" *ngFor="let option of question.surveyOptionList" [value]="option">
          {{option.optionText}}
        </mat-radio-button>
      </mat-radio-group>
  </mat-step>
</mat-horizontal-stepper>

A: I think there are several solutions to your question, but one way of achieving this would be by using Reactive Forms.
You would loop through your "formQuestionsFormatted" in the ngOnInit of your component and create what is called a "FormArray" in Reactive Forms. In your FormArray you would have one FormControl for each question, and you would set 'Validators.required' on all of them.
Then when you want to check if it is valid you can call 'myFormArray.valid', and it will be true only if all your questions have been answered.
(You would need to read up on Reactive Forms if you have not used them before. They are very powerful when you want to do complex forms, but it can take some time to learn how to use them.)


text:
Q: How do I remove the p tag and its content using p php? I'm using simple_html_dom to scrap a website and it has a section like this
$content =

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio, voluptas, sint, accusantium,

    Wikipedia (Listeni/ˌwɪkɨˈpiːdiə/ or Listeni/ˌwɪkiˈpiːdiə/ wik-i-pee-dee-ə) is a collaboratively edited, multilingual, free Internet encyclopedia that is supported by

    the non-profit Wikimedia Foundation. Volunteers worldwide collaboratively write Wikipedia's 30 million articles in 287 languages, including over 4.4

    million in the English Wikipedia. Anyone who can access the site can edit almost any of its articles, which on the Internet

    quidem repellendus nulla incidunt ullam?

But I only want the result to be like this.
Wikipedia (Listeni/ˌwɪkɨˈpiːdiə/ or Listeni/ˌwɪkiˈpiːdiə/ wik-i-pee-dee-ə) is a collaboratively edited, multilingual, free Internet encyclopedia that is supported by

the non-profit Wikimedia Foundation. Volunteers worldwide collaboratively write Wikipedia's 30 million articles in 287 languages, including over 4.4

million in the English Wikipedia. Anyone who can access the site can edit almost any of its articles, which on the Internet

I know the finding and fetching the content inside the #content part.I only want to know how to remove the p tag and content inside it.
Thank you.

A: $content = 'hi
 this is a test
 hello
 the other test
';

echo removeP($content);

function removeP($content){

    while(strpos($content, '
') != ''){

        $start = strpos($content, '
');
        $end = strpos($content, '
')+4;

        $string_being = substr($content, 0, $start);
        $string_end = substr($content, $end, strlen($content));

        $content = $string_being.$string_end;

    }

    return $content;
}

A: To remove the p tags with simple you would do:
foreach($doc->find('p') as $p) $p->outertext = '';


text:
Q: ArcGIS not finding newly installed toolbar (.dll, .tlb files?) I'm trying to use a toolbar that was developed by the EPA for BMP siting (see below link). The download seems like it should be fairly straightforward, an executable (BMPSitingTool_Setup.msi) is run and the toolbar is downloaded to the Program Files x86 folder within my C-drive. The BMP siting tool comes with a host of .dll, .tlb, .olb, etc files. According to the installation instructions, once I open a new ArcGIS map, it should find this new toolbar automatically and it should show up under Customize > Customize Mode. It doesn't. I've tried doing "add from file" and manually selecting the .tlb file but I get a message of "can't load type library from specified file" followed by "no new objects added". Any idea what's causing this? I'm on ArcGIS 10.3 and the tool was developed within ArcGIS 10.1, but I didn't think there were any compatibility issues with later versions of ArcGIS.
Edit: I've verified that I have administrator privileges on my computer.
https://www.epa.gov/water-research/best-management-practices-bmps-siting-tool

A: Try manually registering the dll. The double quotes are needed because of spaces in the paths. The following is a single command.
"C:\Program Files (x86)\Common Files\ArcGIS\bin\ESRIRegAsm.exe" /P:desktop "C:\Program Files (x86)\BMP Siting Tool\ESRI.ArcGIS.DataSourcesGDB.dll"

A: The way I was able to add the BMP Siting Toolbar was by clicking the "Add From File" button under ArcMap's Customize box and then opening the .dll diles from the C:\SUSTAIN\ETC folder.


text:
Q: How do you define Domain Objects and Repositories, when dealing with multiple database tables? Imagine an application that allows you to add line items to a quote.  The end result is like a sales person giving you a printed sheet with information such as name of the business, name of the sales person, and various service line items printed on the quote along with pricing, description, and quantity.
To implement this on the database level I have tables Item (holds 0-to-many items per Quote) and QuoteMeta (holds quote meta-information like who created the quote, quote number, revision, status, etc).

Then I have a domain object called Quote, which is not aware of the database layer directly, but receives data from both Item and QuoteMeta.  The Quote is the "quote sheet" described previously.
My question is how to handle this domain object when I have more than one table representing it internally.  For example, with my Quote domain object I can do something like ...
Single Repository, Single Domain object
//Repository populates $quote from both database tables
$quote = (new QuoteRepository())->getQuoteById($id);

$quote->getQuoteNumber(); //gets data from quote metadata table
$quote->getItemByLineNumber(5); //gets an item from items table

The above "marries" the tables into the one domain Quote object.  QuoteRepository handles queries directed to and from both database tables.  My question is .. can I do this?
For example, will it be better to keep concepts separate, maybe like so?
Multiple Repositories, Multiple domain objects
//repository strictly deals with quote meta data
$quoteMeta = (new QuoteMetaRepository())->getQuoteMetaById($id);
$quote->getQuoteNumber();

//repository strictly deals with item handling
$items = (new ItemRepository())->getItemsByQuoteId($id);
$items->getItemByLineNumber(5);

Here the concerns are more separated, but I have complexity of dealing with multiple objects, when physical Quote representation is typically understood to be the items + quote metadata merged together.  You don't have just items without metadata, and there is little point in having metadata without service items.
That said, is preferred to keep repositories separate, or together?  And if separate, how do I handle things like table JOINs that operate on both tables?  Which repository do they go to?
Dealing with multiple tables
To shift gears a bit, I have some code purpose of which is to delete an Item.  An item record is deleted from the table.  Then references to other data that are tied to the Item are deleted from 5 other tables (things like graphs, design, etc, and other data that belongs to the item).  Should this "Item Deletion" be a single handler method that deletes data from multiple tables directly in the place of one method, or should each table have their own respective Repository handler class and method, and I can call each handler to delete their portion of the item?
Also, in the example where I delete the item, I am not really touching much of QuoteMeta table or entity.  Thus I may only use the ItemRepository handler by itself, which makes me lean towards separate repositories in this case.
Notes on ORM
In my codebase I am using an ORM, where I have entities, such as Item Entity corresponds to item table, and QuotaMeta corresponds to quote_meta.  The focus of my question though is not on an ORM.  ORM provides a convenient way to populate my entities from tables, but without ORM I'd either be populating Entities anyway (i.e. via mysqli_fetch_object), or I'd be using arrays.  The question still stands -- how do I model my domain objects and corresponding repositories?  Do I ... have one per table, or do I go to a higher level of abstraction, to where I operate on multiple tables per single domain/repository?
Final Thoughts..
To be super-specific, do I have a Quote domain object that operates on both tables, or do I have separate ItemGroup and QuoteMeta objects, where one manages items that belong to the Quote but doesn't care about the metadata, and one manages Quote metadata, without the dealing with items that belong to it?

A: Your first approach is basically creating an ORM. If ORM is what you are after then go with it, but remember that objects from the ORM do not and should not represent your domain - ie. the layer enforcing your business rules presented by the stakeholders. They are objects which understand persistence and as such they should not contain business rules, because that would be breaking of the Single Responsibility Principle, which is not a rule to blindly follow but which greatly increases code readability.
With that in mind, your domain layer not working with ORM objects, you would need to transform the ORM objects to your domain objects anyway, which seems kind of pointless.
I greatly favor the direct repository approach, as it very clearly states what each object does:

*

*a domain object represents a domain entity,

*a repository is used to provide an abstraction to CRUD operations on a domain object.

You have a domain object and want more data related to it, then use a service which knows how to communicate with outer world, in this case the persistence layer.

Also, completely avoiding ORM when querying the database lifts the constraint that you need to use the ORM objects, which you don't. Many times you need different representations of the same entity, for different purposes, and for that you can sometimes use even very simple DTOs. This makes it easier to construct such objects, leaves less memory footprint and generally makes the applications faster, because you can specifically craft queries to reduce the number of times you need to go from the application server to the database server and back.


text:
Q: How to remove elements of a list containing specific patten with python? Given a list of strings
listA=['a', 'b', 'a@b=c', 'a @ b = c', 'a@ =b', 'a@=b' 'a=b@c', 'a@b' ]
                   ^         ^

we want elements marked in "^" removed, and get
ListB=['a', 'b', 'a@ =b', 'a@=b' 'a=b@c', 'a@b']

Here we removed all elements containing '@', followed by some character, then followed by '=', but ignored "@=" or '@ ='
How to do such regex matching for a python list?
EDIT:
I know if we know specific index of a elements to delete, we can use numpy.delete(list, index) to delete it. But it is not true in this case.

A: Using the expression @\s*\S\s*= and re.search() we can filter this list down:
import re
listB = [str for str in listA if re.search(r'@\s*\S\s*=', str) is None]

print listB
# ['a', 'b', 'a@ =b', 'a@=ba=b@c', 'a@b']

A: Regex searches in python can be done with the re module; specifically, re.search('@\w=', my_string) will not be None if my_string contains an @ and a = separated by a member of \w, i.e. a word character (alphanumerics and _).
I've expanded this to include cases where there's whitespace too, using \s.
import re

listA = ['a', 'b', 'a@b=c', 'a @ b = c', 'a@ =b', 'a@=b' 'a=b@c', 'a@b' ]
listB = [a for a in listA if not re.search('@\s*\w+\s*=', a)]

Update: solution above now using \w+to match multiple word characters instead of just one.

A: import re
listA = ['a', 'b', 'a@b=c', 'a @ b = c', 'a@ =b', 'a@=b' 'a=b@c', 'a@b' ]
print [x for x in listA if not re.search(r'@\s*[a-zA-Z]\s*=', x)]


text:
Q: How to implement snowflake connector with structured streaming in python? Currently I have code that takes the input and creates a data stream. My goal is to have the data uploading to snowflake. Currently I am trying this, is there an easier way to go about this. Or is it possible to have this write to a pandas df and then upload the pandas df to snowflake? It has previously worked just with structured streaming and no connection to snowflake.
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import *

sfconn = {
    "sfURL": f"{os.getenv('SNOWFLAKE_ACCOUNT')}.snowflakecomputing.com",
    "sfUser": os.getenv('SNOWFLAKE_USER'),
    "sfPassword": os.getenv('SNOWFLAKE_PASSWORD'),
    "sfDatabase": "x",
    "sfSchema": "x",
    "sfWarehouse": "x"
}

spark = SparkSession.builder\
    .appName("snowflake-connector")\
    .getOrCreate()

df = spark \
              .readStream\
              .format('json') \
              .schema(spark_schemas['x']) \
              .load(f"s3a://{x_path}")

out = df \
    .writeStream\
    .outputMode("append")\
    .option("dbtable", "scratch_table")\
    .options(sfconn)\
    .trigger(processingTime='1 minutes')\
    .format("snowflake")\
    .start()

Right now it's showing
options() takes 1 positional argument but 2 were given

and
 : java.lang.ClassNotFoundException: Failed to find data source: snowflake.

A: First error is following - options take the variable number of pairs that specify options.  If you have option as map, you need to "unpack" it using the **map syntax, like here:
opts = {'inferSchema': "true", "header": "false"}
df = spark.read.options(**opts)
   .format("csv")
   .schema("ticker String,date Date, price Float")
   .load(".../datasets/dow-quotes.csv")

For 2nd error - you just need to specify correct name of the connector - net.snowflake.spark.snowflake instead of snowflake, and make sure that Snowflake Spark connector is specified when you submitting the job. See Snowflake documentation for more details.


text: Q: How to load generated .bin from processor(AM5728 i'm using) to internal flash of STM32 Board I am using an stm32h series controller and i wanted to load generated .bin file into the controller's internal flash form processor(AM5728) end.if anybody has any idea then please let me know.


text:
Q: How to create a counteranimation with decimals I have a javascript code which turns a text element with the class count into an animated counter.
The script is working well but unfortunately, it only works with non-decimal numbers.
Here is my script:

function startCounter(){
    $('.count').each(function () {
        $(this).prop('Counter',0).animate({
            Counter: $(this).text()
        }, {
            duration: 3000,
            easing: 'swing',
            step: function (now) {
                $(this).text(Math.ceil(now));
            }
        });
    });
}
$( document ).ready(function() {
    startCounter();
});

6.0

600

So now my question is, how can I also show the decimal numbers in the script?

A: You can replace the Math.ceil() with
Math.round(num * 100) / 100

in order to round to two decimal places:

function startCounter(){
    $('.count').each(function () {
        $(this).prop('Counter',0).animate({
            Counter: $(this).text()
        }, {
            duration: 3000,
            easing: 'swing',
            step: function (now) {
                $(this).text(Math.round(now * 100) / 100);
            }
        });
    });
}
$( document ).ready(function() {
    startCounter();
});

6.0

600

If you want to be able to use both, decimal and integer representation, you can do something like this (this snippet is also using toFixed() instead in order to represent "6.00" correctly):

function startCounter(){
    $('.count').each(function () {
        $(this).prop('Counter',0).animate({
            Counter: $(this).text()
        }, {
            duration: 3000,
            easing: 'swing',
            step: function (now) {
                var $this = $(this),
                    isFloat = !!$(this).attr('data-float');
                $this.text(isFloat ? now.toFixed(2) : Math.round(now));
            }
        });
    });
}
$( document ).ready(function() {
    startCounter();
});

6.0

600

A: If you want to keep the 2 decimal places all the time (even 6.00) you can use toFixed(x). It will take any number an return a string with x decimal numbers.

function startCounter(){
    $('.count').each(function () {
        $(this).prop('Counter',0).animate({
            Counter: $(this).text()
        }, {
            duration: 3000,
            easing: 'swing',
            step: function (now) {
                $(this).text(now.toFixed(2));
            }
        });
    });
}
$( document ).ready(function() {
    startCounter();
});

6.0

600


text:
Q: Looking for an Image Conversion Library I am looking for a conversion library that can convert my dds files to tga. I found imagemagick and DevIL. But both come with problems, because my specifications are as follows:

*

*The library needs to be a 64-bit dll

*The library needs to be managed (writing in C#)

DevIL has a wrapper called DevIL.NET, but this is 32-bits. I already tried to build the source in 64-bit, but I was missing a file and the author doesn't seem to respond at the moment.
ImageMagick doesn't seem to support dds formats.
Does anybody know a good library that complies to my requirements?

A: There is a way to do this but it's a bit painfull.
Humus provides C++ source code for both tga and dds reading and saving ( Download the latest framework ). You need to convert it to C# but this should be possible without any problems ( i did it once too ).
You'll find the code in the Imaging\Image.h and Imaging\Image.cpp.
Direct link to the Code( ZIP ).


text:
Q: XamlSpy prevent me from doing actions I installed XamlSpy using NuGet in my UWP app.
I debug my application and connect it successfully using the XamlSpy.
The problem is that every mouse hover is responses by XamlSpy what prevents me from clicking on buttons etc'...
How can I start inspect only when needed ?
I tried CTRL+Shift without success...

A:
How can I start inspect only when needed

According to this article, Ctrl+Shift is worked for XAML Spy 2. By testing on my side, I guess you are using XAML Spy 3.
In that case, when you are using the  XAML Spy desktop app to inspect, the "Select Visual" button which is for moving your mouse to the app, and click to select a visual in the user interface, is highlighted by default. You may need to click it to not highlight the button to stop inspecting, and click again can  start inspecting again when you needed.


text:
Q: AmCharts 4 Breaking when a series has no value I have a graph with two "series", only when one has value and the other does not, it breaks and has no background. How to fix it? I've tried several posts from various sites, videos and also read the documentation a lot. No example seems to work, so I don't know exactly what to do. If it has value it looks like it looks normal.
Javascript
    function initChartVendas() {
            am4core.useTheme(am4themes_animated);

            let chart = am4core.create(this.chartElement.nativeElement, am4charts.XYChart);
            chart.data = this.generatechartData();
            chart.numberFormatter.numberFormat = "'R$ ' #,###.##";

            // Create axes
            let dateAxis = chart.xAxes.push(new am4charts.DateAxis());
            dateAxis.startLocation = 0.5;
            dateAxis.endLocation = 0.5;
            dateAxis.extraMax = null;
            dateAxis.extraMin = null;
            dateAxis.dateFormats.setKey('day', 'dd');

            // Create value axis
            let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
            valueAxis.baseValue = 900;

            // Create series
            let series = chart.series.push(new am4charts.LineSeries());
            series.name = 'Pagos ';
            series.dataFields.valueY = 'valor';
            series.dataFields.dateX = 'dia';
            series.strokeWidth = 3;
            series.tooltipText = '{valueY.value}';
            series.fillOpacity = 0.1;
            series.tensionX = 0.8;
            series.tensionY = 1;
            series.fill = am4core.color('#5770ef');
            series.stroke = am4core.color('#5867dd');

            // Create series 2
            if (this.dataCancelados) {
                let seriesCancelados = chart.series.push(new am4charts.LineSeries());
                seriesCancelados.name = 'Cancelados ';
                seriesCancelados.dataFields.valueY = 'cancelado';
                seriesCancelados.dataFields.dateX = 'dia';
                seriesCancelados.strokeWidth = 3;
                seriesCancelados.tooltipText = '{valueY.value}';
                seriesCancelados.fillOpacity = 0.1;
                seriesCancelados.tensionX = 0.8;
                seriesCancelados.tensionY = 1;
                seriesCancelados.fill = am4core.color('#f96191');
                seriesCancelados.stroke = am4core.color('#fd397a');
            }

            // Add cursor
            chart.cursor = new am4charts.XYCursor();
            chart.cursor.behavior = 'none';

            series.tooltip.getFillFromObject = false;
            series.tooltip.adapter.add('x', (x, target) => {
                // @ts-ignore
                const valueY = series.tooltip.tooltipDataItem.valueY;
                if (valueY < 0) {
                    series.tooltip.background.fill = chart.colors.getIndex(4);
                } else {
                    series.tooltip.background.fill = am4core.color('#5770ef');
                }
                return x;
            });

            if (this.dataCancelados) {
                chart.legend = new am4charts.Legend();
            }
        }

Image 1
Image 2

A: I found the solution the dates should be ordered. Before they were not, for example, the 20th came before the 16th. That's why the problem. My ordering solution is this (it only matters the day)
 chartData.sort((v1, v2) => (v1.dia.getDate() > v2.dia.getDate() ? 1 : -1));


text:
Q: A left invariant vector field on a Lie group Let $G$ be a matrix Lie group. Let $v$ be a left invariant vector field on $G$ and $v_1 \in  \frak g$, where $\frak g$ is a Lie group of $G$. Let $v_1$ be its value at the identity. We define $\phi_t :G \to G$ by $\phi_t(g)=g \exp(t v_1)$.
I want to show that
$$ \frac{d}{dt} \phi_t(g)|_{t=0} = v_g $$ for all $g \in G$.
I calculated that
$$ \frac{d}{dt} \phi_t(g)|_{t=0} = g v_1 \exp(tv_1) |_{t=0}=gv_1$$
I want to show that $g v_1=v_g$.
Now $v_g=(L_g)_* v_1$, where $L_g$ is a left multiplication map by $g\in G$.
Evaluated at $f \in C^{\infty}(G)$, we have
$$v_g(f)=(L_g)_*v_1(f)=v_1(L_g^* f)$$.
On the other hand we have
$$ g v_1(f)=L_g v_1 (f)$$.
But I could not show that these are equal.
Did I make any mistake in the calculation? How can I prove they are equal?

A: Since for $ h \in G $, $ L_g(h) = g h $, and since $ exp(t v_1) $ is a curve with velocity $ v_1 $, the line $ \frac{d}{dt} \phi_t(g)|_{t=0} = \frac{d}{dt} g \exp(tv_1) $ is precisely the definition of the pushforward of $ v_1 $ by $ L_g $,
Note that you have assumed that $ G $ is embedded in a matrix group $ GL_n $ for some $ n $, so that the group operation is matrix multiplication and the exponential is literally matrix exponentiation. You are also so choosing embedding $ T_g G $ in $ T_g GL_n \approx End(\mathbb{R}^n) $. This is why you can further simplify $L_g v_1 $ to write $ g v_1 \in T_g G $.
Edit: Remember that you can think of the tangent space of a manifold $ M $ at $ p $ as equivalence classes of curves passing through $ p $. In this picture, if a vector $ v \in T_p M $ is represented by a curve $ \gamma(t) $ with $ \gamma(0) = p, \frac{d\gamma}{dt} (0) = v $, and if $ f: M \rightarrow M $, then the pushforward is given by composition: $ f_* v $ is represented by $ f(\gamma(t)) $.

A: First, $\mathfrak g$ is the Lie algebra. The mistake is in your calculation of the derivative. Although you can make sense of $gv_1$ when working with matrix groups, this doesn't make sense in general.
As @user116293 told you, in the setting of general manifolds, if $f\colon M\to N$ is a smooth map and $v\in T_pM$, one way to understand/define $f_*(v) = df_p(v)$ is to define a curve $\gamma(t)$ in $M$ with $\gamma(0)=p$ and $\gamma'(0) = v$ and then compute $(f\circ\gamma)'(0)\in T_{f(p)}N$. In your situation, $v=v_1$, $\gamma(t) = \exp(tv_1)$, and $f\colon G\to G$ is given by $f(x)=L_gx = gx$.


text:
Q: scheduled query to partitioned and clustered table I have created a BQ table with time partitioned (day/ timestamp) and also clustering data using region and location field.
I have created a daily scheduled query using the query that I ran to create the initial records.  The scheduled query was set to append data to the previously created partitioned and clustered table.  However, scheduled query failed to run with a message below:

Incompatible table partitioning specification. Destination table
exists with partitioning specification
interval(type:DAY,field:timestamp) clustering(location,region), but
transfer target partitioning specification is
interval(type:DAY,field:timestamp). Please retry after updating either
the destination table or the transfer partitioning specification.

The simplified version of the query is below:

CREATE TEMP FUNCTION
  isYesterday(recordTimestamp TIMESTAMP) AS ( DATE(recordTimestamp) = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY) );

WITH
  daily AS (
  SELECT
    TIMESTAMP_TRUNC(timestamp,day) day,
    location,
    direction,
    region,
    MAX(metric1) metric1,
    MAX(metric2) metric2
  FROM (
    SELECT
      location,
      timestamp,
        direction,
        CASE
        WHEN area>0 AND area<20 THEN "region1"
        WHEN area>10
      AND area<20 THEN "region2"
        WHEN area>30 AND area<40 THEN "Region3"
        WHEN area=61 THEN "Region4"
        WHEN area=65 THEN "Region5"
        WHEN area=76 THEN "Region6"
        WHEN area>89 AND area<100 THEN "Region7"
    END
      AS region,

      SUM(terminalcount0) metric1,
      SUM(terminalcount1) metric2
    FROM
      `statistic`
    WHERE
  isYesterday(timestamp)
--      DATE(timestamp) BETWEEN '2020-07-01'
--      AND DATE_SUB(CURRENT_DATE(),INTERVAL 1 day)
        GROUP BY
      location,
      timestamp,
      direction,
      region )
  GROUP BY
    day,
    location,
    direction,
    region)
SELECT
  day as timestamp,
  location,
  direction,
  SUM(metric1) metric1,
  SUM(metric2) metric2
FROM
  daily
GROUP BY
  day,
  location,
  direction,
  region

How do I fix this so that scheduled query can run and save the results to the destination table regularly?   Or is it really the scheduled query to the existing clustered table not supported by GCP?

A: There's an answer for this problem here: 61896744
You can workaround this problem by adding a view with your select query:
SELECT field_a, field_b, datetime, date
FROM large_table
WHERE date >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 WEEK)

And creating a scheduled query like this:
INSERT INTO `my_clustered_table` (field_a, field_b, ...)
SELECT *
FROM `my_view`


text:
Q: KV script not working on pycharm on windows? Windows kivy works fine with
def build(self):
    return #object

but on running even official examples(PONG) with kv script it does not work!!
I have tried Builder load

A: reinstalling helped for me maybe the release had some compatability issues


text:
Q: Hide some built-in build/release tasks in TFS TFS 2017 u2. The task gallery for build/release definitions is crowded by tasks that are utterly irrelevant to our software shop. They're built-in, so removing the extension is not an option.
Any way to hide them?

A: CAVEAT I discourage you: if you need to reinstall a Task, the process is non-trivial.
This has already been answered at Remove custom installed build task on tfs
The idea is to use tfx build tasks delete. You need the GUID of the task: a quick way to get it is to look at the task.json file in the https://github.com/Microsoft/vsts-tasks repository.

A: Unfortunately, there is no way to hide the tasks. You could search the tasks you want to use, and I've submitted a UserVoice at website below, you can vote it:
https://visualstudio.uservoice.com/forums/330519-visual-studio-team-services/suggestions/33373423-hide-build-tasks


text:
Q: webview inside onclick imagebutton error I am trying to open webview with an imagebutton. I was able to do with an intent and uri.parse like so:
        twbutton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent browserIntent = new Intent(android.content.Intent.ACTION_VIEW,
            Uri.parse("website"));
            startActivity(browserIntent);

But it exits the application and opens the browser. I want it to open up without leaving the application
    fbbutton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            View rootView = inflater.inflate(R.layout.fragment_socialmedia, container, false);
            WebView myWebView = (WebView) rootView.findViewById(R.id.webview);
            myWebView.getSettings().setJavaScriptEnabled(true);
            myWebView.setWebViewClient(new WebViewClient());
            myWebView.loadUrl("website");

        }
    });

but I get the error:
W/art﹕ Attempt to remove local handle scope entry from IRT, ignoring
W/AwContents﹕ onDetachedFromWindow called when already detached. Ignoring

A: Are you sure to have the element webview inside the layout fragment_socialmedia.xml ?
 View rootView = inflater.inflate(R.layout.fragment_socialmedia, container, false);
 WebView myWebView = (WebView) rootView.findViewById(R.id.webview);

thats the reason for what you are getting this exception : android.webkit.WebSettings android.webkit.WebView.getSettings()' on a null object reference

A: You need to swap these two lines:
myWebView.loadUrl("website");
myWebView.setWebViewClient(new WebViewClient());

Set WebViewClient before doing the load:
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("website");


text:
Q: When, the code that create the components on the form and the code that set their properties, is called? If I put a component on the form I don't see any code like MyComp:=TMyComponent.Create in unit code. I think the component is created automatically, but when ? And the same happends with the properties that I configured after I put the component on the form. When they are applied at runtime ?

A: Information about controls and components as well as their properties that you edit while designing in IDE will be stored in your form .dfm file. Creation of that form in run-time will trigger the process of automatic loading of that .dfm file and all controls and components will be initialized at that time.
This is rather simple explanation of what exactly happens, you can start debugger at form creation line and follow what is happening there, but it is quite longish process and you can easily get lost if you are still learning.
You can find form creation code that Delphi automatically writes in .dpr file of your project.
  Application.CreateForm(TForm1, Form1);

A: The properties for a form and all the design time components that live on it are streamed in by the framework during the construction of the form. That process is triggered from the form's constructor, in TCustomForm.Create. The pertinent code in there looks like this:
Include(FFormState, fsCreating);
try
  if not InitInheritedComponent(Self, TForm) then
    raise EResNotFound.CreateFmt(SResNotFound, [ClassName]);
finally
  Exclude(FFormState, fsCreating);
end;

The key is the call to InitInheritedComponent. That is a function defined in the Classes unit that does the heavy lifting. In a very broad overview it does the following:

*

*Finds the name of the form class and looks for an RT_RCDATA resource of that name. That resource is the .dfm file.

*Once the .dfm resource has been located it is parsed.

*The .dfm parsing handles the assignment of properties that you set at design-time in the Object Inspector. For instance the parsing might encounter a line like this: Caption = 'My main form' and it turns that into an assignment of the string 'My main form' to the form's property Caption.

*The .dfm file is hierarchical. It contains the properties for the various components and controls that are defined at design-time.

*As well as setting the properties of the form's design-time components, the .dfm streaming process also instantiates those components.

In order for all of this to work, the streaming framework relies on RTTI. It knows nothing at all at compile time of your classes and components. Hence the need for RTTI. The streaming framework uses the old style RTTI and in fact that is the reason for the existence of old style RTTI. If ever you wonder about why old style RTTI is the way it is, try to view it from the perspective of having been designed to support streaming.


text:
Q: Best known constant for parallel sorting I recently found myself talking about Szemerédi's mathematics, and briefly discussed his famous sorting network, discovered with Ajtai and Komlós. Apparently their algorithm is not practical because it takes time $C\log n$ for a fairly large constant $C$, and so in practice it is better to go for an algorithm that takes time, say, $2(\log n)^2$. I have read that reducing this constant is still an interesting open problem, and wondered if there was a good place to find out what the status of this problem is.
The answer may depend on exactly what is required of the algorithm, so let me ask a precise question, though I may be interested in answers to slightly different but related questions. Let's suppose you have $n=2m$ objects to sort, and you want to minimize the number of rounds. In each round you can partition the $n$ objects into $m$ pairs and compare each pair, and in between rounds you can do whatever computations you want. [See below -- I've changed my mind about that last point.] The number of rounds you need is of the form $C\log n$, but what is known about the constant $C$?
If I understand correctly, the question I've just asked isn't the usual one, since usually one requires more. The idea is that you start with the objects lined up from left to right in an arbitrary order, and then at each round you choose some way of partitioning the objects into pairs, but in between rounds the only thing you can do is switch the objects in each pair if the larger one is to the left of the smaller. Also, the comparisons you do in each round are, I think, independent of the results of previous rounds. This is called a sorting network.
One other way in which one can vary the question is according to whether you allow randomized algorithms. The case that interests me most is the one where randomness is allowed and so is any amount of computation between rounds. Actually, I now realize that that's a bit too generous, since it means that we can check every single ordering and see whether it is consistent with the comparisons we have made. So I'd better change what I'm asking. First, what is known about the constant $C$ in the best sorting network, with randomness allowed? Secondly, is the best known constant smaller if you allow "reasonable" additional computations to take place between rounds?


text:
Q: How to add a choice field in JS Grid control I need to add a choice field (dropdownlist) in each row of a JS Grid control. What is the PropertyID for a choice field. How to add a dropdown. Please assist.
i tried like this,but this didnt work
else if (dc.DataType == typeof(Enum))
            {
                gf.PropertyTypeId = "Enum";

                gf.Localizer = (ValueLocalizer)delegate(DataRow row, object toConvert)
                {
                    return toConvert == null ? "" : toConvert.ToString();
                };

                gf.SerializeLocalizedValue = false;

                gf.SerializeDataValue = true;

            }

Please provide the solution
Thanks in advance !


text:
Q: What is the correct way to pass a token to axios from React? The question sounds vague so allow me to explain. I am wondering, what is the correct/best way to pass get a token from local storage and pass it into my axios request.
This is what I am doing now, and I am sure this is not correct so I want to fix it but am unsure how.
I have a component called TicketsComponent that requires authorization. Therefore, in componentDidMount(), I validate the token, and if its invalid then send the user back to login, otherwise, load the tickets. It looks like this:
  componentDidMount() {
    this._isMounted = true;

    // validate token
    const token = localStorage.getItem("token");
    AuthService.validateToken()
      .then((res) => {
        if (res == undefined || res == null || !token) {
          this.props.history.push("/login");
        }
      })
      .then(() => {
        TicketService.getTickets().then((res) => {
          if (this._isMounted) {
            this.setState({ tickets: res.data });
          }
        });
      });
  }

Both AuthService.validateToken() and TicketService.getTickets() require the JWT in the header. Here are those two functions:
  validateToken() {
    return axios
      .get(API_BASE_URL + "authenticate", {
        headers: {
          token: this.getTokenFromLocalStorage(),
        },
      })
      .then("did it")
      .catch((error) => {
        console.log("failed to validate token" + error);
        return null;
      });
  }

  getTickets() {
    console.log("getting tickets!");
    console.log("Environment variable: " + process.env.NODE_ENV);
    return axios
      .get(API_BASE_URL + "tickets", {
        headers: { Authorization: `Bearer ${this.getTokenFromLocalStorage()}` },
      })
      .then("yessssss")
      .catch((error) => {
        console.log("failed to get tickets" + error);
      });
  }

The problem is that both AuthService and TicketService share the same function called getTokenFromLocalStorage(). That looks like this:
  getTokenFromLocalStorage() {
    const token = localStorage.getItem("token");
    console.log("the token is -> " + token);
    if (token === null) {
      return undefined;
    }
    return token;
  }
  catch(err) {
    return undefined;
  }

So obviously this is not ideal. I have the same function in two services just to get the token from the header. What is the recommended way of doing this?
EDIT: I hope this kind of question is allowed. Even though the code is not actually broken per se, I still think this is useful to beginners like me to implement best practice.

A: You can create a shared axios instance like so:
const API_BASE_URL = 'https://example.com/api/'

const instance = axios.create({
  baseURL: API_BASE_URL,
  headers: { Authorization: `Bearer ${this.getTokenFromLocalStorage()}` },
});

Then you'd just import "instance" into the components and call:
import {instance} from '../wherever' // decide if you want to import default or not

// make sure to either include or exclude the / in the first parameter passed into the request method (e.g. '/authenticate' or 'authenticate') below based on whether you provided a / in the API_BASE_URL

instance.post('authenticate', {
  // any additional config relevant to the request, e.g:
  data: {
    username: 'my user!',
    password: 'super_secret_password'
  }
})


text:
Q: In ReSharper Templates Explorer - What is the difference between the #if and if templates? I am playing around with the live templates for C# in ReSharper. I started doing this because of this question. When I get the the ReSharper templates explorer in Visual Studio, I see that there is a #if template and also an if template. My question is why?
I have read through the ReSharper help here, but that doesn't really shed much light on it (for me). I have also tried un-checking each template. It seems like the if template is the ReSharper if snippet, but I can't figure out what the #if template is for.
Is this the Visual Studio if snippet? If so, why don't I see both in the intellisense widow?
I know this is a really small issue, but I just want to know. Thanks.

A: #if is a preprocessor directive where as if is a C# selection statement
Example:
#if DEBUG
    Console.WriteLine("Debug version");
#endif

vs
bool condition = true;

if (condition)
{
    Console.WriteLine("The variable is set to true.");
}


text:
Q: compound proposition logically equivalent I can not solve this question
Find a compound proposition logically equivalent to $p \to q$ using only the logical operator $\downarrow$.

A: It's quite simple; let start with :

$\lnot p \equiv p \downarrow  p$.

Then :

$p \rightarrow q \equiv ((p \downarrow p) \downarrow q) \downarrow ((p \downarrow p) \downarrow q)$.

In order to check the definition, we have to use the truth-table for $\downarrow$ : it is true only when both $p$ and $q$ are false.
This fact justify the definition of $\lnot p$ as $p \downarrow p$.
For the conditional, we will work by steps:

$((p \downarrow p) \downarrow q)$ is $\lnot p \downarrow q$ [see the definition of $\lnot$ above].

Thus, the complete formula is simply : $\lnot ( \lnot p \downarrow q)$.
Now we may check that the only case when it is false (i.e.$0$) is when $p=1$ and $q=0$.
Note. You can see this paper on Adeqaute set of connectives for a general overview of the topic.

A: Given propositions $p$ and $q$, the propositon $p \downarrow q$ is given by the following truth table:
$$
\begin{align}
p \qquad &  q  & p \downarrow q \\
T \qquad & T  & F \\
T \qquad & F  & F \\
F \qquad & T  & F \\
F \qquad & F  & T
\end{align}
$$
Thus we have
$$
T \downarrow T \equiv F, \ \ \ T \downarrow F \equiv F, \ \ \ F \downarrow T \equiv F, \ \ \  F \downarrow F \equiv T. \tag{0}
$$
In fact, we have the logical identity
$$
p \lor q \equiv \overline{p \downarrow q}. \tag{1}
$$
We further note that
$$ p \downarrow p \equiv \overline{p}, \tag{2} $$
because when $p$ is True, we have $T \downarrow T$, which is False, and when $p$ is False, we have $F \downarrow F$, which is true.
And, we also note that
$$
\begin{align}
p \lor q &\equiv \overline{\overline{p \lor q}} \\ &\equiv \overline{p \downarrow q} \qquad \mbox{[ using (1) above ]}\\
&\equiv \big( p \downarrow q \big) \downarrow \big( p \downarrow q \big).
\end{align}
$$
Thus we have the logical identity
$$
p \lor q \equiv \big( p \downarrow q \big) \downarrow \big( p \downarrow q \big). \tag{3}
$$
Now we note that
$$
\begin{align}
p \rightarrow q &\equiv \overline{p} \lor q \qquad \mbox{[ using the conditional-disjunction equivalence ] } \\
&\equiv \left( \overline{p} \downarrow q \right) \downarrow \left( \overline{p} \downarrow q \right) \qquad \mbox{[ using (3) above with $\overline{p}$ in place of $p$ ]} \\
&\equiv \big( (p \downarrow p) \downarrow q \big) \downarrow \big( (p \downarrow p) \downarrow q \big) \qquad \mbox{[ using (2) above ]},
\end{align}
$$
as required.


text:
Q: Bootstrap datetimepicker - will not display the calendar or format the date I am trying to use the bootstrap datetime picker. The input box with the glyphicon is displayed; however, no calendar appears when I click in the input and manually entering the date does not result in it being formatted. I have copied this from sample code and spent a lot of time ensuring I have the libraries required.
This is displayed:

The HTML and js is:
<!DOCTYPE html>

    <title>Cub Award Overview</title>
    <meta http-equiv=Content-Type content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta name="description" content="A Scout award tracking application">
    <meta name="author" content="Glyndwr (Wirrin) Bartlett">

    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.css" rel="stylesheet"/>
    <link href="resources/bootstrap-3.3.7-dist/css/bootstrap.css" rel="stylesheet"/>
    <link href="resources/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet"/>
    <link href="resources/bootstrap-3.3.7-dist/css/bootstrap-theme.min.css" rel="stylesheet"/>
    <link href="resources/bootstrap-3.3.7-dist/css/bootstrap-responsive.css" rel="stylesheet"/>

    <link rel="shortcut icon" href="resources/favicon.png">

                        <input type='text' class="form-control" />

I know it is frowned upon to have the script with the HTML and will separate when working.

A: Try to swap the order of loading datetimepicker and moment.js, so that moment.js is loaded first

Edit
As your code examples has some local resources which we can not check, here is a simple working example with external resources only:

<!DOCTYPE html>

    <title>Cub Award Overview</title>
    <meta http-equiv=Content-Type content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="A Scout award tracking application">
    <meta name="author" content="Glyndwr (Wirrin) Bartlett">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

                        <input type='text' class="form-control" />

You maybe want to try to adapt that. If it doesn't work inside your code, try to check for errors on the console. Another try would be to implement my code, comment out all of your initial includes and un-comment them step by step to find the source of evil.

A: Checked your code and it seems like you have not included the moment.js file first before jquery library and bootstrap js file. Also you have not included the moment.js file in your code. Please try as mentioned below
Ex :
<link rel="stylesheet"

href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />

Another thing I noticed is, you didn't provided an id to the input field. Try to provide an id to input field and use in jquery
Ex :

                        <input type='text' class="form-control" id="datetimepicker1" />

Now in script

Its worked for me and hope it works for you.


text:
Q: Rails execute script I am building a script in on of my controllers to fill a database with an excel files data. I would build the function, then access it through a route. (That i guess i can protect with cancan) But i thought about it, and it doesn't seem very ... 'Railsy'.

I know the scripts folder exists, and it is probably for these kinds of tasks. I've tried googling stuff like 'rails execute script' and other stuff, but i can't find any good advice for what to do next.

I'm sorry if this seems kind of stupid, but in my apps i've been kind of hacking around stuff to make it work, so any advice on this task would be appreciated.

A: If you need to upload the file in the app and process it, it should probably go in the "lib"directory and be accessed like any other Ruby library/module/etc.
If it's something you need to run locally, "on demand", "scripts" is fine. If you need access to your rails environment when running it like any Rails models, you can run it from "rails console" or "rails runner".
As Aln said, there are a variety of ways it could be scheduled as well.

A: You could simply do
#!/usr/bin/env ruby
require 'rubygems'

# regular ruby code here

and have it running just like any other util. Of course you can always call any *.rb with simply
ruby somescript.rb

If you need some scheduled script, check into rufus-scheduler gem.


text:
Q: using subfig (side-by-side) figures I used the package subfig for my first time, I got this error:
! LaTeX Error: File figures/Rnefft1310' not found.
! LaTeX Error: Filefigures/imt1310' not found.
However, I am sure the file is there as eps. What is wrong?
Am I using the wrong code for subfig?
here is what I wrote:
\begin{figure}
\centering
\subfloat[]{\includegraphics[width=3.1in]{figures/Rnefft1310}}
\subfloat[]{\includegraphics[width=3.1in]{figures/imt1310}}
\caption{Real and imaginary part of effective index }
\label{fig:EcUND}
\end{figure}

A: This is not really an answer - I don't know what the problem you are having is! It is really hard to help with this sort of thing! It's very strange that you can plot them when not in the subfloat - it implies there is no package missing for rendering graphics generally.
I thought it might be useful for me to send you some code that works for me so you can see if there is a difference in what you are doing or how you are loading the packages. Obviously replace my .eps files with your own!
If this doesn't point you in the right direction, please change your question to include a minimal working example - i.e. something that can be compiled by someone else, as it may help someone to spot some incompatibility somewhere in your preamble.
\documentclass{report}

\usepackage{graphicx}      % needed for including graphics
\usepackage{epstopdf}
\usepackage{grffile}
\graphicspath{{figures/}}
\usepackage{caption, subfig}

\makeatletter
\g@addto@macro\@floatboxreset\centering % automatically center floats
\makeatother

\begin{document}

\begin{figure}

  \subfloat[Temperature]{\label{fig:opt_nmc_t}\includegraphics[clip=true, width=0.4\textwidth, height=0.3\textheight]{figures/AoptBandB_t_RTTOV10_MoistCovVNMC_F_TH_NEW.eps}} \quad
  \subfloat[Watervapour]{\label{fig:opt_nmc_q}\includegraphics[clip=true,  width=0.4\textwidth, height=0.3\textheight]{figures/AoptBandB_q_RTTOV10_MoistCovVNMC_F_TH_NEW.eps}}

  \caption{Some figures}
  \label{fig:opt_nmc_bc}

\end{figure}

\end{document}


text:
Q: Is using KDoc/Javadoc comments inside of a function considered bad practice? I often find it helpful to use KDoc/Javadoc comments inside of a class or function instead of normal comments. IntelliJ colorizes them more obviously by default and, more importantly, allows hyperlinking to definitions. I'm wondering if it is considered bad practice to do so.
For example:
/**
 * Standard kdoc comment here...
 */
fun saveUser(user: User) {

    /**
     * Save the user to the [UserRepository]
     */
    userRepo.save(user)
}

In the inner comment, [UserRepository] will be linked to the type definition for that class. This example is a bit forced, but I often find it helpful in read code.

A: You ask "is it considered bad practice", and the answer is Yes.
But not so much because of using KDoc/Javadoc syntax in an inappropriate place, but because of the level of commenting. If you feel compelled to comment your code inside some method, think about rewriting it to achieve better readability.
In your example
fun saveUser(user: User) {

    /**
     * Save the user to the [UserRepository]
     */
    userRepo.save(user)
}

your comment is redundant. To any sane developer, userRepo.save(user) is perfectly readable as "save the user to the repository", so the comment can simply be deleted.
You talk about the linking possibilities. On the userRepo variable, any decent IDE will show you its declared type and let you navigate to the variable definition and to the class source, so this linking also isn't necessary (and it will only work with a non-standard IDE that accepts KDoc/Javadoc in places beyond the specification).
Of course, there might be situations where your comment isn't as trivial as in your example. But then, if your code is so obscure that it needs such a comment, you'd better rewrite it, or restructure it to call smaller methods with sensible names and the opportunity to add KDoc/Javadoc there.

A: It's just not useful to do that.  The purpose of KDoc or JavaDoc is to run a tool to generate HTML documentation for how to use your code.  They way the tool works is it scans for the specially formatted comments in specific locations (i.e. method declarations and class declarations).
Depending on the tool used to scan for those comments you have two potential possibilities:

*

*The scanner gets confused and generates erroneous documentation

*The comments are ignored and simply treated like normal comments

My recommendation is to simply use regular comments inside your methods/functions.  Standard multiline comments in many languages look like this:
/* This is a multiline
 * comment
 */

In fact the Javadoc notation is a standard multiline comment so it can be ignored by the compiler, and the extra * is there to call out that this comment is used for the tool that generates documentation pages.


text:
Q: vue.js: Tree View with components Is it possible to add a tree like here with components?
I have a structure with organisations, organisation units and section. I want to show them organised.
It temporary looks like this:

One input-group example:
<b-input-group prepend="Org">
     <b-form-input v-model="org.name"></b-form-input>
     <b-input-group-append>
         <b-btn variant="outline-danger">Delete</b-btn>
         <b-btn v-on:click="editOrg(org.id, org.name)" variant="outline-success">Save</b-btn>
     </b-input-group-append>
</b-input-group>

A: Yes it is possible, I recently created a drag and drop menu builder using recursive components. Here is a good tutorial that can walk you through how to handle that part: https://alligator.io/vuejs/recursive-components/
Once you have an understanding of how recursive components work you should be able to build your array and nest any content you want, i.e. <input> elements inside of your list. Then just reference the input by a key, to bind the input to the item in your array.


text:
Q: Как изменить цвет иконок в меню android приложения? Как изменить цвет иконок в меню android приложения? Нужно цвет кнопок сделать белым.

Вот мой файл styles.xml:
<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="titleTextColor">@color/colorBackground</item>
    </style>
</resources>

A:  <android.support.v7.widget.Toolbar>
...
 android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
 app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
 </android.support.v7.widget.Toolbar

Или вместо <style name="AppTheme" parent="Theme.AppCompat.Light">
напишите  <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar


text:
Q: Use Lax-Milgram theorem to prove the existence of weak solution for an elliptic equation Let $\Omega$ an open bounded and regular domain to $\mathbb{R^n}$ and let $\{\overline{\Omega_1},\overline{\Omega_2}\}$ a partition of $\Omega.$
$\bar{\Omega} = \bar{\Omega_1} \cup \bar{\Omega_2}.$ We put $\Gamma = \partial \Omega_1 \cap \partial \Omega_2$ the interface between $\Omega_1$ and $\Omega_2$ such that $\Gamma \subset  \Omega.$
We put $u_1 = u/\Omega_1$ (restriction $u$ to $\Omega_1$) and we condider the problem:
$$-k_i \Delta u_i = f , x \in \Omega_1 , i=1,2$$
$$u_1=0 , x \in \partial \Omega$$
$$u_1 = u_2 , x \in \Gamma$$
$$k_1 \nabla u_1 n = k_2 \nabla u_2 n , x \in \Gamma$$
$k(x)$ is an piecewise constant , with $k(x) = k_i > 0, i = 1,2$  and $f \in L^2(\Omega)$
My questions are, how:
1-prouve that this problem admit a unique solution in an adequat Hilbert space $V.$
2- Prouve that $\exists c > 0, ||u||_V \leq c$ and prouve that $u$ verfies the minimum of energy.

A: The big picture is: If $u$ satisfies those two continuity conditions on $\Gamma$ together with the equation in each subdomain, then $u$ solves the weak problem for the following diffusion equation on the whole domain:
$$\left\{\begin{aligned}
-\nabla \cdot (k\nabla u )&= f \quad\text{in } \Omega,
\\
u&=0 \quad\text{on } \partial \Omega.
\end{aligned}\right.
$$

Multiply both equations by a same $H^1_0(\Omega)$ test function $v$:
$$
-\int_{\Omega_1}k_1 \Delta u_1\,v -\int_{\Omega_2}k_2 \Delta u_2\,v= \int_{\Omega}f\,v.
$$
Integrating by parts using Green's identity on each domain:
$$
\int_{\Omega_1}k_1 \nabla u_1\cdot\nabla v - \int_{\partial \Omega_1}k_1 (\nabla u_1\cdot n_1)v  + \int_{\Omega_2}k_2 \nabla u_2\cdot\nabla v - \int_{\partial \Omega_2}k_2 (\nabla u_2\cdot n_2)v =  \int_{\Omega}f\,v,
$$
where $n_1$ and $n_2$ are the unit vector normal to the boundaries of $\Omega_1$ and $\Omega_2$ respectively. Now we focus on the boundary part, for $\partial \Omega_1\cap \partial \Omega_2 = \Gamma$:
$$
\begin{aligned}
&\int_{\partial \Omega_1}k_1 (\nabla u_1\cdot n_1)v + \int_{\partial \Omega_2}k_2 (\nabla u_2\cdot n_2)v
\\
=& \int_{\partial \Omega_1\backslash\Gamma}k_1 (\nabla u_1\cdot n_1)v + \int_{\partial \Omega_2\backslash\Gamma}k_2 (\nabla u_2\cdot n_2)v + \int_{\Gamma} (k_1 \nabla u_1\cdot n_1 + k_2\nabla u_2\cdot n_2)v
\\
=& \int_{\partial \Omega}k (\nabla u\cdot n)v + \int_{\Gamma} (k_1 \nabla u_1\cdot n_1 + k_2\nabla u_2\cdot n_2)v.
\end{aligned}
$$
The first term vanishes because $v=0$ on $\partial \Omega$. Second term vanishes because $$k_1 \nabla u_1\cdot n - k_2\nabla u_2\cdot n = k_1 \nabla u_1\cdot n_1 + k_2\nabla u_2\cdot n_2 = 0,$$
by $n_1$ and $n_2$ share the same magnitude but point the opposite direction pointwisely. By the other interface condition $u_1 = u_2$ on $\Gamma$, we know $u\in H^1_0(\Omega)$, therefore
$$
\int_{\Omega} k\nabla u\cdot \nabla v = \int_{\Omega}f\,v,\quad \forall v\in H^1_0.\tag{1}
$$
To prove the existence of a solution in $V = H^1_0$, we need to fulfill the conditions of Lax-Milgram theorem:

*

*$\displaystyle \int_{\Omega} k\nabla u\cdot \nabla v \leq C\|u\|_{H^1_0(\Omega)} \|v\|_{H^1_0(\Omega)}$, this is trivial by Cauchy-Schwarz inequality.

*Coercivity relies on Poincaré inequality for $v\in H^1_0$: $\|v\|_{L^2(\Omega)} \leq c\|\nabla v\|_{L^2(\Omega)}$, so we have
$$\int_{\Omega} k|\nabla v|^2 \geq \alpha (\|v\|_{L^2(\Omega)}^2 + \|\nabla v\|_{L^2(\Omega)}^2)$$
for some constant $\alpha>0$ (You need to work out this $\alpha$, it depends on $k_1$, $k_2$ and $c$ in Poincaré inequality).
The second question is then trivial, let $v=u$ in (1), using Cauchy-Schwarz and Poincaré inequality on the right hand side:
$$
\alpha \|u\|_{H^1_0(\Omega)}^2\leq  \int_{\Omega} k|\nabla u|^2 =  \int_{\Omega}f\,u\leq \|f\|_{L^2(\Omega)} \|u\|_{L^2(\Omega)} \leq c\|f\|_{L^2(\Omega)} \|u\|_{H^1_0(\Omega)},
$$
hence the Céa's lemma holds:
$$\|u\|_{H^1_0(\Omega)} \leq \frac{c}{\alpha}\|f\|_{L^2(\Omega)}.$$
And if $u$ solves (1), $u$ also minimize the energy functional:
$$
\mathcal{F}(u) = \frac{1}{2}\int_{\Omega} k|\nabla u|^2 - \int_{\Omega}f\,u.
$$

There are several typos in your question, please double check your notes:

*

*It should be $u_1 = u|_{\Omega_1}$.

*It should be $u= 0$ on $\partial \Omega$, not just $u_1$.

*There should be a dot product between the gradient and the normal, $k_1 \nabla u_1\cdot n= k_2\nabla u_2\cdot n$ because they are vectors.

*"prove", not "prouve".

*Céa's lemma has some norm of $f$ on the right hand side, because $\|u\|_V$ depends on that, you can't find a single $c$ satisfying that property.


text:
Q: Displaying retrieved value in combobox I am accesing value from database and displaying them on form ,i have successfully displayed retrived value in textbox and radiobox but  i am not able to display them in combbox .
In combox items I have values(1 2 3 4) in this combox i want to display fetched value from database for eg. i accesed value 4 for combbox then it should display 4 value selected in it .
how could i achieve this?
public EditQuestionMaster(int qid_value)
{
    InitializeComponent();
    string columns = db.GetEditQuestions(qid_value);
    string[] coldata=columns.Split('~');

    txtQuestion.Text = coldata[1];
    txtOption1.Text = coldata[2];
    txtOption2.Text = coldata[3];
    txtOption3.Text = coldata[4];
    txtOption4.Text = coldata[5];
    string a = coldata[6];

    if (a == "1")
    {
        radioButton1.Checked = true;
    }
    else if (a == "2")
    {
        radioButton2.Checked = true;
    }
    else if (a == "3")
    {
        radioButton3.Checked = true;
    }
    else if (a == "4")
    {
        radioButton4.Checked = true;
    }
        cmbMarks.ValueMember = coldata[7];//in cmbMarks.ValueMember i am getting fetched value but it is not displaying in combbox ,where i am wrong?
}

GetEditQuestions(qid_value) Code
public string GetEditQuestions(int qid)
{
    string data = "";
    try
    {
        string sql = "select QID,Question,Opt1,Opt2,Opt3,Opt4,AnsOp,Marks from Questions where QID IN(" + qid + ") ";
        cmd = new OleDbCommand(sql, acccon);
        rs = cmd.ExecuteReader();
        if (rs.Read())
        {
            data = rs[0].ToString() + "~" + rs[1].ToString() + "~" + rs[2].ToString() + "~" + rs[3].ToString() + "~" + rs[4].ToString() + "~" + rs[5].ToString() + "~" + rs[6].ToString() + "~" + rs[7].ToString() + "$";
        }
    }
    catch (Exception err)
    {
    }
    return data;
}

Thanks in Advance for any help

A: cmbMarks.Text = coldata[7].Substring(1)

See this MSDN page. The .Substring(1) is assuming that coldata[7] is a string with a $ as the first character.


text:
Q: How do I find the solution to the equation $z^2=-81i$? This question is from the Powers of Complex Numbers, Precalculus section of KhanAcademy
Find the solution to the following equation whose argument is between $90°$ and $180°$
$$z^2=-81i$$
What I understand thus far:
I am going to set $r$ and $\theta$ to be the modulus and argument of $z$, respectively.
Therefore, $z^{ 2 }=r^{ 2 }[cos(2\cdot \theta )+isin(2\cdot \theta )]$
Now, I can understand how the modulus is $81$, but I do not understand how it was determined that the argument is $270°$ plus any multiple of $360°$. I am quite confused at this point and a hint in the right direction would be the best thing to help me figure out the solution to this problem and ones like it that I will encounter in the future.

A: $$z^2=-81i\Longleftrightarrow$$
$$z^2=|-81i|e^{\arg(-81i)i}\Longleftrightarrow$$
$$z^2=81e^{-\frac{\pi i}{2}}\Longleftrightarrow$$
$$z=\left(81e^{\left(2\pi k-\frac{\pi}{2}\right)i}\right)^{\frac{1}{2}}\Longleftrightarrow$$
$$z=9e^{\frac{1}{2}\left(2\pi k-\frac{\pi}{2}\right)i}$$
With $k\in\mathbb{Z}$ and $k:0-1$
So, the solutions are:
$$z_0=9e^{\frac{1}{2}\left(2\pi\cdot0-\frac{\pi}{2}\right)i}=9e^{-\frac{\pi i}{4}}$$
$$z_0=9e^{\frac{1}{2}\left(2\pi\cdot1-\frac{\pi}{2}\right)i}=9e^{\frac{3\pi i}{4}}$$
Now, notice that:
$$\color{red}{\frac{\pi}{2}<\arg\left[9e^{\frac{3\pi i}{4}}\right]<\pi\Longleftrightarrow\frac{\pi}{2}<\frac{3\pi}{4}<\pi}$$
So, your right answer is:
$$9e^{\frac{3\pi i}{4}}=9\cos\left(\frac{3\pi}{4}\right)+9\sin\left(\frac{3\pi}{4}\right)i=-\frac{9\sqrt{2}}{2}+\frac{9\sqrt{2}}{2}i$$

A: I think you have understood why the modulus is $81$.
Now, since $r^2(cos(2θ)+isin(2θ)) = -81i$
 clearly, $[cos(2θ)]+[sin(2θ)]i = -i = (0) + (-1)i$.
Since the real and imaginary parts of the complex number are independent, you can equate them to get the answer.
So, you need to solve the equations $$cos(2\theta) = 0,\,\ sin(2\theta)=-1$$

A: Write $-81i$ in trigonometric form:
$$
-81i=81\cdot(-i)=81\left(\cos\frac{3\pi}{2}+i\sin\frac{3\pi}{2}\right)
$$
so by De Moivre its square roots are
$$
9\left(\cos\frac{3\pi}{4}+i\sin\frac{3\pi}{4}\right)
$$
and
$$
9\left(\cos\left(\frac{3\pi}{4}+\pi\right)+
i\sin\left(\frac{3\pi}{4}+\pi\right)\right)
=
9\left(\cos\frac{7\pi}{4}+i\sin\frac{7\pi}{4}\right)
$$
Since $\pi/2<3\pi/4<\pi$, the first one is what you're looking for. Thus the answer is
$$
9\left(-\frac{\sqrt{2}}{2}+i\frac{\sqrt{2}}{2}\right)
$$
If you use degrees, $\frac{3\pi}{2}=270^\circ$ and $\frac{3\pi}{4}=135^\circ$.

In general, if $z=r(\cos\alpha+i\sin\alpha)$, the $n$-th roots of $z$ are
$$
\sqrt[n]{r}\left(
   \cos\left(\frac{\alpha}{n}+\frac{2k\pi}{n}\right)
 +i\sin\left(\frac{\alpha}{n}+\frac{2k\pi}{n}\right)
\right),
\qquad k=0,1,\dots,n-1
$$

A: I would highly recommend using De Moivre's formula and graphing.
Start by getting some graphing paper and label your $x$-axis as real values from $-100$ to $100$ and label your $y$-axis as imaginary values from $-100i$ to $100i$.  (go by $10$'s for the intervals.)
Place the complex number you are trying to square root on the graph.
Measure the angle it makes with the positive $x$-axis, the axis-line that points right.  The angle measure for any real positive values is $0\deg$, naturally, and you can go from there?  (Note: we measure our angles counterclockwise)
Now, all you have to do to square root this number is simply to 'half' the angle and square root the magnitude.
$$\text{magnitude}=|a+bi|=\sqrt{a^2+b^2}$$
In your case, $|-81i|=81$, so the square root of that is $9$.
Since we can see the angle measure is $270\deg$, half of that is $135\deg$.  To calculate the exact value of that, the trigonometric equation is DeMoivre's Formula:
$$(a+bi)^n=|a+bi|^n\cdot(\cos(n\theta)+i\sin(n\theta))$$
For our case, $\sqrt{-81i}=(-81i)^{0.5}=81^{0.5}\cdot(\cos(0.5\cdot270)+i\sin(0.5\cdot270))=9(\cos(135)+i\sin(135))=9(-\frac{\sqrt2}{2}+i\frac{\sqrt2}2)$
Lastly, note that $270\deg=270+360\deg$ because the extra $360$ is just another spin around the circle, which ends up back at $270\deg$.  However, when you half this 'new' angle, you get a different result, which notably explains why we sometimes have $x^2=a\implies x=\pm\sqrt a$ instead of $x=\sqrt a$.
If you want more insight on how DeMoivre's formula comes about, I recommend graphing $(1+i)^n$ for $n=0,1,2,3,\dots$ and measuring the angle measure and magnitude.  (You can calculate $(1+i)^3=(1+i)(1+i)(1+i)$, for example.  Just foiling)


text:
Q: Count actual bytes written to tomcat HttpServletResponse I need to count the actual bytes written to a HttpServletResponse to make sure that the whole file has been transfered. My naive approach is like this:
            InputStream instream = InputStream instream = new FileInputStream("myfile.zip");
            ServletOutputStream outputStream = res.getOutputStream();

            CountingInputStream countingInputStream = new CountingInputStream(instream);
            IOUtils.copy(countingInputStream, outputStream);

            log.debug("Expected count: " + String.valueOf(contentLength));
            log.debug("getCount: " + countingInputStream.getCount());

            outputStream.close();
            countingInputStream.close();
            instream.close();

While this approach works well on Jetty, Tomcat returns always the full outputstream to be written, even if the client has canceled the download.
Futhermore this has also worked well for years on Tomcat 6. We now had to migrate to Tomcat 7 and experienced this issue.
Is there a way to count the bytes that have been actually sent to the client?

A: There are several things that you have to investigate:

*

*Is the content length header provided? If not, tomcat will cache the entire response

*Make sure the container is configured to support chunked encoding.

*Make sure the client supports chunked encoding (it is not HTTP 1.0)

Another thing is that the tomcat streaming infrastructure suffered a major refactoring with the websockets implementation after version 7.0.27. For more details, take a look here:
http://www.tomcatexpert.com/blog/2012/05/01/how-apache-tomcat-implemented-websocket


text:
Q: HTML Canvas measureText is way off I'm trying to draw a line under a string of characters on an HTML Canvas and the value coming back from measureText is wrong.
Here's the code:

var theCanvas =  document.querySelector('canvas')
var ctx = theCanvas.getContext("2d");
if (ctx) {
    var theString = "Drawing Text on a Canvas";
    ctx.font = "28px Verdana"
    ctx.fillText(theString, 20, 160);
    var textW = ctx.measureText(theString);
    ctx.beginPath();
    ctx.strokeStyle = "black";
    ctx.moveTo(20, 170);
    ctx.lineTo(Math.round(textW.width), 170);
    ctx.stroke();
}
<canvas width="600" height="200"></canvas>

The line doesn't reach all the way to the end of the string.

A: When you set the endpoint of the line, you're forgetting to take the offset into account. Your text starts at x = 20, then it should end at the calculated endpoint + 20
Instead of (x,y) = Math.round(textW.width), 170, then it should be (x,y) = Math.round(textW.width) + 20, 170


text:
Q: Why isn't copy operation implemented in kernel? It's my understanding that most file IO operations are implemented in the kernel, such as CRUD, move or remove. However file copy is not implemented as a kernel level API.
In order to detect a file copy in the kernel one will need to use heuristics approach (discussion on this approach), e.g. as detect file reads, file creates and file writes from the same user with the same file name, but different paths.
Why copy is a user land operation?

A: First, because caring about whether or not two different files have the same content, where one file's content is copied directly from the other, is a user-space concern that has no logical reason to exist inside a kernel.
At best.
Bytes are bytes.
Second, how would the kernel distinguish copying a file between what are just two different file descriptors?  See the man page for sendfile().  Why should the kernel track if the calling user called sendfile() to send the contents of a file to a TCP socket to who-knows-where or to another file?
Third, even if the kernel tracked copying a file, what on God's good Earth would it do with such data?
If you care about such file copy events, set up auditing.


text:
Q: Related to parabola The equation of a parabola is given by:
$y= ax^2 + bx+c$
Why is it that when the coefficient of $x$ i.e. $a$ is positive we get an upward parabola and when it's negative we get a downward parabola?
Also, I saw that increasing the value of $|a|$ narrows the parabola, why?
Lastly, what is the role of $b$ in determining the structure of this parabola?

A: In the quadratic equation "$b$" and "$c$" terms are correlated to an axis translation, thus we can consider the simpler case $$y=ax^2$$ for which is clear the role of "$a$" to determine the sign of $y$.
To clarify the first point suppose to change the coordinates by translation by means of $y=(y+k)$ and $x=(x+h)$ then $$(y+k)=a(x+h)^2$$ $$y=ax^2+2hx+h^2-k$$ which is in the form $$y=ax^2+bx+c$$
I think this way is simpler because you don't need any calculus knowledge.

A: let $$f(x)=ax^2+bx+c$$ then we have $$f'(x)=2ax+b$$ and $$f''(x)=2a$$ if $$a>0$$ then we get a Minimum Point, if $a<0$ then we get a Maximum Point.

A: You're given $y = a x^2 + b x + c $
Start your analysis by completing the square in $x$, as follows:
$\begin{equation}
\begin{split}
 y &= a ( x^2 + \dfrac{b}{a} x ) + c \\
&= a (x + \dfrac{b}{2a} )^2 - a (\dfrac{b}{2a})^2 + c  \\
&= a (x - x_0)^2 + y_0 \\
\end{split}
\end{equation}$
So that,
$ (y - y_0) = a (x - x_0)^2 $
If $a \gt 0 $, then as $x $ gets away from $x_0$ in either direction (left or right),  $y$ will increase above $y_0$, and if we increase $a$ then $y$ will grow faster, thus for the same value of $|x - x_0|$ , $y $ will be higher, thus making the graph look narrower.  The same can be said when $a \lt 0$ where deviations of $x$ from $x_0$ cause $y$ to dip below $y_0$ , and as we make the negative $a$ more negative, the deviation of $y$ from $y_0$ will increase, again making the graph narrower.


text:
Q: Cannot find symbol variable GoogleAuthUtil after updating to Google Play services 9.0.0 Compilation error:
Error:(xx, xx) error: package com.google.android.gms.auth does not exist
Error:(xx, xx) error: cannot find symbol variable GoogleAuthUtil

A: GoogleAuthUtil has moved to the -auth SDK split in the Google Play services 9.0+ SDK.
If you need to access the REST API on Android, include the -auth split in your build.gradle file:
compile 'com.google.android.gms:play-services-auth:9.0.0'

Otherwise, we recommend migrating your app to the Google Sign-In API to incorporate the latest improvements in security and user experience into your app.
Please read the migration guide:
https://developers.google.com/identity/sign-in/android/migration-guide#migrate_from_the_googleauthutil_id_token_flow
And a blogpost for more details:
http://android-developers.blogspot.com/2016/05/improving-security-and-user-experience.html