text:
Q: C# OpenXml Selective Font Bolding I have a function that takes a couple of font parameters, and produces the required font in a RunProperties class. How can I turn on/off the Bold class? MSDN was pretty useless on this issue.
public RunProperties getRCFont(int size, string color = "000000", string font = "Futura Bk BT", bool bld = false, bool und = false) {

    return new RunProperties(new Bold() { Val = bld ? OnOffOnlyValues.On : OnOffOnlyValues.Off });

}

This doesn't work, produces this error:

Error 1 Cannot implicitly convert type 'DocumentFormat.OpenXml.Wordprocessing.OnOffOnlyValues' to 'DocumentFormat.OpenXml.OnOffValue'

But OnOffValue class has no properties!!
P.S. : Underline class has UnderlineValues class, but not for the Bold class (such as BoldValues), bah.
Edit - I'm sorry I got it. For anyone interested in the solution:
return new RunProperties(new Bold() { Val = bld ? new OnOffValue { Value = true } : new OnOffValue { Value = false } });

A: RunProperties(new Bold() { Val = bld ? new OnOffValue { Value = true } : new OnOffValue { Value = false } });

A: You can resume the line using bld instead of use the operator "?:"
RunProperties(new Bold() { Val =  new OnOffValue { Value = bld } });


text:
Q: What is use of resources in technical settings in Odoo 14 I was checking functionality of resources menu in technical settings under resource. Here is the path: Settings --> Technical --> Resource --> Resources.
But I didn't understand where to use this or what is use of this. I have googled it and also checked Odoo documentation but didn't find the use anywhere. What does this do?

A: Some modules call on this for their own use. For example, HR apps will use 'human' as a resource.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular using PrimeNG charjs problem with font colors Well I have this chart and I want to change the color of the labels
https://i.stack.imgur.com/vsw6x.png
the labels that are seen in gray I want to turn it to white, because it cannot be read
My code
HTML5:

Line Styles

TS:
lineStylesData: any;
lineOptions: any;

constructor() {}

  ngOnInit(): void {
    this.lineStylesData = {
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
      color: 'red',
      datasets: [
        {
          label: 'First Dataset',
          data: [65, 59, 80, 81, 56, 55, 40],
          fill: false,
          tension: 0.4,
          borderColor: '#42A5F5',
        },
        {
          label: 'Second Dataset',
          data: [28, 48, 40, 19, 86, 27, 90],
          fill: false,
          borderDash: [5, 5],
          tension: 0.4,
          borderColor: '#66BB6A',
        },
        {
          label: 'Third Dataset',
          data: [12, 51, 62, 33, 21, 62, 45],
          fill: true,
          borderColor: '#FFA726',
          tension: 0.4,
          backgroundColor: 'rgba(255,167,38,0.2)',
        },
      ],
    };

    this.lineOptions = {
      legend: {
        fontColor: '#fff',
      },
      scales: {
        xAxes: [
          {
            ticks: {
              fontColor: 'white',
            },
          },
        ],
        yAxes: [
          {
            ticks: {
              fontColor: 'white',
              beginAtZero: true,
            },
          },
        ],
      },
    };

  }

Any way to solve this problem with the font colors of the X and Y axis labels. Thanks in advance I tried various stack overflow codes with no positive results

A: You are using V2 syntax while using V3, there are some major breaking changes between these 2 version, for all changes please read the migration guide for all changes.
To resolve your issue you options need to look like this:
options: {
  scales: {
    x: {
      ticks: {
        color: 'white'
      }
    },
    y: {
      ticks: {
        color: 'white'
      }
    }
  },
  plugins: {
    legend: {
      labels: {
        color: 'white'
      }
    }
  }
}


text:
Q: Getting the error code message in twitter api request (java) I'm trying to use twitter api in the following way:
String urlAdd = "https://api.twitter.com/1/following/ids.json?user_id=1000123";
URL url = new URL(urlAdd);
URLConnection urlConnection = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

getInputStream input stream throws IOException, it happens because i've reached my request limit.
 I want to be able to distinghuish between request limit error and other errors. Twitter returns error message in json format, but i can't read it because of the thrown exception.
Any ideas on how can I fetch the error message?

A: I found a way to do it:
String urlAdd = "https://api.twitter.com/1/following/ids.json?user_id=1000123";
URL url = new URL(urlAdd);
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)urlConnection;
InputStream is;
if (httpConn.getResponseCode() >= 400) {
    is = httpConn.getErrorStream();
} else {
    is = httpConn.getInputStream();
}
BufferedReader in = new BufferedReader(new InputStreamReader(is));


text:
Q: How to extract data from a file and construct a filename from one of the values I'm trying to pull two values from a configuration file and write them to a new file. The hard part is that I want the name of the new file to be determined by one of the values in the input file.
The values I'm trying to pull are "Build_Version" and the four-letter acronym from the Docker name ("docker_Name").  For example, if the file says docker_Name='bcbs_pr-app-01', I want only the "bcbs". And I want to write them to a file with the build's name, such as bcbs_build.txt.
Here is an excerpt from the log file:
nonSSL_port=80  # FOR STAGING
Build_Type=prod
Build_Version=9.0.00.01_134143
docker_Name='bcbs-pr-app-01'

The desired file output is
bcbs
9.0.00.01_134143

I came up with a sed command that worked for pulling the values I wanted
sed -n -e '/Build_Version=/p' -e '/docker_Name=/p' environment-info.conf > build_version.txt

but this extracts the Build_Version= and docker_Name= lines in their entirety, and I want only the Build_Version and docker name values.
And I still need to figure out how to name the file with the four-letter Docker name acronym (bcbs).

A: 1) alternating your sed, to a) remove first single quote of docker_Name, b) remove -pr-app-01' (including the last single quote), c) remove the <value>= part:
 sed -n "/Build_Version=/s/.*=//p;/docker_Name=/s/.*=//;s/'//;s/-.*//p"

Where /match/s/pattern/replacement/ replaces pattern with replacement at a matching line. If replacement is an empty string, it is effectively removed. Note that I switched from single to double quotes to handle the single quote in your string and that you can use wildcards * . to match more complex strings and combine sed commands with a semi-colon.
2) We read in the two results as a BASH array:
values=( $( sed -n "/Build_Version=/s/.*=//p;/docker_Name=/s/.*=//;s/'//;s/-.*//p" file ) )

Where array=( value1 value2 value3 ) and $(do this command)
3) We use the array for our purposes, note that the counter starts at 0:
echo ${values[1]} > ${values[1]}
echo ${values[0]} >> ${values[1]}

Where we address an entry of an array via the array name and the intex of the entry ${array[intex]}.

A: That file looks like sh syntax. So, if that file is indeed a configuration file intended to be sourced in sh scripts, just do:
. ./environment-info.conf &&
  printf '%s\n' "${docker_Name%%-*}" "$Build_Version" > "${docker_Name%%-*}_build.txt"

A: Do you have to use sed for this? grep and perl can do what you need.
grep 'Build_Type\|docker_Name' environment-info.conf | perl -pe "s|docker_Name='(.*?)-.*|docker_Name=\1|" > build_version.txt

A: Using GNU sed:
sed -nr "s/^Build_Version=([^=]+)$/\1/p; s/^docker_Name='([^-]+).*/\1/p" file.txt

We are using capturing groups to get desired portions from the relevant lines. It has two parts:

*

*s/^Build_Version=([^=]+)$/\1/ gets us 9.0.00.01_134143

*s/^docker_Name='([^-]+).*/\1/ gets us bcbs
To save the output to build_version.txt:
sed -nr "s/^Build_Version=([^=]+)$/\1/p; s/^docker_Name='([^-]+).*/\1/p" \
        file.txt >build_version.txt

Example:
% cat file.txt
nonSSL_port=80  # FOR STAGING
Build_Type=prod
Build_Version=9.0.00.01_134143
docker_Name='bcbs-pr-app-01'

% sed -nr "s/^Build_Version=([^=]+)$/\1/p; s/^docker_Name='([^-]+).*/\1/p" file.txt
9.0.00.01_134143
bcbs

A: You are looking for a way to name the file with four letters from docker name. That can be achieved by the below command, which will assign the four letters to a variable called File_Name.
File_Name=`cat file | grep "docker_Name" | awk -F"'" '{print $2}' | awk -F'-' '{print $1}'`

As mentioned in above answers below command will assign the docker_Name and build_version to an array called values:
values=($(sed -n "/docker_Name=/s/.*=//;s/'//;s/-.*//p;/Build_Version=/s/.*=//p" file))

We are accessing the array in reverse order to capture the output the way you want:
for i in 1 0; do echo ${values[$i]} >> $File_Name.txt; done

File will be ready with name you want and cat will display its content:
% cat bcbs.txt
bcbs
9.0.00.01_134143


text:
Q: Calculating CPU usage on a Linux multicore machine using C I'm working on a program that shows the percentage of every process running on a machine with Linux. The problem is that the percentage I get often differs from the one displayed by the top command.
I searched for many hours on the web but what I find is almost always the same formula
100 * (stime + utime)/ (totalCPUTime - processStartTime).
I get the totalCPUTime summing the 7 CPU values in /proc/stat , while stime, utime and processStartTime are values taken form /proc/<pid>/stat.
Am I doing something wrong?
Does the fact that I am running the program on a multicore machine affect somehow the result?
Does somone know how the top calculates this value?
Thank you

A: If you want to know what top does you should have a look in the source code :)
top.c cvs repository
procps Homepage


text:
Q: Android - Setting the app's default "Open supported links" option How can I control the default Open supported links to either Ask every time or Open in this app for my Android app? Does it happen in the manifest?
I have two apps that try to accept the same universal link scheme, and the ideal behavior is to have the user decide which app to open when they click on the link. However, it seems that the first app correctly has the Open supported links in settings set to Ask every time, while the other app has the Open supported links as Open in this app. Thus, when both apps are installed, only the second one will be opened straight away, whereas the first one won't even be prompted.
The portion that accepts universal links in both of the AndroidManifest.xml files are almost identical.
<intent-filter android:autoVerify="true">
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:host="foo.bar.com" android:pathPrefix="/action/" android:scheme="https" />
</intent-filter>


