text:
Q: EF Core: How to best aggregate over related entitiy properties Let's say I have a list Books and a list BooksRead, where I could track if I have read a book, so I have an Entity "Book" and an entity "BookRead".
Everytime I assign a BookRead entity to Book, I want a counter on Book to increment (property: TimesRead).
I have implemented such a scenario in different ways already. One time using a NotMapped property, where I  do something like this:
[NotMapped]
int TimesRead => ReadEntries.Count

But because I use a component, that cannot sort by a property which is not mapped, I switched it to a property that is mapped. Everytime I now add a BookRead entry, or delete one, I also update the corresponding "TimesRead" value.
As there are different places in my applications a user can add such an entry, I had to include this calculation in multiple places, so I wonder if there is better approach.
Also I switched my AverageRating property to mapped, which is even more bothering, as the rating can be set on various pages.
I had a look at calculated columns, but I believe they only work for data that is in the same table.
There is also the INotifyPropertyChanged interface, so I could theoretically work with events. But I'm not to fond of this idea.
What would be a clean approach for this scenario?


text:
Q: Safari keeps crashing after updating to Big Sur. Termination Reason: Namespace ASSERTIOND After I upgraded to MacOS Big Sur, Safari started to crash and the crash logs look very similar.
Sometimes it would crash when I click a link, sometimes it would crash when not doing anything. Often I would notice that Safari crashed when I was away from my computer.
The message is about the same every time:
System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_CRASH (SIGKILL)
Exception Codes:       0x0000000000000000, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Termination Reason:    Namespace ASSERTIOND, Code 0xd00d2bad

Application Specific Information:
Enabled App Extensions:
com.Tab-Suspender.Extension (DZ2G3D39GP) (Version: 39 - Display Version: 2.1.1) Tab Suspender
com.adguard.safari.AdGuard.AdvancedBlocking (TC3Q7MAJXF) (Version: 48 - Display Version: 1.8.10) AdGuard Advanced Blocking
de.APPenzeller.PiPifier.PiPifier-Safari-Extension (AW9CBV6SY7) (Version: 8 - Display Version: 1.2.4) PiPifier Button
com.adguard.safari.AdGuard.Extension (TC3Q7MAJXF) (Version: 48 - Display Version: 1.8.10) AdGuard Safari Icon

Enabled Content Blockers:
com.adguard.safari.AdGuard.BlockerExtension (TC3Q7MAJXF) (Version: 48 - Display Version: 1.8.10) AdGuard General
com.adguard.safari.AdGuard.BlockerSecurity (TC3Q7MAJXF) (Version: 48 - Display Version: 1.8.10) AdGuard Security
com.adguard.safari.AdGuard.BlockerCustom (TC3Q7MAJXF) (Version: 48 - Display Version: 1.8.10) AdGuard Custom
com.adguard.safari.AdGuard.BlockerOther (TC3Q7MAJXF) (Version: 48 - Display Version: 1.8.10) AdGuard Other
com.adguard.safari.AdGuard.BlockerPrivacy (TC3Q7MAJXF) (Version: 48 - Display Version: 1.8.10) AdGuard Privacy
com.adguard.safari.AdGuard.BlockerSocial (TC3Q7MAJXF) (Version: 48 - Display Version: 1.8.10) AdGuard Social

Any ideas how to debug this or what it could be?
Thanks.

A: The problem seems fixed as of MacOS 11.2

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loss of precision when converting from float to double? Let's say I have variables named pi (float) & pi2 (double). I assigned the value of (float)3.14159 to pi and it is 3.14159 exactly.
    float pi;
    pi = (float)3.14159;
    System.out.println(pi);   //3.14159

I typecasted the pi (float) variable into a double and assign the value of pi2 (double) to it. However I get a value that's not exactly 3.14159. I get 3.141590118408203 and it has more significant digits than 3.14159 however it's less precise than 3.14159 because it is farther from 3.14159. On the other hand, if I directly assign pi2 = 3.14159, it is exactly 3.14159.
    double pi2 = (double)pi;
    System.out.println(pi2);   //3.141590118408203
    pi2 = 3.14159;
    System.out.println(pi2);   //3.14159

Why is it that when I change a double into a float and changed it back to double again I get unwanted imprecisions?
The answer to this question isn't clear cut to me: "When you convert a float into a double, there is no loss of information. Every float can be represented exactly as a double." Why is it that when we convert from a float to a double, there are extra non-zero significant digits which lessens the precision rather than adding to it? If what he said is true that no loss of information from float to double, I should be getting 3.141590000000000 and not 3.141590118408203.


text:
Q: how to load "NEXT_PUBLIC" env variables from AWS ELB how to load "NEXT_PUBLIC" env variables from AWS ELB ?
I deployed my project to AWS ELB and set the env variables in settings.
other env Key has loaded like this "process.env.SOMETHING"
but env Key name starts with "NEXT_PUBLIC" cannot loaded in Next.js client side.
I'd appreciate it if you could solve it


text:
Q: Как пробросить события через родительский компонент? (Angular) Имеются несколько компонентов и поле ввода:
Компонент 1 -> компонент 2 -> ... -> input

Необходимо получать события поля ввода в компоненте 1
Я знаю такой способ решения, создавать в каждом компоненте @Output EventEmitter и привязывать эти их к полю:
  /** Передача значения поля */
  @Output() onValueChange: EventEmitter<any> = new EventEmitter<any>();

  /** Передача события blur */
  @Output() onBlur: EventEmitter<any> = new EventEmitter<any>();

  /** Передача события focus*/
  @Output() onFocus: EventEmitter<any> = new EventEmitter<any>();

  <input type="text"
    (input)="this.onValueChange.emit($event)"
    (blur)="this.onBlur.emit($event)"
    (focus)="this.onFocus.emit($event)"/>

Есть ли способ не множить эмиттеры для разных событий? Или существует какой-то более лучший способ это сделать?


text:
Q: Trying to open a Excel file dropped into an S3 bucket I'm trying to open an Excel file dropped into an S3 bucket. I'm not sure how to go about this, however the following code is giving me an error.
s3 = boto3.resource('s3')
bucket=s3.Bucket('mybucket')
rawstream = io.StringIO()
csvwriter = csv.writer(rawstream, delimiter="\t",doublequote=True,
strict=True)

for key in bucket.objects.all():
    if key.key.startswith('dropzone'):
        if 'Air' in key.key:
            wb = xlrd.open_workbook(key.key)
            sheet = wb.sheet_by_index(0)

I'm getting the error:
[Errno 2] No such file or directory:
The full path of the excel file is
s3://mybucket/dropzone/nike_Air.xlsx

A: open_workbook is expecting to open a file on a file system, not an object in an S3 bucket.  You'll need to first download the file to the local file system.  This would be something like:
for key in bucket.objects.all():
    if key.key.startswith('dropzone'):
        if 'Air' in key.key:
            with open('local_file_name', 'wb') as f:
                s3.download_fileobj('mybucket', key.key, f)
            wb = xlrd.open_workbook('local_file_name')
            sheet = wb.sheet_by_index(0)


text:
Q: jquery ajax form submit not working with codeigniter but working otherwise I tried to submit a form using jquery ajax without codeigniter just to understand how ajax works. It worked fine but now I want to do it in codeigniter (since I am developing my application in CI). It's not inserting the values in the database. I do not know how to check where the problem is
This is my form in view :-
<form name="article_form" method="POST" action="">
 <input type="text" name="title" placeholder="Title for your article" />

 <textarea rows="12" name="body" placeholder="Tell your story"></textarea>

 <input type="submit" name="submit_article" id="submit_article" value="Post" />
</form>

This is my jquery ajax script :-

Main is the controller and this the function submit_article :-
public function submit_article()
{
        $article_title = $this->input->post('title');
        $article_body = $this->input->post('body');

    $this->load->model("model_articles");

    if($this->model_articles->article_submit($article_title, $article_body))
    {
        return true;
    }
    else
    {
        return false;
    }
}

