text:
Q: Core Data issue. Insert new NSManagedObject I want to insert 200 5Mb records in my Core Database.  But when I save the NSManagedObject,  the memory wasn't released (autoreleased pool didn't help), and after inserting 30 records I got the memory warning and the application crashed. Here is my code
- (void)SaveItem
    {
        NSString *entityName = kEntityName;
        AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
        NSManagedObjectContext *context = appDelegate.managedObjectContext;
        NSEntityDescription *entityDesctiption = [NSEntityDescription
                                                  entityForName: entityName
                                                  inManagedObjectContext:context];
        // check if town exists
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id == %d", self.imageID];
        NSFetchRequest *requestToCheckExistense = [[NSFetchRequest alloc] init];
        [requestToCheckExistense setEntity:entityDesctiption];
        [requestToCheckExistense setPredicate:predicate];
        NSArray *objects = [context executeFetchRequest:requestToCheckExistense error:nil];
        [requestToCheckExistense release];
        if (objects == nil)
        {
            NSLog(@"there was an error");
        }
        NSManagedObject *object;
        if ([objects count] > 0)
        {
            // edit item
            object = [objects objectAtIndex:0];
        }
        else
        {
            // if object doesn't exist, find max id to imlement autoincrement
            NSFetchRequest *request = [[NSFetchRequest alloc] init];
            [request setEntity:entityDesctiption];
            request.propertiesToFetch = [NSArray arrayWithObjects: @"id", nil];
            NSArray *allobjects = [context executeFetchRequest:request error:nil];
            [request release];
            NSInteger newID = 1;
            if ([allobjects count] > 0)
            {
                NSNumber *maxID = [allobjects valueForKeyPath:@"@max.id"];
                newID = [maxID intValue] + 1;
            }

            // write item
            object = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:context];
            [object setValue:[NSNumber numberWithInt:newID] forKey:@"id"];
            self.imageID = newID;
        }
        // fill NSManagedObject
        // size of objNSData is about 5MB
        NSMutableData *objNSData = [[DatabaseManager sharedDatabaseManager] encryptedDataFromImage:bigImage];
        [object setValue:objNSData forKey:@"big"];

         [context save:nil];
     }

When I commented
[object setValue:objNSData forKey:@"big"];

everything was OK.
I tried to add the code into @autoreleasepool , but that didn't help.
I know, that now, when I save data to database, it's still in iPhone RAM. How to release it from this memory? When I get a set of Managed Objects from the database, they are not in the RAM (I can easyly get 100 object, each of them has 5Mb fields)

A:  object =(tblEntity *) [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:context];

try to type cast the object,this may solve the problem

A: I've solved the issue.
after call of [self SaveItem];
I used
[context save];
[context reset];
[context save];

all the NSManagedObjects from the context will be released.
After that operation I can add as many big objects as I want

A: Because you don't own an NSManagedObject when you create it, it may be retained by the core data stack even after releasing it (when using an autoreleasepool contained inside the loop).
This may help:

*

*Set the undo manager of your managedobjectContext to nil:
[context setUndoManager:nil];

*Be sure that no properties of that object are retained anywhere, because then the managed object will not be released on time inside your loop.

*Be sure to add an autorelease pool inside every loop execution, not wrapping all the loop itself, similar to:
for(i;i<n;i++) {
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    [obj saveItem];
    [pool drain];
 }

*If that object belongs to a hierarchy of NSManagedObjects, then you need to release the owner of this object too, for this one to be deallocated from memory.
You can check apple's documentation about memory management in CoreData.
Warning: big objects (> 1MB) are not recommended by Apple to be stored inside CoreData (Check this other question/answer.)


text:
Q: How do I create an animation in google earth using png overlays with kml timestamps? I have the following kml files, each with a different timestamp and png:
<?xml version="1.0" encoding="UTF-8"?>
 <kml xmlns="http://www.opengis.net/kml/2.2"
 xmlns:gx="http://www.google.com/kml/ext/2.2">
 <GroundOverlay>
 <name>gx:LatLonQuad Example</name>
 <Icon>
<href>
/Users/asd/Dropbox/0mylayerExport.png
</href>
 </Icon>
<gx:LatLonQuad>
<coordinates>
-71.007186998722,42.2869344810739 -70.9807964189347,42.360133347777 -71.1410513483055,42.3916360561188 -71.1680083772048,42.3178859041619
</coordinates>
<TimeStamp>
<when>1944-06-06T06:2010-10-26T06:30:08
></when></TimeStamp><rotation>100</rotation>
</gx:LatLonQuad>
</GroundOverlay>
</kml>

What I'm trying to do is to animate the sequence of png overlays, but I can't figure out how. I can view all of the kml files in google earth, and click through them manually, but I was wondering if there was a neater way of animating this, instead of ticking them on and off.

I have tried manually adding timestamps, and time intervals in google-earth, and am still failing to automatically animate overlays, so I would appreciate any advice on how to do this too.
Thanks!

A: I think the problem is your time span.  Its supposed to be in the format
YYYY-MM-DDThh:mm:sszzzzzz (see KML Ref)
"1944-06-06T06:2010-10-26T06:30:08
"
is wrong in the "mm" part. Also, if you're trying to animate a set of time periods rather than points, you need timestamp rather than span.
Time should be before  and after  according to the documentation although I'm not sure if that actually matters in KML?
Final point: png makes the output KMZ large (or takes longer to download if you leave them out there on the web), best to convert to jpg if an image or gif if a simple cartoon/icon.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Azure SQL Database - Disable SQL Server Authentication mode I would like to use Azure SQL Database with Azure AD authentication only.
I couldn't find any way to disable the sql authentication mode either the server admin login. Any hint?
Thank you,
Alessandro

A: This is now possible as announced https://techcommunity.microsoft.com/t5/azure-sql/azure-active-directory-only-authentication-for-azure-sql/ba-p/2417673
Tick box in the portal as the screenshot from the article linked above

A: When we are creating a new Azure SQL server, we need these following values:

*

*Server name: Enter mysqlserver.

*Server admin login: Type azureuser.

*Password: Enter Azure1234567.

*Confirm Password: Retype the password.

*Location: Drop down and select any valid location.

Other words, when the Azure SQL Server is created, the SQL Server admin account is created. We can't connect to the Azure SQL Server without it.
Other words, Azure SQL Server is created based on Azure SQL Server Authentication.
One of the benefits for using the Azure AD authentication is that it provides an alternative to SQL Server authentication.
Each Azure SQL server (which hosts a SQL Database or SQL Data Warehouse) starts with a single server administrator account that is the administrator of the entire Azure SQL server. If we want to use Azure AD Authentication, a second SQL Server administrator must be created, that is an Azure AD account.(Reference:Create an Azure AD administrator for Azure SQL server
).
Administrator structure:

We can understand like this, Azure AD authentication is a complement to SQL Server authentication.
We can remove Azure Active Directory administrator. Removing the Azure Active Directory administrator for Azure SQL server prevents any Azure AD authentication user from connecting to the server. If necessary, unusable Azure AD users can be dropped manually by a SQL Database administrator.

And combine the blob David Browne mentioned, we can get the result: we can not disable the SQL Server Authentication.
Hope this can helps you.


text:
Q: how to change color theme in materializecss I have created nodejs project. Here is package.json
{
  "name": "materializecssdemo",
  "version": "1.0.0",
  "description": "Use of material design components",
  "main": "index.js",
  "scripts": {
    "prestart": "node-sass ./scss/theme.scss ./css/materialize-theme.css",
    "start": "lite-server",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Sunil Kumar",
  "license": "ISC",
  "devDependencies": {
    "lite-server": "^2.3.0"
  },
  "dependencies": {
    "materialize-css": "^0.100.2",
    "node-sass": "^4.7.2"
  }
}

I just want to change the colour of my app from its default colour to blue. So I have created theme.scss file and using node-sass module trying to generate CSS file. Here is my theme.scss
$primary-color: color("blue", "lighten-2") !default;
@import "../node_modules/materialize-css/sass/materialize";

but this is showing
{
  "status": 1,
  "file": "D:/SK/Study/MaterializeCSSDemo/node_modules/materialize-css/sass/components/_variables.scss",
  "line": 39,
  "column": 23,
  "message": "argument `$color` of `lighten($color, $amount)` must be a color\n\nBacktrace:\n\tnode_modules/materialize-css/sass/components/_variables.scss:39, in function `lighten`\n\tnode_modules/materialize-css/sass/components/_variables.scss:39",
  "formatted": "Error: argument `$color` of `lighten($color, $amount)` must be a color\n\n       Backtrace:\n       \tnode_modules/materialize-css/sass/components/_variables.scss:39, in function `lighten`\n       \tnode_modules/materialize-css/sass/components/_variables.scss:39\n        on line 39 of node_modules/materialize-css/sass/components/_variables.scss\n>> $primary-color-light: lighten($primary-color, 15%) !default;\n   ----------------------^\n"
}

is there any simple and clean way to make modifications to the theme? On the documentation page, it is saying by changing the _variables.scss file directely.

A: Materialize comes with a color palette based on the material design base colors.
I recommend you to use these to set theme colors, to follow the Material Design color system.
To be able to do so, you have to import the file which defines these colors first, then set your theme color variables, then import the rest of materialize files. Not sure about our npm setup, but in Rails with materialize-sass it works like this:
@import "materialize/components/color-variables";
$primary-color: color("blue", "lighten-2") !default;
$secondary-color: color("yellow", "base") !default;
@import 'materialize';

A: Try this
$primary-color: lighten(blue, 2) !default;

Args passed to function should be a color and number. Not a string.
And there is no color function in scss.
You can create color using other function like hsl or rgb.
Check full list of scss functions here


text:
Q: android.view.ViewRootImpl$CalledFromWrongThreadException, OkHttp I am following an android tutorial and I building a Weather app, but when I try to set mTemperature TextView to the temperature I get from the forecast API, I get this error "android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.". The code did work fine, when I was logging to see all of the weather details.
Can anybody suggest a solution? I have to mention that I am using 3th party API for the asynchronous HTTP call called OkHTTP.
This is my code in my MainActivity:
public class MainActivity extends Activity {
public static final String TAG = MainActivity.class.getSimpleName();
private TextView mTemperature;
private CurrentWeather mCurrentWeather;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //-----------MY CODE STARTS HERE------------------
    mTemperature = (TextView)findViewById(R.id.temp);
    String API_KEY = "API_KEY";
    //aberdeen, coordinates
    double latitude = 57.1531;
    double longtitude = -2.0928;
    String forecast = "https://api.forecast.io/forecast/"+ API_KEY +"/"+ latitude+","+ longtitude;

    if(isNetworkAvailable()) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(forecast)
                .build();

        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {a

            }
            //when the call to the Okhttp library finishes, than calls this method:
            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    String jsonData = response.body().string();
                    //Log.v(TAG, jsonData);
                    if (response.isSuccessful()) {
                        mCurrentWeather = getCurrentDetails(jsonData);
                        //do sth with the forecast details
                        mTemperature.setText(mCurrentWeather.getTemperature()+"");
                    } else {
                        alertUserAboutError();
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Exception caught:", e);
                }
                catch (JSONException e){
                    Log.e(TAG, "Exception caught:", e);
                }
            }
        });
    }else{
        //Toast.makeText(this,getString(R.string.network_unavailable_message),Toast.LENGTH_LONG).show();
        WIFIDialogFragment dialog = new WIFIDialogFragment();
        dialog.show(getFragmentManager(), getString(R.string.error_dialog_text));
    }
    Log.d(TAG, "Main UI code is running!");

}
//throws JSONException, doing it like that, we place the
// responsability of handaling this exeption to the caller of the method
private CurrentWeather getCurrentDetails(String jsonData) throws JSONException{
    JSONObject forecast = new JSONObject(jsonData);
    String timezone = forecast.getString("timezone");
    Log.i(TAG,"From JSON: " + timezone);

    JSONObject currently = forecast.getJSONObject("currently");
    CurrentWeather currentWeather = new CurrentWeather();
    currentWeather.setHumidity(currently.getDouble("humidity"));
    currentWeather.setTime(currently.getLong("time"));
    currentWeather.setIcon(currently.getString("icon"));
    currentWeather.setPrecipChange(currently.getDouble("precipProbability"));
    currentWeather.setSummery(currently.getString("summary"));
    currentWeather.setTemperature(currently.getDouble("temperature"));
    currentWeather.setTimeZone(timezone);

    Log.d(TAG,currentWeather.getFormattedTime());
    return currentWeather;
}