text:
Q: When is my multiple AFJSONRequestOperations finished? I am starting multiple AFJSONRequestOperation in a for loop like this:
for(NSString *obj in collection)

operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

         //NSLog(@"success");

        }
        failure:nil];
[operation start];

How can I determine that all of my operations has finished?
I guess the operations are added a to the operationQueuein AFHTTPClient but I am not sure. Eitherway I dont know how to access the instance of the AFHTTPClient being used.

A: Outside the loop, define a counter (int) which is initially set to the number of elements of collection. In each completion block (that explicitly means, in success AND failure handler!) decrement the counter by one. If it reaches zero, all requests have been finished.
Caution: I'm not completely sure, but as far as I know, AFJSONRequestOperation won't invoke the handler blocks when it will be cancelled. Please consult the docs. (Personally, I think this is a design issue - but alas ... )
There are more elegant solutions to this problem. However, this would require a more specialized set of classes and tools which help to implement common asynchronous design patterns, like this one.

A: Add the AFJSONRequestOperation objects in a NSMutableArray (I'm using operations in this case) instead of starting each one, then use the method :
AFHTTPClient *client = [[AFHTTPClient alloc] initWithURL:baseURL];
[client enqueueBatchOfHTTPRequestOperations:operations progressBlock:nil completionBlock:^(NSArray *operations) {
    // called when all operations have finished.
}];


text:
Q: How to display map dynamically changed as per drilldown selectInput() based on previous selections?
I would like to render a map based on selectInput(). I have two selectInput()s: first one product_type and second one product_name. In the second one selectInput() the drop down options should be display only relevant to first selectInput(). Based on these drill down inputs map should change dynamically.
Here is the code:
ui <- shinyUI(dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    fluidPage(
      box("",
          leafletOutput("abc", width = '100%', height = 300),

          height = 350, width = 12),

      box("",
          selectInput('vtype', label = 'Prod Type',choices = brand$prod_type),
          selectInput('vname', label = 'Prod Name',choices = brand$prod_name),
          width = 4),

      valueBoxOutput("gr", width = 8)

    )
  )
))

server <- shinyServer(function(input,output,session){
  a <- ship %>% select(prod_name,prod_type,LON,LAT) %>% filter(prod_type == input$vtype)
  output$gr <- renderValueBox({
    box(table(a))
  })
  output$abc <- renderLeaflet({

      leaflet() %>% addProviderTiles(providers$OpenTopoMap )
%>% setView(lat = a$LAT ,lng = A$LON, zoom = 4)
  })

})

shinyApp(ui,server)

The dynamically changed points in the map should be marked up. I tried but could not able to build the code.
Any help on this code would be graceful for me.

A: I hope my example helps. I invented a data.frame 'ship' and made everything dependent on it. That means it is used for your variable 'brand' as well as 'ship'.
I'm not sure how you envisioned the value box, so I put category and products in it.
library(shiny)
library(shinydashboard)
library(dplyr)
library(leaflet)

ship <- data.frame(
    product_type = c("food","food","tool","tool","tool","accessories","accessories","lighting","lighting","lighting"),
    product_name=c("eggs", "bread","clamp","hammer","screw driver", "watch" ,"sun glases","LED","bulb","briquette"),
    LON=c(-61.783,2.632,47.395,20.068,44.563,17.544,-170.730,-65.167,136.189,50.562),
    LAT=c(17.078 ,28.163 ,40.430 ,41.143 ,40.534 ,-12.296 ,-14.318 ,-35.377 ,-24.973 ,26.019),
    stringsAsFactors = F)

ui <- dashboardPage(
    dashboardHeader(),
    dashboardSidebar(collapsed = TRUE, disable = FALSE),
    dashboardBody(
        # fluidPage(
            box(
                leafletOutput("abc", width = '100%', height = 300),
                height = 350,
                width = 12),

            box(
                selectInput('vtype', label = 'Prod Type', choices = c("< select product type>"="", ship$product_type)),
                selectInput('vname', label = 'Prod Name', choices = c("< select item>"="", ship$product_name)),
                width = 4),

            valueBoxOutput("gr", width = 8)
        #)
    )
)

server <- shinyServer(function(input,output,session){

    a <- reactive({
        ship %>%
            select(product_name, product_type, LON, LAT) %>%
            filter(product_type %in% input$vtype)
    })

    output$gr <- renderValueBox({
        valueBox( input$vtype, paste(a()$product_name, collapse=' - ') )
    })

    observe({
        updateSelectInput(session,
                          inputId='vname',
                          choices = c("< select item>"="", a()$product_name ))
    })

    output$abc <- renderLeaflet({
        leaflet() %>%
            addProviderTiles(providers$OpenTopoMap ) %>%
            setView(lng=0, lat=0, zoom = 1)
    })

    observe({
        selection <- a() %>% filter(product_name %in% input$vname)
        leafletProxy("abc") %>%
            flyTo(lat = selection$LAT,
                    lng = selection$LON,
                    zoom = 4)
    })
})

shinyApp(ui,server)

Please provide example data next time.


text:
Q: Lazy loading doesn't work for me inEntity Framework 4 I'm trying to enable Lazy Loading on an EF4 context.
The code that is trying to load the data is:
using (IUnitOfWork uw = new EFUnitOfWork())
{
    foreach (Document doc in uw.Documents.All)
    {
        Console.WriteLine("Name: {0} Description: {1} Category: {2}", doc.Name, doc.Description, doc.DocumentCategory.Name);
    }
}

I am experimenting with the Repository and Unit Of Work patterns but as I understand it, the command below should work.
ctx.ContextOptions.LazyLoadingEnabled = true;

The problem I have is when accessing doc.DocumentCategory.Name, I get a NullReferenceException.
Why isn't this data being loaded lazily?
If I have DocumentCategories loaded, the DocumentCategory property is resolved.
My Document class is defined as follows:
public class Document
{
    public Document()
    {

    }

    public Document(int id)
    {
        Id = id;
    }

    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual string Description { get; set; }
    public virtual int DocumentCategoryId { get; set; }
    public virtual bool Deleted { get; set; }
    public DocumentCategory DocumentCategory { get; set; }

    public override string ToString()
    {
        return Name;
    }
}

A: The DocumentCategory property also needs to be marked as virtual in order for lazy loading to be supported. Have a look at http://msdn.microsoft.com/en-us/library/dd468057.aspx

A: Is Document.DocumentCategory declared as virtual? EF requires this, to generate a proxy type, that will actually perform the lazy loading when you access the property. (Otherwise EF does not know, when you access the property's value)
Also, if DocumentCategory is already virtual, there might be other properties that prevend EF from generating a proxy-type. Inspect a "Document" instance with the debugger to see, whether it is actually a proxy-type.


text:
Q: I can't post a certain string of Arabic text here I am trying to post a bug report here that contains some Arabic text (it's an RTL issue). You can read the text of the bug report at this pastebin link: http://pastebin.com/raw.php?i=HCUHQdb8.
When I do so, I get one of those red boxes at the right side of the textarea that tells me my post cannot be submitted. You can read the text of that red box at this pastebin link: http://pastebin.com/raw.php?i=NT83uzFv. (Pastebin links so I don't trip the validator in this post, of course.)
I can't read Arabic, so I don't know what the problematic string says (though a helpful anonymous editor informs me that it says: "Hakeem/Hakim the lost Philosopher"), but I don't see any reason why any particular string of Arabic text would be excluded by the validation machinery.
In case this is a client-side issue - I'm using Chrome 35 on Windows 7.

A: Well, this is a blast from the past. About a year ago this happened, and we ended up blacklisting Arabic characters on a number of sites, most notably Ask Different. There may have also been a troll or two who kept making posts to trigger the vulnerability? I forget the specifics now.
Either way, it looks like that blacklist entry survived up until now here on MSE. I removed it. Let me know if you still have problems posting.

A: It seems like a legitimate rejection on the server-side validator.  It's literally handing back this JSON to inform us what the error is:
{"success":false,"errors":{"Body":["Body cannot contain \"<REDACTED>\"."]}}

It feels like a bug, but it could also be the case that Stack Exchange hasn't had a need to support this sort of text before.
If we try with a single character, the validation still fails. It could be the case that the validator just doesn't support those characters.


text:
Q: Transform multiple lists to dictionary of tuples I'm attempting to convert multiple lists into a dictionary where the initial list contains the keys.
For example:
list_keys = ['a' , 'b']
list_vals_1 = ['tick' , 'tack']
list_vals_2 = ['big' , 'small']

is transformed into:
expected = {}
expected['a'] = ('tick' , 'big')
expected['b'] = ('tack', 'small')
print('expected' , expected)

I could transform the lists using into a dictionary using:
mappings = {}
i = 0
for l in list_keys :
    mappings[l] = (list_vals_1[i] , list_vals_2[i])
    i = i + 1

Is there a cleaner/better solution using Python to accomplish this ?

A: try zip
dict(zip(list_keys, zip(list_vals_1, list_vals_2)))

{'a': ('tick', 'big'), 'b': ('tack', 'small')}

A: Use zip():
>>> {k: (v1, v2) for k, v1, v2 in zip(list_keys, list_vals_1, list_vals_2)}
{'a': ('tick', 'big'), 'b': ('tack', 'small')}

Also, for what it's worth, you could have used enumerate() to improve your existing solution:
for i, k in enumerate(list_keys):
    mappings[k] = (list_vals_1[i], list_vals_2[i])

By the way, note that l is a bad variable name since it looks like 1 and I. I used k instead - short for "key".


text:
Q: Youtube not loading completely in chrome Dont know why youtube is not loading completely in chrome.It was working fine till yesterday.Few screenshots are normal zoom pic and zoom:50%.My internet speed is fine as all other sites are opening normally, further youtube is also working well when I am it opening it with microsoft edge but really not getting why it is not loading completely in chrome.

A: Try the following:

*

*In the command prompt run: ipconfig /flushdns

*If possible, delete all browsing history/cookies from Chrome

*Disable ad-block or similar programs.

Once done see if it loads properly. If not, try to uninstall/reinstall chrome if that is an option for you.

A: Problem is with adblock filters.Updating them should fix the problem.