This loads the model - model_articles and passes two value namely $article_title and $article_body to the function article_submit(). This is the function in the model that has to insert the values into the database :-
public function article_submit($article_title, $article_body)
    {
        $article_data = array(
            'title' => $article_title,
            'body' => $article_body
            );

        $query_insert_article = $this->db->insert('articles', $article_data);
        if($query_insert_article)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

A: You need to change your controller function and ajax to
try this one

and this one is yours controller
  public function submit_article($article_title,$article_body )
  {

$this->load->model("model_articles");

if($this->model_articles->article_submit($article_title, $article_body))
{
    return true;
}
else
{
    return false;
}

}
hope it will sovle .....

A: You need to change your JavaScript to this:
$('#submit_article').click(function(e) {

    var article_title = $('input[name="title"]').val();
    var article_body = $('textarea[name="body"]').val();

    $.ajax({
        url: '<?php echo base_url(); ?>main/submit_article',
        type: 'POST',
        dataType: 'json',
        data: 'title=' + article_title + '&body=' + article_body,
        success: function(output_string) {
            $('#result_table').append(output_string);
        }
    });

    // Add this if you want to prevent the normal form from sending:
    e.preventDefault();
});


text:
Q: Is it possible to plot a single second period in xts (sub-second series)? I get an error "Error in if (on == "years") { (from #17) : missing value where TRUE/FALSE needed" when trying to plot sub-second series in xts. That is, my xts object only includes observations for the same second:
                         value
2013-04-23 13:09:29.0000 471295
2013-04-23 13:09:29.0000 471296
2013-04-23 13:09:29.0002 471297
2013-04-23 13:09:29.0002 471298
2013-04-23 13:09:29.0004 471299
2013-04-23 13:09:29.0004 471300
2013-04-23 13:09:29.0006 471295

A similar question about this error was already asked in this thread but I'm not clear if there is a workaround to plot sub-second series.

A: R> zzz <- xts(100+cumsum(rnorm(10)), Sys.time() + cumsum(runif(10))/1e3)
R> zzz
                               [,1]
2013-04-30 10:15:15.588007  98.9827
2013-04-30 10:15:15.588615 100.0029
2013-04-30 10:15:15.589559 100.6558
2013-04-30 10:15:15.590063  98.7353
2013-04-30 10:15:15.590466 100.0204
2013-04-30 10:15:15.590787 100.5416
2013-04-30 10:15:15.591345 100.5990
2013-04-30 10:15:15.591624 100.7908
2013-04-30 10:15:15.592415 101.8566
2013-04-30 10:15:15.592915 102.4576
R> plot(zzz)
Error in if (on == "years") { : missing value where TRUE/FALSE needed
R> traceback()
4: endpoints(x, cl, ck)
3: axTicksByTime(x, major.ticks, format.labels = major.format)
2: plot.xts(zzz)
1: plot(zzz)
R>

So the error comes from the axis formatting.  You can either override this, suppress it by now asking for axis to be drawn or just do
R> plot(as.zoo(zzz))

which works fine as your series is univariate anyway.

A: This is essentially the same issue as in this post.  A solution is to specify major.ticks
> set.seed(1)
> zzz <- xts(100+cumsum(rnorm(10)), .POSIXct(0) + cumsum(runif(10))/1e3)
> plot(zzz, major.ticks="seconds")


text:
Q: AWS Glue Crawler for JSONB column in PostgreSQL RDS I've created a crawler that looks at a PostgreSQL 9.6 RDS table with a JSONB column but the crawler identifies the column type as "string". When I then try to create a job that loads data from a JSON file on S3 into the RDS table I get an error.
How can I map a JSON file source to a JSONB target column?

A: It's not quite a direct copy, but an approach that has worked for me is to define the column on the target table as TEXT. After the Glue job populates the field, I then convert it to JSONB. For example:
alter table postgres_table
 alter column column_with_json set data type jsonb using column_with_json::jsonb;

Note the use of the cast for the existing text data. Without that, the alter column would fail.

A: Crawler will identify JSONB column type as "string" but you can try to use Unbox Class in Glue to convert this column to json
let's check the following table in PostgreSQL
create table persons (id integer, person_data jsonb, creation_date timestamp )

There is an example of one record from person table
ID = 1
PERSON_DATA = {
               "firstName": "Sergii",
               "age": 99,
               "email":"Test@test.com"
               }
CREATION_DATE = 2021-04-15 00:18:06

The following code need to be added in Glue
# 1. create dynamic frame from catalog
df_persons = glueContext.create_dynamic_frame.from_catalog(database = "testdb", table_name = "persons", transformation_ctx = "df_persons ")
# 2.in path you need to add your jsonb column name that need to be converted to json
df_persons_json = Unbox.apply(frame = df_persons , path = "person_data", format="json")
# 3. converting from dynamic frame to data frame
datf_persons_json = df_persons_json.toDF()

# 4. after that you can process this column as a json datatype or create dataframe with all necessary columns , each json data element can be added as a separate column in dataframe :
final_df_person = datf_persons_json.select("id","person_data.age","person_data.firstName","creation_date")

You can also check the following link:
https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-Unbox.html


text:
Q: CoreAnimation: failed to allocate 1971232 bytes with my iPad apps? I am using core plot frame work ,i am refresh the view after some time i got the error for
"CoreAnimation: failed to allocate 1971232 bytes".
here am attaching my code for plotting chat
- (void)ipadDraw
{
    CPTGradient *overlayGradient = [[[CPTGradient alloc] init] autorelease];
    overlayGradient.gradientType = CPTGradientTypeRadial;
    overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.0] atPosition:0.0];
    overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.5] atPosition:0.9];
    overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.8] atPosition:1.0];
    CGRect rect=self.view.bounds;

    if(currentOrientation   == UIInterfaceOrientationPortrait || currentOrientation== UIInterfaceOrientationPortraitUpsideDown)
    {

        NSLog(@"%@",NSStringFromCGRect(rect));
        rect.size.width = rect.size.width;
        rect.origin.x=0;
        rect.origin.y-=120;
    }
    else
    {
        NSLog(@"%@",NSStringFromCGRect(rect));

        rect.origin.x=60;
        rect.origin.y+=25;
        rect.size.width=600;
        rect.size.height=700;
    }

    defaultLayerHostingView = [(CPTGraphHostingView *)[CPTGraphHostingView alloc] initWithFrame:rect];
      defaultLayerHostingView.userInteractionEnabled=YES;
    defaultLayerHostingView.exclusiveTouch=YES;
    defaultLayerHostingView.multipleTouchEnabled=YES;
    defaultLayerHostingView.backgroundColor= [UIColor clearColor];
    //defaultLayerHostingView.delegate=self;

    [myScrollView addSubview:defaultLayerHostingView];
    myScrollView.delegate=self;

    CGRect bounds  = defaultLayerHostingView.bounds;
    graph  = [[CPTXYGraph alloc] initWithFrame:[defaultLayerHostingView bounds]];

    defaultLayerHostingView.hostedGraph = graph;

    CPTMutableTextStyle *textStyle  = [CPTMutableTextStyle textStyle];//
    textStyle.color = [CPTColor grayColor];
    textStyle.fontName = @"Helvetica-Bold";
    textStyle.fontSize = bounds.size.height / 20.0f;
    graph.titleTextStyle = textStyle;
    graph.titleDisplacement = CGPointMake(0.0f, bounds.size.height / 18.0f);
    graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
    graph.plotAreaFrame.masksToBorder = NO;

    // Graph padding
    CGFloat boundsPadding = bounds.size.width / 20.0f;
    NSLog(@"the bounds padding is %f",boundsPadding);
    graph.paddingLeft = boundsPadding;
    graph.paddingTop = graph.titleDisplacement.y * 2;
    graph.paddingRight = 32;
    graph.paddingBottom = boundsPadding;
    graph.axisSet = nil;

    // Add pie chart

     CPTPieChart *piePlot = [[CPTPieChart alloc] init];

    piePlot.dataSource = self;
    piePlot.title=@"First";

    piePlot.pieRadius=200;
    piePlot.startAngle = M_PI_4;
    piePlot.sliceDirection = CPTPieDirectionCounterClockwise;
    piePlot.overlayFill = [CPTFill fillWithGradient:overlayGradient];
    piePlot.delegate = self;
    [graph addPlot:piePlot];

    [piePlot release];

    CPTLegend *theLegend = [CPTLegend legendWithGraph:graph];
    theLegend.numberOfColumns = 2;
    theLegend.fill = [CPTFill fillWithColor:(CPTColor *)[UIColor clearColor]];
    theLegend.cornerRadius = 5.0;
    theLegend.swatchSize=CGSizeMake(25, 25);
    theLegend.textStyle=textStyle1;
    graph.legend = theLegend;
    graph.legendAnchor =CPTRectAnchorCenter;

    graph.legendDisplacement=CGPointMake(-10, -275);

    UIButton *ProceedButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [ProceedButton setImage:[UIImage imageNamed:@"details_button_land.png"] forState:UIControlStateNormal];
    [ProceedButton setUserInteractionEnabled:YES];

    [myScrollView  addSubview:claimsProceedButton];
    ProceedButton.tag=0;
    if(currentOrientation   == UIInterfaceOrientationPortrait || currentOrientation== UIInterfaceOrientationPortraitUpsideDown)
    {

        [ProceedButton setFrame:CGRectMake((myScrollView.frame.size.width-300)/2, 720, 300.00 , 51.00)];
    }
    else{
        [ProceedButton setFrame:CGRectMake((myScrollView.frame.size.width-300)/2, 690, 300.00 , 51.00)];
    }

    rect=self.view.bounds;
    [ProceedButton addTarget:self action:@selector(ProceedDetail:) forControlEvents:UIControlEventTouchUpInside];
    UILabel *viewDetails = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300.00, 51.00)];
    [ProceedButton addSubview:viewDetails];
    [viewDetails setText:@"View Chart Data"];
    [viewDetails setFont:[UIFont boldSystemFontOfSize:13]];
    [viewDetails setBackgroundColor:[UIColor clearColor]];
    [viewDetails setTextAlignment:UITextAlignmentCenter];

    NSLog(@"%@",NSStringFromCGRect(rect));

    rect=self.view.bounds;

    defaultLayerHostingView=nil;

}

A: You can autorelease while you initialize the object

A: You can replace the existing code to this
    - (void)ipadDraw

{
CPTGradient *overlayGradient = [[[CPTGradient alloc] init] autorelease];
overlayGradient.gradientType = CPTGradientTypeRadial;
overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.0] atPosition:0.0];
overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor]
overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.5] atPosition:0.9];
enter code here   overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.8] atPosition:1.0];

CGRect rect=self.view.bounds;if(currentOrientation==UIInterfaceOrientationPortrait || currentOrientation== UIInterfaceOrientationPortraitUpsideDown)
  { NSLog(@"%@",NSStringFromCGRect(rect));

rect.size.width = rect.size.width;
rect.origin.x=0;
rect.origin.y-=120;
}

else {
 NSLog(@"%@",NSStringFromCGRect(rect));
rect.origin.x=60;
rect.origin.y+=25;
rect.size.width=600;
rect.size.height=700;
}

defaultLayerHostingView = [[(CPTGraphHostingView *)[CPTGraphHostingView alloc] initWithFrame:rect]autorelease];
defaultLayerHostingView.userInteractionEnabled=YES;
defaultLayerHostingView.exclusiveTouch=YES;
defaultLayerHostingView.multipleTouchEnabled=YES;
defaultLayerHostingView.backgroundColor= [UIColor clearColor];
[myScrollView addSubview:defaultLayerHostingView];
myScrollView.delegate=self;
CGRect bounds  = defaultLayerHostingView.bounds;
graph  = [[[CPTXYGraph alloc] initWithFrame:[defaultLayerHostingView bounds]]autorlease];
defaultLayerHostingView.hostedGraph = graph;

CPTMutableTextStyle *textStyle  = [CPTMutableTextStyle textStyle];//
textStyle.color = [CPTColor grayColor];
textStyle.fontName = @"Helvetica-Bold";
textStyle.fontSize = bounds.size.height / 20.0f;
graph.titleTextStyle = textStyle;
graph.titleDisplacement = CGPointMake(0.0f, bounds.size.height / 18.0f);
graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
graph.plotAreaFrame.masksToBorder = NO;

// Graph padding
CGFloat boundsPadding = bounds.size.width / 20.0f;
NSLog(@"the bounds padding is %f",boundsPadding);
graph.paddingLeft = boundsPadding;
graph.paddingTop = graph.titleDisplacement.y * 2;
graph.paddingRight = 32;
graph.paddingBottom = boundsPadding;
graph.axisSet = nil;

// Add pie chart

 CPTPieChart *piePlot = [[[CPTPieChart alloc] init]autorelease];

piePlot.dataSource = self;
piePlot.title=@"First";

piePlot.pieRadius=200;
piePlot.startAngle = M_PI_4;
piePlot.sliceDirection = CPTPieDirectionCounterClockwise;
piePlot.overlayFill = [CPTFill fillWithGradient:overlayGradient];
piePlot.delegate = self;
[graph addPlot:piePlot];

[piePlot release];

CPTLegend *theLegend = [CPTLegend legendWithGraph:graph]autorlease];
theLegend.numberOfColumns = 2;
theLegend.fill = [CPTFill fillWithColor:(CPTColor *)[UIColor clearColor]];
theLegend.cornerRadius = 5.0;
theLegend.swatchSize=CGSizeMake(25, 25);
theLegend.textStyle=textStyle1;
graph.legend = theLegend;
graph.legendAnchor =CPTRectAnchorCenter;