private boolean isNetworkAvailable() {
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();
    boolean isAvailable = false;
    //contition to check if there is a network and if the device is connected
    if(networkInfo != null && networkInfo.isConnected()){
        isAvailable = true;
    }

    return isAvailable;
}

private void alertUserAboutError() {
    AlertDIalogFragment dialog = new AlertDIalogFragment();
    dialog.show(getFragmentManager(),getString(R.string.error_dialog_text));
}

}
This is the full log from logcat:
05-16 03:25:59.941    5348-5370/koemdzhiev.com.stormy E/AndroidRuntime﹕ FATAL EXCEPTION: OkHttp Dispatcher
Process: koemdzhiev.com.stormy, PID: 5348
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
        at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6357)
        at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:874)
        at android.view.View.requestLayout(View.java:17476)
        at android.view.View.requestLayout(View.java:17476)
        at android.view.View.requestLayout(View.java:17476)
        at android.view.View.requestLayout(View.java:17476)
        at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:360)
        at android.view.View.requestLayout(View.java:17476)
        at android.widget.TextView.checkForRelayout(TextView.java:6871)
        at android.widget.TextView.setText(TextView.java:4057)
        at android.widget.TextView.setText(TextView.java:3915)
        at android.widget.TextView.setText(TextView.java:3890)
        at koemdzhiev.com.stormy.MainActivity$1.onResponse(MainActivity.java:67)
        at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:168)
        at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:818)

A: This error occurs when trying to access UI elements from any thread that is not the UI thread.
To access/modify elements from a non-UI-thread, use runOnUIThread


text:
Q: Generate graphics for different categories in R The code below generates a graph with dots and a "prediction" line, so to speak. However, as you can see for each date there are two Codes: ABC and CDE. So, there will be two different graphics for the same day. But I don't know how to do this. This graph that I generated, I believe it is for ABC. Could you help me make graphics for both Code?
library(dplyr)
library(tidyverse)
library(lubridate)

df1 <- structure(
  list(date1 = c("2021-06-28","2021-06-28","2021-06-28","2021-06-28"),
       date2 = c("2021-07-02","2021-07-02","2021-07-08","2021-07-08"),
       Code = c("ABC","CDE","ABC","CDE"),
       Week= c("Friday","Friday","Thursday","Thursday"),
       DR1 = c(11,17,14,12),
       DR01 = c(14,11,13,12), DR02= c(14,14,16,17),DR03= c(19,17,18,12),
       DR04 = c(11,14,13,13),DR05 = c(12,11,11,11),DR06 = c(14,13,12,11)),
  class = "data.frame", row.names = c(NA, -4L))

> df1
       date1      date2 Code     Week DR1 DR01 DR02 DR03 DR04 DR05 DR06
1 2021-06-28 2021-07-02  ABC   Friday  11   14   14   19   11   12   14
2 2021-06-28 2021-07-02  CDE   Friday  17   11   14   17   14   11   13
3 2021-06-28 2021-07-08  ABC Thursday  14   13   16   18   13   11   12
4 2021-06-28 2021-07-08  CDE Thursday  12   12   17   12   13   11   11

dmda<-"2021-07-02"

x<-df1 %>% select(starts_with("DR0"))

x<-cbind(df1, setNames(df1$DR1 - x, paste0(names(x), "_PV")))
PV<-select(x, date2,Week, Code, DR1, ends_with("PV"))

med<-PV %>%
  group_by(Code,Week) %>%
  summarize(across(ends_with("PV"), median))

SPV<-df1%>%
  inner_join(med, by = c('Code', 'Week')) %>%
  mutate(across(matches("^DR0\\d+$"), ~.x +
                  get(paste0(cur_column(), '_PV')),
                .names = '{col}_{col}_PV')) %>%
  select(date1:Code, DR01_DR01_PV:last_col())

SPV<-data.frame(SPV)

datas<-SPV %>%
  filter(date2 == ymd(dmda)) %>%
  summarize(across(starts_with("DR0"), sum)) %>%
  pivot_longer(everything(), names_pattern = "DR0(.+)", values_to = "val") %>%
  mutate(name = readr::parse_number(name))
colnames(datas)<-c("Days","Numbers")

plot(Numbers ~ Days,  xlim= c(0,7), ylim= c(0,30), xaxs='i',data = datas,main = dmda)

model <- nls(Numbers ~ b1*Days^2+b2,start = list(b1 = 0,b2 = 0),data = datas, algorithm = "port")

new.data <- data.frame(Days = with(datas, seq(min(Days),max(Days),len = 45)))
new.data <- rbind(0, new.data)
lines(new.data$Days,predict(model,newdata = new.data),lwd=2)
coef<-coef(model)[2]
points(0, coef, col="red",pch=19,cex = 2,xpd=TRUE)
text(.99,coef + 1,round(coef,1), cex=1.1,pos=4,offset =1,col="black")

A: In the last step, we need to group by 'Code' and summarise before doing the pivot_longer.  Thus, we have a 'Code' column
library(dplyr)
library(tidyr)
datas <- SPV %>%
  filter(date2 == ymd(dmda)) %>%
  group_by(Code) %>%
  summarize(across(starts_with("DR0"), sum)) %>%
  pivot_longer(cols = -Code, names_pattern = "DR0(.+)",
         values_to = "val") %>%
  mutate(name = readr::parse_number(name))
colnames(datas)[-1] <-c("Days","Numbers")

-output
> datas
# A tibble: 12 × 3
   Code   Days Numbers
   <chr> <dbl>   <dbl>
 1 ABC       1      11
 2 ABC       2      11
 3 ABC       3      11
 4 ABC       4      11
 5 ABC       5      11
 6 ABC       6      11
 7 CDE       1      17
 8 CDE       2      17
 9 CDE       3      17
10 CDE       4      17
11 CDE       5      17
12 CDE       6      17

Inorder to do the plotting by 'Code', split or either loop over the unique values of 'Code', extract the subset of data and plot
lstdatas <- split(datas, datas$Code)
par(mfrow = c(2, 1))
lapply(names(lstdatas), function(nm) {
   dat <- lstdatas[[nm]]
   plot(Numbers ~ Days,  xlim= c(0,7), ylim= c(0,30),
       xaxs='i',data = dat,main = paste0(dmda, "-", nm))

  model <- nls(Numbers ~ b1*Days^2+b2,start = list(b1 = 0,b2 = 0),data = dat, algorithm = "port")

  new.data <- data.frame(Days = with(dat, seq(min(Days),max(Days),len = 45)))
  new.data <- rbind(0, new.data)
   lines(new.data$Days,predict(model,newdata = new.data),lwd=2)
  coef<-coef(model)[2]
   points(0, coef, col="red",pch=19,cex = 2,xpd=TRUE)
   text(.99,coef + 1,round(coef,1), cex=1.1,pos=4,offset =1,col="black")
   })

-output

If we want this as a function
f1 <- function(dat, code_nm) {
    dat <- subset(dat,  Code == code_nm)
    plot(Numbers ~ Days,  xlim= c(0,7), ylim= c(0,30),
       xaxs='i',data = dat,main = paste0(dmda, "-", code_nm))

  model <- nls(Numbers ~ b1*Days^2+b2,start = list(b1 = 0,b2 = 0),data = dat, algorithm = "port")

  new.data <- data.frame(Days = with(dat, seq(min(Days),max(Days),len = 45)))
  new.data <- rbind(0, new.data)
   lines(new.data$Days,predict(model,newdata = new.data),lwd=2)
  coef<-coef(model)[2]
   points(0, coef, col="red",pch=19,cex = 2,xpd=TRUE)
   text(.99,coef + 1,round(coef,1), cex=1.1,pos=4,offset =1,col="black")
}

Then call the function as
f1(datas, "ABC")
f1(datas, "CDE")


text:
Q: Extract prices from string I did a google form of items I'm selling, and the form is linked to a
google sheet. I want to extract the prices and add them in a separate column.

In the entries I have the price and name of the item, but I want to add only the prices
in the next column.
I was using:
=VALUE(RIGHT($D2, 4))

but that will only extract the price when there is one item.
Any information will be helpful!

A: SUM() doesn't care about text so you should be able to do:
=SUM(SPLIT(D2," ,$"))

A: Try
=sum(split(join("|",REGEXEXTRACT(substitute(A1,"$",""),REGEXREPLACE(substitute(A1,"$",""),"(\d+.\d+)","($1)"))),"|"))


text:
Q: What's the best way to integrate Designers using Dreamweaver with Visual Studio C# developers? I know about code-behind files, but what is the best real-world way of Designers that are using DreamWeaver or other Design Tools to work with Visual Studio programmers?
For example, say you have a basic website with user interface forms hitting the database... the database work is definitely done by the developer but how to tie the designed forms with the database coding or client-side logic that may involve events on controls, or other GUI related tie-ins.  Are the graphic designers also controlling application flow?  There seems to be a large disconnect that needs addressed - especially when it comes time to tweak the design after it's been implemented.