text:
Q: Не работает Ctrl + V в Android Studio Здравствуйте, встретился с необычной проблемой. В Android Studio не работает  Ctrl + V, пробовал также через контекстное меню, ничего не работает. А вот с Ctrl + C все нормально, копировал текст из студии в браузер, и все работает. Также не работают сочетание клавиш shift + F6 (переименовать), и F6 (переместить), однако с контекстного меню они работают замечательно.
Использую Windows 10, Android Studio 3.0.1
P.S.  Simple Paste работает нормально, и картинки в drawable тоже копируется нормально.


text:
Q: Populate in redshift the same entry with two csv Example:
Csv 1: key, d1, d2, d3
Csv 2: key, d4, d5
Expected on redshift: key, d1, d2, d3, d4, d5
Is this possible? In case you know how to do it tell me but my primary concern is if it is possible to start with.

A: Direct copy like this is not possible, you have the following options:
1) Use Redshift Spectrum service - create external schema and query it with a join to get the desired data structure in Redshift. The downside is that it's a pay per run service.
2) Process CSVs with Python or Athena to combine them into the desired data structure and then COPY it.
3) Import them separately into two staging tables and then join into the final table. The downside is that if your data is big it might be problematic to reserve 2x space (one for staging tables, another for resulting table) but you can simply create a view with join.

A: Directly, no, but you could either join the objects in your original ETL process, or use a staging table in Redshift, before then materialising it and dropping the staging tables.


text:
Q: Force DataGridView Entire Row selection I have a datagridview showing in a UI with a list of devices. I want to force the user to select the entire row instead of a single cell... Googling for awhile it looks like there is no way to force row selection using the methods supplied for datagridview.
I did this, which works 50% of the time, some times, however it doesn't. Any ideas?
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.Rows[dataGridView1.SelectedCells[0].OwningRow.Index].Selected = true;
}

A: There is an easy way, just set the SelectionMode to FullRowSelect:
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

A: This code works fine to Select the whole row when the user clicks on any cell in the DGV:
    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        dataGridView1.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
        dataGridView1.Rows[e.RowIndex].Selected = true;
    }