graph.legendDisplacement=CGPointMake(-10, -275);

UIButton *ProceedButton = [[UIButton buttonWithType:UIButtonTypeCustom];
[ProceedButton setImage:[UIImage imageNamed:@"details_button_land.png"] forState:UIControlStateNormal]autorelease];
[ProceedButton setUserInteractionEnabled:YES];

[myScrollView  addSubview:claimsProceedButton];
ProceedButton.tag=0;
if(currentOrientation   == UIInterfaceOrientationPortrait || currentOrientation== UIInterfaceOrientationPortraitUpsideDown)
{

    [ProceedButton setFrame:CGRectMake((myScrollView.frame.size.width-300)/2, 720, 300.00 , 51.00)];
}
else{
    [ProceedButton setFrame:CGRectMake((myScrollView.frame.size.width-300)/2, 690, 300.00 , 51.00)];
}

rect=self.view.bounds;
[ProceedButton addTarget:self action:@selector(ProceedDetail:) forControlEvents:UIControlEventTouchUpInside];
UILabel *viewDetails = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300.00, 51.00)];
[ProceedButton addSubview:viewDetails];
[viewDetails setText:@"View Chart Data"];
[viewDetails setFont:[UIFont boldSystemFontOfSize:13]];
[viewDetails setBackgroundColor:[UIColor clearColor]];
[viewDetails setTextAlignment:UITextAlignmentCenter];

NSLog(@"%@",NSStringFromCGRect(rect));

rect=self.view.bounds;

defaultLayerHostingView=nil;

}


text:
Q: Cant Migrate to bigquery because bigquery column names allow only english characters Bigquery column names (fields) can only contain English letters, numbers, and underscores.
I am using python and I want to create a script to migrate my data from Postgres to Bigquery and the Postgres tables have many non-english column names.
I will probably need to encode the column names to some format that Bigquery accepts, but I will need the ability to later decode it back to the original.
what is the best way to do this?

A: You can encode the column names to something like base64 and replace the +=/ characters to some kind of place holder.
If you don't care about fields length you can encode to base32 (its about 20% longer then base64 but don't use '+' or '/' and the '=' is used only for padding so you can discard it and it wont affect the string)
Except that you can make small conversion table for each non English character in your language to some combination in English chars, this will work only if you have small amount of non-english characters.


text:
Q: How to remove extra header from excel export from GI When I export GI data to excel, it does export some header info such as GI name, filter, etc. Where as if I export any data from grid such as SO Line items, it does not export any header info. Does anyone has any idea how can I get rid of those extra header info when I export it to excel from GI. Or it would have been better if there is any option (check/uncheck) whether one needs these header or not while export GI data.

A: No option is available to export GI to Excel without header because of the DashboardType attribute decorating PXGenericInqGrph class (PXGenericInqGrph is used to open every GI in the application):
[DashboardType(PXGenericInqGrph.DASHBOARD_TYPE, PXGenericInqGrph.DASHBOARD_CHART_TYPE)]
public partial class PXGenericInqGrph : PXGraph<PXGenericInqGrph>
{
    ...
}

As a workaround you can create a custom inquiry screen, that will not have DashboardTypeAttribute.
For additional information, you might also check Can I add a custom header to exported Excel file? thread


text:
Q: NHibernate GenericAdoException was unhandled could not execute query I have an exception "GenericAdoException was unhandled" could not execute query while i was trying to do the nhibernate example on this line:
var users = session.CreateCriteria<User>().List<User>();

Inner exception is: incorrect syntax near 'User'
My Main method on Program.cs:
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var cfg = new Configuration();
            cfg.DataBaseIntegration(x =>
            {
                x.ConnectionString = "Server=.;database=NHibernateTryOutDB;uid=sa;pwd=Hasar2012";
                x.Driver<SqlClientDriver>();
                x.Dialect<MsSql2012Dialect>();
            });
            cfg.AddAssembly(Assembly.GetExecutingAssembly());
            var sessionFactory = cfg.BuildSessionFactory();
            using (var session = sessionFactory.OpenSession())
            using (var tx = session.BeginTransaction())
            {
                var users = session.CreateCriteria<User>().List<User>();
                foreach (User item in users)
                {
                    Console.WriteLine("{0} {1}", item.Name, item.Surname);
                }
                tx.Commit();
            }
            Console.WriteLine("Press <Enter> to exit...");
            Console.ReadLine();
        }
    }
}

I ve a table named Users:
USE [NHibernateTryOutDB]
GO