A: The best way is to make sure that your designers have some knowledge of what kind of HTML they will be working with.
Every ASP.NET developer is aware of MS-HTML, that lovely nesting of HTML tables, but designers aren't. Designers have their own requirements to meet and they'll do them in the best manner possible. Sadly it's not often good for us.
I am always frustrated when I receive a design from our UI team which shows radio-buttons nicely layed out in a grid using floating div's. Then I have to shatter their dreams that no, I can't generate you that HTML (ok, I can with the use of ControlAdapters, but every time they are different designs!).
Try and have a 90%/ 10% rule, where 90% of the design is done before the ASP.NET starts and the 10% is done once the ASP.NET is completed, and done against ASP.NET generated HTML.
And make sure you're using source control! Code doesn't exist unless it's in source control! And thanks to the latest TFS PowerTools there's a lovely Windows Shell integration component so you don't need to use VS to check in and out now more :D

A: Use another approach like MVC, separate your design from your logic. Like this every member (designer / developer) of the team can focus on what they do best.
MVC implementations: link / link

A: This may sound really cheezy, but when I was working with Dreamweaver / Visual Studio, I'd do my layouts, and then conveniently put [RADIO BUTTON HERE], [INPUT TEXT HERE], etc. in the places where my form elements/controls would go, and I'd save the page as a basic HTML document.
That way Dreamweaver wouldn't nest its own form tags in and I'd have easy to locate places to drop in my ASP.NET controls when I went to merge things in. It was easy enough to create a fresh web form page in Visual Studio and then copy and paste everything over. If for some reason I mucked things up, I'd have a basic HTML "template" to start over wtih.

A: Unfortunately this is an all too common problem. Dreamweaver typically doesn't write html that is friendly to a .net developer. If at all possible, get someone who can actually read, and write HTML,not just use the Dreamweaver WYSIWYG editor.
I often found that if I'm working with a designer that doesn't know html, that I actually save a lot of time be just having them mock up everything in photoshop, then give me sliced up images. I find that my writing the actual HTML in a .net friendly format saves a ton of time, instead of having to go back and forth with the designer in this situation.


text:
Q: Which design pattern is the opposite of the Assembler pattern? As I understand it, an Assembler is a design pattern used to convert a domain object to a DTO.
What would you call the design pattern that is used to convert a DTO to a domain object ?

A: Data Transfer Object is the (P of EAA) design pattern. Assembler is just a name given to one of its components.
I think you could use the term Assembler when going in either direction (another common term is Mapper). Or you could say Assembler for domain object -> DTO, and Disassember for DTO -> domain object.


text:
Q: The digits of a positive integer, having three digits, are in A.P and their sum is $15$. The number .. The digits of a positive integer, having three digits, are in A.P and their sum is $15$. The number obtained by reversing the digits is $594$ less than the original number. Find the original number.
My Attempt:
Let the three digits number be $100x+10y+z$ where $x$, $y$ and $z$ are in A.P.
Then,
$y=\frac {x+z}{2}$
$2y=x+z$.
Then, what should I do??

A: So,
$$x-2y+z = 0$$
$$x+y+z = 15$$
$$100z+10y+x +594= 100x+10y+z \implies 99x-99z=594$$
i.e.
$$\left[ \begin{array}{ccc}
1 & -2 & 1 \\\
1 & 1 & 1 \\\
99 & 0 & -99 \end{array} \right] \left[ \begin{array}{ccc}
x \\\
y \\\
z \end{array} \right] = \left[ \begin{array}{ccc}
0 \\\
15 \\\
594 \end{array} \right]$$
Solving for $x,y,z$, our number is 852.

A: I wouldn't bother using algebra on such an easy problem. The three digits are in arithmetic progression and add up to $15$ so the middle digit is $5.$ Since the number is bigger than its reversal, the only possibilities are $654,753,852,$ and $951.$ Let's see, $654-456=198,$ nope. $753-357=396,$ nope. $852-258=594,$ we have a winner. The answer is $852.$

A: Suppose the number is $abc$, notice that $594=abc-cba=99(a-c)$, so $a-c=6$.
Since the digits are in arithmetic progression they must be $a,a-3,a-6$. Since they add $15$ we have $a=8$.
So the number is $852$

A: You have used the fact that the digits are in arithmetic progression.  You have not used the fact that the difference between the original number and the reversed number is $594$.  You need to do so.  Now you have $(100x+10y+z)-(100z+10y+x)=594$.  Does this help?

A: You are off to a good start, but you need to use all of the given information.
The fact that $x,y,z$ are an arithmetic progression means that $y = \dfrac{x+z}{2}$.
The problem also gives that the sum of the digits is $15$, i.e. $x+y+z = 15$.
Finally, reversing the digits gives the number $100z+10y+x$. So we have $100z+10y+x = (100x+10y+z)-594$.
Now, you have $3$ linear equations and $3$ unknowns. Is this enough to solve the problem?

A: You know that $x+y+z=15$, so if you replace $x+z$ with $2y$ in this equation, you'll find $y$. Also, using the fact that this is an arithmetic progression, you can say that $x=y+d$ and $z=y-d$, where $d$ is the difference of this progression (and $y$ already has a known numerical value). That leaves you with only one unknown quantity $d$. Set the difference of the original and reversed numbers to be equal $594$, and you'll be able to find $d$.


text:
Q: How to set the _CheckinComment with CSOM I'm looking for a way to set the _CheckinComment.
If i try It like this:
Microsoft.SharePoint.Client.File myUploadFile = myList.RootFolder.Files.Add(fileCreationInformation);
            ListItem myItem = myUploadFile.ListItemAllFields;
            myItem["Title"] = Path.GetFileName(sDocPath);
            myItem["_CheckinComment"] = "This is the comment";
            myClientContext.Load(myItem);
            myClientContext.Load(myUploadFile);
            myClientContext.ExecuteQuery();

I get Microsoft.SharePoint.Client.ServerException: ... The field that you want to upgrade, may be write protected.
I want to change the _CheckinComment (InternalName) and not this:
myUploadFile.CheckIn("This is the comment", CheckinType.OverwriteCheckIn)

Who can help?