-Or- the simple ever way  is this (from project's "Properties"):


text:
Q: FXMLLoader.load() throws IllegalAccessError I am building javafx application in which i am trying to load .fxml file using FXMLLoader. Doing so, it throws IllegalAccessError Without FXMLLoader application runs fine. I am using Maven tool and dependencies are included:
<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-controls</artifactId>
    <version>15.0.1</version>
</dependency>
<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-fxml</artifactId>
    <version>15.0.1</version>
</dependency>

Overriden start method:
@Override
public void start(Stage primaryStage) throws Exception
{
    System.out.println(getClass().getResource(""));
    URL url = getClass().getResource("fxml/defaultScene.fxml");
    Scene scene = new Scene(FXMLLoader.load(url)); // <- exception occurs here
    ViewController viewController = new ViewController(scene);

module-info.java:
module DesktopApp
{
    exports core;
    requires javafx.graphics;
    requires javafx.fxml;
}

Exception:
java.lang.IllegalAccessError: superclass access check failed: class com.sun.javafx.scene.control.ControlHelpe
r (in unnamed module @0x67583cb) cannot access class com.sun.javafx.scene.layout.RegionHelper (in module javafx.graphics
) because module javafx.graphics does not export com.sun.javafx.scene.layout to unnamed module @0x67583cb

A: Solution is adding requires javafx.controls to module-info.java. It was compile-able, because there are no referenced classes from javafx.controls package in .java file and exception was raised because classes from javafx.controls are referenced in fxml file.


text:
Q: trying to add facebook like button on my website Below script will downlaod the facebook sdk to generate the code to create the like button
  (function() {
            var scrFaceBook = document.createElement('script');
            scrFaceBook.type = 'text/javascript';
            scrFaceBook.src = document.location.protocol +                            '//connect.facebook.net/en_US/all.js';
            scrFaceBook.async = true;
            document.getElementById('fb-root').appendChild(scrFaceBook);
        })();

I am doing like this to add the FaceBook like button. When I run my application and see I get "object does not support this property or method, all.js, uri: https://connect.facebook.net/en_US/all.js"
Can some one suggest me how do I fix this? Thanks in advance.

A: You forgot to add the

 to the body of the HTML.
Also you seem to have forgotten the APP ID

A: You need to make sure the dom element is declared above the script tag. Otherwise it might not load:

A: are your broswer support html5? maybe the error is here "scrFaceBook.async = true;"


text:
Q: Moving DotNetNuke From Local To Host I have installed DotNetNuke 5.6 on my local drive,now i want to move it to host to run web site. What steps should I do to run my web site?

A: If you haven't done anything to the site on your localhost, it might be easiest to have your host install a clean copy of DotNetNuke to a site for you. Many hosts will do that for you or provide automated tools to install it through their control panel.
In order to help you move a DotNetNuke site, we really need more details in order to provide a complete answer (your hosting company should be able to give you guidance) but the basics are:
1a. If you are just using SQL Express on the local host and plan to
use it under SQL Express on the host as well, you'll just need to
FTP up the DB files along with all the other files.
1b. If you'll be
running the DB under a full SQL Server: Backup your database on your
localhost, copy the DB backup to your host, and restore the database
to the database server provided by the host.
2. Create a blank website on the host.
3. FTP all site files from your localhost to the root directory of your new website.
4. Make sure the Network Service account has Full Access permissions to the root directory and all sub-directories.
5. If you're using a full SQL Server, you'll need to update connection strings in the web.config to point to the restored DB and
ensure you're using a user/login with read/write rights to the DB.
6. Browse to the site.

That should do it.


text:
Q: scala regex pattern giving matcherror I have a string
val path = "/bigdatahdfs/datalake/raw/lum/creditriskreporting/iffcollateral/year=2017/month=05/approach=firb/basel=3/version_partition=8/vFirbtestCollateralBaselIIIData_201705_8_20170620.txt.gz"

the pattern
.*version_partition=(\d+)(.*)

is working as expected in regex101.com.
Requirement is to extract two strings. one is "8" (exactly after version_partition=)and another is "/vFirbtestCollateralBaselIIIData_201705_8_20170620.txt.gz"
In scala REPL the same pattern is giving scala.MatchError. I am new in using regular expressions. Not sure what I am doing wrong here. Please help me here.
scala code is
val P = """.*version_partition=(\d+)(.*)""".r

val P(ver,fileName) = path;

I have tried with /g and /m flag also. It didn't work.

A: Your code works : https://scalafiddle.io/sf/Xz1Y0Ze/0
You don't need /g and /m flag.

*

*/g ==>  Perform a global match (find all matches rather than stopping
after the first match)

*/m ==>  Perform multiline matching

code :
val path = "/bigdatahdfs/datalake/raw/lum/creditriskreporting/iffcollateral/year=2017/month=05/approach=firb/basel=3/version_partition=8/vFirbtestCollateralBaselIIIData_201705_8_20170620.txt.gz"

val P = """.*version_partition=(\d+)(.*)""".r

val P(ver,fileName) = path;

println(ver)
println(fileName)

A: Try it using a match like this:
val path = "/bigdatahdfs/datalake/raw/lum/creditriskreporting/iffcollateral/year=2017/month=05/approach=firb/basel=3/version_partition=8/vFirbtestCollateralBaselIIIData_201705_8_20170620.txt.gz"
val P = """.*version_partition=(\d+)(.*)""".r

path match {
  case P(a,b) ⇒
    println(a)
    println(b)
}

Test

A: You accidentally added a white space at the end.
https://regex101.com/r/FLkZEu/2
The .* at the beginning of the regex is useless


text:
Q: A cycle is an even permutation iff its length is odd
Prove that for all pairwise distinct $a_1,a_2,\ldots,a_t \in \{1,2,\ldots,n\}, (a_1,a_2, \ldots a_t) \in A_n$ if and only if $t$ is odd.

How to prove the odd cycles of transposition will be product of even number of transpositions in this case

A: $(123\dots n)=(1n)(1n-1)\dots(12)$ for instance.  There's nothing special about $1,2,\dots,n$ here.Thus a cycle of odd length is even.


text:
Q: Cartesian product of nonempty closed convex subsets of R is a polyhedral I want to prove that for a finite number of $\mathcal{X}_i\subseteq\mathbb{R}$ that are nonempty, closed and convex, the set $\prod_{i} \mathcal{X}_i$ is a polyhedral set.
My solution: $\mathbb{R},(-\infty,b],[a,b],[a,+\infty),\{a\}$ for any $a<b$ are all the candidates for $\mathcal{X}_i$. All of these candidates are polyhedral sets, thus $\prod_{i} \mathcal{X}_i$ is a polyhedral set too.
Is this solution correct?
Thanks for your time!
EDIT: The definition that I'm using for polyhedral is $\{x\in\mathbb{R}^n:Ax\leq b,\ Cx=d\}$ for some matrices $A\in\mathbb{R}^{m\times n},C\in\mathbb{R}^{\ell\times n}$ and vectors $b\in\mathbb{R}^m,d\in\mathbb{R}^\ell$.


text:
Q: Change active to inactive using buttons realtime I am using DataTables with ajax using PHP CodeIgniter Framework. I am having a problem with switching Active buttons to Inactive buttons, vice versa.
What I want is:

When I click Active button, It should change to Inactive in realtime without refreshing the page.

Controller:
function activateStatus() {
    $id = $this->uri->segment(3);
    $data = array(
        'status' => 1
    );
    $this->equip_model->updateAccount('equip', $data, array('id' =>$id));
}

function deactivateStatus() {
    $id = $this->uri->segment(3);
    $data = array(
        'status' => 0
    );
    $this->equip_model->updateAccount('equip', $data, array('id' =>$id));
}

View:

          ID
          Status

    <?php
       foreach ($equip as $row){
    ?>

          <?= $row->id ?>

               <?php
               $status = $row->status;
               if($status  == "1") { ?>
                        <button id="<?php echo $row->id ?>" class="btn btn-xs green-jungle statusupdate1">&#10003</button>
               <?php } else  { ?>
                        <button id="<?php echo $row->id ?>" class="btn btn-xs red-flamingo statusupdate0" >&#10005</button>
               <?php } ?>

AJAX:
var oTable =  $('#equipmain').DataTable( {
            "searching": false,
            "processing":true,
            "columnWidth": 20,
            "serverSide": true,
            "autoWidth": true,

        });

$(document).on('click', '.statusupdate0', function() {
            var id = $(this).attr("id");

            $.ajax({
                url: "<?= base_url() ?>Admin/activateStatus/" + id,
                success: function (data) {
                    oTable.ajax.reload();
                }
            });

        });

        $(document).on('click', '.statusupdate1', function() {
            var id = $(this).attr("id");

            $.ajax({
                url: "<?= base_url() ?>Admin/deactivateStatus/" + id,
                success: function (data) {
                    oTable.ajax.reload();
                }
            });

        });

I don't know where is the error why the buttons are not working.

A: It may be that you are missing the semicolon (;) after your base_url() call. In the AJAX section for both buttons, try changing <?= base_url() ?> to <?= base_url(); ?> and see if that solves the issue.


text:
Q: if and else if statements ignored, Javascript I have a purple button. It becomes green onclick, even if in the if statement instead of purple I wrote Yellow.
Then it remains green, although the else if statement should make it purple again onclick.
What's wrong with my code?
`var m = document.getElementById ("buttonanimation");
    function changecolor(){
        if (m.style.backgroundColor="yellow"){
        m.style.backgroundColor="green";
        } else if (m.style.backgroundColor="green"){
        m.style.backgroundColor="purple";
        }
    }`

A: This symbol = is the assignment, not the comparison. if (m.style.backgroundColor="yellow") should be if (m.style.backgroundColor === "yellow").

A: use comparison operator if (m.style.backgroundColor==="yellow") instead of if (m.style.backgroundColor="yellow")


text:
Q: Is the scaling performed in a Right way for further use of the multiple linear regression? My data consists of variables such as Profit,R&D spend,Administrative spend and Marketing spend. I need to perform multiple linear regression to find the profit of these startups based on their spending. I got stuck in standardising the data using R. I used the scaling function for all the columns individually and put it into a new dataframe. I'm new to data science and need to ensure whether the scaling technique performed, (i.e) to have mean=0 and sd=1, is right or any other way to proceed ahead?
startup<-read.csv(file.choose())
View(startup)
install.packages("mnormt")
library(psych)
pairs.panels(startup)
attach(startup)
model.startup<-lm(Profit~R.D.Spend+Administration+Marketing.Spend)
summary(model.startup)

library(car)
vif(model.startup)

range(R.D.Spend)
range(Administration)
range(Marketing.Spend)
range(Profit)

Profitscale<-scale(Profit)
View(Profitscale)
summary(Profitscale)
sd(Profitscale)

RDscale<-scale(R.D.Spend)
summary(RDscale)
sd(RDscale)

Adscale<-scale(Administration)
Marscale<-scale(Marketing.Spend)

Scaled_startup<-data.frame(Profitscale,RDscale,Adscale,Marscale)
View(Scaled_startup)
pairs.panels(Scaled_startup)
attach(Scaled_startup)

model.startup1<-lm(Profitscale~RDscale+Adscale+Marscale)
summary(model.startup1)


text:
Q: How to delete a group permanently? I have been trying to permanently delete a group from 0365 via PowerShell by using AppRegistration but I keep getting Insufficient Permissions.
I can delete the group with Remove-PnPMicrosoft365Group or Remove-MgGroup and after these commands, the group is moved to deleted items. But when I try to delete the deleted group permanently, I always get insufficient permissions. Both Remove-MgDirectoryDeletedItem and Remove-PnPDeletedMicrosoft365Group did not work for me:

I also tried directly from Graph explorer but I received the same error although I consented all possible permissions.
By the way, I can permanently delete the deleted group from Azure Portal.
Any ideas ?
Thx

A: Just in case if anybody needs help for such requirement, there are two options:

*

*Give the app registration "Company Admin (Global Admin as of today)" as described here : https://konstantinvlasenko.wordpress.com/2016/12/22/microsoft-graph-api-insufficient-privileges-to-delete-a-group/
But this option will not work later than July 2023 because Microsoft is deprecating MSOL.

*App Registration usage is not possible for permanently deleting directory objects : https://learn.microsoft.com/en-us/graph/api/directory-deleteditems-delete?view=graph-rest-1.0&tabs=http
So you will need to use MSGraph with user authentication.
Just fyi, when you try to permanently delete O365 group from Graph Explorer, you will need to consent to Directory.AccessAsUser.All
Regards,


text:
Q: Bad request 400 error while acessing wcf rest service frequently I am facing the problem of Bad request 400 while accessing the wcf service. I have tried all the solution related to this topic but still not solved. Wcf service is on IIS7 .
I am trying to call the service with below code.
try
        {
            WebClient client = new WebClient();
            byte[] data = client.DownloadData(ApplicationRunTimeSettings.ServiceURL() + userID);
            Stream stream = new MemoryStream(data);

            DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(string));
            result = obj.ReadObject(stream).ToString();
        }
        catch (Exception)
        {

        }

        return result;

The config file at service is below, the config file is same for the wcf as well as web application. Actually wcf service is developed with in the web application and the web app hosted on iis7 and we are accessing the service with in it.
The configuration file is below. Most of the time it does not return error but it is breaking after some time. Request on the wcf service is frequent . Data is form of JSON.

Now after making the below suggested changes for serviceThrottling the web.config file look like mentioned below but it still gives the same error some times.
 <system.web>
<sessionState timeout="1440"/>
<customErrors mode="Off"/>
<httpRuntime executionTimeout="90" maxRequestLength="104857600" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" enableVersionHeader="true"/>
<!--set compilation defug="false" when releasing-->
<compilation targetFramework="4.0" >
  <assemblies>
    <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
  </assemblies>
</compilation>
<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" timeout="86400"/>
</authentication>
<pages>
  <namespaces>
    <add namespace="System.Web.Helpers"/>
    <add namespace="System.Web.Mvc"/>
    <add namespace="System.Web.Mvc.Ajax"/>
    <add namespace="System.Web.Mvc.Html"/>
    <add namespace="System.Web.Routing"/>
    <add namespace="System.Web.WebPages"/>
  </namespaces>
</pages>
</system.web>
<system.webServer>
<security>
  <requestFiltering>
    <!-- maxAllowedContentLength = bytes -->
    <requestLimits maxAllowedContentLength="104857600"/>
  </requestFiltering>
</security>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0"/>
  </dependentAssembly>
</assemblyBinding>
</runtime>
<system.serviceModel>

<services>
  <service name="Glance.DynamicBusinessService.DynamicBusinessService" behaviorConfiguration="ServiceBehaviour">
    <!-- Service Endpoints -->
    <!-- Unless fully qualified, address is relative to base address supplied above -->
    <endpoint address="customBinding" binding="customBinding" bindingConfiguration="basicConfig" contract="Glance.DynamicBusinessService.IDynamicBusinessService"/>
    <endpoint address="" binding="webHttpBinding" contract="Glance.DynamicBusinessService.IDynamicBusinessService" behaviorConfiguration="REST">
      <!--
          Upon deployment, the following identity element should be removed or replaced to reflect the
          identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity
          automatically.
      -->
    </endpoint>
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="throttleThis">
      <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
      <serviceMetadata httpGetEnabled="True" />
      <serviceThrottling
          maxConcurrentCalls="40"
          maxConcurrentInstances="20"
          maxConcurrentSessions="20"/>

      <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="REST">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<bindings>

  <webHttpBinding>
    <binding maxReceivedMessageSize="999999999" receiveTimeout="24" closeTimeout="24" maxBufferPoolSize="999999999" maxBufferSize="999999999">
      <readerQuotas maxDepth="32" maxStringContentLength="999999999" maxArrayLength="99999" maxBytesPerRead="4096" maxNameTableCharCount="99999" />
    </binding>
  </webHttpBinding>

  <customBinding>
    <binding name="basicConfig">
      <binaryMessageEncoding/>
      <httpTransport transferMode="Streamed" maxReceivedMessageSize="67108864"/>
    </binding>
  </customBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="0"/>
</system.serviceModel>
</configuration>

Thanks for any suggestion and help.

A: I'd be tempted to comment out that  configuration line on the client and host, and then trying running it. That config seems to set minimums and performance limits. If that doesn't change anything, you might try setting the performance throttling.
You could add this to the configuration and tinker with the settings until the performance of your web service smooths out. The default, for instance, for concurrent calls is 16, but if you raise that number using the ServiceThrottling, you might get better results.
<serviceBehaviors>
        <behavior name="throttleThis">
            <serviceMetadata httpGetEnabled="True" />
            <serviceThrottling
                maxConcurrentCalls="40"
                maxConcurrentInstances="20"
                maxConcurrentSessions="20"/>
        </behavior>
    </serviceBehaviors>


text:
Q: Alerting a user when someone replies to their post I have an application that allows users to submit posts and comment on other posts. Is it possible to alert the user when someone comments on their post using connect-flash? How else can I do this? I am using node.js and express and mongodb

A: You can have 2 approaches:

*

*On your client side make some GET request in some time frame, and ask if that post is commented

*(preferred) Using web sockets (for eg. Socket.IO), make socket between client and server, then when post is commented, send that information to client.
And for both options, make some alert logic on client side


text:
Q: TestCafe: Selector within Selector I work on a set of helpers for my page model.
This is how the DOM may look like:

hello

world

hello

world

Now I want to inspect one of the.child elements within #parentA or #parentB.
import { Selector } from "testcafe";

fixture `children`
    .page `http://localhost:8080/index.html`;

// an example of what I expect.
// this is not how i want to write tests.
test("hard-coded: child in A has class 'yes'", async (t) => {
    const yesChild = Selector("#parentA .child").withText("hello");
    t.expect((await yesChild.classNames).includes("yes"));
});

// helper function for the page model (in a shared module later)
function getParent(name: string) {
    return Selector(`#parent${name}`);
}
// helper function for the page model (in a shared module later)
function getChild() {
    return Selector(".child");
}

// this is how I want to write tests.
test("parametric-find: child in A has class 'yes'", async (t) => {
    const parent = getParent("A");
    const child = getChild().withText("hello");
    const yesChild = parent.find(child); // there is no overload for find that takes another Selector.
    t.expect((await yesChild.classNames).includes("yes"));
});

I think one solution could be a function like this:
async function withinParent(child: Selector, parent: Selector): Selector {
   // how should I implement this?
}

Another solution could be a higher order function that creates the filterFunction:
test("parametric-find-descendantChild: child in A has class 'yes'", async (t) => {
    const parent = getParent("A");
    const child = getChild().withText("hello");
    const yesChild = parent.find(descendantChild(child));

    t.expect((await yesChild.classNames).includes("yes"));
});
function descendantChild(child: Selector): (node: Element) => boolean {
    // how should I implement this?
}

but all the approaches I can think of lead to dead-ends.

*

*parent and child could match multiple elements

*there is no easy way to access an element selected by a selector in order to compare it to another selector

*how do I compare Selectors?

*functions/callbacks that operate on the Element level are executed in the browser. How cold I pass a Selector or the Elements matched by a selector into a browser function?

Well, should I write a feature request, or is there a smart way to do this?

A: You can chain Selector methods to achieve this.
function getParent(name) {
    return Selector(`#parent${name}`);
}

function getChildren(selector) {
    return selector.child('.child');
}

test(`parametric-find: child in A has class 'yes'`, async (t) => {
    const parent = getParent('A');
    const child  = getChildren(parent).withText('hello');

    await t.expect(child.classNames).contains('yes');
});


text:
Q: H2 database: Column "U" must be in the GROUP BY list; SQL statement My native query looks like this:
SELECT u
FROM (SELECT max(difficulty), u
      FROM (SELECT sum(difficulty) AS difficulty, username AS u
            FROM user_answer ua
                     JOIN question q ON ua.question_id = q.id
                     JOIN answer a ON ua.answer_id = a.id
                     JOIN user_quiz uq ON ua.user_quiz_id = uq.id
                     JOIN account ac ON uq.account_id = ac.id
            WHERE a.correct = 1
              AND uq.quiz_start_date_time >= (CURDATE() - INTERVAL 7 DAY)
            GROUP BY ua.user_quiz_id
            ORDER BY difficulty DESC) AS max_week) as d_u

Everything works fine in MySQL. I have an error in the H2 database:
org.h2.jdbc.JdbcSQLSyntaxErrorException: Column "U" must be in the GROUP BY list; SQL statement:
SELECT u FROM (SELECT max(difficulty), u FROM (SELECT sum(difficulty) AS difficulty, username AS u FROM user_answer ua JOIN question q ON ua.question_id = q.id JOIN answer a ON ua.answer_id = a.id JOIN user_quiz uq ON ua.user_quiz_id = uq.id JOIN account ac ON uq.account_id = ac.id WHERE a.correct = 1 AND uq.quiz_start_date_time >= (CURDATE() - INTERVAL 7 DAY) GROUP BY ua.user_quiz_id ORDER BY difficulty DESC) AS max_week) as d_u [90016-200]

how to fix it?

A: Simply add an aggregation function around username
    SELECT u
    FROM (SELECT max(difficulty), u
          FROM (SELECT sum(difficulty) AS difficulty, MAX(username) AS u
                FROM user_answer ua
                         JOIN question q ON ua.question_id = q.id
                         JOIN answer a ON ua.answer_id = a.id
                         JOIN user_quiz uq ON ua.user_quiz_id = uq.id
                         JOIN account ac ON uq.account_id = ac.id
                WHERE a.correct = 1
                  AND uq.quiz_start_date_time >= (CURDATE() - INTERVAL 1 MONTH)
                GROUP BY ua.user_quiz_id
                ORDER BY difficulty DESC
            ) AS max_month
        GROUP BY u
        ) as d_u

When the option ONLY_FULL_GROUP_BY is enabled you need to have all columns with aggregation functions or have them in the GROUP By see https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html


text:
Q: Powershell find applications site collection is using Is there a way in powershell to find out what Service Apps a site collection is using.
Having some trouble with a site collection that was created when we had a faulty Search Service app, created a new Search Service app, items in that site collection were not coming back so created a new site collection and that now works fine. So just want to understand why the first site collection isn't working.


text:
Q: I want to create an array of scene indexes and use it, when i need. The problem is that i don't know how to create the array itself I did this
    public int[] sceneIndex;
    public Text[] texts;

    IEnumerator ChoosingModes()
    {
        string[] modes = new string[] { "Cocks", "Tanks", "Cars" };
        sceneIndex = new int[] { };
        for (int i = 0; i < 5; i++)
        {
            int x = Random.Range(0, modes.Length);
            texts[i].text = modes[x];
            sceneIndex[i] = x + 3;
            yield return new WaitForSeconds(0.75f);
        }
    }

It obviously doesn't work, what to do with my in array named 'sceneIndex'?

A: When you do sceneIndex = new int[] { };, you're locking the length of the length of sceneIndex to 0. Instead, try either sceneIndex = new int[number or scenes]; (locking the length of sceneIndex to the number of scenes you have) or just doing nothing. Since the array is public, you can set the values in the inspector and you won't have to define it in the code.


text:
Q: Universal Image Loader with PhotoView I've united these two classes. Why doesn't work??? HELP ME
06-14 06:35:38.250: E/AndroidRuntime(1774): FATAL EXCEPTION: main
06-14 06:35:38.250: E/AndroidRuntime(1774): Process:          com.nostra13.example.universalimageloader, PID: 1774
06-14 06:35:38.250: E/AndroidRuntime(1774): android.view.InflateException: Binary XML file line #6: Error inflating class PhotoView
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:707)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at com.nostra13.example.universalimageloader.ImageGridActivity$ImageAdapter.getView(ImageGridActivity.java:106)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.widget.AbsListView.obtainView(AbsListView.java:2263)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.widget.GridView.onMeasure(GridView.java:1044)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.View.measure(View.java:16497)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.View.measure(View.java:16497)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.View.measure(View.java:16497)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.View.measure(View.java:16497)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.Choreographer.doCallbacks(Choreographer.java:574)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.Choreographer.doFrame(Choreographer.java:544)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.os.Handler.handleCallback(Handler.java:733)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.os.Handler.dispatchMessage(Handler.java:95)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.os.Looper.loop(Looper.java:136)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.app.ActivityThread.main(ActivityThread.java:5017)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at java.lang.reflect.Method.invokeNative(Native Method)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at java.lang.reflect.Method.invoke(Method.java:515)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at dalvik.system.NativeStart.main(Native Method)
06-14 06:35:38.250: E/AndroidRuntime(1774): Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.PhotoView" on path: DexPathList[[zip file "/data/app/com.nostra13.example.universalimageloader-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.nostra13.example.universalimageloader-1, /vendor/lib, /system/lib]]
06-14 06:35:38.250: E/AndroidRuntime(1774):     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.LayoutInflater.createView(LayoutInflater.java:559)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.LayoutInflater.onCreateView(LayoutInflater.java:652)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:66)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
06-14 06:35:38.250: E/AndroidRuntime(1774):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
06-14 06:35:38.250: E/AndroidRuntime(1774):     ... 35 more