/****** Object:  Table [dbo].[Users]    Script Date: 12/10/2013 16:04:12 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Users](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NULL,
    [Surname] [nvarchar](50) NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

My class names User.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class User
    {
        public virtual int ID { get; set; }
        public virtual string Name { get; set; }
        public virtual string Surname { get; set; }
    }
}

My .hbm.xm file that is User.hbm.xml:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="ConsoleApplication2"
                   namespace="ConsoleApplication2">
  <class name="User">
    <id name="ID">
      <generator class="native"/>
    </id>
    <property name="Name"/>
    <property name="Surname"/>
  </class>
</hibernate-mapping>

How can i solve this issue?

A: User is a reserved word in sql, you need to add [] around user or choose a different name for your object. Besides that your table name is Users, instead of user from your mapping.

A: First, check connecting database name, use correct database name in connection string.


text:
Q: Problem with exported members 'StatSyncFn' There is this error on my build, i dont no from where and why, is coming like this...
Error: node_modules/webpack-dev-middleware/types/index.d.ts:204:27 - error TS2694: Namespace '"fs"' has no exported member 'StatSyncFn'.

 statSync?: import("fs").StatSyncFn;

I have try to re-install webpack, but and don't know what, i will doing for resume this error...
Having some solutions or ideas for ? Please,
Thank all us for you help...

A: Did you check this and this.
There are 2 possible reasons:

*

*Haven't updated node to latest (npm@7.5.4 => fs-extra@8.0.1) version

*Messed-up with destination locations.

**most probably updating npm and fs-extra would solve


text:
Q: PHP Foreach loop take an additional step forward from within the loop Basically I have a foreach loop in PHP and I want to:
foreach( $x as $y => $z )
    // Do some stuff
    // Get the next values of y,z in the loop
    // Do some more stuff

A: It's not practical to do in a foreach.
For non-associative arrays, use for:
for ($x = 0; $x < count($y); $x++)
 {
   echo $y[$x];  // The current element

   if (array_key_exists($x+1, $y))
    echo $y[$x+1]; // The next element

   if (array_key_exists($x+2, $y))
    echo $y[$x+2]; // The element after next

 }

For associative arrays, it's a bit more tricky. This should work:
$keys = array_keys($y); // Get all the keys of $y as an array

for ($x = 0; $x < count($keys); $x++)
 {
   echo $y[$keys[$x]];  // The current element

   if (array_key_exists($x+1, $keys))
    echo $y[$keys[$x+1]]; // The next element

   if (array_key_exists($x+2, $keys))
    echo $y[$keys[$x+2]]; // The element after next

 }

When accessing one of the next elements, make sure though that they exist!

A: use the continue keyword to skip the rest of this loop and jump back to the start.

A: Not sure if you simply want to do just "some stuff" with the first element, only "some more stuff" with the last element, and both "some stuff" and "some more stuff" with every other element. Or if you want to do "some stuff" with the first, third, fifth elements, and "some more stuff" with the second, fouth, sixth elements, etc.
$i = 0;
foreach( $x as $y => $z )
    if (($i % 2) == 0) {
       // Do some stuff
   } else {
       // Do some more stuff
   }
   $i++;
}

A: Ok, following up on my comment on Pekka's solution, here is one that takes into account the fact that the array might be associative. It's not pretty, but it works. Suggestions on how to improve this are welcomed!
<?php
    $y = array(
        '1'=>'Hello ',
        '3'=>'World ',
        '5'=>'Break? ',
        '9'=>'Yup. '
    );

    $keys = array_keys($y);
    $count = count($y);

    for ($i = 0; $i < $count; $i++) {
        // Current element
        $index = $keys[$i];
        echo "Current: ".$y[$index];  // The current element

        if (array_key_exists($i+1, $keys)) {
            $index2 = $keys[$i+1];
            echo "Next: ".$y[$index2]; // The next element
        }

       if (array_key_exists($i+2, $keys)) {
            $index3 = $keys[$i+2];
            echo "Nextnext: ".$y[$index3]; // The element after next
        }
     }
?>

A: try something like...
for ($i=0, $i<count($x); $i++)
{
    // do stuff with $x[$i]
    // do stuff with $x[$i+1], unless you're on the last element of the array
}

A: reset($arr);
while(list($firstindex,$firstvalue) = each($arr)){
   list($secondindex,$secondvalue) = each($arr);
   //do something with first & second.
}


text:
Q: Non-explicit use of Weirestrass Extreme Value Theorem Consider the following well known theorems due to Weierstrass. If $f:[a,b]\to\mathbb{R}$ is continuous on its domain, then

*

*$f$ is bounded from above and from below.

*$f$ attains its maximum and minimum on the interval, i.e. - There exists $x_{\min},x_{\max}\in[a,b]$ such that for all $x\in [a,b]$ one has that $$ f(x_{\min} ) \leq f(x) \leq f(x_{\max}) \, .$$

My Question: Most of the examples I've seen for using these theorems are very explicit - show that the function $f$ under some conditions has maximum/minmum. I'm looking for an example in which we need to use either of these theorems, but we are not asked to do it explicitly.
In terms of prerequisites I can only rely on these theorems, basic continuity definitions and the mean value theorem.
Thanks


text:
Q: Drag and Drop between trees and within one of the trees I have two trees in Extjs 4.1 with the drag and drop plugin enabled.  The user can drag and drop between these trees.  Here is the only relevant configurations for these trees in this situation is the viewConfig:
tree 1:
viewConfig:{
            plugins: [
                new PmProjectManagement.viewEdit.AvailableCriteriaTreeViewDragDrop({
                    allowContainerDrop: true,
                    allowParentInsert: false,
                    expandDelay: 30000,
                    dropGroup: "secondGridDDGroup",
                    dragGroup: "firstGridDDGroup"
                })
            ]
        }

tree 2:
viewConfig:{
            plugins: [
                new PmProjectManagement.viewEdit.ViewConfigTreeViewDragDrop({
                    allowContainerDrop: true,
                    allowParentInsert: false,
                    expandDelay: 30000,
                    dropGroup: "firstGridDDGroup",
                    dragGroup: "secondGridDDGroup"
                })
            ]
        }

Right now I can drag and drop from one tree to another just fine, but what I really want is to be able to drag from tree 1 to tree 2, from tree 2 to tree 1, AND within tree 2.  I am having trouble with the draggin around in tree 2 because the ddGroup is set to the other tree.  I also need tree 1 to not be able to drag around within it.  Does anyone have a suggestion as to go about this?  The only solution I can think of involves using overrides on the isValidDropPoint function and removing the ddGroup qualifiers, but I would really like a more elegant approach to this.

A: ddGroup should be the same for both trees.
In ext 4.2 you have the nodedragover event notifying the Ext.tree.View during dragging.
This event is going from the Ext.tree.ViewDropZone#isValidDropPoint.
So in the ext 4.2 you just need to processing this event and decide drop is allowed or not, event firing gives you a lot of information, so you can found out that is dragging and which tree is used the event description.
dragData parameter contains "view" property from which you can take the tree - drop destination tree, like dragData.view.panel.
In ext 4.1 you are right there was no the view notifications, guys from sencha even placed a todo marker that this must be implemented in the new version. And yes you can extend the Ext.tree.ViewDropZone and firing kind of event to notify the view about the dragging over (something similar to 4.2). Also you need to extend the Ext.tree.plugin.TreeViewDragDrop plugin to inject there your's just extended Ext.tree.ViewDropZone.
It is just overriding onViewRender method of the plugin and use your's just extended drop zone.
Then use new plugin. Another way just override the Ext.tree.ViewDropZone to be applied everywhere in the application.
IMHO you do no need change the dd groups, all you need is just processing the nodedragover in 4.2 of some kinda of implementation.


text:
Q: Comparing two passwords PHP Here's my code it seems to work fine, how ever it doesn't look right.
I know I'm vulnerable to injections. Just want to know if the this
is the best way of comparing two passwords ?
if (empty($_POST['password'])) {
    $errors[] = "Please enter a password";
} else {
    if ($_POST['password'] != $_POST['password1']) {
        $errors[] = "Your password did not match the confirmed password";
    } else {
        $p = $_POST['password'];
    }
}

A: Your code is fine, I would just write it a bit differently:
if (empty($_POST['password'])) {
   $errors[] = "Please enter a password";
} elseif($_POST['password'] !== $_POST['password1']) {
   $errors[] = "Your password did not match the confirmed password";
} else {
   $p = $_POST['password'];
}

A: I suggest You must check both $_POST['password'] and $_POST['password1'] at very beginning.
if (!empty($_POST['password']) && !empty($_POST['password1'])) {
        if (strcmp($_POST['password'], $_POST['password1']) === 0) {
            $p = $_POST['password'];
        } else {
            $errors[] = "Your password did not match the confirmed password";
        }
    } else {
        $errors[] = "Please enter a password";
    }


text:
Q: How to create mysql database with sequelize (nodejs) I am trying to automate the process of creating db and tables as much as possible. Is it possible to create database via sequelize? Can I make a connection string that connects just to server, not to db directly?

A: Short Answer: Sure you can!
Here's how I got it done:
//create the sequelize instance, omitting the database-name arg
const sequelize = new Sequelize("", "<db_user>", "<db_password>", {
  dialect: "<dialect>"
});

return sequelize.query("CREATE DATABASE `<database_name>`;").then(data
=> {
  // code to run after successful creation.
});

P.S. Where to place code would depend on your need. Inside an initial migration file worked for me.

A: Here are main steps to populate mySql tables with sequelize and sequelize-fixtures modules:
step 1: creating model
module.exports = function(sequelize, Sequelize) {
// Sequelize user model is initialized earlier as User
const User = sequelize.define('user', {
    id          :       { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
    firstname   :       { type: Sequelize.STRING },
    lastname    :       { type: Sequelize.STRING },
    email       :       { type: Sequelize.STRING, validate: {isEmail:true} },
    password    :       { type: Sequelize.STRING },
});

// User.drop();
return User;
}

Step 2: creating a config file to store database configs
{
  "development": {

    "username": "root",
    "password": null,
    "database": "hotsausemedia",
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "test": {
    "username": "",
    "password": null,
    "database": "hotsausemedia",
    "host": "",
    "dialect": "mysql"
  },
  "production": {
    "username": "",
    "password": null,
    "database": "hotsausemedia",
    "host": "127.0.0.1",
    "dialect": "mysql"
  }
}

step 3: creating sequelize-fixture to populate tables. here is an example of a json file to use for populating data
[
    {
        "model": "product",
        "keys": ["id"],
        "data": {
            "id": 1,
            "name": "Product #1",
            "src": "./assets/img/products/01.jpg",
            "price": 9.99,
            "desc": "Product description..."
        }
    },
    {
        "model": "product",
        "keys": ["id"],
        "data": {
            "id": 2,
            "name": "Product #2",
            "src": "./assets/img/products/02.jpg",
            "price": 19.99,
            "desc": "Product description..."
        }
    },
    ...

]

step 4: connecting to database and populating tables
models.sequelize.sync().then(() => {
    console.log('You are connected to the database successfully.');
    sequelize_fixtures.loadFile('./fixtures/*.json', models).then(() =>{
        console.log("database is updated!");
   });
   }).catch((err) => {
       console.log(err,"Some problems with database connection!!!");
});

A: Despite this question been answered a while ago, please take a look at this other answer (mine) from a very similar question (perhaps a duplicate?) that definitely applies here: https://stackoverflow.com/a/62413891/1971120
The idea is to use Sequelize Migrations, where you let Sequelize handle the migrations using files with this format:
module.exports = {
  up: (queryInterface, Sequelize) => {
    // logic for transforming into the new state
  },
  down: (queryInterface, Sequelize) => {
    // logic for reverting the changes
  }

Yeah, it handles rollbacks too. Making this process very easily to automate.

A: None of the solutions worked for me for sequelize db and model sync. Taking inspiration from osifo's answer, I solved it using beforeConnect hook of sequelize as below:
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];

const { host, port, username, password } = config;

# create sequelize instance without providing db name in config
sequelize = new Sequelize('', username, password, config);

sequelize.beforeConnect(async (config) => {
     const connection = await mysql.createConnection({ host: host, port: port, user: username, password: password });
     await connection.query(`CREATE DATABASE IF NOT EXISTS \`${process.env.DB_NAME}\`;`);
     config.database = process.env.DB_NAME;
});

Config.json file contains configurations for different dbs like
{
  "development": {
    "username": "root",
    "password": "init@123",
    "host": "mysqldb",
    "dialect": "mysql"
  },
  "test": {
    "username": "root",
    "password": null,
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "production": {
    "username": "root",
    "password": null,
    "host": "127.0.0.1",
    "dialect": "mysql",
  }
}

Database name is provided after db connection and creation(if required) in sequelize beforeConnect hook


text:
Q: Linking to a Specific Comment I posted this question.
And wanted to provide a link to a comment. I can find a solution to provide a link to a specific answer.
Apart from going to the user's profile and their activity, finding the comment and obtaining a link from there,
I there an easier way to a specific comment?

A: Sure, the comment time stamp is a link:

When in doubt, hover! :)

A: Yes, click the 'Date' stamp against the comment and you'll get the anchor link for that comment that you can use.
For example - Reduce close vote expiration restrictions


text:
Q: Converting code from c to assemly I cant convert a c code to assembly code properly
the code is
    #include <stdio.h>      /* Standard Library of Input and Output */
   #include <complex.h>    /* Standard Library of Complex Numbers */

 double complex power(double complex value, int power){
     double complex result=1;
    for (int i=0;i<power;i++){
        result  = result * value;
    }
    return result;
 }

  double complex function(double order,double complex * array,double complex value) // a function that calculates f(x)
  {
    double complex result=0;
     for (int i = order ; i >= 0 ; i--){
      result = result + array[i]*(power(value,i));
  }
   //printf("the value of f(x) is:  = %.10f %+.10fi\n",creal(result), cimag(result));
  return result;
 }
double complex derivefunction(double order,double complex * array,double complex value,double complex * darray){
  for (int i = order-1 ; i >= 0 ; i--){
       darray[i] = array[i+1]*(i+1);
}
return function(order-1,darray,value);

  }
   double abs(double m){//absolute
    if (m<0)
        return -m;
    return m;
  }

  int main(void) {

   double tol,order;
   double arrayr[100];//assuming the maximum order is 0
   double arrayi[100];
   double complex array[100];

    printf("Enter the tolarence:\n");
    scanf("%lf", &tol);
    printf("the toleracnce is: %.10f\n",tol);

printf("Enter the order\n");
scanf("%lf", &order);
printf("the order is: %lf\n",order);

for (int i = order ; i >= 0 ; i--){
    printf("Enter the %d coeficience\n",i);
    scanf("%lf", &(arrayr[i]));//taking the real number
    scanf("%lf", &(arrayi[i]));// taking the imaginary number
    array[i] = arrayr[i] + arrayi[i] * I;//summing the complex number
    printf("The %d coeficience is  = %.2f %+.2fi\n",i ,creal(array[i]), cimag(array[i]));
}

double initialr, initiali;
double complex initial;
printf("Enter the initial value of z(the guss) \n");
scanf("%lf", &initialr);//taking the real number
scanf("%lf", &initiali);// taking the imaginary number
initial = initialr + initiali*I;

printf("The initial is  = %.2f %+.2fi\n", creal(initial), cimag(initial));
double complex result1 = function(order,array,initial);

     if (order > 0) {

    double complex darray[sizeof(array)];
    double complex result2 = derivefunction(order,array,initial,darray);

    //now the newton-rashford method
      double complex m = result1/result2;//the initial
    while (abs((double)(m)) >= tol)//if it is in the range
  {

        m = function(order,array,initial) / derivefunction(order,array,initial,darray);//f(x)/f'(x)
        initial = initial - m;
        //printf("The initial is  = %.10f %+.10fi\n", creal(initial), cimag(initial));
  }
  printf("The root is  = %.10f %+.10fi\n", creal(initial), cimag(initial));
 }

return 0;

  }

I used the command gcc -S -O main.c to create an assembly file called main.s
but when I try to compile the assembly file I get many errors
    nasm -g -f elf64 -w+all -o main.o main.s
    main.s:1: error: attempt to define a local label before any non-local labels
    main.s:1: error: parser: instruction expected
    main.s:2: error: attempt to define a local label before any non-local labels

and so on.. I think it relates to the fact that I use complex number but I am not sure how to fix this.


text:
Q: Datetime from MySQL in Kafka is converted to wrong timestamp (for dates less than year 0100) Why datetime from MySQL in Kafka is converted to wrong timestamp (for dates less than year 0100) ?
I have a table with a datetime column, where I insert the value 0078-10-15 10:00:00.0000000, timestamp = 277293600000 appears in kafka for this row (human date from online timestamp converter is 15 10 1978, 10:00:00) .
The MySQL documentation says:

"Dates containing two-digit year values   are ambiguous because the
century is unknown. MySQL interprets two-digit year values   using
these rules:
Year values   in the range 70-99 become 1970-1999.
Year values   in the range 00-69 become 2000-2069."