text:
Q: error checking version of Rails     rails -v
/usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/2.0.0/tmpdir.rb:85:in `mkdir': ERROR: Failed to build gem native extension. (Gem::Ext::BuildError)

    Permission denied - ./.gem.20150402-853-1qotwlg

Gem files will remain installed in /usr/local/rvm/gems/ruby-2.0.0-p451/gems/json-1.8.2 for inspection.
Results logged to /usr/local/rvm/gems/ruby-2.0.0-p451/extensions/x86_64-darwin-13/2.0.0/json-1.8.2/gem_make.out
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/2.0.0/tmpdir.rb:85:in `block in mktmpdir'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/2.0.0/tmpdir.rb:142:in `create'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/2.0.0/tmpdir.rb:85:in `mktmpdir'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/ext/ext_conf_builder.rb:14:in `build'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/ext/builder.rb:161:in `block (2 levels) in build_extension'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/ext/builder.rb:160:in `chdir'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/ext/builder.rb:160:in `block in build_extension'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/ext/builder.rb:159:in `synchronize'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/ext/builder.rb:159:in `build_extension'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/ext/builder.rb:198:in `block in build_extensions'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/ext/builder.rb:195:in `each'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/ext/builder.rb:195:in `build_extensions'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/specification.rb:1436:in `block in build_extensions'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/user_interaction.rb:45:in `use_ui'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/specification.rb:1434:in `build_extensions'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/stub_specification.rb:60:in `build_extensions'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/basic_specification.rb:56:in `contains_requirable_file?'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/specification.rb:925:in `block in find_inactive_by_path'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/specification.rb:924:in `each'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/specification.rb:924:in `find'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/specification.rb:924:in `find_inactive_by_path'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems.rb:185:in `try_activate'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:132:in `rescue in require'
    from /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:144:in `require'
    from /usr/local/rvm/gems/ruby-2.0.0-p451@global/gems/rubygems-bundler-1.4.2/lib/rubygems_executable_plugin.rb:4:in `block in <top (required)>'
    from /usr/local/rvm/gems/ruby-2.0.0-p451@global/gems/executable-hooks-1.3.1/lib/executable-hooks/hooks.rb:50:in `call'
    from /usr/local/rvm/gems/ruby-2.0.0-p451@global/gems/executable-hooks-1.3.1/lib/executable-hooks/hooks.rb:50:in `block in run'
    from /usr/local/rvm/gems/ruby-2.0.0-p451@global/gems/executable-hooks-1.3.1/lib/executable-hooks/hooks.rb:49:in `each'
    from /usr/local/rvm/gems/ruby-2.0.0-p451@global/gems/executable-hooks-1.3.1/lib/executable-hooks/hooks.rb:49:in `run'
    from /usr/local/rvm/gems/ruby-2.0.0-p451/bin/ruby_executable_hooks:10:in `<main>'

A: Reinstall Ruby:
sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

With RVM
sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

And Rails
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs
gem install rails -v 4.2.0
rbenv rehash

Test
rails -v
# Rails 4.2.0


text:
Q: Переезд к новому хостеру Я впервые переезжаю на новый хостинг. На предыдущем хостинге был зарегистрирован домен. Что нужно, чтобы домен привязался к новому хостингу: только поменять запись А в панели управления доменом или что-то еще?
A: Хостинг-провайдер это не регистратор в большинстве случаев. У хостинг-провайдера заключен договор с регистратором. Регистратор предоставляет API посредством которого Вы можете регистрировать и в последующем управлять своим доменом из панели управления хостинг-провайдера. Вы можете выполнить 2 вида переноса доменного имени:1. Технический перенос домена - для этого необходимо указать NS сервера своего нового хостинг-провайдера в разделе управления записями DNS для домена в панели управления своего старого хостинг-провайдера. После этого необходимо разместить информацию о домене на NS серверах нового хостинг-провайдера, обычно эта процедура автоматизирована. Стоит отметить, что юридически домен остается на обслуживании у регистратора, с которым сотрудничает Ваш старый хостинг-провайдер, соответственно продлевать доменное имя прийдется тоже у него. Однако управлять DNS записями Вы сможете из панели управления нового хостинг-провайдера.2. Юридический перенос домена - это перенос доменного имени к регистратору, с которым заключен договор у Вашего нового хостинг-провайдера.Для этого необходимо связаться с доменной службой старого хостинг-провайдера и узнать в какой форме необходимо написать заявление на перенос доменного имени на обслуживание к новому регистратору. После этого нужно написать заявлению новому регистратору о желании перенести доменное имени к ним на обслуживании. В этом случае оплачивать продление доменного имени Вы сможете уже через нового хостинг-провайдера.P.S. Стоит отметить, что второй вариант хоть и сложнее, но предпочтительнее, т.к. избавит Вас от неприятностей в будущем.
A: Домен зарегистрирован на вас? Если да, в DNS поменять A запись. Если нет, позаботиться о домене, и поменять запись, в принципе всё. )
A: Если домен остается у хостера как у регистратора, то просто поменять запись типа А, так чтобы она указывала на ip нового сервера. А если домен переносится к другому регистратору, то еще поменять сервера имен.


text:
Q: How to stop public seeing error messages in PHP Pretty much if i mistake does happen in my php i do not want the public to see the error for security purposes, is there anyway of having like a log or file that only people with that file or access can see it?

A: Use the following line as the first line:
   error_reporting(0);

Another alternative is the .htaccess file.

A: You'll need to set the flag with php_flag log_errors on,
then use php_value error_log path to log file
To suppress warnings/errors you can use
php_flag display_errors off


text:
Q: How to make global objects for multithreaded applications I have a boost multi_index container
typedef multi_index_container<
    myData,
        indexed_by<
            random_access<>,  // keep insertion order
            ordered_non_unique< member<myData, time_t, &myData::timestamp> >
        >
> myContainerType;

class myDataOperator
{
    myContainerType myContainer;
    // some functions for inserting and searching myContainer
}

And another class which has general functionalities for whole project
class MasterClass
{
private:
    myDataOperator myOp;

public:
    // some general functionalities
    // some procedures using myContainer
}

And two classes which are going to work in threads by using the class MasterClass functionalities
class ThreadClass1
{
    private:
    MasterClass master;

    // some function calls of MasterClass with master
    // thread 1 internal functionalities
}

class ThreadClass2
{
    private:
    MasterClass master;

    // some function calls of MasterClass with master
    // thread 2 internal functionalities
}

Whenever I run the project, every thread (there will be more than 6 threads) creates its own MasterClass and myContainer object. What I want is to have one MasterClass object that handles all the functionalities and full control over the container by myDataOperator and one myContainer onject for all threads. So they need to be some kind of Singleton or Global I guess, but I don't know how to do it.
As far as I searched internet, I saw that I need some kind of synchronization or locking. So how can I make MasterClass and myContainer global (or singleton) where they serve all the threads?
Thanks.
Note: I am using Visal C++ in Visual Studio 2008 on a Win7 x64 computer

A: I think you need thread-safe singleton here.
http://www.nuonsoft.com/blog/2012/10/21/implementing-a-thread-safe-singleton-with-c11/


text:
Q: How to iterate over a list that has multiple sets of items in jsp I have a list as following
dnsList has
urls(url1,url2,url3 and so on) and their corresponding values of dns_time,update_time,status_code.
connList has
urls(url1,url2,url3 and so on) and their corresponding values of connection_time,update_time.
My servlet returns the dnsList,connList to jsp.Now I am trying to display it in jsp

 <c:forEach items="${dnsList}" begin="0" end="${fn:length(dnsList)}"var="dnsList" varStatus="iter">
 <c:forEach items="${connList}" begin="0" end="${fn:length(connList)}"var="connList" varStatus="iter">

 here I am displaying the values

 ${dnsList[0]}
 ${dnsList[1]}
 ${connList[0]}
 ${connList[1]}

 </c:forEach>
 </c:forEach>

My problem is I am getting the same results repeatedly for 2 times.For each url dnstime,connection time records are repeating for multiple times in browser.Please help me.How to iterate over the list.So that I get output in a table as
 Required output format is
-------------------------------------------------------------
url1
------------------------------------------------------
dns_time           connection_time
dns_update_time    conn_update_time
status_code

url2
-----------------------------------------
dns_time          connection_time
dns_update_time   conn_update_time
status_code

Please anyone can help me??

A: Make a JSON object and pass the parameters via the response of the servlet. So you'll get the array as such and can easily print it by a simple loop or counter increment.
 JSONArray urls=new JSONArray();
 JSONArray time=new JSONArray();
 //Input urls, time and so on ....
 JSONObject dnslist=new JSONObject();
 res.put("urls", urls);
 res.put("time", time);
 PrintWriter out=response.getWriter();
 out.println(res.toString());

This is in your servlet code.
Now your script code is :
$(document).ready(function(){
 something();
});

function something()
{
   $.ajax({
    type: "post",
    success: function(resp) {
    alert(resp);
    if(resp!=null)
    {
    var response=eval('('+resp+')');
    /*we do this to make resp as an object. O/w we get it as string*/

    urls=response.urls;
    time=response.time;

    }
   }});
}

Now urls and time contains both arrays and you can easily print them.
Start using JSON for passing values between sevlets and JSP pages. Hope this helps :)

A: It's better to do complex logic on server side and create special list of objects with required structure. Then you could have simple iteration.


text:
Q: LoopBack Storage Service: how to use upload/download methods from js code? How can I upload/download files in the simplest way using storageService.upload and storageService.download function from my JavaScript/Loopback code? I'm trying do something like that:
app.post("/sendFile", (req, res) => client.upload( req, res, {}, () => {console.log("cb")} ) );

But this doesn't work. I make my REST request with Advanced Rest Client Application in Google Chrome. I set Content-Type for multipart-form-data and add my jpg file in files section.
I got Failed to create a multipart upload on S3: {"message":"Missing required key 'Bucket' in params","stack":"MissingRequiredParameter: Missing required key 'Bucket' in params (...) error.
I'm newbie here, but I have impression that Loopback documentation should be much better. Thanks for help!

A: I got the exact same error, and fixed by adding a property to the req-object with your bucket name, before calling .upload() - like so:
app.post("/sendFile", (req, res) => {
  req.params.container = "name-of-your-bucket";
  client.upload( req, res, {}, (err, fileObject) => {});
});

Or an perhaps even better way if you are going to define some options:
app.post("/sendFile", (req, res) => {

  var options = {
    container: "name-of-your-bucket"
  };

  client.upload( req, res, options, (err, fileObject) => {});
});

To make upload/download work with Loopback I recommend this Stackoverflow question


text:
Q: New to coding having problems getting a output from this code I keep getting 0 as an output for taxRate and amount of taxes paid when I need to be getting a value back. the tax rate is 15% of the gross profit which makes the amt of taxes paid gross profit times tax rate.
import java.util.*;

public class ProfitProjection{

    double totalSales;
    double profitMargin;
    double projectedtotalSales;
    double grossProfit;
    double taxRate;
    double taxPaid;
    double netProfit;

    Scanner dataIn=new Scanner (System.in);

    public ProfitProjection(){

        System.out.print("Enter projected amount of total sales:");
        totalSales=dataIn.nextDouble();
        System.out.print("Enter the profit margin:");
        profitMargin=dataIn.nextDouble();

        taxRate = grossProfit * .15f;
        grossProfit = totalSales * profitMargin;
        netProfit = grossProfit - taxRate;
        taxPaid = grossProfit * taxRate;

        System.out.println("Projected total sales:" + totalSales);
        System.out.println("Profit margin:" + profitMargin);
        System.out.println("Estimated gross profit:" + grossProfit);
        System.out.println("Tax rate:" + taxRate);
        System.out.println("Amount of tax paid:" + taxPaid);
        System.out.println("Estimated net profit:" + netProfit);

    }

    public static void main(String args[]){

        new ProfitProjection();
    }

}

A: You only declared grossProfit without assigning any value to it, be default it is 0.0
public ProfitProjection(){
    grossProfit = 1.0; // assign value to it in your constructor
    taxRate = grossProfit * .15f;
}

A: In this line:
taxRate = grossProfit * .15f;
You never initialized grossProfit, but only declared it. Thus, the value is being treated as 0 and thus taxRate is getting set to 0.

A: You are doing the calculations in the wrong order.

*

*You use the value of grossProfit to calculate taxRate

*You calculate the value for grossProfit.

The problem is that in the first step, where you haven't yet calculated the real grossProfit value, its value will be 0.0.  This is due to Java's default initialization rule which applies to all fields of a class.

If a field is not explicitly initialized, or you can (somehow) see its
  value before explicit initialization takes places, then you will see
  the default initial value.

*

*false for a boolean,

*zero for any other primitive type,

*null for any reference type.

In short, you did the calculations in the wrong order.
Solution: change the order of those two statements ... and check that you haven't made the same mistake elsewhere.

In fact, there is another important mistake (maybe) ... that lead to this one not being detected.
You declared those variables as instance fields.  Given the code that written so far, they could have been declared as local variables.  If you had done that then the compiler would have told you that grossProfit is being used before it has been initialized.
I say this is maybe a mistake because it depends on whether there is more code / functionality that needs to be added later.

There are a couple of other errors:

*

*The taxRate variable is misnamed.  The tax rate is 0.015f.  What that variable contains is the actual tax payable,  not the tax rate.

*You should specify the tax rate as accurately as possible.  Use 0.015, not 0.015f.  The eff form is a float literal not a double literal.

A: What your problem is is that you are not setting gross profit before you set taxRate. So what the above answers are saying is slightly true, but not 100% I'll show you:
public class ProfitProjection{

double totalSales;
double profitMargin;
double projectedtotalSales;
double grossProfit;
double taxRate;
double taxPaid;
double netProfit;

Scanner dataIn=new Scanner (System.in);

public ProfitProjection(){

System.out.print("Enter projected amount of total sales:");
totalSales=dataIn.nextDouble();
System.out.print("Enter the profit margin:");
profitMargin=dataIn.nextDouble();

grossProfit = totalSales * profitMargin; //Swapped this line
taxRate = grossProfit * .15f;       //With this line to have grossProfit set at a value before multiplication.
netProfit = grossProfit - taxRate;
taxPaid = grossProfit * taxRate;

    System.out.println("Projected total sales:" + totalSales);
    System.out.println("Profit margin:" + profitMargin);
    System.out.println("Estimated gross profit:" + grossProfit);
    System.out.println("Tax rate:" + taxRate);
    System.out.println("Amount of tax paid:" + taxPaid);
    System.out.println("Estimated net profit:" + netProfit);

}
public static void main(String args[]){

    new ProfitProjection();
    }
}

Hope this helps!
Edit:
The change I made in the code above is I swapped the setting of grossProfit, and the setting of taxRate. I also added comments onto those lines.


text:
Q: Spring Security SQLException Подключил к учебному проекту Spring security. Но не слишком успешно. Пользовался этим tutorial:
https://tutorials.webencyclop.com/spring-boot/03-create-user-login-registration/#define-controllers-for-login-registration   Подскажите пожалуйста почему Spring выбрасывает SQL Exception  java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0). когда я пытаюсь залогониться. Провел куча часов пытаясь выяснить что не так, но так и не выяснил. Мой проект на гитхаб: https://github.com/SerhiiRyzhkov/english
Мой конфиг:
@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;

@Autowired
private DataSource dataSource;
@Value("${spring.queries.users-query}")
private String usersQuery;

@Value("${spring.queries.roles-query}")
private String rolesQuery;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.jdbcAuthentication().usersByUsernameQuery(usersQuery).authoritiesByUsernameQuery(rolesQuery)
            .dataSource(dataSource).passwordEncoder(bCryptPasswordEncoder);
}

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
            // URLs matching for access rights
            .antMatchers("/").permitAll()
            .antMatchers("/login").permitAll()
            .antMatchers("/register").permitAll()
            .antMatchers("/home/**").hasAnyAuthority("SUPER_USER", "ADMIN_USER", "SITE_USER")
            .anyRequest().authenticated()

            .and()

            // form login
            .csrf().disable().formLogin()
            .loginPage("/login")
            .failureUrl("/?error=true")
            .defaultSuccessUrl("/home")
            .usernameParameter("email")
            .passwordParameter("password")
            .and()
            // logout
            .logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/").and()
            .exceptionHandling()
            .accessDeniedPage("/access-denied");
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
   }

}

Мой контроллер:
@Controller
public class AuthenticationController {

@RequestMapping(value = { "/login" }, method = RequestMethod.GET)
public ModelAndView login() {

    ModelAndView modelAndView = new ModelAndView();

    modelAndView.setViewName("login");
    return modelAndView;
}
@RequestMapping(value = "/register", method = RequestMethod.GET)
public ModelAndView register() {
    ModelAndView modelAndView = new ModelAndView();
    // User user = new User();
    // modelAndView.addObject("user", user);
    modelAndView.setViewName("register");
    return modelAndView;
}

@RequestMapping(value = "/home")
public ModelAndView home() {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("home");
    return modelAndView;
}
}

JSP форма:
 <!DOCTYPE html>

   <title>English - login</title>

      <form th:action="@{/login}" method="POST">
      Login

      <input type="text" id="email" name="email" th:placeholder="Email"/>

      Password

      <input type="password" id="password" name="password" th:placeholder="Password"/>

      <button name="Submit" value="Login" type="Submit" th:text="Login"></button>
      Forgot password?
      </form>

Мой properies file:
 #Spring Security login queries
 security.basic.enabled=false
 spring.queries.users-query=select email, password, '1' as enabled from auth_user where email=? and  status='VERIFIED'
 spring.queries.roles-query=select u.email, r.role_name from auth_user u inner join auth_user_role ur on(u.auth_user_id=ur.auth_user_id) inner join auth_role r on(ur.auth_role_id=r.auth_role_id) where u.email=?

Когда я пытаюсь залогониться, я вижу что данные с формы уходят в контроллер:

Я так понимаю, что проблема в моем sql statement, но он практически такой же по синтаксису как дефолтный запрос в JdbcDaoImpl.class.
update
SQL Exception java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
Возникает в момент когда в форме логин пароль я нажимаю кнопку сабмит. В этот момент происходит запрос в базу данных, проверить имеются ли такие email и пароль в БД, и каков статус данного юзера? (забанен или нет). Сами запросы вынесены в файл application.properies - запросы приведены выше. Эти запросы инницируются с помощью
auth.jdbcAuthentication().usersByUsernameQuery(usersQuery).authoritiesByUsernameQuery(rolesQuery)
                .dataSource(dataSource).passwordEncoder(bCryptPasswordEncoder);

в классе SecurityConfiga. А сами statements передаются переменными usersQuery и rolesQuery. Ожидалось, что при вводе логина и пароля, SecurityConfig проверяет есть ли в базе такой пользователь или нет и впускает в приложение если пароль совпал в БД и статус usera VERIFIED. но меня не отправляет на страницу home и нет сообщения о успешном логине, а выбрасывается исключение


text:
Q: vuejs retorna objeto student null ao tentar buscar estudante por id Galera.
Eu estou com um problema agora.
Consegui resolver o erro 400,  mas agora eu não estou conseguindo retornar os dados do estudante pelo id dele.
Segue meu código abaixo:
    data() {
        return {
            student: {
                name: "",
                lastname: "",
                telephone: ""
            }
        }
    },
    methods: {
        async updateStudent() {
            const url = http://localhost:5000/students/student
            await axios.put(url, {
                name: this.student.name,
                lastname: this.student.lastname,
                telephone: this.student.telephone
            })
            .then((response) => {
                console.log(response)
                this.student = response.data
            })
            .catch((error) => {
                console.log("Erro!! " + error)
            })
        },
        clean() {
            this.student.name = ""
            this.student.lastname = ""
            this.student.telephone = ""
        },
        created() {
            this.updateStudent()
            this.clean()
        }
    }
}

erros:
[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'student' of null"

found in

---> <FormSearchStudent>
       <SearchStudent> at src/pages/Students/SearchStudent.vue
         <App> at src/App.vue
           <Root>
warn @ vue.runtime.esm.js?2b0e:619
logError @ vue.runtime.esm.js?2b0e:1884
globalHandleError @ vue.runtime.esm.js?2b0e:1879
handleError @ vue.runtime.esm.js?2b0e:1839
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1862
invoker @ vue.runtime.esm.js?2b0e:2179
original._wrapper @ vue.runtime.esm.js?2b0e:6917

TypeError: Cannot read property 'student' of null
    at submit (eval at ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"574491ba-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/Students/FormSearchStudent.vue?vue&type=template&id=6e70ea68& (app.js:1502), <anonymous>:15:43)
    at invokeWithErrorHandling (vue.runtime.esm.js?2b0e:1854)
    at HTMLFormElement.invoker (vue.runtime.esm.js?2b0e:2179)
    at HTMLFormElement.original._wrapper (vue.runtime.esm.js?2b0e:6917)
logError @ vue.runtime.esm.js?2b0e:1888
globalHandleError @ vue.runtime.esm.js?2b0e:1879
handleError @ vue.runtime.esm.js?2b0e:1839
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1862
invoker @ vue.runtime.esm.js?2b0e:2179
original._wrapper @ vue.runtime.esm.js?2b0e:6917

A: Para resolver este problema específico, no seu bloco catch, você deve tratar os dados para você ter um retorno esperado.
Segue um exemplo de como seria o block catch:
.catch((error) => {
    console.log("Erro!! " + error)
    this.student: {
            name: "",
            lastname: "",
            telephone: ""
        }
    })

Após fazer este tratamento não deve mais ocorrer o erro "TypeError: Cannot read property 'student' of null".
Porém gostaria de deixar claro que este não é a causa raiz do seu problema, apenas vai tratar para o objeto student não ser nulo, após ocorrer um erro na requisição.

A: As vezes o axios muda a referência do "this" e então você não consegue acessá-lo para atribuir o valor de resposta para "student", para resolver isso uma possível solução seria deixar seu método updateStudent da seguinte maneira:
async updateStudent() {
            let self = this;
            const url = http://localhost:5000/students/student
            await axios.put(url, {
                name: this.student.name,
                lastname: this.student.lastname,
                telephone: this.student.telephone
            })
            .then((response) => {
                console.log(response)
                self.student = response.data
            })
            .catch((error) => {
                console.log("Erro!! " + error)
            })
        };

A: Isso tem cara de problema de escopo (this), vc pode resolver fazendo assim:
methods: {
    async updateStudent() {
        try {
          const url = http://localhost:5000/students/student
          const { data } = await axios.put(url, {
            name: this.student.name,
            lastname: this.student.lastname,
            telephone: this.student.telephone
          })
          this.student = data
        } catch (error) {
          console.log(error)
        }

    },
    clean() {
        this.student.name = ""
        this.student.lastname = ""
        this.student.telephone = ""
    },
    created() {
        this.updateStudent()
        this.clean()
    }
}


text:
Q: php syntax with visual paradigm I'm getting an error on my PHP code when I try to reverse-egineer PHP code.
This line in particular
$adapter  = new \Geocoder\HttpAdapter\CurlHttpAdapter();

It's not liking the backslash. How can I fix this, is there better way in PHP to write this perhaps?
Reason :
Error occured when analysis: /home/vincent/dnseq/geo.php. Lexical error at line 189, column 29.  Encountered: "\\" (92), after : ""

A: That code is perfectly valid in PHP 5.3 and 5.4
Look like you need to update Visual Paradigm, or 5.3 is not supported.
http://forums.visual-paradigm.com/posts/list/288199.html


text:
Q: debug an evaluate expression on intellij Using evaluate expression/code fragment:
https://www.jetbrains.com/idea/help/evaluating-expressions.html
Is it possible to debug evaluated expression/code fragment on intellij?.
On eclipse if you launch a code evaluation on display window and that code has any breakpoint inside, eclipse debugger stops on that breakpoint. If you try again eclipse says it can execute inspections on nested debug session.
Intellij seems to launch expression in a different session.
My workflow on this is to stop on "whatever line" of code and add fragment I want to evaluate for a Q&D debug. Many times this leads to a debug restart.

A: Unfortunately it's not possible in Intellij 14 and stated in the official link you provided:

If a method invoked within the Expression Evaluation has a breakpoint inside its body, this breakpoint will be ignored.

To eliminate the problem you mentioned with frequent restarting of a debug session I use the following work-around with the drop-frame debug feature:

*

*Step in to a method and before return use the drop-frame functionality to fall back to a previous stack frame. See the drop-frame icon's location on the screenshot below:

*Now it's possible to rerun this method with different parameters without restarting the debug session (parameters can be set using Evaluate Expression dialog).

A: The feature is not available in IntelliJ IDEA 2019.2
The workaround I use is to update the code as follows,
                    Boolean shouldExecute = false;
                    if(shouldExecute){
                        //method call
                    }

During the debug session, I will change shouldExecute flag to true. This way I can debug the method call when needed.
Of coarse this is just a workaround, I need to remove this flag later.

A: Alt + F8 is the shortcut for evaluation of an expression or variable.
However, you can also select the variable, right click on it and evaluate as explained in this article.

A: Select the variable that you want to evaluate and press Alt + F8. Detail steps is given here:
https://www.websparrow.org/misc/shortcut-key-to-evaluate-expression-variable-in-intellij-idea


text:
Q: How To pull a text html attribute using HTMLabilityPack I need to pull the highlighted text from this Site I am using the code below and getting the error of Object reference not set to an instance of an object. I am Also using this Guide in the guide it says use Xpath expression. I go to the line i want and right click => copy => copy xpath. I get //[@id="profile"]/div2/div2/div1/div1/div1/div1/div/text()"); I have to escape the quotes. If i just do "//[@id="profile"]" then it works fine and i get profile, but i just cant get this to work and get the stat.
EDIT: What I need is to get the rank value. But i cannot simply call that one rank because rank is used for Solo, FPP Solo, and so on. But i am trying to get he "1,510,890" number currently.

[Command("test")]
[Alias("ti")]
public async Task Stats(string name)
{
    string path = "https://pubgtracker.com/profile/pc/" + name + "?region=agg";
    HtmlWeb web = new HtmlWeb();
    HtmlDocument Doc = web.Load(path);

    var htmlNodes = Doc.DocumentNode
                    .SelectNodes("//*[@id=\"profile\"]/div[2]/div[2]/div[1]/div[1]/div[1]/div[1]/div/text()");

    foreach (var node in htmlNodes)
    {
        foreach (var att in node.Attributes)
        {
            Console.WriteLine(att.Value);
        }
    }
}

A: EDIT: My previous answer is no longer valid, please read my new findings below.

I do not think what you are trying to do currently is possible.
It seems that the data that displays your Solo rank (and tons of other data) is being loaded in after the HTML is loaded (meaning that the javascript in the browser is handling some databinding after the html has been downloaded).
You can test this yourself in two ways:

*

*Put a debugger on the HtmlDocument Doc = web.Load(path); line in your code, and check the value of Doc.DocumentNode.InnerHtml, copy and paste this into Notepad++ or another text editor and look at the data thats there.  You will find that your rank is not loaded by the server (i.e its not available in the source HTML)

*Instead of inspecting element on the page in Chrome, right click and "View Source". This is the same data that HtmlAgilityPack sees when it "loads" the HTML into the object.  It does not allow javascript to run (meaning your values are never bound to any HTML).
The only way I can see to gather the data you need is to get the javascript object that is embedded in the source from the server.  You will see it towards the end of the document in a <script> tag.  Its a giant javscript object that (among other things) contains your rank.
You can see this for yourself by viewing the source like I explained above, and doing a Ctrl+F for your rank.  You will see it show up in two places in the object.


text:
Q: How can I compute the integral $\int_{\psi(0,1)}\frac{z+z^*}{z-1/2}$? I am working out some exercises that came with some notes on complex analysis. Forgive me if the answer is obvious, it's just not my day today. The tools I can use are:

*

*Cauchy's Integral Theorem

*Cauchy's Integral Formula (also for derivatives)

*Deformation Theorem

*A bunch of other theorems but they all rely on the integrand being holomorphic inside and/or the region enclosed by the contours.

*I can't use the Residue Theorem because it's not covered in the notes

$$\int_{\psi(0,1)} \frac{Re(z)}{z-1/2}\text{ }dz$$
By $\psi_{(0,1)}$ we understand the set of points $\{z:|z| = 1\}$.
Here's what I've tried:

*

*The first time I saw it, I tried to use Cauchy's Integral Formula. No good, because $Re(z)$ is not holomorphic anywhere.

*I had the idea to rewrite $Re(z)$ as: $$\frac{z+z^*}{2}$$ and split the integral. This allows me to work out the first half using Cauchy's, but not the second half.

*I tried rewriting the numerator as $z - i Im(z)$ but this looks about the same problem shifted on $Im(z)$ instead.

*I tried rewriting the integral in its explicit parameterisation. It didn't end up simplifying much. I arrived at:$$\int_0^{2\pi}\frac{i(\cos^2 (t) + \cos(t)\sin(t))}{e^{it}-\frac{1}{2}}dt$$

*I am not very confident when it comes to variable substitution in complex analysis. I suspect this might make the integral much easier to work it. I understand from the notes that a reparameterisation must be a 'continuously differentiable bijective function'.

The answer is listed as $\frac{i\pi}{2}$.

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\int_{\verts{z}\ =\ 1}{\Re\pars{z} \over z - 1/2}\,\dd z & =
\int_{\verts{z}\ =\ 1}{\pars{z + \overline{z}}/2 \over z - 1/2}\,\dd z =
{1 \over 2}\int_{\verts{z}\ =\ 1}{z + \pars{z\overline{z}}/z \over z - 1/2}\,\dd z
\\[5mm] & =
{1 \over 2}\int_{\verts{z}\ =\ 1}{z^{2}  + 1 \over z\pars{z - 1/2}}\,\dd z =
{1 \over 2}\, 2\pi\ic
\pars{{0^{2} + 1 \over 0 - 1/2} + {\pars{1/2}^{2} + 1 \over 1/2}}
\\[5mm] & =
\pi\ic\pars{-2 + {5 \over 2}} = \bbx{\large{\pi \over 2}\,\ic} \\ &
\end{align}


text:
Q: C++ pool allocator vs static allocation , cache performance Given that I have two parallel and identically sized arrays of the following structs:
    struct Matrix
    {
        float data[16];
    };

    struct Vec4
    {
        float data[4];
    }

    //Matrix arrM[256];  //for illustration
    //Vec4 arrV[256];

Lets say I wish to iterate over the two arrays sequentially as fast as possible.  Lets say the function is something like:
for (int i=0; i < 256; ++i)
{
    readonlyfunc(arrMPtr[i].data);
    readonlyfunc(arrVPtr[i].data
}

Assuming that my allocations are aligned for each array, both in the case of statically allocated or heap memory. Assuming that my cache line size 64 bytes.
Would I achieve the same cache locality and performance if I were to store my data as:
A)
//aligned
 static Matrix arrM[256];
 static Vec4 arrV[256];

 Matrix* arrMPtr = arrM[0];
 Vec4* arrVPtr = arrV[0];

vs
B)
//aligned
char* ptr = (char*) malloc(256*sizeof(Matrix)+256*sizeof(Vec4));

Matrix* arrMPtr = (Matrix*) ptr;
Vec4* arrVPtr = (Vec4*) ptr+256*sizeof(Matrix);

A: How the memory is allocated (heap or statically allocated) makes no difference to the memory's ability to be cached. Since both of these data structures are fairly large (1024 and 4096 bytes, respectively), the exact alignment of the first and last elements probably doesn't matter either (but it does matter if you are using SSE instructions to access the content!).
Whether the memory is close together or not won't make a huge difference, as long as the allocation is small enough to easily fit in the cache, but big enough to take up multiple cache-lines.
You may find that using a structure with 20 float values works out better, if you are working sequentially through both arrays. But that only works if you don't ever need to do other things with the data where having a single array makes more sense.
There may be a difference in the compiler's ability to translate the code to avoid an extra memory access. This will clearly depend on the actual code (e.g. will the compiler inline function containing the for-loop, does it inline the readonlyfunc code, etc, etc. If so, the static allocation can be translated from the pointer variant (which loads the address of the pointer to get the address of the data) into a constant address calculation. It probably doesn't make a huge difference in such a large loop as this.
Always, when it comes to performance, sometimes small things can make big differences, so if this is really important, do some experiments, using YOUR compiler, YOUR actual code. We can only give relatively speculative advice, based on our experience. Different compilers do different things with the same code, different processors do different things with the same machine code (both different actual architectures (whether it's instruction set architecture ARM vs X86, or implementation of the architecture such as AMD Opteron vs Intel Atom or ARM Cortex A15 vs Cortex M3). Memory configurations on your particular system will also affect things, how big caches are, etc, etc.

A: It's impossible to say without knowning more about what your doing and testing.  It might be more efficient to use a struct of arrays.
struct MatrixVec
{
    float m[16];
    float v[4];
};

One important point is that malloc allocates memory from the heap whereas static arrays are allocated on the stack.  The stack is already likely in the L1 cache whereas the memory from the heap will have to be read in.  Instead you can try a less known function for dynamic memory allocation called alloca which allocates memory on the stack.  In your case you could try
char* ptr = (char*) alloca(256*sizeof(Matrix)+256*sizeof(Vec4))

See Agner Fog's Optimizing software in C++.  See the section "9.6 Dynamic memory allocation".  Here are the advantages he lists for alloca compared to malloc

*

*There is very little overhead to the allocation process because the microprocessor
has hardware support for the stack.

*The memory space never becomes fragmented thanks to the first-in-last-out nature
of the stack.

*Deallocation has no cost because it goes automatically when the function returns.
There is no need for garbage collection.

*The allocated memory is contiguous with other objects on the stack, which makes
data caching very efficient.


text:
Q: Hibernate How to add a column in a middle table Here's the details.
I have 2 entity tables with one to many relationship.
First, Exam class has many Category class. Hibernate generates this tables
______________
Exam
- Id
- Name
- Category
______________
Category
- Id
- Name
______________
Exam_Category
- Exam_Id
- Category_Id

I need to add an extra column in Exam_Category table
ex:
______________
Exam_Category
- Exam_Id
- Category_Id
* User_Id

How am i going to accomplish this. if ever, how will i also get the user_id value because the Exam_Category is not exposed. Thanks

A: The best way to do this is to use a collection of elements.
@Entity
public class Exam {
    @CollectionOfElements(fetch = FetchType.LAZY)
    @JoinTable(name = "EXAM_CATEGORY", joinColumns = @JoinColumn(name = "FK_EXAM"))
    public Set<CategoryEntry> getCategories() {
        return this.categories;
    }
}

@Embeddable
public class CategoryEntry{

    private Category category;
    private User user;

    @ManyToOne
    @JoinColumn(name = "FK_CATEGORY", nullable = false)
    public Category getCategory() {
        return this.category;
    }

    @ManyToOne
    @JoinColumn(name = "FK_USER", nullable = false)
    public User getUser() {
        return this.user;
    }

// ... setters and such

}

@Entity
public class Category {
}

This approach is cleaner than mapping it as an entity, since, logically, it is not an entity to begin with.
Then you can add some other methods in Exam to get all the categories (without the users) or to retrieve it as a map, or whatever.  You can completely hide this intermediate object through encapsulation, if that is required.

A: This is the case of many-to-many relationship with three tables (three foreign keys) involved. This cannot be achieved in Hibernate by simple mapping. You will have to extend your definition of Entity classes to support custom primary key column on the "middle" table·
Check out this reference.

A: You could use a Map field in your Exam class. See this post


text:
Q: Apache .htaccess mod_rewrite - can't redirect to a file with the same prefix? Why this .htaccess rule doesn't work? I get 404 when requesting mydomain.com/login:
RewriteEngine On
RewriteRule ^login$ login.php [L]

If I change ^login$ to ^logn$ or login.php to login1.php it does work.
I can change my file names, but I wonder why it doesn't work.
The problem is happening on Ubuntu 14.04. Apache version: 2.4.2.
On my development Windows7 it seems to work fine.

A: Your rule is correct, but you probably have a problem with multiviews. Try it like this (only adding the top line, and giving you an optional slash after login so that login/ also gets redirected):
Options -Multiviews
RewriteEngine On
RewriteRule ^login/?$ login.php [L]


text:
Q: Is it reasonable to expect that in Linux, fd < maximum number of open file descriptors? I'm writing a server that needs to handle many open sockets, so I use setrlimit() to set the maximum number of open file descriptors (as root, before dropping privileges) like so:
#include <sys/resource.h>
#define MAX_FD_C 9001

if (setrlimit(
      RLIMIT_NOFILE, &(struct rlimit){.rlim_cur = MAX_FD_C, .rlim_max = MAX_FD_C}
    ) == -1) {
    perror("Failed to set the maximum number of open file descriptors");
    return EXIT_FAILURE;
}

Now, I realize there probably won't be any guarantees and that I'm at the mercy of whatever method the Linux kernel uses to implements file descriptor tables; but in practice, is it reasonable to assume that any fd this program receives from the Linux kernel will have a value less than the MAX_FD_C I set above?
I'd like to keep per socket data as compact as possible which could mean simply using an array like static struct client clients[MAX_FD_C] = {{0}}; and using the fd as the index to the client struct (which would basically be my own version of the FDT).

A: There are functions in the POSIX standard which assume this already.  Have a look at FD_SETSIZE, select(), FD_SET.


text:
Q: Error with the IdentityKey while trying to clone entity into another Context, using EF7 (core) I have been looking into different solutions regarding possibilities to copy entity from one context into another.
I keep facing the following error:

{"The instance of entity type 'Plugin.Core.Domain.Socket' cannot be
  tracked because another instance of this type with the same key is
  already being tracked. For new entities consider using an
  IIdentityGenerator to generate unique key values."}

To get a copy of the existing Socket I am using the following method:
public Socket GetCopyOfSocket(Socket socket)
        {
            if (socket == null) return null;
            var newSocket = DatabaseContext.Sockets.AsNoTracking().FirstOrDefault(s => s.SocketId == socket.SocketId);
            if (newSocket == null) return null;
            DatabaseContext.Entry(newSocket).State = EntityState.Detached;
            return newSocket;
        }

After this:
_newContext.Sockets.Add(newSocket);

The problem seems to be with the IdentityKey, because for example, the newSocket maintains its IdentityKey and if I already have existing Socket with the same IdentityKey on the destination Context, I receive the error described above.
But shouldn't the destination context automatically give the new instance of the Socket a new unique IdentityKey?

Both Context are new instances of the same SqLite DbContext schema,
  different files.

Edit 1
Partial solution for the problem seems to obediently follow the sequence of Add(newSocket) and SaveChanges()

However, after successfully saving entity, and after new entity received new Id and was saved into the database. I am calling custom GetLocal() method which gives the exact same error as above!
Error is happening on this line:
var data = Context.ChangeTracker.Entries<TEntity>().Select(e => e.Entity);

the error stays the same if I am replacing the previous line with:
var data = Context
                .ChangeTracker
                .Entries<TEntity>()
                .Where(e => e.State != EntityState.Detached)
                .Select(e => e.Entity);

Edit 2
(deleted many-to-many problem description, its ruled out as not to be the source of problem)
Edit 3
After adding the copy of newSocket, and calling SaveChanges() once everything is ok ( new entity receives new ID etc. ) But, if I call SaveChanges() second time right after, the exception happens. ?
Is there maybe something wrong with the way I handle dBContext ( lifetime etc.. ) ?

A: For the moment problem has disappeared after updating to Entity Framework Core RC2.


text:
Q: Is Ring $\mathbb C[x]/(x^2+1) \cong \mathbb C$
Is Ring $\mathbb C[x]/(x^2+1) \cong \mathbb C$

I had proved that Ring $\mathbb C[x]/(x^2+1)\cong \mathbb C$
is it right?
My attempt
$\mathbb C[x]/(x^2+1)=$ {$ax+b|a,b\in \mathbb C$} with $x^2+1=0$
also $x^2+1=0$
implies $x=i$
Putting this in above set
we are left with  C
Is it correct?
I will be thankful if someone correct me
Any help will be appreciated

A: By the Chinese Remainder Theorem we have
$$\mathbb C[X]/(X^2+1)\cong \mathbb C\times\mathbb C\not\cong \Bbb C.$$
Further reference: Error in proof: $\mathbb{C} \cong \mathbb{C} \times \mathbb{C}$??

A: $\mathbb{C}[X]/(X^2+1)$ is not isomorphic to $\mathbb{C}$ because it has divisor of zero, $X^2+1=(X-i)(X+i)$ we deduce that the image of $X+i$ by $\mathbb{C}[X]\rightarrow \mathbb{C}[X]/(X^2+1)$ is a divisor of zero. $\mathbb{C}$ does not have divisor of zero since it is a field.

A: Note that $\Bbb C$ is a field. That would imply $\langle x^2+1\rangle$ is a maximal ideal and hence a prime ideal in $\Bbb C$, which is not true (because $x^2+1=(x-i)(x+i)\in \langle x^2+1\rangle $, but $x-i, x+i\notin \langle x^2+1\rangle$).


text:
Q: remove checkbox item in ArrayAdapter and listview I make an application to show the name of a country in two languages, and a check box to use for contextual action mode.
After remove the selected item the checkbox auto checked next item.
I try to override getcount but it not work.
My code:
MyCountry.java
public class MyCountry {
private String nameEn;
private String nameVi;
private Drawable flag;
private boolean isCheck;
public String getNameEn() {
    return nameEn;
}
public void setNameEn(String nameEn) {
    this.nameEn = nameEn;
}
public String getNameVi() {
    return nameVi;
}
public void setNameVi(String nameVi) {
    this.nameVi = nameVi;
}
Drawable getFlag() {
    return flag;
}
void setFlag(Drawable flag) {
    this.flag = flag;
}
public MyCountry(String nameEn, String nameVi, Drawable flag) {
    // TODO Auto-generated constructor stub
    this.nameEn = nameEn;
    this.nameVi = nameVi;
    this.flag = flag;
}
public boolean isCheck() {
    return isCheck;
}
public void setCheck(boolean isCheck) {
    this.isCheck = isCheck;
}

}
CountryAdapter.java
public class CountryAdapter extends ArrayAdapter<MyCountry>{
Context context;
int layoutResourceId;
ArrayList<MyCountry> countries;
ContextualActionMode activity;
public CountryAdapter(Context context, int layoutResourceId,
        ArrayList<MyCountry> countries) {
    super(context, layoutResourceId, countries);
    // TODO Auto-generated constructor stub
    this.context = context;
    this.countries = countries;
    this.layoutResourceId = layoutResourceId;
    activity = (ContextualActionMode) context;
}
@Override
public int getCount() {
    return countries.size();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    //View v;
    final MyCountry country = countries.get(position);
    ViewHolder viewHolder = null;
    if(convertView == null)
    {
        viewHolder = new ViewHolder();
        //bươc 1: khoi tao doi tuong layoutInflater
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(layoutResourceId, null);
        viewHolder.nameEn = (TextView) convertView.findViewById(R.id.tvNameEn);
        viewHolder.nameVi = (TextView) convertView.findViewById(R.id.tvNameVi);
        viewHolder.flag = (ImageView) convertView.findViewById(R.id.ivFlag);
        viewHolder.check = (CheckBox) convertView.findViewById(R.id.checkBox1);
        convertView.setTag(viewHolder);
    }
    else
        viewHolder = (ViewHolder) convertView.getTag();
    viewHolder.nameEn.setText(countries.get(position).getNameEn());
    viewHolder.nameVi.setText(countries.get(position).getNameVi());
    viewHolder.flag.setImageDrawable(countries.get(position).getFlag());
    viewHolder.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // TODO Auto-generated method stub
            count = 0;
            for (MyCountry country : countries) {
                if(country.isCheck())
                    count++;
            }
            if(isChecked)
            {
                if(activity.actionMode == null || count == 0)//chua co
                activity.actionMode = activity.startActionMode(activity.callback);
                count++;
                country.setCheck(true);
            }
            else
            {
                country.setCheck(false);
                count--;
                if(count == 0)
                activity.actionMode.finish();
            }
        }
    });
    return convertView;
}
int count = 0;
public class ViewHolder{
    TextView nameEn;
    TextView nameVi;
    ImageView flag;
    CheckBox check;
}

}
ContextualActionMode.java
public class ContextualActionMode extends Activity {

ArrayList<MyCountry> countries = new ArrayList<MyCountry>();
ListView listView;
CountryAdapter adapter;

ActionMode.Callback callback = new ActionMode.Callback() {

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        // TODO Auto-generated method stub
        getMenuInflater().inflate(R.menu.floating_menu, menu);
        return true;
    }
    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        // TODO Auto-generated method stub

        switch (item.getItemId()) {
        case R.id.mnDelete:
            //for(int i = countries.size()-1; i >= 0; i--)
            for (int i = 0; i < countries.size(); i++)
            {
                if (countries.get(i).isCheck()) {

                    countries.remove(countries.get(i));

                }

            }

            adapter.notifyDataSetChanged();
            mode.finish();
            return true;
        default:
            break;
        }
        return false;
    }
};

ActionMode actionMode;

void initData() {
    String[] arrNameVi = getResources().getStringArray(R.array.nameVi);
    String[] arrNameEn = getResources().getStringArray(R.array.nameEn);
    TypedArray arrFlag = getResources().obtainTypedArray(
            R.array.country_flag);
    //Boolean[] checkbox=getResources().
    for (int i = 0; i < arrNameEn.length; i++)
        countries.add(new MyCountry(arrNameEn[i], arrNameVi[i], arrFlag
                .getDrawable(i)));

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initData();
    listView = (ListView) findViewById(R.id.listView1);
    adapter = new CountryAdapter(this, R.layout.item_listview_layout,
            countries);

    listView.setAdapter(adapter);

    listView.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            // TODO Auto-generated method stub
            actionMode = startActionMode(callback);
            actionMode.setTag(position);
            return false;
        }
    });
}

}
maybe problem here
case R.id.mnDelete:
            //for(int i = countries.size()-1; i >= 0; i--)
            for (int i = 0; i < countries.size(); i++)
            {
                if (countries.get(i).isCheck()) {
                 countries.remove(countries.get(i));
                }

            }

            adapter.notifyDataSetChanged();
            mode.finish();


text:
Q: When i use pacman -Syu, the package needed is not there for mingw So i want to download gcc using msys for c++ but my problem is when I use pacman -Syu, it doesn't show the needed package such as mintty or bash etc. Im very new with these things so this has been making me crazy. Sorry if what i'm saying isn't clear.
in case anyone has dealt with similar problems


text:
Q: What are the "smallest" topoi? Yesterday I was talking to somebody from the Haskell community.
Late in the night we found ourselves discussing possible topoi.
Lets order topoi (up to equivalence, ...) by number of objects/morphisms

*

*The smallest topos is a point (this is the only finite topos)

*Then there is FinSet (each topos has a functor from FinSet, and this is either "injective" on objects or the topoi in question is trivial)

*Next we (might) have Set

Questions:

*

*Are there topoi "in between" FinSet & Set?
(There are more Set-like topos, limiting by cardinality of the set, see nlab.)
Are there more toposes "in between" FinSet & Set?

*Is each topos with countable many objects automatically equivalent to FinSet? (take the minimum over all equivalent topoi ...)

Edits:

*

*added "definitions" of Set & FinSet (via linking nlab)

*I noted that the nlab entry already answers the first questions, so I made the question more precise

*added a rough definition of smallnes

A: Here are some examples, that should show you that there is a lot of countable toposes and lot of things in between finite sets and sets, too much to actually hope to list or classifies.

*

*First as I said a lots of usual construction of Grothendieck toposes have a finistic version, which produces elementary toposes (in fact, bounded toposes over FinSet most of the time). For example given a finite category $C$ the category of finite presheaves on $C$ is a topos, in fact you can even take a topology and look at finite sheaves. You can have a look to chapter 5.2 in the third volume of Borceux's handbook of categorical algebra for some details on these.

*If you have an inaccesible cardinal $\lambda$, then the category of sets of cardinality less than $\lambda$ is an essentially small elementary topos with a natural number objects.

*As mentioned by Todd Trimble, elementary toposes are a bit weaker than ZF because they don't allow for unbounded replacement. concretely it means that you can construct essentially small full subcategory of the category of sets that are elementary topos without invoking an inaccessible cardinal. If you take any set $X$, the full subcategory of sets that appears as element of $\mathcal{P}^{n}(X)= \mathcal{P} (\mathcal{P}( \dots \mathcal{P}(X)) \dots )$ for some $n$ ($\mathcal{P}(X)$ being the set of subsets of $X$) is an elementary topos. If $X$ is finite, this is justs the category of finite sets, but if $X$ is infinite it will have a natural number object, but it will be uncountable. This produces a lot of concrete example of full subcategory of the category of sets that are small toposes.

*Every time you have a model of ZF, its "category of sets" is a topos. Because of Löwenheim–Skolem there exists countable model of ZF, so this produces example of countable toposes admiting natural number objects.

*There exists a "free topos" which admit a unique logical morphisms to any topos, and a "free topos with a natural number object" which admit a unique logical morphisms preserving the natural number object to any topos with a natural number object, see there as well as the reference given there for more details. It admit a syntactical description which shows that it is countable (informally: its objects can be describe as certain formula involving the operation that you have in a topos, like taking power objects and finite limits, and there is only a countable number of these, same for the maps).


text:
Q: Is it possible to create a public static constructor anyway? In Visual Studio 2012 there is a rule saying that : Static constructors should be private, but the compiler doesn't allow this. So anyway can we create public static constructor?

Update: in the link, it says "If a static constructor is not private, it can be called by code other than the system.". It drives me to this question.

A: You must omit the public/private modifier:
public class Test
{
    static Test()
    {
    }
}

and in truth the concept of private static constructor is a little flimsy, because the static constructor is called (and can be called) only by the CLR (the runtime). So the private is present probably only because each method must have a modifier, not because it means anything (to make it clear: a private non-static constructor can be invoked by the class that defines it, while a static constructor can't be directly invoked by the class that defines it)
Note that technically, by writing directly IL code, you can make the static constructor public... Then you can call it as if it was a "normal" method... and bad things happen... To make it clear:
Base source code:
using System;
using System.Linq;
using System.Reflection;

public class Program
{
    static void Main(string[] args)
    {
    }
}

public class Test
{
    static Test()
    {
        ConstructorInfo ci = typeof(Test).GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).Single();
        Console.WriteLine("Static constructor: IsPublic: {0}, IsPrivate: {1}", ci.IsPublic, ci.IsPrivate);
    }
}

Compile it with Visual Studio.
From the Developer Command Prompt:
ildasm YourExe.exe /out:test.il

Change the Main body to
.entrypoint
// Code size       2 (0x2)
.maxstack  8
IL_0000:  nop

// we call manually the cctor (the static constructor)
call void Test::.cctor()
IL_0001:  ret

then change the Test.cctor signature to
.method public hidebysig specialname rtspecialname static
      void  .cctor() cil managed

(see the public?)
Now
ilasm test.il
test.exe

The output:
Static constructor: IsPublic: True, IsPrivate: False
Static constructor: IsPublic: True, IsPrivate: False

The static constructor has been executed twice: your call to the .cctor plus the automatic call that the CLR does to the .cctor. The check that a static constructor is run only once is done only when the static constructor is called by the CLR, not when you call it manually! :-)

A:
So anyway can we create public static constructor?

No, you cant, and you don't need to. Static constructors are not callable, and aren't used like regular constructors. They are used internally by the runtime to initialize static members of your class.

If a static constructor is not private, it can be called by code other
  than the system.", it drives me to this question.

Don't forget that code analysis is available for languages other than C#, where it is possible that a static constructor would be non-private. Hence why this warning exists. In C#, this could never happen.

A: Static Constructor does not have access Modifiers. Other Static elements do.
We can have static classes, fields, property and methods denoted with access modifier. But if you do so with static constructor:
//Static class with Access Modifier
public class SomeClass
{
    //Static Field with Access Modifier
    public static int intstatic = 0;

    //Static Property with Access Modifier
    public static string StaticProperty { get; set; }

    //Trying to declare static Constructor with Access Modifier
    public static SomeClass()
    { }

    //Static Method with Access Modifier
    public static void DoSomething()
    {
        Console.WriteLine(intstatic);
    }
}

It will result in compilation error.
"Access modifiers are not allowed on static constructors"
Haz, this will help you. go through it, it will clear your basics.
http://www.codeproject.com/Articles/891433/Must-Remember-Key-Concepts-to-Keyword-Static

A: No, you can not make a static constructor public or explicitly private in C# or VB.NET.
You could, however, possible do it in another programming language.
So the rule is there to highlight those problems.
For C# and VB.NET the rule will have no effect since you're unable to break it.
Whether it will matter is debatable since only the CLR can call the static constructor anyway, but that is why the rule exists.

A: Access modifiers make no sense in a static context.  This is because they can not be called by you directly, they are called implicitly by the .NET Framework.
What is guaranteed it that your static constructor will be executed at some point in time before the first call to any static content.
You have no control over when this might be, in practice, it almost invariably directly before the first time you access a static member.  Don't rely on this though.  Also, pay attention to whether your static constructor changes any state outside it's own class as this could mean some very weird, irreproachable bugs.


text:
Q: rsyncing files based on size I am trying to rsync files with the extension *.scala and only those no other files between two directories. If the size is different they should be synced. I am executing this command and seeing no scala files being synced even though I know the sizes are different.
rsync -rnvh --ignore-times --size-only --include '*/' --include '*.scala' --exclude '*' /home/salilsurendran/code/servlet-app /home/salilsurendran/code/sbt-runs/servlet-app/

With the -n option I am doing a dry run and the output prints out a bunch of directories but not any files. Please help

A: You were very close; as you need to move any file ending in .scala, not just any literal .scala, you need *.scala as the --include's glob pattern.
Do:
rsync -rnvh --ignore-times --size-only --include '*/' --include '*.scala' \
    --exclude '*' /source/ /dest/

A: rsync -nrvh --size-only --include="*/" --include=" * .scala" --exclude="*" /home/salilsurendran/code/servlet-app/ /home/salilsurendran/code/sbt-runs/servlet-app/ worked.
the issue was with the trailing '/' at the end of the from directory. Adding that made it work as I expected. Thanks.


text:
Q: Python 3 Ошибка "Удаленный интерпретатор инициализирован повторно" Друзья,только изучаю программирование. Изучаю по книжке. Там был такой пример: Вычислить площадь фигуры,ограниченной графиками y=x и y=x^2. И так же приведен листинг программы:
n=500
dz=1/n
pts=0
i=0
while i<=n:
    x=dz*i
    j=0
    while j<=n:
        y=dz*j
        if y<=x and y>=x**2:
            pts=pts+1
        j=j+1
    i=i+1
s=pts/((n+1)**2)
print ('Square of the figure:',s)

Однако у меня вместо результата площади, получается значение s=1 и пишет что "Удаленный интерпретатор инициализирован повторно"
Вот описание метода из книжки:

"При вычислении площади фигуры мы будем исходить из следующих
  соображений. Во-первых, замечаем, что область, ограниченная кривыми,
  полностью попадает в единичный квадрат с левой нижней вершиной в точке
  начала координат и правой верхней вершиной в точке с единичными
  координатами. Если мы случайным образом выберем точку внутри этого
  квадрата, то она с некоторой вероятностью попадает в область, что
  ограничена кривыми (то есть попадет внутрь "лепестка"). Теория
  вероятностей утверждает, что эта самая вероятность равна отношению
  площадей "лепестка" и квадрата. У квадрата с единичной стороной
  площадь равна единице. Поэтому площадь "лепестка" (которую нам
  необходимо вычислить) равняется вероятности, с которой случайным
  образом выбранная точка попадает внутрь "лепестка". Это будет
  "во-вторых". В третьих, если взятгь очень много случайных точек,
  равномерно распределенных по квадрату, и вычислить отношение
  количества точек внутри "лепестка" к общему количеству точек, в идеале
  получим оценку, близкую к вероятности попадания случайно выбранной
  точки внутрь "лепестка". Мы всю эту процедуру немного модифицируем и
  поступим следующим образом. Вместо того чтобы генерировать случайные
  точки, покроем весь квадрат равноотстоящими узловыми точками.
  Посчитаем, сколько их попало внутрь "лепестка" (то есть области,
  ограниченной кривыми), и поделим на общее количество точек. Это и
  будет результат. Программный код, в котором реализован такой подход,
  представлен в листинге"


text:
Q: Navigation Bar not visible in simulator but visible in storyboard Additional info >>
Just noticed that in my application didFinishLaunchingWithOptions: i've got this
self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
UIViewController *viewController = [[UIViewController alloc]  init];
viewController = [storyboard instantiateViewControllerWithIdentifier:@"frontScreen"];
self.window.rootViewController = viewController;
[self.window makeKeyAndVisible];

Is this part of the problem?
R
=================
Hi I'm developing an app in storyboard.
I'm using the publicly available SWRevealViewController to manage some navigation bar reveal menus.
I've set up a simple UIViewController, lets call it WelcomeViewController. I've dragged a segue from the RevealViewController to my new WelcomeViewController and then I've embed in a Navigation Controller. To the navigation bar I've added a menu reveal button.
All looks good in the storyboard, however when I run in the simulator the navigation bar isn't there.
I've added
self.navigationController.navigationBarHidden = NO;

in the viewWillAppear method - to no avail.
I should mention that I've got an entire branch of viewcontrollers and functionality already coming off the revealviewcontroller with no problems.
Any help. I've search stack overflow but found nothing that matches my specific problems. All advice gratefully received.
R

A: The storyboard entry point needs to be from the navigation controller and not the main view controller. That should make the navigation toolbar show up in the simulator.

A: Try adding
[[UIApplication sharedApplication] setStatusBarHidden:NO];

in the view controller's viewDidLoad method

A: Because the default navigation bar property translucent is set to YES
you can set it to NO on your second view page on viewDidLoad.
navi.translucent = NO;