A: It is telling that it didn't find class "android.view.PhotoView". PhotoView is not a standard Android view so it must be a custom view. When using custom views in XML, you have to write its full package name like this:
<com.nostra13.example.views.PhotoView
      android:id="@+id/myPhotoView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />

I assumed PhotoView is in com.nostra13.example.views package.


text:
Q: On usage of DbContext in ASP.NET using EF 6.1.1 Since I have been working on my web application with MVC framework, I have been wondering about where I should have a definition of DbContext. I am aware of memory leak and normally, that is in ConsoleApplication, I would enclosed usage of DbContext withing using() {} clause. However, Web Application seems to be different and I am pretty sure lifetime of DbContext is different and I cannot just dispose it a controller and then try to read from it in Views. Or maybe I am wrong here. At first, I was creating multiple references in each Action. I came with this idea to put DbContext definition as a readonly private field within each controller:
public HomeController : controller
{
    private readonly MyDBContext myDbContext = new MyDBContext();

    // ... and in actions

    public ActionResult Index()
    {
        // ... usage of myDbContext
    }

    public ActionResult Create()
    {
        // ... usage of myDbContext
    }

    public ActionResult Edit()
    {
        // ... usage of myDbContext
    }

    public ActionResult Delete()
    {
        // ... usage of myDbContext
    }
}

Do you think it is correct.
Cheers!

EDIT:
I changed the code to this:

public ActionResult Index()
{
    IQueryable<MyViewModel> viewModel = null;
    using (MyDBContext dB = new MyDBContext())
    {
        viewModel = from st in dB.Students
                    join d in dB.Departments on st.DepartmentID equals d.DepartmentID
                    join g in dB.Genders on st.GenderID equals g.GenderID
                    select new MyViewModel
                    {
                        StudentID= st.StudentID,
                        StudentName = st.StudentName,
                        Gender = g.GenderName,
                        DepartName = d.DepartmentName
                    };
    }
    return View(viewModel);
}

and exception was thrown saying: "The operation cannot be completed because the DbContext has been disposed" when I refer to @Model in View in the line:
@foreach (MyViewModel item in @Model) // compiler points at @Model

PLEASE Note that the code works otherwise, without any other changes but removing using() {}.

A: Nothing is different. The Controller is dead when the view is called. Use using within the actions in the controller, so not keep a DbContext around.
Generally: NOTHING is different in MVC than in any other .NET technology, in regards of the handling of and EF context.

A: Try a ToList as in select new {...}.ToList()
You are trying to access a data from a querable source. That source is closed on the end of the using scope.

A: Since viewModel is an IQueryable<MyViewModel>, it doesn't hold the data in the controller. It contains an execution plan of your query which will be executed when you do this in your view
@foreach (MyViewModel item in @Model)

You got the error because the above syntax is outside of the using block so the DbContext is already disposed and the query can't be executed at that moment. Although removing the using block would make the code works without any errors, it's not the best practice for MVC. The model is supposed to only hold the data and the view isn't supposed to do any database operations at all.
The correct way for your case is using IEnumerable<MyViewModel> instead of IQueryable<MyViewModel> as the model, so viewModel will hold the data after the using block. You can use ToList() method to force the execution of the query inside the using block as below
public ActionResult Index()
{
    IEnumerable<MyViewModel> viewModel = null;
    using (MyDBContext dB = new MyDBContext())
    {
        viewModel = (from st in dB.Students
                    join d in dB.Departments on st.DepartmentID equals d.DepartmentID
                    join g in dB.Genders on st.GenderID equals g.GenderID
                    select new MyViewModel
                    {
                        StudentID= st.StudentID,
                        StudentName = st.StudentName,
                        Gender = g.GenderName,
                        DepartName = d.DepartmentName
                    }).ToList();
    }
    return View(viewModel);
}