And it really does work like this, but the date in the database looks like this: 0078-10-15 10:00:00.0000000, i.e. century is specified.
For years greater than 0099 everything works fine and the timestamp is -many digits
Debezium connector configuration:
{
"name": "source-param-datetime",
"config": {
        "connector.class" : "io.debezium.connector.mysql.MySqlConnector",

        "database.hostname": "hostname",
        "database.port": "3306",
        "database.user": "user",
        "database.password": "password",
        "database.server.id" : "12",
        "database.server.name": "erp_pd",
        "database.include.list": "bgcrm_v21",

        "table.include.list": "bgcrm_v21.param_datetime",

        "database.history.kafka.bootstrap.servers": "server",
        "database.history.kafka.topic": "dbhistory.erp.param_datetime",
        "include.schema.changes": "false",
        "snapshot.mode": "schema_only",
        "snapshot.locking.mode" : "minimal_percona",

        "transforms": "unwrap",

        "transforms.unwrap.type": "io.debezium.transforms.ExtractNewRecordState",
        "transforms.unwrap.drop.tombstones" : "false",

        "key.converter":"io.confluent.connect.avro.AvroConverter",
        "key.converter.schema.registry.url":"http://localhost:8081",

        "value.converter":"io.confluent.connect.avro.AvroConverter",
        "value.converter.schema.registry.url":"http://localhost:8081",

        "name": "source-param-datetime"
        }
}

Thought the problem was
time.precision.mode and try different values for this setting but it didn't help.

A: "enable.time.adjuster" : "false"
https://debezium.io/documentation/reference/stable/connectors/mysql.html#mysql-property-enable-time-adjuster


text:
Q: Angular 11 'error NG2007: Class is using Angular features but is not decorated.' But the class is Decorated In my angular workspace I have several libraries and 2 apps.
I have a Component class "LogoutComponent" in my library.  I compiled it using ng build mms-common --watch.  I have no errors.
The app I am currently working on is called "my"  When I use ng serve my, I get an

Error: dist/mms-common/fesm2015/mms-common.js:99:7 - error NG2007: Class is using Angular features but is not decorated. Please add an explicit Angular decorator.
99 class LogoutComponent
~~~~~~~~~~~~~~~

But I have the component decorated.  Not only that but I am not using the Logout Component at this time.  I have tried the following:

*

*deleted the dist/mms-common directory

*compiled the mms-common directory using --prod flag

*deleted the dist/my directory

*deleted and recreated the LogoutComponent

*removing all of the code from the LogoutComponent excluding the decorator and basic class call

*compiled the my app with and without --prod flag

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { User } from '../models/user';
import { UserService } from '../services/user.service';

@Component({
  selector: 'lib-logout',
  templateUrl: './logout.component.html',
  styleUrls: ['./logout.component.css']
})
export class LogoutComponent implements OnInit {

  constructor(
    private router: Router,
    private userService: UserService
  ) { }

  ngOnInit(): void {
    this.userService.logout();
    this.userService.currentUser = new User();
    this.router.navigate(['']);
  }

}

My library module is
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { LogoutComponent } from './logout/logout.component';

@NgModule({
  declarations: [LogoutComponent],
  imports: [
    RouterModule
  ],
  exports: [LogoutComponent]
})
export class MMSCommonModule { }

my public-api is
export * from './lib/models/user';
export * from './lib/services/user.service';
export * from './lib/mms-common.module';
export * from './lib/logout/logout.component'

A: I had a similar situation when running ng serve. I was getting that error for 3rd party libraries and for all my Angular components even though they were decorated.
The problem for me was that I was targeting es6. I changed my tsconfig.json to target es5:
{
  "compileOnSave": true,
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "enableIvy": true,
  },
  "compilerOptions": {
    "lib": ["es6", "dom"],
    "module": "es6",
    "target": "es5", // <-- CHANGE THIS FROM es6 to es5
    ...
  },
  ...
}

A: So the answer was in the "my" project.  I had created a component and was using one of the services exported by the mms-common library.  But the import statement on the new component was:
import { UserService } from 'dist/mms-common/fesm2015/mms-common';

The proper form of the import should have been
import { UserService } from 'mms-common';

The problem itself was created by visual studio code auto complete.
This does solve the problem but why did the compiler did not point to the new component.


text:
Q: Sending RAW data to IP (TCP/IP) I'm trying to learn some WinSock and stuck in place. I want to sent RAW packet (256 bytes) to another device in the network. This device is just a listener. I'm using VC++ 2010 and WinSock.
So there a code I'm working on:
// winsock.cpp : main project file.

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <string.h>
//#include <WinSock2.h>
#define WIN32_LEAN_AND_MEAN

using namespace System;

int main(array<System::String ^> ^args)
{

WORD RequiredVersion;
    WSADATA WData;
    SOCKET s;
    struct sockaddr_in addr;
    long val;
    struct hostent *he;
    char host[128];
    int port;

    printf("HOST: ");
    scanf("%s",host);
    printf("PORT: ");
    scanf("%d",&port);
    printf("Data to send: ");
    scanf("%d",&val);

    RequiredVersion = MAKEWORD(2, 0);

    if (WSAStartup(RequiredVersion, &WData) != 0) {
    printf("ERROR! WinSock2\n");
    return 1;
    }

    //he = gethostbyaddr((char *) host, 4, AF_INET);
    he = gethostbyname(host);
    if (he == NULL) {
    printf("host not found.\n");
    system("PAUSE");
    return 1;
    }

    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = *((unsigned long*) he->h_addr);

    s = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
            //SOCK_RAW, IPPROTO_TCP);

    connect(s, (struct sockaddr*) &addr, sizeof(addr));
    printf("SENDING %d TO %s\n",val,inet_ntoa(addr.sin_addr));
    val = htonl(val);

    send(s, (char*) &val, sizeof(long), 0);
    printf("WAITING FOR RESPONSE...\n");
    recv(s, (char*) &val, sizeof(long), 0);
    val = ntohl(val);
    printf("RE: %d\n", val);
    closesocket(s);

    WSACleanup();
    system("PAUSE");
    return 0;

}

The problems I've got:

*

*I'm probably not creating a real RAW socket.

*I think I should not use 'gethostbyname', but I don't know how to replace it for an const. IP

*My program doesn't sent any data over LAN. I'm using WireShark to check this. I think this can be a problem with 'gethostbyname'

Any tips? I really appreciate any help you can provide!


text:
Q: Editing pythonpath for every script in a project So I structure almost all of my projects like this:
root/
|- scripts/
|- src/
|- etc. ...
I put runnable scripts in scripts/ and importable modules in src/, and by convention run every script from the root directory (so I always stay in root, then type 'python scripts/whatever')
In order to be able to import code from src/, I've decided to start every script with this:
import sys
import os
# use this to make sure we always have the dir we ran from in path
sys.path.append(os.getcwd())

To make sure root/ is always in the path for scripts being run from root.
My question is: is this considered bad style?  I like my conventions of always running scripts from the root directory, and keeping my scripts separate from my modules, but it seems like a weird policy to always edit the path variable for every script I write.
If this is considered bad style, could you provide alternative recommendations?  Either different ways for me to keep my existing conventions or recommendations for different ways to structure projects would be great!
Thanks!

A: My recommendation is to use:
root/$ python -m scripts.whatever

With the -m you use the . notation rather than the file path and you won't need to setup path code in each of the scripts because the -m tells Python to start looking for imports in the directory where you called Python.
If your file structure also happens to be installed using setup.py and may be found within the site_packages there are some other things to consider:

*

*If you call -m from the root of the directory structure (as I've shown above) it will call the code found in your directories

*If you call -m from anywhere else, it will find the installed code from sys.path and call that

This can be a subtle gotcha if you happen to be running an interpreter that has your package installed and you are trying to make changes to your scripts locally and can't figure out why your changes aren't there (this happened to a coworker of mine who wasn't using virtual environments).


text:
Q: How can my player collides with the border of the canvas? The Player should collide with the border of the canvas, but I don't know how to do it.
from tkinter import *
import time

the window
tk = Tk()
tk.title("Game")
tk.geometry("500x500")
tk.wm_attributes("-topmost", 1)
tk.resizable(0, 0)

the canvas
canvas = Canvas(tk, width=500, height=500, bg="#FFD700")
canvas.pack()
canvasx = canvas.winfo_width()
canvasy = canvas.winfo_height()

player = canvas.create_rectangle(240, 240, 260, 260, fill="blue",
outline="dark blue")

the Player class
class Player:
    def __init__(self, event, canvas):
        def move(event):
            if event.keysym == "Up" or event.keysym == "w":
                canvas.move(1, 0, -5)
            elif event.keysym == "Down" or event.keysym == "s":
                canvas.move(1, 0, 5)
            elif event.keysym == "Right" or event.keysym == "d":
                canvas.move(1, 5, 0)
            else:
                canvas.move(1, -5, 0)

what should I write in this function?
        def hit_border():
            pass

        canvas.bind_all("<KeyPress-Up>", move)
        canvas.bind_all("<KeyPress-w>", move)
        canvas.bind_all("<KeyPress-Down>", move)
        canvas.bind_all("<KeyPress-s>", move)
        canvas.bind_all("<KeyPress-Right>", move)
        canvas.bind_all("<KeyPress-d>", move)
        canvas.bind_all("<KeyPress-Left>", move)
        canvas.bind_all("<KeyPress-a>", move)

here is the loop that makes the everything work
while True:
    player = Player(canvas, canvas)
    tk.update()
    time.sleep(0.001)


text:
Q: Remove unrecognised staticContent mimeMap entries On a default installation of IIS there are approximately 350 <mimeMap /> elements specified in the <staticContent> section. Some file extensions seem alien to me e.g. .sv4cpio, .cpio, .onetoc2.
I was wondering if it would be worth removing file extensions that I know I will never be serving? Is there a benefit to doing so?

A: Yes, and it's recommended as a defence-in-depth security measure.
If IIS doesn't have an extension defined, the staticfilehandler won't serve it (it'll 404 instead).


text:
Q: how to run the same integral for different values of constants? I want to run an integral for different values of "e" and "m" and put the results in a list.
m =[0.14, 0.14, 0.14, 1.30, 4.50]
e = [2/3, -1/3, -1/3, 2/3, -1/3]

def f(z, r):
return ((e)**2)*(alpha_elm*Nc/2*np.pi**2)*(4)*(Q2)*(z**2)*((1-z)**2)*((scipy.special.k0(r*(z*(1-z)*Q2 + (m**2))))**2)

integrate.nquad(f, [[0, 1],[0, np.inf]])

how can i do that?

A: You can define a partially applied version of your function where you set the values for e and m. Then iterate over their ranges of values and compute the specific results:
from functools import partial

def f(m, e, z, r):
    return ((e)**2)*(alpha_elm*Nc/2*np.pi**2)*(4)*(Q2)*(z**2)*((1-z)**2)*((scipy.special.k0(r*(z*(1-z)*Q2 + (m**2))))**2)

results = []
for mm, ee in zip(m, e):
    partial_f = partial(f, mm, ee)
    result = integrate.nquad(partial_f, [[0, 1], [0, np.inf]])
    results.append(result)

I would however strongly suggest to reformat and break down the overly complex definition of your function f.


text:
Q: cakePHP - many to many - accessing players and showing them in the rounds view I have a rounds table who has many videos. My videos table has a many to many relationship with players. In my rounds view I show the related videos, but I'm trying to show the related players of a video as well in the rounds view. But I'm failing in that regard. I'm posting the code that works, that is the rounds view where I show the related videos.
How can I access the players that are related to videos in the rounds view? This is bugging me for a while now!
rounds table :
round_id    int(11)
round_name  varchar(45)
tournament_id   int(11)

videos table :
video_id    int(11)
video_title varchar(45)
video_date  date
video_scoreA
video_scoreB
video_url   varchar(255)
tournament_id   int(11)
round_id    int(11)

players table :
player_id   int(11)
player_firstname    varchar(45)
player_surname  varchar(45)
player_birthDate    date
player_turnedPro    year(4)
player_nickname varchar(45)
player_nationality  varchar(45)
player_flag varchar(255)
player_highestBreak varchar(45)
player_highestRanking   int(11)
player_centuryBreaks    int(11)s
player_careerWinnings   varchar(55)
player_worldChampion    varchar(45)
player_image    varchar(255)
player_category varchar(45)

players_videos table :
id  int(11)
video_id    int(11)
player_id   int(11)

Roundscontroller view action :
public function view($id = null) {
    if (!$this->Round->exists($id)) {
        throw new NotFoundException(__('Invalid round'));
    }
    $options = array('conditions' => array('Round.' . $this->Round->primaryKey => $id));
    $this->set('round', $this->Round->find('first', $options));
}

Rounds view.ctp :

        <?php echo __('Video Id'); ?>
        <?php echo __('Video Title'); ?>
        <?php echo __('Video Date'); ?>
        <?php echo __('Video ScoreA'); ?>
        <?php echo __('Video ScoreB'); ?>
        <?php echo __('Video Url'); ?>
        <?php echo __('Tournament Id'); ?>
        <?php echo __('Round Id'); ?>
        <?php echo __('Actions'); ?>

    <?php foreach ($round['Video'] as $video): ?>

            <?php echo $video['video_id']; ?>
            <?php echo $video['video_title']; ?>
            <?php echo $video['video_date']; ?>
            <?php echo $video['video_scoreA']; ?>
            <?php echo $video['video_scoreB']; ?>
            <?php echo $video['video_url']; ?>
            <?php echo $video['tournament_id']; ?>
            <?php echo $video['round_id']; ?>

    <?php endforeach; ?>

A: The ContainableBehavior is what you want: http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
so go to your AppModel and add public $actsAs = array('Containable'); to it.
In the controller method add the contain key to the options-array:
$options = array(
    'conditions' => array('Round.' . $this->Round->primaryKey => $id),
    'contain' => array(
        'Video' => array('Player'),
    ),
)

In your view, you can access the first Player-name from the first Video like:
echo $round['Video'][0]['Player'][0]['player_surname'];

or with foreach-loops:
foreach ($round['Video'] as $video){
    echo $video['video_title'];
    foreach ($video['Player'] as $player){
        echo $player['player_surname'];
    }
}


text:
Q: verifying imagemagick is installed through browser url we installed imagemagick in our server using pecl install imagick is there any way we can check it is succesfuly installed or not in server ?
can we paste any url in browser and check whether it is installed or not?
please help me to find solution.
Thanks in advance.


text:
Q: Swift error: index out of range i'm working on my tableView and just now i implemented the function to delete the rows, but after i delete a row the app crash with this error (fatal error: index out of range)
struct User {

        var name: String
        var images: UIImage
        var coordinate : (Double , Double)
        var type: String
        var address: String
    }

      var users = [User]()

override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
            rows = 0
            tableView.reloadData()
            insertRowsMode3()
    }

        @IBAction func refreshTapped(_ sender: Any) {

            rows = 0
            tableView.reloadData()
            insertRowsMode3()
        }

        func insertRowsMode2() {

            for i in 0..<users.count {
                insertRowMode2(ind: i, usr: users[i])
            }
        }

        func insertRowMode2(ind:Int,usr:User) {

            let indPath = IndexPath(row: ind, section: 0)

            rows = ind + 1
          tableView.insertRows(at: [indPath], with: .right)
        }

        func insertRowsMode3() {

            rows = 0
            insertRowMode3(ind: 0)
        }

        func insertRowMode3(ind:Int) {

            let indPath = IndexPath(row: ind, section: 0)
            rows = ind + 1
            tableView.insertRows(at: [indPath], with: .right)

            guard ind < users.count-1 else { return }
            DispatchQueue.main.asyncAfter(deadline: .now()+0.20) {
                self.insertRowMode3(ind: ind+1)
            }
        }

        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return rows
        }

        public  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell

            let user = users[indexPath.row]

            cell.selectionStyle = .none

            cell.myImage.image = user.images
            cell.myLabel.text = user.name
            cell.myTypeLabel.text = user.type
            return (cell)
        }

         func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

            tableView.deselectRow(at: indexPath, animated: true)

            UIView.animate(withDuration: 0.2, animations: {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell
            })

            performSegue(withIdentifier: "goToLast" , sender: users[indexPath.row])

        }

         func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return 100
        }

        func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
            return true
        }

        func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

            if editingStyle == UITableViewCellEditingStyle.delete {

                users.remove(at: indexPath.row)
                tableView.reloadData()

            }
        }

this is the part of the code of my tableView, i think i know why the application go in crash but i don't know how to solve this problem, what i can do?

A: update your numberOfRowsInSectionas rather than return rows return return users.count as per @vadian's comment.
and
    update delete code with this
users.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)


text:
Q: How do I log in when my OpenID provider is down or offline? When I registered with Stack Overflow 18 months ago, I used myOpenID as my login preference. That service seems to be down at the moment (I have since this discovered that this is a common problem), so I am struggling to get logged in.
When I requested account recovery details, the email message simply confirmed my credentials at myOpenID, without providing any alternative options.
I have created a separate account with Stack Exchange to make this post, but I would like to access my other account. I investigated merging this new account with the inaccessible one, but it seems that this is impossible in the current scenario.
How can I get logged in while the myOpenID service is down?

A: Now that you've created another account, you can flag one of your posts and ask a moderator to merge your accounts as described here.
Once the accounts are merged, you can login with either of the OpenIDs that you've used on both the accounts.
Personally, I have added 3 services to the My Logins section of my profile...

... so that nothing comes in my way of my Stack Exchange addiction.

A: The "correct" solution is to add an alternate OpenID provider to your account when you can access it. If you go to your profile you'll see a "my logins" link (#1 in the image below). Click that and you'll see something like the following dialog:

(Obviously yours will only have one OpenID).
Click on the "add more logins..." link (#2 in the image above) and add an ID from another provider—Facebook, Stack Exchange themselves, etc.
Then the next time myOpenID is down, you can use one this to access your account.
However, in your current situation as myOpenID is down, you can't do that. So you have done the right thing by creating a second account with a different OpenID provider. The next step is to get the two accounts merged. If you used the same e-mail address on both, that will make it easier for the moderators to confirm that you own both accounts. You may have to give hints as to the OpenID used as well, but that will depend on who's doing the merging.
This will add the new OpenID to your existing account, putting you in the same position as if you'd added it yourself.


text:
Q: Reading the output from console and print in XML file in java
Possible Duplicate:
How could I read Java Console Output into a String buffer

I know how to read input from user and put it on XML file.Here is the sample:
from http://www.mkyong.com/java/how-to-create-xml-file-in-java-dom/
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class WriteXMLFile {

    public static void main(String argv[]) {

      try {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("company");
        doc.appendChild(rootElement);

        // staff elements
        Element staff = doc.createElement("Staff");
        rootElement.appendChild(staff);

        // set attribute to staff element
        Attr attr = doc.createAttribute("id");
        attr.setValue("1");
        staff.setAttributeNode(attr);

        // shorten way
        // staff.setAttribute("id", "1");

        // firstname elements
        Element firstname = doc.createElement("firstname");
        firstname.appendChild(doc.createTextNode("yong"));
        staff.appendChild(firstname);

        // lastname elements
        Element lastname = doc.createElement("lastname");
        lastname.appendChild(doc.createTextNode("mook kim"));
        staff.appendChild(lastname);

        // nickname elements
        Element nickname = doc.createElement("nickname");
        nickname.appendChild(doc.createTextNode("mkyong"));
        staff.appendChild(nickname);

        // salary elements
        Element salary = doc.createElement("salary");
        salary.appendChild(doc.createTextNode("100000"));
        staff.appendChild(salary);

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("C:\\file.xml"));

        // Output to console for testing
        // StreamResult result = new StreamResult(System.out);

        transformer.transform(source, result);

        System.out.println("File saved!");

      } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
      } catch (TransformerException tfe) {
        tfe.printStackTrace();
      }
    }
}

but my question is how to read the output from the console in java and print it in specified XML file.

A: I am not sure what exactly you mean by "reading the output from the console" but you can intercept calls to System.out by using http://docs.oracle.com/javase/6/docs/api/java/lang/System.html#setOut%28java.io.PrintStream%29.
If you elaborate more on what you are trying to do I can be more specific.


text:
Q: What file metadata is preserved by Git? What file metadata is preserved by Git?
What are from ACL, owner, group ID, file permissions, atime, ctime, mtime preserved in Git history?
As I know executable permission is treated specially:
git add --chmod=+x one.txt
git add --chmod=-x two.txt

Is anything else preserved by Git?

A: https://git.wiki.kernel.org/index.php/ContentLimitations

By design, git cannot track other aspects of the filesystem, including:

*

*File modes (except for the "executable" bit, and being symbolic link)

*File ownership (commits, however, remember 'author' and 'committer' info)

*File modification and access times (these are set to checkout time for files which are modified during checkout)

*File ACLs and extended attributes

*Hard links

*Empty directories (although it is not a fundamental limitation, git just automatically removes empty directories and does not add empty directories)

A: Only executable bit. Git concentrates on storing file content.
If you need to preserve something else you have to to do it yourself or use some kind of metadata helpers like metastore or gibak.