and make sure you have the below syntax at the top of your view code
@model IEnumerable<MyViewModel>


text:
Q: would you use AOP to track points? would you use springs AOP (aspects) if you had to track user points throughout your application?
it seems like a potential fit, since points are awarded etc. throughout the application, kind of like security checks.
(just reading on AOP, trying to grasp its potential and usage other than say security or logging).
when you wire up your joinpoints, are they "setup" on the fly or once?  I'm just concerned as to how this effects performance, or is it a non-issue really?

A: Yes, this sounds like a good use of AOP.
As to the specifics of how it works, that depends which AOP framework you're using. Some do the aspect weaving at compile time (e.g. AspectJ CTW), some do it when the lasses are loaded (e.g. AspectJ LTW), some do it dynamically at runtime (e.g. Spring AOP).
There is an inevitable performance impact, but don't let that stop you from giving it a go.

A: It might be a cross-cutting concern.  It's hard to tell without knowing more about your app.
Spring AOP sets them up at runtime after the application context is established.

A: I think that you could use aspects to track the user points. This 'requirement' is a crosscutting concern, because it cuts your code in many points.
If you want to use aspects with Java you should use AspectJ that is the most evolved aspect extension to Java. If you want to get an introduction about aspects read the AspectJ Programming Guide
And about the join points, they usually are wired up on compilation. So, after the weaving (composition of your new behavior with the old behavior) you will have new Java code with the new behavior injected. Another good book about aspects is Eclipse-AspectJ-Aspect-Oriented-Programming-Development

A: i dont think I would use AOP for this.  I would model the user and point, and implement the point awarding in some sort of business class.  I am new to AOP as well, but how I understand it, an aspect is really something that crosscuts your program.


text:
Q: What's the rule to convert CocoaAPI to MacRuby API - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:     (BOOL)flag
{
[self showWindow:self];
return YES;
}

how to convert this method to MacRuby ?
I tried
def applicationShouldHandleReopen(the_application, k)
    @window.makeKeyAndOrderFront
end

but not works

A: You need to use the selector syntax for the 2nd argument, e.g.:
def applicationShouldHandleReopen(the_application, hasVisibleWindows:k)
    ...
end

See http://www.macruby.org/documentation/tutorial.html for more on this exact topic.


text:
Q: Passing Class object containing HashMap> as instance variable to RESTService i have a POJO class BookType as:
package com.jersey.series.json.service;

import java.util.HashMap;
import java.util.Set;

public class BookType {

@Override
public String toString() {
    return "BookType [bookId=" + bookId + ", bookName=" + bookName + ", author=" + author + ", category=" + category
            + ", obj=" + obj + "]";
}

protected int bookId;
protected String bookName;
protected String author;
protected String category;
protected HashMap<String, Set<String>> obj = new HashMap<>();

public HashMap<String, Set<String>> getObj() {
    return obj;
}

public void setObj(HashMap<String, Set<String>> obj) {
    this.obj = obj;
}

public int getBookId() {
    return bookId;
}

public void setBookId(int value) {
    this.bookId = value;
}

public String getBookName() {
    return bookName;
}

public void setBookName(String value) {
    this.bookName = value;
}

public String getAuthor() {
    return author;
}

public void setAuthor(String value) {
    this.author = value;
}

public String getCategory() {
    return category;
}

public void setCategory(String value) {
    this.category = value;
}

}

And a rest Service :
 package com.jersey.series.json.service;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/bookservice")
public class BookServiceImpl implements IBookService {

@POST
@Path("addbookandreturnjson")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public BookType saveAndReturnBookInfojson(BookType bookType) {

    return bookType;
}
}

i ma making this call using PostMan:
http://localhost:8080/Jersey-JSON-IO/rest/bookservice/addbookandreturnjson

this is my message body with type application Json
 {"bookId":5,"bookName":"abc","author":"saurabh","category":"Test","obj":{"1":["abc","xyz"]}}

Service is receiving everything correct except for the "obj" field where am i doing wrong or what i need to do.I am using Glassfish 4.1.1 as web container.Here is my pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>in.bench.resources</groupId>
<artifactId>Jersey-JSON-IO</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Jersey-JSON-IO</name>
<description>Jersey web service using JSON (Jackson parser) as request/response</description>
<!-- https://jersey.java.net/documentation/latest/media.html#json.jackson -->

<!-- Jersey repository -->
<repositories>
    <repository>
        <id>snapshot-repository.java.net</id>
        <name>Java.net Snapshot Repository for Maven</name>
        <url>https://maven.java.net/content/repositories/snapshots/</url>
        <layout>default</layout>
    </repository>
    <repository>
        <id>prime-repo</id>
        <name>PrimeFaces Maven Repository</name>
        <url>http://repository.primefaces.org</url>
        <layout>default</layout>
    </repository>
</repositories>

<properties>
    <jersey.version>2.12</jersey.version>
    <jersey.scope>compile</jersey.scope>
    <compileSource>1.7</compileSource>
    <maven.compiler.target>1.7</maven.compiler.target>
    <maven.compiler.source>1.7</maven.compiler.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<build>
    <finalName>Jersey-JSON-IO</finalName>

    <!-- maven compiler plugin -->
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>

    </plugins>
</build>

<dependencies>
        <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet-core</artifactId>
        <version>${jersey.version}</version>
        <scope>${jersey.scope}</scope>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>${jersey.version}</version>
        <scope>${jersey.scope}</scope>
    </dependency>

</dependencies>


text:
Q: Argument passed in must be a Buffer or string of 12 bytes or a string of 24 hex characters while using OR condition in node js / javascript I want to fetch data from database by _id and ownerId so I gave OR condition, but getting this error
Argument passed in must be a Buffer or string of 12 bytes or a string of 24 hex characters

My code as follow
var ObjectId = require("mongodb").ObjectId;

const getDetailById = async (req, res) => {
  const { id } = req.params;
  try {
    let detail = await Task.find(
      { $or: [{ ownerId: id }, { _id: ObjectId(id) }] }
    ).populate("shop");
    } catch (err) {
    sendError(401, "Cannot get detail by given id", err.message, req, res);
  }
};

here I can get data from database by passing _id which is 24 character but when I tried to fetch data by ownerId its shows me this error:
Argument passed in must be a Buffer or string of 12 bytes or a string of 24 hex characters

My output look like this
 {
      "_id": "61483aa5e6dcd5bb6b2c9c58",
      "ownerId": "b0jytaonktsc5ghf",
      "ownerName": "check demo",
      "ownerDescription": "Testing purpose",
      "shop": {
        "_id": "61483aa5e6dcd5bb6b2c9c55",
        "shopName": "Aakash",
        "shopPlace": "Mumbai",
        "__v": 0
      },

      "createdAt": "2021-09-20T07:39:17.528Z",
      "updatedAt": "2021-09-20T07:39:17.528Z",
      "__v": 0
    },

and this is my Schema:
const mongoose = require("mongoose");
const uniqid = require("uniqid");

const ownerSchema = new mongoose.Schema(
  {
    ownerId: {
      type: String,
      default: uniqid(),
      unique: true,
    },
    OwnerName: {
      type: String,
    },
    taskTag: [
      {
        type: String,
      },
    ],
    onwerDescription: {
      type: String,
    },
    shop: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "peoples",
      default: null,
    },
  },
  { timestamps: true }
);

const owner = mongoose.model("task", ownerSchema);

module.exports = owner;

A: The problem is the call of ObjectId(id) because it can not handle the input of an ownerId string as soon as you are passing the ownerId.
The cleanest solution (in my opinion) would be to change the type of ownerId to ObjectId as well:
const mongoose = require("mongoose");
const uniqid = require("uniqid");