A: Virtually none.
Git will look at the x bits in the result of stat.  If any of the three are set, Git will save the file using a tree entry in which the mode is 100755.  Otherwise Git will save the file using a tree entry in which the mode is 100644.
This does not depend on any of the other mode bits (except that the file must be a file, not a directory—Git does not save directories—nor a symbolic link).  A file whose actual mode is 100 (--x------) is saved as 100755.


text:
Q: How to use ReorderableListView with flutter_bloc? I'm new to flutter_bloc and trying to implement a ReorderableListView, to allow the user to rerange the order of textfields in a listview.
Unfortunately it isn't working. After dropping the listtile to the new position it changes back to the old one:

This is the output in the screen:
class _Levels extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<DifficultyLevelsCubit, DifficultyLevelsState>(
      builder: (context, state) {
        print('rebuild');
        return Flexible(
          child: ReorderableListView(
            shrinkWrap: true,
            children: state.levels
                .asMap()
                .map((i, lvl) => MapEntry(
                      i,
                      ListTile(
                        key: ValueKey(i),
                        title: TextField(
                          onChanged: (lvl) => context
                              .read<DifficultyLevelsCubit>()
                              .levelChanged(lvl, i),
                          decoration: InputDecoration(
                            labelText: 'Level',
                            helperText: '',
                            errorText: state.levels[i].invalid
                                ? 'invalid level'
                                : null,
                          ),
                        ),
                        trailing: Icon(Icons.menu),
                      ),
                    ))
                .values
                .toList(),
            onReorder: (int oldIndex, int newIndex) => context
                .read<DifficultyLevelsCubit>()
                .orderChanged(oldIndex, newIndex),
          ),
        );
      },
    );
  }
}

And this my implementation of the reorder function in my cubit class:
void orderChanged(int oldIndex, int newIndex) {
    List<DiffLevel> _list = state.levels;

    if (newIndex > oldIndex) {
      newIndex -= 1;
    }
    final items = _list.removeAt(oldIndex);
    _list.insert(newIndex, items);

    emit(state.copyWith(levels: _list));
}

Does someone know why this behaviour appears and how to solve this? Thanks in advance!
Note: print('rebuild)` is not being triggerd on reorder. I don't really understand why, cause I emit the state in the reorder function and expect the blocbuilder to react on that change.

A: What's happening here is you are mutating the same list and not overwriting it - bloc expects and entirely new list in order to rebuild.
Also, I'm not entirely sure you can emit state directly like that. I generally follow the pattern suggested here where the emitted state carries the updated list
 const ListState.success(List<Item> items)
      : this._(status: ListStatus.success, items: items);

With that said, here  is the approach I would suggest !
void orderChanged(int oldIndex, int newIndex) {

    if (newIndex > oldIndex) {
      newIndex -= 1;
    }

// First get the items at the old index
    final items = state.levels[oldIndex];

//Then remove it from the old position and insert it at the new one
    final reorderedList = List.of(state.levels)
    ..removeWhere((element) => element.id == items.id)
    ..insert(newIndex, items);

    emit((ListState.success(reorderedList);
}


text:
Q: Avoid execute function body pararally by user events until finishes previously triggered execution - Javascript In my component implementation, doSomething function is triggered on a user button click. The problem is that doSomething takes around 200-1100ms to complete execution with a state change. I face the problem where rapid button clicks trigger this function body simultaneously which causes unexpected final states.
I don't require a complex mutual exclusion solution. The requirement is just to ignore all other calls until the current execution finishes, I tried the following flagging approach:
doSomething = () => {
    if(this.running){
        return //ignore the event
    }
    this.running=true;
    //do processing
    this.setState({someVariable:answer_of_process}, ()=>this.running=false);
}

render(){
    return(<ImportedComponent doSomething={this.doSomething}/>)
}

This made the probability of state corruption lesser but, occasionally it happens.ie: before 20% now 2% . How do I improve this solution to be 0% of the failure rate?
Edited:
The function triggering button is from an imported complex component and it cannot be disabled. The component takes doSomething as a prop.

A: Guessing you need only the last action proceeds in a certain period of time after multiple events been fired.
That belongs to the field of debounce function.

Creates a debounced function that delays invoking function until after wait milliseconds have elapsed since the last time the debounced function was invoked.

For example: if the user inputs very quickly, and request costs times, we want only the last user input value been fired.
import React, { useState, useCallback } from "react";
import "./styles.css";
import { debounce } from "lodash";

const request = debounce(value => {
  alert(`request: ${value}`);
}, 1000);

export default function App() {
  // const [input, setInput] = useState("");
  const debouceRequest = useCallback(value => request(value), []);
  const onChange = e => {
    // setInput(e.target.value);
    debouceRequest(e.target.value);
  };
  return (
    <div className="App">
      <input onChange={onChange} />
      {/* {input} */}
    </div>
  );
}

A: If anyone has the issue, I adapted the solution from the marked answer for this question with minimum edits :
const _ = require('lodash');

doSomething = _.debounce(() => {
    if(this.running){
        return //ignore the event
    }
    this.running=true;
    //do processing
    this.setState({someVariable:answer_of_process}, ()=>this.running=false);
}, 500)

render(){
    return(<ImportedComponent doSomething={this.doSomething}/>)
}


text:
Q: PHP Memory Limit not working
PHP Deprecated:  google-api-php-client's autoloader was moved to
  vendor/autoload.php in 2.0.0. This redirect will be removed in 2.1.
  Please adjust your code to use the new location. in
  /root/plus/plus/google-api-php-client/src/Google/autoload.php on line
  19
PHP Notice:  Trying to get property of non-object in
  /root/plus/plus/UploadAlbumPicasa.php on line 32
PHP Fatal error:  Allowed memory size of 536870912 bytes exhausted
  (tried to allocate 322957319 bytes) in
  /root/plus/plus/UploadAlbumPicasa.php on line 80

I tried to increase the memory limit as can be seen in
info.php
memory_limit    1024M

But whenever I run the script, it tells me the message as shown above. The allowed memory exhausted error.
Any idea what is causing this issue and how do I resolve it?


text:
Q: Computing the gradient of scalar wrt a vector Let
$$
\alpha = x^TAx \enspace x\in \mathbf{R}^{nx1}, A \in \mathbf{R}^{nxn}
$$
How do I compute the derivative $\Large \frac{\partial\alpha}{\partial x}$
without using the coordinate way i.e, writing A in terms of $\large A = (a_{ij})$
My attempt is as follows (using the product rule):
$$
\begin{align}
\frac{\partial\alpha}{\partial x} = &\frac{\partial(x^TAx)}{\partial x}\\
=&\frac{\partial(x^TA)x}{\partial x} + x^TA\frac{\partial x}{\partial x}\\
=&\frac{\partial(A^Tx)^Tx}{\partial x} + x^TAI\\
=&\left(\frac{\partial A^Tx}{\partial x}\right)^Tx+ x^TA\\
=&Ax+x^TA
\end{align}
$$
This is different from the answer that I find in wikipedia which says is to be:
$$
\frac{\partial\alpha}{\partial x} = x^TA+x^TA^T
$$
Where am I going wrong, please present your answer in the product rule form.

A: WE can write $\frac{\partial \alpha}{\partial x}$ in form of a row vector as:
$$
\frac{\partial \alpha}{\partial x}=x^T(A+A^T)
$$
as you find in Wikipedia, or as a column vector
$$
\frac{\partial \alpha}{\partial x}=(A+A^T)x
$$
as you can see here at pag 11.
In your result you have the addition of a row with a column vector that is not possibile. Changing one of the two you find one of the two forms.

A: The product rule is not valid for the gradients of matrix/vector expressions.
For example
$$\frac{\partial(a^Tb)}{\partial x} \ne \Bigg(\frac{\partial a^T}{\partial x}\Bigg)b + a^T\Bigg(\frac{\partial b}{\partial x}\Bigg)$$
However, the product rule is valid for the differentials of such expressions
$$d(a^Tb) = (da^T)b + a^T(db)$$
Note that the gradient of a vector is a matrix, which behaves differently than a vector.
But the differential of a vector is just another vector, and behaves accordingly.
So let's approach your problem using differentials.
$$\eqalign{
 \alpha &= x^TAx \cr
d\alpha
 &= dx^T\,Ax + x^TA\,dx \cr
 &= x^TA^T\,dx + x^TA\,dx \cr
\frac{\partial \alpha}{\partial x} &= x^TA^T + x^TA \cr\cr
}$$


text:
Q: Capture, save and retrieve images/pictures using Sqlite database In my windows 8 application(C#), I want to capture images (I done) and then save it to a Sqlite database. As Sqlite is not supporting BipmapImage, Uri types etc (I tried but giving exceptions of not supported storage..) How can I do this?
I simply want to save images in local database that I have captured using camera and then retrieve these images (set to binding). Please suggest me other options to achieve this.
I also tried to convert Uri into string and then saving this string into SQLite db and then again converting string to Uri and then making Bitmap images but I couldn't achieve this (is it a right approach ?).
If you can share me any sample please do it. I spent many hours in it but don't know where I am doing wrong!
Thanks Zauk

A: Although I do not prefer to save images in a database.
But if you want to save images in the database then one way of doing this is to convert your images to base64 string and then save the string in SQLite database.
public string ConvertToString(Image image)
{
    // First Convert image to byte array.
    byte[] byteArray = new byte[0];
    using (MemoryStream stream = new MemoryStream())
    {
        image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        stream.Close();

        byteArray = stream.ToArray();
    }

    // Convert byte[] to Base64 String
    string base64String = Convert.ToBase64String(byteArray);

    return base64String;
}

A: You can save camera captured image into SQLitedatabase in this way..
public class CamActivity extends Activity {
byte[] byteArray;
private static final int CAMERA_REQUEST = 1888;
protected static final int TAKE_PHOTO_CODE = 0;
public ImageView imageView;
private DBAdapter db;
byte [] imgbyte;
EditText txtView ;
String name;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    db=new DBAdapter(CamActivity.this);
    db.open();
    this.imageView = (ImageView)this.findViewById(R.id.imageView1);
  txtView=(EditText)findViewById(R.id.editText1);
    Button B = (Button) this.findViewById(R.id.camera);
    B.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
           // cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,getImageUri());
            startActivityForResult(cameraIntent,CAMERA_REQUEST );
        }
    });

    Button save = (Button)findViewById(R.id.saving);
    save.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            name=txtView.getText().toString();

            try
            {

db.insertImageDetails(byteArray,name);
            }

            catch (Exception e) {
                e.printStackTrace();
            }
             //mySQLiteAdapter.close();

            Toast.makeText(getApplicationContext(), "processing", Toast.LENGTH_SHORT).show();
            Toast.makeText(getApplicationContext(), "image saved", Toast.LENGTH_SHORT).show();

            }});

    Button G = (Button) this.findViewById(R.id.get);
    G.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v)

        {

            Intent intent= new Intent(CamActivity.this,SecondActivity.class);
            startActivity(intent);

}
        });
    }

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //final byte[] byteArray;
    if (requestCode == CAMERA_REQUEST) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
       //imageView.setImageBitmap(photo);
       ByteArrayOutputStream stream = new ByteArrayOutputStream();
       photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
         byteArray = stream.toByteArray();
       System.out.println(byteArray);
       Toast.makeText(getApplicationContext(), byteArray.toString(), Toast.LENGTH_SHORT).show();

    }

}

    }