const ownerSchema = new mongoose.Schema(
  {
    ownerId: {
      type: mongoose.Schema.Types.ObjectId,
      default: mongoose.ObjectId(),
      unique: true,
    },
    OwnerName: {
      type: String,
    },
...

Or to handle the different inputs like:
var ObjectId = require("mongodb").ObjectId;

const getDetailById = async (req, res) => {
  const { id } = req.params;

  let filter = [{ ownerId: id }]
  try {
    const _id = ObjectId(id);
    filter.push({ _id })
  } catch () {
    // Do nothing
  }

  try {
    let detail = await Task.find(
      { $or: filter }
    ).populate("shop");
  } catch (err) {
    sendError(401, "Cannot get detail by given id", err.message, req, res);
  }
};

PS: Do not forget to perform some input validation! Never trust user input ;)

A: Problem

*

*ObjectId has exactly 24 hex characters or string of 12 bytes

*uniqid library that you use for generating ownerId generates 18 byte unique id

Reason
As you see the format of these 2 is not compatible. So what happened is this:

*

*You try to query database based on the value that uniqid() generated

*The second parameter of $or will try to generate ObjectId based on that value, and since the format is not compatible with ObjectId format, it will throw the error that it is invalid format of the ObjectId
Solution
You can change the uniqid library with the native Node crypto library to generate 24 hex characters string of 12 bytes, that will be compatible with ObjectId format. Since it is native package, you don't need to install it, you can just import it and use it. Now you can also remove uniqid package from you project and decrease the number of dependencies.
const mongoose = require("mongoose");
const crypto = require("crypto");

const ownerSchema = new mongoose.Schema(
  {
    ownerId: {
      type: String,
      default: crypto.randomBytes(12).toString('hex'),
      unique: true
  },
  ...
);


text:
Q: Read part of yaml in Java using Jackson if I have the following yaml (which I found online) representing a java Order class, order.yaml:
orderNo: A001
customerName: Customer, Joe
orderLines:
  - item: No. 9 Sprockets
    quantity: 12
    unitPrice: 1.23
  - item: Widget (10mm)
    quantity: 4
    unitPrice: 3.45

I was able to use
ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
Order order = objectMapper.readValue(new File(<path_to_order>), Order.class);

But this means that I need to define orderNo and orderLines in advance... If I have a giant yaml with a bunch of nested properties this can get really annoying. What if I want a class than can read one property or a class that can read another property and "ignore" other ones? Is that even possible? That way I could just specify which java object I want without necessarily having to recursively define every property of the yaml. Thank you!

A: The Map approach will lose you the type safety. There's no need to define every single property. You can use the Json annotations just fine with YAML too, it's just a historical leftover that it is called Json. What you are looking for is @JsonIgnoreProperties(ignoreUnknown = true).
If you don't like to specify the Annotation for every class, use objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);.
public static void main(String[] args) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
    Order order = objectMapper.readValue(new File("foo.yml"), Order.class);
    System.out.println(order.getOrderLines().get(0).getItem());
}

@JsonIgnoreProperties(ignoreUnknown = true)
static class Order {
    private String orderNo;
    private List<OrderLine> orderLines;

    public String getOrderNo() {
        return orderNo;
    }

    public void setOrderNo(String orderNo) {
        this.orderNo = orderNo;
    }

    public List<OrderLine> getOrderLines() {
        return orderLines;
    }

    public void setOrderLines(List<OrderLine> orderLines) {
        this.orderLines = orderLines;
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    static class OrderLine {
        private String item;

        public String getItem() {
            return item;
        }

        public void setItem(String item) {
            this.item = item;
        }
    }
}

A: You can read the json in a Map and then retrieve whatever you want from there
ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
Map<String,Object> jsonMap = objectMapper.readValue(new File(<path_to_order>), Map.class);


text:
Q: Let $G$ be a finite group, $ord(G)=p^2$ ($p$ is a prime) prove that there is a subgroup of order $p$ in $G$
Let $G$ be a finite group, $ord(G)=p^2$ ($p$ is a prime) prove that there is a subgroup of order $p$ in $G$

I thout about Sylow theorem but it didn't helped me.

A: Here's an approach that doesn't use Cauchy's Theorem. An element of order $p$ generates a subgroup of order $p$, so we need to find some $x\in G$ with $|x|=p$.
Let $x\in G$ be a non-identity element. By Lagrange's Theorem, order of $x$ divides $p^2$, so $|x|=1, p$ or $p^2$. Since $x$ is not the identity element, $|x|=p$ or $|x|=p^2$. If $|x|=p$, we win. If $|x|=p^2$, then the element $y=x^{p}$ has order $p$.

A: You can solve this particular problem very elementarily, without even invoking Cauchy's theorem, let alone Sylow's. Hints:
1) Every non-trivial subgroup of $G$ has order $p$ or $p^2$.
2) Suppose $G$ had no subgroup of order $p$. Pick any $g\ne e$ in $G$. Let $H=\langle g \rangle$ be the generated subgroup.
3) Argue that $|H|=p^2$, and thus $G=H$.
4) But then $G$ is cyclic, so it is isomorphic to.... and in that group you can easily find an element of order $p$. Contradiction.


text:
Q: SQL UPDATE with database values It is possible to UPDATE sql column with the actual values ?
EXAMPLE :
UPDATE TEST SET example = {actual_value}, other = 'test'

I want to replace {actual_value} with the actual value without ask sql server before update.

A: Ok, found the answer thanks to @muasif80.
IF you want to update with actual value :
UPDATE TEST SET column_name = column_name


text:
Q: What does the language level setting in android studio 0.3.2 Do? In the latest release of Android Studio (0.4.2), a new setting has been added when creating a new project, namely Language Level
I want to know what that refers to, and the consequence of selecting any of the provided options.
The doc doesn't give me a clear picture of this and i don't want to select an option when i don't know what that will result in?
Thanks

A: It's about what Java language level you want to use. KitKat supports full Java 7, Gingerbread and up support Java 6 and older versions are Java 5. At least when it comes to the core Java APIs. Roughly the same setting is mentioned here.
You can often use language features that were added in one version in an older version if the compiler knows how to do it. For example the Diamond Operator was added in Java 7 but you can still use that feature in Java 6 since
List<String> list = new ArrayList<>();

actually compiles into the same thing as
List<String> list = new ArrayList<String>();

did.
The "try with resource" construct on the other hand can't be compiled into legal Java 6 compatible code and is therefore exclusive to Apps that require KitKat and up.

A: The answer can be phrased better, IMHO. The docs are clear about Java 7 and below.

*

*This setting affects which Java language features you can use in your source code.

*All Java language features that you use will be compiled so that the code will work in all Android versions, except for the "try with resources" language feature.

*From the docs: "If you want to use try with resources, you will need to also use a minSdkVersion of 19. You also need to make sure that Gradle is using version 1.7 or later of the JDK. (And version 0.6.1 or later of the Android Gradle plugin.)"

A: Java 7 support was added at build tools 19. You can use now features like the diamond operator, multi-catch, try-with-resources, strings in switches, etc. Add the folowing to your build.gradle.
android {
compileSdkVersion 19
buildToolsVersion "19.0.0"

defaultConfig {
    minSdkVersion 7
    targetSdkVersion 19
}

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

Gradle 1.7+, Android gradle plugin 0.6.+ are required.
Note, that only try with resources require minSdkVersion 19. Other features works on previous platforms.


text:
Q: How to compare a text value in a list of sobjects? The following gives me a list of texts which are customer numbers (CUST_NUM__c)
 List<SYSTEMS__c> lst_PartnersAcc = [SELECT CUST_NUM__c
                                             FROM SYSTEMS__c WHERE Account__c IN (Select  AccountId from AccountShare where ( UserOrGroupId IN : map_group OR  UserOrGroupId =:userId )AND RowCause IN ('Territory', 'TerritoryManual', 'TerritoryRule'))
                                             ];

I have 4 text fields in another custom object orders__c==> customer_1__c,customer_2__c,customer_3__c, customer_4__c.
I'm trying to find out if **lst_PartnersAcc ** contains 1 or more of the 4 text field. My Final Aim is to find a list of orders if any matches from the string in the list.
Following is what I tried...
Attempt 1:
Set<String> tempList = new Set<String>();
tempList.addAll(lst_PartnersAcc);

Error: Compile Error: Incompatible argument type List for All method on Set

Attempt 2:
List<orders__c> orders = [select id,name from orders__c WHERE customer_1__c IN( SELECT CUST_NUM__c
                                             FROM SYSTEMS__c WHERE Account__c IN
                                             (Select  AccountId from AccountShare where ( UserOrGroupId IN : map_group OR  UserOrGroupId =:userId )AND RowCause IN ('Territory', 'TerritoryManual', 'TerritoryRule')))
                                             ];

Error: Compile Error: Nesting of semi join sub-selects is not supported

Attempt 3
List<SYSTEMS__c> lst_PartnersAcc = [SELECT CUST_NUM__c
                                             FROM SYSTEMS__c WHERE Account__c IN  (Select  AccountId from AccountShare where ( UserOrGroupId IN : map_group OR  UserOrGroupId =:userId )AND RowCause IN ('Territory', 'TerritoryManual', 'TerritoryRule'))];

List<gew_orders__c> orders = [select id,name from gew_orders__c WHERE  GEW_SAP_Bill_to__c IN: lst_PartnersAcc OR
                                    GEW_SAP_Payer__c IN: lst_PartnersAcc OR
                                    GEW_SAP_Ship_To IN: lst_PartnersAcc OR
                                    GEW_SAP_Sold_to__c IN: lst_PartnersAcc];

Error: Compile Error: Invalid bind expression type of SYSTEMS__c for column of type String

How should I proceed to compare 4 values to a list? Thanks in advance!

A: This should work:

List lst_PartnersAcc = [SELECT CUST_NUM__c
                                             FROM SYSTEMS__c WHERE Account__c IN (Select  AccountId from AccountShare where ( UserOrGroupId IN : map_group OR  UserOrGroupId =:userId )AND RowCause IN ('Territory', 'TerritoryManual', 'TerritoryRule'))
                                             ];
Set tempList = new Set();
for(Systems__c s : lst_PartnersAcc) {
    tempList.add(s.Cust_Num__c);
}
List orders = [select id,name from orders__c WHERE customer_1__c IN :tempList OR customer_2__c IN :tempList ETC...
                                             ];

Just needed to add the Customer Number to the set individually for each Systems__c.


text:
Q: How to serialize and deserialize python object to JSON without json library My task is to create a JSON serialiser which can serialize different Python objects to JSON. So of course I can't use JSON library. But searching the information about serialisation gives something like "Use import json and be happy.
So can anybody give me some piece of advice of how to realize this task?


text:
Q: kdb: What's the idiomatic way to join two tables by a composite foreign key? I have two tables t1 and t2 defined as:
t1:([a:`datetime$(); b:`$()] x:`float$(); y:`float$());
meta t1
> c| t f a
> -| -----
> a| z
> b| s
> x| f
> y| f

t2:([t1:`t1$(); c:`$()] z:`float$());
meta t2
> c | t f  a
> --| ------
> t1| i t1
> c | s
> z | f

where t1 defines a composite primary key from attributes a and b. t2 defines a forein key t1 to table t1.
I have looked all over the documentation how to join these two tables but had no luck. Is there a straighforward way to join them? I worked out the following way though:
ej[`t1;update t1:`t1$(a,'b) from t1;t2]
> a b x y t1 c z
> --------------

Basically doing an equal join between tables t1 and t2 after expanding table t1 to expose the composite foreign key i.e. the column type t1. Is there a more idiomatic and simpler way? for example doing t2 ij t1 leads to error: ``a

A: A slightly more efficient & neater way to do this would be to utilise the hidden i column (i.e. row index) in kdb tables instead of generating the composite of the key columns of t1 & enumerating against t1 e.g.
q)ej[`t1;update t1:`t1!i from t1;t2]
a b x y t1 c z
--------------

This is slightly more efficient:
q)\ts:1000 ej[`t1;update t1:`t1!i from t1;t2]
11 1904
q)\ts:1000 ej[`t1;update t1:`t1$(a,'b) from t1;t2]
12 2256

(efficiency gain will be increased with populated tables, of course)

EDIT:
Another option is to use the foreign keys in a select statement something like:
select t1.a,t1.b,t1.x,t1.y,c,z from t2
This is considerably more efficient than using an actual join:
q)\ts:1000 select t1.a,t1.b,t1.x,t1.y,c,z from t2
2 1712
q)\ts:1000 ej[`t1;update t1:`t1!i from t1;t2]
12 2496

The downside here is having to name all the fields in the select statement.
One more option involving a join is to use the "t1" column from t2 to index into t1, and then join each record. To do this you'll have to use 0! to unkey the tables for indexing:
q)((0!t1)@(0!t2)`t1),'t2
t1 c  | a                       b   x         y        z
------| -------------------------------------------------------
0  gck| 2004.02.13T15:53:44.342 ndd 4.49731   7.833686 9.030751
1  job| 2001.07.22T05:29:31.118 hpb 0.1392076 4.099561 7.750292

(I added some dummy records for demonstration)
This is slightly less efficient than the select statement, but better than the ej:
q)\ts:1000 ((0!t1)@(0!t2)`t1),'t2
4 1920


text:
Q: Change UIAlertView size In my cocos2d game i can't change size of uialertview, i have changed statusbarorientation to landscape, and now want to init alertview with frame, and initwithframe method does not affect the size of alertview, every time the size of alert is the same, is there any way to change it ?

A: Here is what i did.  Create your uialertview in your controller.  then override the following class within your controller (after setting the uialertview delegate ... ie. myalertview.delegate=viewcontroller)
- (void)willPresentAlertView:(UIAlertView *)alertView {
    [alertView setFrame:CGRectMake(1, 20, 2700, 400)];
}

the frame size should change after this.

A: its not possible to customized UIAlertView cause its view hierarchy is private.
its clearly mentioned here UIAlertView_Class
You can go for UIView and create it similar to UIAlertView.

A: Just create UIView which looks like UIAlertView. That will solve all the problem you mentioned.

A: If a alert view has any title or messages text input within its view, then just append as many new line '\n' at the end of text it automatically scale its size.
Its just a mock, but stil doable to retain the alertbox usage in you application.


text:
Q: Case for using inheritance or interface in Java? I have a very simple application which needs a data source. At present it is a flat file but later on it will change to a database. I need your opinion on using inheritance or interfaces here. Which one would be better and why? My opinion is using interfaces because it would be flexible but then i could make data source as an abstract class too.

A: You would use an abstract class where there is common functionality that all the implementations need access to. Here the database and file implementations are so different they will have nothing in common, so I'd go with interfaces.

A: You use an interface when only the methods and types for accessing the data will remain the same.  You use inheritance when there will be common code/functionality between things that needs to be shared as well.
In this case, it would seem an interface would suffice and utilizing an abstract class with no common code would be a waste.  One often forgotten benefit of using interfaces is that you can implement multiple interfaces at once whereas you can only inherit from one parent class.

A: In this case, it would be more convenient to use an interface.
By abstracting out the implementation details, you can provide a common interface that both the flat-file and database backed can use. When it comes time to change, only the code of implementing this interface will change and not any code using them.

A: I would go with an abstract class. Going about a pure-object oriented approach, the class would be very small, only the necessities, and then have the child classes contain all parameters and values for the objects.
An example of what would be in the abstract class to get you ready for the database you plan is an int for the unique id.

A: As you mentioned in your post, it would be best to create an interface which defines the operations which can be done on your data source. For each single data source you can create a class which implements that interface.
To operate on a flat file you could implement the class FileDataWrapper implements DataWrapper, where the class FileDataWrapper implements the operations that can be performed on the data source. Later, when you change to a database, just implement the class DatabaseDataWrapper implements DataWrapper.

A: You can use the DAO design pattern and Factory. You can find an example in Advanced DAO programming and more information in Core J2EE Patterns - Data Access Object.


text:
Q: Is it possible to navigate to a different screen through a screen's JS code? This is basically what I want to do:
myapp.StartScreen.created = function (screen) {
    screen.getIsAdmin().then(function success() {
        this.navigate("AdminHome.lsml");
    }, function error() {
        this.navigate("UserHome.lsml");
    });
};

But navigating with "this.navigate" or "this.location" does not seem to work. Any suggestions?

A: Looks like the following works for me:
myapp.StartScreen.created = function (screen) {
    screen.getIsAdmin().then(function success() {
        this.window.location.href = '#/AdminHome/undefined/[dee7135da]';
    }, function error() {
        this.window.location.href = '#/ClientHome/undefined/[c4fb70ef3]';
    });
};


text:
Q: How to improve perl Gtk2 performance when we have a large number of widgets I'm writing a perl GUI using Gtk2, it has a scrolled window which contains a number of GTk2::Expander which includes different widgets.
The poroblem is when i have a large number of Expanders (~80,000) the time it takes to perform show_all() is large, and when i open a single expander it takes several seconds. Running the same script with less expanders give a very fast response.
Since my expanders exists in a scrolled window and only part of them would be really visible, is there a way to improve the performance? like showing only the visible expanders and keeping all others as hidden?
I can't use GTK3, I need to use Perl and Gtk2 only.
Example Code:
my $ItemsCount = 10000;
my $ScWin      = Gtk2::ScrolledWindow->new(undef, undef);
my $Frame      = Gtk2::Frame->new('Items');
my $ItemsBox   = Gtk2::Table->new(2, $ItemsCount+1, FALSE);

my  $View = Gtk2::Viewport->new();

$ScWin->set_policy('automatic', 'automatic');
$View->add($ItemsBox);
$ScWin->add($View);

for my $i (0 .. $ItemsCount-1)  {
    my $exp =  Gtk2::Expander->new();
    $exp     ->set_label("Item #$i");
    $ItemsBox->attach($exp, 0, 1, $i, $i+1, 'fill', 'fill', 1, 2);
}
$MainBox    ->pack_start    ($ScWin     , TRUE, TRUE, 0);


text:
Q: Discord.JS Command Handler Sub-Folders I currently have a Discord.JS command handler that loads all commands in the command folder. However it is getting a bit messy now due to all the commands, therefore I have been trying to implement Sub-Folders. This would clean up the files inside the commands folder, organizing them into folder groups.
I currently have this code for loading the commands in the same folder.
But I am stuck on how I could go into each folder in the commands directory and load the commands.
If someone could help me, that would be appreciated.

const allCommands = fs.readdirSync('./commands');
for (const command of allCommands) {
    try {
        const loadedCommand = require(`./commands/${command}`);
        commands.set(loadedCommand.name, loadedCommand);

        for(const alias of loadedCommand.aliases || [])
            commands.set(alias, { ...loadedCommand, alias: true });

        logger.info(`Loaded command ${loadedCommand.name} (${command})`);
    } catch (error) {
        logger.error(`Failed to load command ${command}. **Please report the following error:**`);
        logger.error(error);
    }
}

A: Move everything into its own function with the path as a parameter.
Every time you find a folder, call the function with the folder path.
(function readdir(path='./commands') {
    const allCommands = fs.readdirSync(path);
    for (const command of allCommands) {
        if(fs.statSync(`${path}/${command}`).isDirectory()) {
            readdir(`${path}/${command}`);
            continue;
        }

        try {
            const loadedCommand = require(`${path}/${command}`);
            commands.set(loadedCommand.name, loadedCommand);

            for(const alias of loadedCommand.aliases || [])
                commands.set(alias, { ...loadedCommand, alias: true });

            logger.info(`Loaded command ${loadedCommand.name} (${path}/${command})`);
        } catch (error) {
            logger.error(`Failed to load command ${path}/${command}. **Please report the following error:**`);
            logger.error(error);
        }
    }
})();

A: Honestly, I don't recommend importing this way. You might have better luck if you import each of your commands into a seperate javascript file then export each of your commands from there, it should make your controller level code much easier to read


text:
Q: XPATH Matching Sale Price or Regular Price I need to match either the sale price (if on sale) or the regular price using one expression(hope that's the right term). Here's the two example HTML structures:
On Sale

        $
        14.99

        $
        12.99

Regular Price

    $
    25.00

The expression I have so far is:
//*[@class="woocommerce-Price-amount amount"][last()]

It matches on both scenarios but returns both regular and sale prices for the "On Sale" scenario. Do I need some conditional to only return the sale price?
I thought I could possibly only return the last [@class="woocommerce-Price-amount amount"]. I tried last-child but wasn't fully comprehending.

A: First, note that in your "on sale" snippet, you are missing a closing , but if we fix it, this convoluted expression should do the trick.
It's formatted for easier reading:
//span[@class="woocommerce-Price-amount amount"]

[parent::p

or

parent::ins

]

Try it on your actual code and see if it works.


text:
Q: Why does my javascript-code to hide/show div-boxes not work? I'm trying to hide/show the main-contentholders on my website based on what menu-option the reader clicks on. This seems like a simple thing to me, I've done it multiple times before but now it just won't work. My code looks like this:
<!DOCTYPE html>

<title id="titel">Mercedes F1</title>
<link rel="stylesheet" href="mercedes.css">
<meta name="viewport" content="width=device-width; initial-scale=1">

Förarbiografi

Mercedes F1

Statistik

Förare

Mercedes F1 genom åren

Statistik

A: The main problem is that whenever you are clicking on the a tag the page reloads. So put # inside the href attributes of the a tags. Thats it.
Click Here

jsFiddle
Note : The local p declared inside the function is of no use as you are using the parameter. So better you remove that if you are only using the parameter, though it doesn't effect your code unless you refer to that with this keyword. Like,
this.p // refers to the local p you declared.

A: You're reloading the page each time the action is triggered, so the default state is returned, meaning that the transformation is no longer applied. By giving the  tag an href of # or javascript:void(0);, you can prevent the page refresh. Or even better, you can actually execute the JS from the href itself.
I actually recommend using javascript:void(0);, since it doesn't jump to the top of the page by default, while # does. However, that behavior can be prevented with a simple onclick="return false".
Codepen

A: Find the below code which i did using jQuery. It's very short and easy to understand.
HTML

    Förarbiografi

    Mercedes F1

    Statistik

Förare

Content

Mercedes F1 genom åren

Content

Statistik

Content

JS
$('.one').click(function(){
    $('.main').hide();
    $('#forare').show();
});
$('.two').click(function(){
    $('.main').hide();
    $('#mercedes').show();
});
$('.three').click(function(){
    $('.main').hide();
    $('#statistik').show();
});

CSS
.main{
    display:none;
}

JS FIDDLE DEMO