text:
Q: Get a list of installed applications I'm trying to build a list of installed applications, similar to the list in Add/Remove Programs list in the control panel.
I've tried using Win32_Product WMI Class and MsiEnumProducts.
Both of them outputted very similar outputs but both were missing programs that are in Add/Remove Programs. For example I know I have Adobe Flash Player installed, but it was on neither of these lists.
I've been trying to avoid reading the registry, because I've read that it's better to use some API to retrieve the list, but none of the methods I've found so far have worked.
Is there any other built in API/COM methods that could work? Or should I just try to read everything from the registry?
ALSO...
There are programs in the registry that are not in the Add/Remove Programs list, for example I have Microsoft Security Essentials installed. In the registry there is an entry to uninstall Microsoft Antimalware, which I'm assuming is apart of Microsoft Security Essentials but its not in the Add/Remove Programs list and I see no do-not-display value of any kind. (Part of the reason I want to use an API of some kind)

A: If you want to show the same items as in the "Programs and Features" list, you can just bind to the folder and ask for its contents. Here is the scripting version:
var shell = new ActiveXObject("Shell.Application");
var programsFolder = shell.Namespace("::{26EE0668-A00A-44D7-9371-BEB064C98683}\\0\\::{7b81be6a-ce2b-4676-a29e-eb907a5126c5}");
var items = programsFolder.Items();
for (var i = 0; i < items.Count; i++) {
 var item = items.Item(i);
 WScript.StdOut.WriteLine(item);
}

The C++ version of this involves a lot more typing but the idea is the same.

A: Figured it out, the SystemComponent value hides it from the Add/Remove program list.

And since I can't find any other API to use, I'm just going to enumerate the registry.


text:
Q: Why do I get "Uncaught TypeError: Cannot read property 'length' of undefined(…)"? Error Message: Uncaught TypeError: Cannot read property 'length' of undefined(…)
Line 44, Column 23
I have read every post I can find related to this error but have not found anything applicable to this situation.
I'm trying to take a string and turn it into an array of arrays that is formatted to take the shape of steps (codewars' kata); one word across, next word down and so on. The problem I'm running into is that I keep getting an Uncaught TypeError: Cannot read property 'length' of undefined(…) when trying to use the length of an array element within a for loop. So in this nested loop:
for(var i = 0; i < masterStringOdd.length; i++){
    temp2 = proArr.slice(0);
    start2 = even[i].length - 1;
    for(let j = 0; j < odd[i].length; j++){
        let replace2 = masterStringOdd.charAt(i);
        Array.prototype.splice.apply(temp2, [start2, 1].concat(replace2));
        finalOdd.push(temp2);
    }
    start2 += even[i+1].length - 1;
}

With the last line "start2 += even[i+1].length - 1;" (I have tried about a thousand different various of this) I get the error, but if I return that line "return even[i+1].length - 1;" I get 5, which is the correct length. My complete code is at the end of this email if anyone wants to look at it, and believe me I understand it is ridiculous and awkward (working code and completely unpolished) - skills at hand and all that.
Just can't figure out why I can't get and use the value of the element's length in this case. Any help would be greatly, greatly appreciated.
function wordStep(str) {
    let array = str.split(" ");
    let even = [], odd = [], proArr = [], finalEven = [], finalOdd = [];
    //for loop to create sperate arrays for across and down
    for (let i = 0; i < array.length; i++){
        if (i%2 === 0){
            even.push(array[i]);
        } else {
            odd.push(array[i].slice(1,-1));
        }
    }
    //data collection and tool variables, might delete them if the are not    needed
    let finalLength = even.join("").toString().length - (even.length - 1);
    let masterStringEven = even.join("").toString();
    let yAxis = odd.join("").toString().length;
    let masterStringOdd = odd.join("").toString();
    //for loop to create protype array
    for (let i = 0; i < finalLength; i++){
        proArr.push(",");
    }
    // for loop to create final evens arrays
    let start = 0;
    for(let i = 0; i < even.length; i++){
        let temp1 = proArr.slice(0);
        let replace = even[i].split("");
        Array.prototype.splice.apply(temp1, [start, replace.length].concat(replace));
        finalEven.push(temp1);
        start += replace.length-1;;
    }
    // nested loops for final odds' array
    let temp2 = []
    let start2 = 0;

    for(var i = 0; i < masterStringOdd.length; i++){
        temp2 = proArr.slice(0);
        start2 = even[i].length - 1;
        for(let j = 0; j < odd[i].length; j++){
            let replace2 = masterStringOdd.charAt(i);
            Array.prototype.splice.apply(temp2, [start2, 1].concat(replace2));
            finalOdd.push(temp2);
        }
        start2 += even[i+1].length - 1;
    }
}

A: Fundamentally, what's happening is that you're going past the end of the even array, so even[i] gives you undefined, and then you try to read the length of undefined, which causes the error.
And indeed, we can see that in this loop:
for(var i = 0; i < masterStringOdd.length; i++){
    temp2 = proArr.slice(0);
    start2 = even[i].length - 1;
    for(let j = 0; j < odd[i].length; j++){
        let replace2 = masterStringOdd.charAt(i);
        Array.prototype.splice.apply(temp2, [start2, 1].concat(replace2));
        finalOdd.push(temp2);
    }
    start2 += even[i+1].length - 1;
}

...you're assuming that masterStringOdd.length will always be less than even.length. Nothing in the code ensures this, and in fact it will frequently not be true. masterStringOdd.length is the length of the odd array's entries joined together as a string; even.length is the number of even entries. So there are two reasons why even.length may not be at least as big as masterStringOdd.length: 1. The latter is the length of a string, not an array; and 2. The latter relates to odd, not even.

A: The issue with your code is that you are not checking the even and odd arrays length before accessing them. This will create issue if you have str value in  wordStep(str) which do not push values in these array at the indices where you are accessing those.
Put proper array length check for accessing the array at the particular index.
for(var i = 0; i < masterStringOdd.length; i++){
    temp2 = proArr.slice(0);
    if(even.legth > i)
    start2 = even[i].length - 1;
    if(odd.length > i){
    for(let j = 0; j < odd[i].length; j++){
        let replace2 = masterStringOdd.charAt(i);
        Array.prototype.splice.apply(temp2, [start2, 1].concat(replace2));
        finalOdd.push(temp2);
    }
    }
    if(even.length > i +1)
    {
      console.log(even.length);
      start2 += even[i+1].length - 1;

    }
}

for example wordStep("Life is good for us"); this call will fill the array properly and you will not get any error.
but if its wordStep("Life Good");, you will see the issue in your code if proper length check are not applied
plunker to verify : http://plnkr.co/edit/QQovAAzlDhXgucikCGAb?p=preview


text:
Q: Translational invariance of sources/materials implies translational field invariance Let's say we have an electromagnetic problem where $\epsilon = \epsilon(x,y)$, $\rho = \rho(x,y)$, and $J = J(x,y)$. The physicist argument is that by the symmetry of the problem we also have $E = E(x,y)$ and $H = H(x,y)$. However, I am a terrible physicist so usually arguments from symmetry are not obvious to me. Therefore I was trying to prove this from Maxwell's equations. Someone told me to take $\partial z$ of both sides of each equation.
Ok, so here was my attempt (assuming $\epsilon$ is scalar)...
$$ \nabla \cdot D = \rho$$
$$ \nabla \cdot \epsilon E = \rho$$
$$ \partial_z(\nabla \cdot \epsilon E) = 0$$
$$ \nabla \cdot \partial_z(\epsilon E) = 0$$
$$ \nabla \cdot \epsilon \partial_z E = 0$$
$$ \partial_x(\epsilon \partial_z E_x) + \partial_y(\epsilon \partial_z E_y) + \partial_z(\epsilon \partial_z E_z)= 0$$
$$ \partial_x(\epsilon \partial_z E_x) + \partial_y(\epsilon \partial_z E_y) + \epsilon \partial^2_z E_z= 0$$
Didn't see where to go so I tried Ampere's Law
$$ \nabla \times H = J + \partial_t D $$
$$ \partial_z (\nabla \times H) = \partial_t \partial_z D $$
$$ \nabla \times \partial_z H = \partial_t \partial_z \epsilon E $$
$$ \nabla \times \partial_z H = \partial_t (\epsilon \partial_z E) $$
Again, not clear to me how to conclude $d_zE = 0$.
In addition, I can think of a simple counter example to this symmetry argument. In empty space we have invariance in all directions. But, for any direction you choose I can form a plane wave traveling in that direction, so $E$ varies in that direction.
So when and how can we really conclude that translational invariance of sources/materials implies translational invariance of fields?
EDIT:(Attempting Mark's comment)
$$ \nabla \times (\nabla \times E) = -\partial_t \nabla \times B $$
$$ \nabla(\nabla \cdot E) - \nabla^2 E = -\mu (\partial_t J + \partial_t \epsilon E) $$
$$ \nabla(\nabla \cdot E) + \mu \partial_t J = \nabla^2 E - \mu \epsilon \partial_t E $$
so we get the three scalar equations
$$ \partial_x(\nabla \cdot E) + \mu \partial_t J_x = \nabla^2 E_x - \mu \epsilon \partial_t E_x $$
$$ \partial_y(\nabla \cdot E) + \mu \partial_t J_y = \nabla^2 E_y - \mu \epsilon \partial_t E_y $$
$$ \mu \partial_t J_z = \nabla^2 E_z - \mu \epsilon \partial_t E_z $$


text:
Q: Deployment to Azure using Jenkins and github I need to deploy code from github to Azure. i have configured jobs to perform test on the script and based on the result i want to deploy those script in Azure.
I need help on what jenkins plugin to us for deployment in Azure. if Plugin is not available do we have any other way to do a deployment from jenkins to Azure.
Any Links or Blogs will be really helpful.

A: Jenkins and Azure may work together, absolutely - just a two days ago there was another announcement about that. You may host it in Azure.
But it looks like you want to host Jenkins outside of Azure.
I would offer you to try out Visual Studio Team Services - its build part. You can define the build and add Jenkins as the part of that process. There is the plugin for Jenkins here with a good documentation on how to set up that.
Here is the tutorial on integrating Jenkins and VSTS. And you can set up the deployment to Azure from the same tab - see how to use VSTS build functionality.