text:
Q: Cache Credentials During SVN Merge A merge from a feature branch to trunk took over 45 minutes to complete.
The merge included a whole lot of jars (~250MB), however, when I did it on the server with the file:// protocol the process took less than 30 seconds.
SVN is being served up by Apache over https.
The version of SVN on the server is
svn, version 1.6.12 (r955767)
   compiled Sep  3 2013, 17:49:49

My local version is
svn, version 1.7.7 (r1393599)
   compiled Oct  8 2012, 20:42:17

On checking the Apache logs I made over 10k requests and apparently each of these requests went through an authentication layer.
Is there a way to configure the server so that it caches the credentials for a period and doesn't make so many authentication requests?
I guess the tricky part is making sure the credentials are only cached for the life of single svn 'request'. If svn merge makes lots of unique individual https requests, how would you determine how long to store the credential for without adding potential security holes?

A: First of all I'd strongly suggest you upgrade the server to a 1.7 or 1.8 versions since 1.7 and newer servers support an updated version of the protocol that requires fewer requests for many actions.
Second, if you're using path based authorization you probably want SVNPathAuthz short_circuit in your configuration.  Without this for secondary paths (i.e. paths not in the request URI) as may happen for many recursive requests (especially log) when the authorization for those paths are run it runs back through the entire Apache httpd authentication infrastructure.  With the setting instead of running the entire authentication/authorization infrastructure for httpd, we simply ask mod_authz_svn to authorize the action against the path.  Running through the entire httpd infrastructure can be especially painful if you're using LDAP and it needs to go back to the LDAP server to check credentials.  The only reason not to use the short_circuit setting is if you have some other authentication module that depends on the path, I've yet to see an actual setup like this in the wild though.
Finally, if you are using LDAP then I suggest you configure the caching of credentials since this can greatly speed up authentication.  Apache httpd provides the mod_ldap module for this and suggest you read the documentation for it.
If you provide more details of the server side setup I might be able to give more tailored suggestions.
The comments suggesting that you not put jars in the repository are valuable, but with some configuration improvements you can help resolve some of your slowness anyway.

A:
The merge included a whole lot of jars (~250MB)

That's your problem!  If you go through your network via http://, you have to send those jars via http://, and that can be painfully slow. You can increase the cache size of Apache httpd, or you can setup a parallel svn:// server, but you're still sending 1/4 gigabyte of jars through the network. It's why file:// was so much faster.
You should not be storing jars in your Subversion repository. Here's why:
Version control gives you a lot of power:

*

*It helps you merge differences between branches

*It helps you follow the changes taking place.

*It helps identify a particular change and why a particular change took place.

Storing binary files like jars provide you none of that. You can't merge binary files, and you can't track their changes.
Not only that, but version control systems usually use diffs to track changes. This saves a lot of space. Imagine a 1 kilobyte text file. In 5 revisions, six lines are changed. Instead of taking up 6K of space, only 1K plus those six changes are stored.
When you store a jar, and then a new version of that jar, you can't easily do a diff, and since jar format is zip, you can't really compress them either, store five versions of a jar in Subversion, and you store pretty close to five times the size of that jar. If a jar file is 10K, you're storing 50K of space for that jar.
So, not only are jar files taking up a lot of space, and they don't give you any power in storage, they can quickly take over your repository. I've seen sites where over 90% of a 8 gigabyte repository is nothing but compiled code and third party jars. And, the useful life of these binary files is really quite limited too. So, in these places, 80% of their Subversion repository is wasted space.
Even worse, you tend to lose where you got that jar, and what is in it. When users put in a jar called commons-beans.jar, I don't know what version that jar is, whether that jar was built by someone, and whether it was somehow munged by that person. I've see users merge two separate jars into a single jar for ease of use. If someone calls that jar commmons-beanutils-1.5.jar because it was version 1.5, it's very likely that someone will update it to version 1.7, but not change the name. (It would affect the build, you have to add and delete, there is always some reason).
So, there's a massive amount of wasted space with little benefit and almost no information. Storing jars is just plain bad news.
But your build needs jars! What should you do?
Get a jar repository like Nexus  or Artifactory. Both of these repository managers are free and open source.
Once you store your jars in there, you can fetch the revision of the jar you want either through Maven, Gradel, or if you use Ant and want to keep your Ant build system, Ivy. You can also, if you don't feel like being that fancy, fetch the jars via an Ant <get/> task. If you use Jenkins, Jenkins can easily deploy the built jars for other projects to use in your Maven repository.
So, get rid of the jars. Merging will then be a simple diff between text files. Merging branches will be much quicker, and less information has to be sent over the network. If you don't want to switch to Maven, then use Ivy, or simply update your builds with the <wget> task to fetch the jars and the versions you need.


text:
Q: Checked = true not working together with other events on same element I'm using Django inline formsets and trying to use the delete checkbox dynamically with Javascript. Everything works as it is supposed to, however the checked = true property (although showing true in the console) won't check the box as long as updateSunForm() and totalForms.setAttribute(...) are present.
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <link rel="stylesheet" type="text/css" href="{% static 'css/availability_update_new.css' %}">
</head>
<body>
<form id="all-add-form" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <legend class="bottom mb-4">Profiles Info</legend>
    {{ sun_bool.sunday|as_crispy_field }}
    {{ sunday_formset.management_form }}
    {% for sun_form in sunday_formset %}
        {% for hidden in sun_form.hidden_fields %}
            {{ hidden }}
        {% endfor %}
        <div class="sun_time_slot_form">
            {{ sun_form }}
            <button class="delete-sun-form" type="button" id="delete-sun-btn" onclick="one();"> Delete          This Sunday Timeslot
            </button>
        </div>
    {% endfor %}

    <button id="add-sun-form" type="button" class="button">Add Other Sunday Times</button>

    <input type="submit" name="submit" value="Submit" class="btn btn-primary"/>
</form>

<script type="text/javascript" src="{% static 'js/add_timeslot.js' %}"></script>

</body>
</html>
{% endblock content %}

const sunForm = document.getElementsByClassName('sun_time_slot_form');
const mainForm = document.querySelector('#all-add-form');
const addSunBtn = document.querySelector("#add-sun-form");
const submitFormBtn = document.querySelector('[type="submit"]');
const totalForms = document.querySelector("#id_id_sunday_formset-TOTAL_FORMS");

let formCount = sunForm.length - 1;

addSunBtn.addEventListener('click', function (e) {
    e.preventDefault();

    const newSunForm = sunForm[0].cloneNode(true);
    const formRegex = RegExp(`id_sunday_formset-(\\d){1}-`, 'g');

    formCount++;

    newSunForm.innerHTML = newSunForm.innerHTML.replace(formRegex,
    `id_sunday_formset-${formCount}-`);
    mainForm.insertBefore(newSunForm, submitFormBtn);
    totalForms.setAttribute('value', `${formCount + 1}`);
});

function updateSunForm() {
    let count = 0;
    for (let sun_form of sunForm) {
        const sunFormRegex = RegExp(`id_sunday_formset-(\\d){1}-`, 'g');
        sun_form.innerHTML = sun_form.innerHTML.replace(sunFormRegex,
            `id_sunday_formset-${count++}-`)
    }
}

mainForm.addEventListener('click', (ee) => {
    if (ee.target.classList.contains('delete-sun-form')) {
        ee.preventDefault();
        ee.target.value;
        ee.target.parentElement.querySelector('input[id$="-DELETE"]' +
            '[type="checkbox"]').checked = true;
        ee.target.parentElement.style.display = "none";
        formCount--;
        updateSunForm();
        totalForms.setAttribute('value', `${formCount + 1}`);
    }
});

I've tried many variations of DOM manipulation and nothing seems to be working.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to maintain view-related information in MVVM and may I store this in the model? I have an ongoing discussion with some colleagues on how to manage the views to our model.
We've got a model which may be represented by many views. Let's say we've got some data that is stored in an array and we'd like to display the data in a table and in charts.
A certain chart is unique but you're able to duplicate the chart. This duplicate should display the data in the very same way as the original, but it does not display the same part (e.g. if the data is too big to display it at once and you can scroll, so the original shows the first 10 items while the duplicated one shows the last 10).
At any time you can remove a view. The view and the view-model are then deleted from the memory. The model persists even if there's no view representing the data.
There is a handful of displaying information on the view which tells how and what part of the data is displayed. Scrolling is one of those, so let's stay with that example. This displaying information is neither persistent nor is it stored in the model.
If you shut down the application and restart, we don't care about how the view has been before and we always set up a default. If you, however, delete a view and then undo, we'd like to display the data exactly as it's been before deleting. The newly created view is technically not the same as before.
In order to adjust the view, I need to maintain the scrolling position.
I would simply put the displaying information into the model as this continued to exist for the whole time. However, some colleagues disagree and they say the model should only contain persistent data (like the actual data we're representing).
Hence we shouldn't keep track of the displaying information about the view in the model.
Q1: Is it correct from a design perspective that the model contains only persistent data? If yes, how would you maintain view-related information?
As said above, the model may be represented by many views, some of which may be duplicates of each other.
Let's say I found a way to maintain the data. I would have a collection of X displaying information.
Q2: When creating new views which actually replace the old views (keyword undo), how can I determine which displaying information of the collection should be associated to which view.
I mean even if my view had a unique ID, since we've created new one, we cannot rely on this data.
I can't quite figure out how I could associate these information correctly. The only idea that raises is having a separate view-model for each view and keeping the view-models alive, too. On the other hand, I think that's not what it's supposed to be, is it?

A: I would have to agree with your colleagues.  You don't want to mix View State information with your Model.
Right now you have 1 model and potentially many ViewModels and Views which are destroyed when closed, right?
It sounds like what you need is 1 model, 1 Parent ViewModel, and potentially many Child ViewModels and Views (which, again, are destroyed when closed).  The key difference here is that the Parent VM doesn't get destroyed when the Child VMs do.
Its responsibilities include persisting View State between View instances, and also ensuring no two Views are showing the same portion of the Model (I believe that was one of your requirements?)
This helps keep your View State information separate from your Model and your "Undo" operations are relatively easy to implement.
Something like
  V     V     V
  |     |     |
  VM   VM    VM
   \    |    /
    Parent VM
        |
      MODEL

A: I fully agree with your colleagues that View state does not belong in the Model. That is what you have the ViewModels for.
To support an undo operation of closing a View, you could either keep the ViewModel of a closed View around until it is old enough that the closing can't be undone, or you can implement the Memento pattern to squirrel away the relevant View state in your undo list.

A: If your view is complex and need to store some data, perhaps your view has a model, a model that belongs only to your view, of course. IMHO this is a different model from your core business model, complex applications can have multiple, independent, models.


text:
Q: Download csv from website directly into R I have a Shiny App program that depends on input that is user-specific in the form of a csv. Currently I have the user download it from the website, and then upload it to the Shiny App. Instead, I want the program to download the csv directly from the website (assuming the user is logged-in to the website).
Generally, I would use this method:
library(RCurl)
urlCSV <- getURL('https://{some url}.csv')
df <- read.csv(textConnection(urlCSV))

But in this case, the url does not end in .csv, so this method returns an empty string.
The url:
http://ebird.org/ebird/MyEBird?cmd=list&rtype=custom&r=world&time=life&fmt=csv
I realize this could be hard to communicate since few of you probably have eBird accounts. To try to help you understand: this link normally opens a popup that asks you if you want to open or save the file, just as a .csv url would.


text:
Q: C# code to simulate clicking on links Please take a look at this website. It allows you to change the date using either the calendar or the 'next' and 'previous' links. Whenever a date is changed, the match data below is updated. I want to programmatically select a date, then retrieve the URL behind the 'Boxscore' link in the lower part.
I have tried the WebBrowser control, which often doesn't load the page fully, and if it does, I can't find a way to interact with the controls. (I'm stuck at webBrowser.Document.GetElementById("calendar id")). I've also tried WatiN(watin.org), which causes problems with dependencies:

Unhandled Exception:
  System.IO.FileNotFoundException: Could
  not load file or assembly
  'Interop.SHDocVw, Version=1.1.0.0,
  Culture=neutral,
  PublicKeyToken=db7cfd3 acb5ad44e' or
  one of its dependencies. The system
  cannot find the file specified

I'm also trying to work something out using IeUnit, but currently I have no idea how to use it in a C# program.
Does anyone have any libraries to recommend/any other method of getting the data?

A: Try just sendkeys and use the tab button to move through links, enter to goto hyperlinks, and f5 to refresh.

A: Try Selenium. IMHO its much better than Watin.
Download with the C# (Selenium WebDriver) link.
Edit: First tutorial that popped up on google.  Looks ok.

A: I have also used watin API for screen scraping, from the exception you have posted, does not reflect any problem in your code. You must be have missed a reference to the "Interop.SHDocVw.dll" file or else if you had added a reference, please do it again.
If this does not help you out then please check that .NET framework is properly installed in your machine and .dll file are there in the assembly to load from. I was getting the same problem and I solved it in this way.

A: I answered a similar question recommending HtmlUnit under .NET: Looking for a simple C# scraping library with JavaScript support


text:
Q: Putting the end results in a Map efficiently I am getting the result of the query into a list which I want to put into the map, actually, I have a query which selects the records from the table of two columns based on the input conditions   passed and fetches the result into the list
Now I want to change the concept as I want to store the results of two columns into the map,    for example, first value abcId would be the key and the second value pack would be the value of that key in a map. Later I would change the return type of that map also so please advise how can I place it on the map?
@Transactional
    public List<CTM> fetchAllCTMinfo(String avJobCode){
        TypedQuery<CTM> typedQuery = em.createQuery("SELECT i.abcId , i.pAcq FROM CTM i where i.avJobCode = :avJobCode", CTM.class);
        typedQuery.setParameter("avJobCode", avJobCode);
        Map<Integer, String> hm = new HashMap< Integer , String>
        List<CTM> list = typedQuery.getResultList();
        if(list != null && list.size()>0)
        {
        return list;
        }
        return null;
    }

so the resulting map should be like
abcId   |  pAcq
10          fgtr
20          fgrt

A: Iterate the list and put it into the map
HashMap<Integer, String> hm = new HashMap<Integer , String>
List<CTM> list = fetchAllCTMinfo(String avJobCode);
for (CTM ctm : list) {
    hm.put(ctm.getId(), ctm.getString());
}

Replace getId() and getString() methods according to your CTM class.


text:
Q: Running ArcGIS field calculation using Python with algebraic expression using other field values as variables?
I'm trying to run a field calculation using multiple fields in a table as well as independent numeric values with python code in the field calculator window.  I've included the first 7 lines of the code below.  I'm not getting any syntax errors, but I'm also not getting any results.  The other fields used as variables include: Appraised_Value, Ag_value, and TaxRate_Municipal  Not sure how to fix it.
Pre-Logic Script Code:
def Reclass( Exemp_Code_Int ) :
 if (Exemp_Code_Int == '0') :
  return (Appraised_Value / 100) * TaxRate_Municipal
 elif (Exemp_Code_Int == '2') :
  return (Ag_Value / 100) * TaxRate_Municipal
 elif (Exemp_Code_Int == '4') :
  return 0

Codeblock looks like this:
 Reclass( !Exemp_Code_Int! )

Screenshot too:

A: All fields have to be included in the Reclass definition to be used by the calculation.
Reclass(!Exemp_Code_Int!, !Appraised_Value!, !TaxRate_Municipal!, !Ag_Value!, etc.)
Then those variables have to be included in the def of Reclass.
def Reclass(Exemp_Code_Int, Appraised_Value, TaxRate_Municipal, Ag_Value, etc.)
Also, if Exem_Code_Int is actually an integer value, then the logical comparison value cannot be a string.  I.e.,
if (Exemp_Code_Int == '0'):
must become:
if (Exemp_Code_Int == 0):


text:
Q: Can NHibernate be configured to automatically call .CustomType for all columns of a certain type? I have a model that has a property of an Enum type:
public virtual Units Unit { get; set; } // Units is an enum

I have a class called EnumMapper which handles some custom mapping logic I have for use with my database.  In my mapping, I have:
Map(x => x.Unit).CustomType<EnumMapper<Units>>();

This works great.  No problems at all.  However, I have quite a few models that have properties of type Units as well.  Rather than call .CustomType<T>() on each one of these, I'm wondering if I can add something to my FluentConfiguration object to tell NHibernate to use this type mapping on any and all properties of type Units.  Here's how I configure NHibernate so far:
private ISessionFactory InitializeSessionFactory()
{
   sessionFactory = Fluently.Configure()
      .Database(DatabaseConfiguration)
      .Mappings(m => m.FluentMappings
          .AddFromAssemblyOf<DatabaseAdapter>()
          .Conventions.Add(Table.Is(x => x.EntityType.Name.ToLowerInvariant())) // All table names are lower case
          .Conventions.Add(ForeignKey.EndsWith("Id"))                           // Foreign key references end with Id
          .Conventions.Add(DefaultLazy.Always()))
      .BuildSessionFactory();

   return sessionFactory;
}

I have a feeling that it's as simple as calling .Conventions.Add() on something else, but I can't seem to get it right.

A: Figured out one solution using ConventionBuilder:
.Conventions.Add(ConventionBuilder.Property.When(
  c => c.Expect(x => x.Type == typeof(GenericEnumMapper<Units>)),
  x => x.CustomType<EnumMapper<Units>>()
))

It's not super pretty, but it works.  I think a better solution might be to write my own convention that automatically maps an enum to its correct custom type.  I will post that here if I get it working.
Update: Cleaned this up a bit.  I've added a static method to my EnumMapper<T> class:
public class EnumMapper<T> : NHibernate.Type.EnumStringType<T>
{
   // Regular mapping code here

   public static IPropertyConvention Convention
   {
      get
      {
         return ConventionBuilder.Property.When(
            c => c.Expect(x => x.Type == typeof (GenericEnumMapper<T>)),
            x => x.CustomType<EnumMapper<T>>()
            );
      }
   }
}

Now I can just configure it with:
.Conventions.Add(EnumMapper<Units>.Convention)


text:
Q: How to generate strings file using ibtool? I installed the command line tools in xcode 7.3 and in the command line I used the following command to generate the strings file:
  ibtool --generate-strings-file testFile.strings MyController.xib

and also I tried to give the directory path for my xib:
  ibtool --generate-strings-file testFile.strings UI/Screens/My\ Card/MyController.xib

I also tried the command with sudo infront of it, suggested from this answer
None of them worked.
I got the error:
 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.ibtool.errors</key>
    <array>
        <dict>
            <key>description</key>
            <string>Interface Builder could not open the document MyController.xib" because it does not exist.</string>
        </dict>
    </array>
</dict>
</plist>

A: I used the wrong location of the xib. I enetered the location of xib by seeing its heirarchy in the project navigatior in xcode. BUt the correct path can be found at File Inspector tab under Source Control option.

*

*Select the xib file

*Go to File Inspector in the Utilities section.

*Look at the Location path under source control option.It will be something like:
  /Users/VenkataManiteja/Desktop/iOS/MyProject/src/MyController.xib

and I changed the command to
   ibtool --generate-strings-file testFile.strings src/MyController.xib

and it worked.


text:
Q: .net core 2.2 facebook auth store access_token I was following the docs here to save the access_token after a successful auth, but I have no idea where that OnPostConfirmationAsync was supposed to be in my project, I have no Account/ExternalLogin.cshtml.cs. I've also noticed that the table AspNetUserTokens at the database was empty (even after a successful login).
What I'm not understanding on how should I do that auth?
Ps::I need the access_token to do a few integrations with the Facebook API.
Ps2:: I'm using dotnet 2.2
    services.AddAuthentication()
        .AddFacebook(fbOption => {
            fbOption.AppId = Configuration["Authentication:Facebook:AppId"];
            fbOption.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
            fbOption.Fields.Add("name");
            fbOption.Fields.Add("email");
            fbOption.SaveTokens = true;
        });

A: It seems you are using ASP.NET Core identity with external login .
ASP.NET Core 2.1 and later provides ASP.NET Core Identity as a Razor Class Library. Applications that include Identity can apply the scaffolder to selectively add the source code contained in the Identity Razor Class Library (RCL).  See document : Scaffold Identity in ASP.NET Core projects
After scaffolding identity source files to your application , you can find the ExternalLogin.cshtml.cs inside Areas/Identity/Pages/Account folder , then you can modify the OnPostConfirmationAsync to add token to cookie .
Don't forget to modify OnGetCallbackAsync function also :
if (result.Succeeded)
{

    // Store the access token and resign in so the token is included in
    // in the cookie
    var user = await _userManager.FindByLoginAsync(info.LoginProvider,
        info.ProviderKey);

    var props = new AuthenticationProperties();
    props.StoreTokens(info.AuthenticationTokens);

    await _signInManager.SignInAsync(user, props, info.LoginProvider);

    _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);
    return LocalRedirect(returnUrl);
}

After user login , you can get the access token in controller by :
var accessToken = HttpContext.GetTokenAsync("access_token").Result;


text:
Q: How to fix this error in hadoop hive vanilla I am facing the following error while executing MapReduce job in Linux(CentOS). I added all the jars in classpath. The database name and table name already in the hive database with some column of data in the table. Then also I can't able to access the data from the hive database table.
I'm using vanilla version of hadoop for work. Should i need to edit hive-site.xml file by mysql driver path, username and password for hive?. if yes please tell me the procedure to add username and password for hive. Thank you in advance

murali]# hadoop jar /home/murali/workspace/hadoop/HiveInputForMapper/target/HiveInputForMapper-0.0.1-SNAPSHOT.jar com.cosmonet.HiveInputDriver -libjars $LIBJARS
Java HotSpot(TM) Server VM warning: You have loaded library /hadoop/hadoop/lib/native/libhadoop.so which might have disabled stack guard. The VM will try to fix the stack guard now.
It's highly recommended that you fix the library with 'execstack -c <libfile>', or link it with '-z noexecstack'.
14/11/21 11:26:19 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
14/11/21 11:26:20 INFO metastore.HiveMetaStore: 0: Opening raw store with implemenation class:org.apache.hadoop.hive.metastore.ObjectStore
14/11/21 11:26:20 INFO metastore.ObjectStore: ObjectStore, initialize called
14/11/21 11:26:20 INFO DataNucleus.Persistence: Property datanucleus.cache.level2 unknown - will be ignored
14/11/21 11:26:20 INFO DataNucleus.Persistence: Property hive.metastore.integral.jdo.pushdown unknown - will be ignored
14/11/21 11:26:22 INFO metastore.ObjectStore: Setting MetaStore object pin classes with hive.metastore.cache.pinobjtypes="Table,StorageDescriptor,SerDeInfo,Partition,Database,Type,FieldSchema,Order"
14/11/21 11:26:22 INFO metastore.MetaStoreDirectSql: MySQL check failed, assuming we are not on mysql: Lexical error at line 1, column 5.  Encountered: "@" (64), after : "".
14/11/21 11:26:23 INFO DataNucleus.Datastore: The class "org.apache.hadoop.hive.metastore.model.MFieldSchema" is tagged as "embedded-only" so does not have its own datastore table.
14/11/21 11:26:23 INFO DataNucleus.Datastore: The class "org.apache.hadoop.hive.metastore.model.MOrder" is tagged as "embedded-only" so does not have its own datastore table.
14/11/21 11:26:23 INFO DataNucleus.Datastore: The class "org.apache.hadoop.hive.metastore.model.MFieldSchema" is tagged as "embedded-only" so does not have its own datastore table.
14/11/21 11:26:23 INFO DataNucleus.Datastore: The class "org.apache.hadoop.hive.metastore.model.MOrder" is tagged as "embedded-only" so does not have its own datastore table.
14/11/21 11:26:23 INFO DataNucleus.Query: Reading in results for query "org.datanucleus.store.rdbms.query.SQLQuery@0" since the connection used is closing
14/11/21 11:26:23 INFO metastore.ObjectStore: Initialized ObjectStore
14/11/21 11:26:24 INFO metastore.HiveMetaStore: Added admin role in metastore
14/11/21 11:26:24 INFO metastore.HiveMetaStore: Added public role in metastore
14/11/21 11:26:24 INFO metastore.HiveMetaStore: No user is added in admin role, since config is empty
14/11/21 11:26:24 INFO metastore.HiveMetaStore: 0: get_databases: NonExistentDatabaseUsedForHealthCheck
14/11/21 11:26:24 INFO HiveMetaStore.audit: ugi=root ip=unknown-ip-addr cmd=get_databases: NonExistentDatabaseUsedForHealthCheck
14/11/21 11:26:24 INFO metastore.HiveMetaStore: 0: get_table : db=bigdata tbl=categories
14/11/21 11:26:24 INFO HiveMetaStore.audit: ugi=root ip=unknown-ip-addr cmd=get_table : db=bigdata tbl=categories
Exception in thread "main" java.io.IOException: NoSuchObjectException(message:bigdata.categories table not found)
 at org.apache.hive.hcatalog.mapreduce.HCatInputFormat.setInput(HCatInputFormat.java:97)
 at org.apache.hive.hcatalog.mapreduce.HCatInputFormat.setInput(HCatInputFormat.java:71)
 at com.cosmonet.HiveInputDriver.run(HiveInputDriver.java:27)
 at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
 at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
 at com.cosmonet.HiveInputDriver.main(HiveInputDriver.java:49)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:606)
 at org.apache.hadoop.util.RunJar.main(RunJar.java:212)
Caused by: NoSuchObjectException(message:bigdata.categories table not found)
 at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.get_table(HiveMetaStore.java:1560)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:606)
 at org.apache.hadoop.hive.metastore.RetryingHMSHandler.invoke(RetryingHMSHandler.java:105)
 at com.sun.proxy.$Proxy9.get_table(Unknown Source)
 at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.getTable(HiveMetaStoreClient.java:997)
 at org.apache.hive.hcatalog.common.HCatUtil.getTable(HCatUtil.java:191)
 at org.apache.hive.hcatalog.mapreduce.InitializeInput.getInputJobInfo(InitializeInput.java:105)
 at org.apache.hive.hcatalog.mapreduce.InitializeInput.setInput(InitializeInput.java:86)
 at org.apache.hive.hcatalog.mapreduce.HCatInputFormat.setInput(HCatInputFormat.java:95)
 ... 10 more


text:
Q: Android DatePicker is so slow in WebView Below is the WebView code, which shows the webpage at here. Everything works fine. The date picker is so slow, everything else works fine. It takes like 4-5 seconds to select a date. Any alternatives?
public class click extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.click);

        WebView webView = (WebView) findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("http://www.exceptnothing.com/appointment.html");

        webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

    }

}

I tried adding android:hardwareAccelerated="true" in that activity, same effect still.
I'm a beginner, so simpler code will be appreciated. Thanks in advance :)

A: try to checkout android DatePickerDialog. Its native and fast way to pick a date on android. Also, using webview in android applications is a bad practice to build a well formed user interfaces, it's realy decreases the application performance, look, and user feel. Native android vidgets are always best to do the work. This tutorial will help you if you decide to build your ui as views layout http://www.tutorialspoint.com/android/android_datepicker_control.htm


text:
Q: use of () in operator overloading I came across this code with operator(). I have never seen this before (I have seen +,>,- <<). Can someone explain when it should be used and how it should be used?
 class sortResults
    {
    public:
        bool operator() (Result const & a, Result const & b);
    };

A: This is called a functor (not to be confused with a functor in functionnal programming languages).
It mimics a function and can be used as such in functions from the standard library :
std::vector<Result> collection;
// fill with data

// Sort according to the () operator result
sortResults sort;
std::sort(collection.begin(), collection.end(), sort);

A nice advantage compared to simple functions, is that it can hold a state, variable, etc. You can make a parallel with closures (if that rings a bell)
struct GreaterThan{
    int count;
    int value;
    GreaterThan(int val) : value(val), count(0) {}
    void operator()(int val) {
        if(val > value)
            count++;
    }
}

std::vector<int> values;
// fill fill fill

GreaterThan gt(4);
std::for_each(values.begin(), values.end(), gt);
// gt.count now holds how many values in the values vector are greater than 4

A: It means that a sortResults instance can be called, just like a function taking two Result parameters:
sortResults sr;
Result r1, r2;
bool b = sr(r1, r2);

Such a class is referred to as a "functor". Most standard library algorithms have overloads that take unary or binary functors such as this one.


text:
Q: Magento2 - Database transactions inside service layer How make database transactions inside service layer on magento2?
I need use transaction on service layer to expose through webservices.

A: The question is not very clear but you should not implement database transaction inside the web service class.
Use the _Repository classes, inject into it's contructor the Resource Model class which contain the code for persisting data into the database.
Example from core Magento: saving a customer group via web service API
<route url="/V1/customerGroups/:id" method="PUT">
        <service class="Magento\Customer\Api\GroupRepositoryInterface" method="save"/>
        <resources>
            <resource ref="Magento_Customer::group"/>
        </resources>
</route>

A: Transaction support is in \Magento\Framework\DB\Adapter\AdapterInterface implementation (\Magento\Framework\DB\Adapter\Pdo\Mysql). You can get this object from \Magento\Framework\App\ResourceConnection object using DI:
/** @var  \Magento\Framework\DB\Adapter\AdapterInterface */
protected $_conn;
/** @var \Magento\Framework\App\ResourceConnection */
protected $_resource;

public function __construct(
    \Magento\Framework\App\ResourceConnection $resource
) {
    $this->_resource = $resource;
    $this->_conn = $resource->getConnection(); // get default connection
}

then you can use database transaction for the connection:
    try {
        $this->_conn->beginTransaction();
        // ...
        $this->_conn->commit();
    } catch (\Exception $e) {
        $this->_conn->rollBack();
    }


text:
Q: Debug Twill Exception Error I have been failing to go to a URL usign twill and I couldn't find a way to debug the issue further. I have enabled debug levels in twill for "http","equiv-refresh" and "commands", still twill is not giving any details about the error. Here is the output from twill-sh:
    $ twill-sh

     -= Welcome to twill! =-

    current page:  *empty page*
    >> debug equiv-refresh 1
    DEBUG: setting equiv-refresh debugging to level 1
    current page:  *empty page*
    >> debug http 1
    DEBUG: setting http debugging to level 1
    current page:  *empty page*
    >> debug commands 1
    DEBUG: setting commands debugging to level 1
    current page:  *empty page*
    >> go https://auth.nbnco.net.au/okta/login

    ERROR: cannot go to 'https://auth.nbnco.net.au/okta/login'

    current page:  *empty page*

And here is the output from the python script:
    $ ./test.py
    Traceback (most recent call last):
      File "./test.py", line 13, in <module>
        go("https://auth.nbnco.net.au/okta/login")
      File "/usr/lib/python2.7/site-packages/twill/commands.py", line 109, in go
        browser.go(url)
      File "/usr/lib/python2.7/site-packages/twill/browser.py", line 91, in go
        raise TwillException("cannot go to '%s'" % (url,))
    twill.errors.TwillException: cannot go to 'https://auth.nbnco.net.au/okta/login'

A: Guess: Twill won't load the page because there is a problem verifying the page's SSL certificate.
Trying to fetch the page using urllib2.urlopen fails with this error:
>>> urllib2.urlopen('https://auth.nbnco.net.au/okta/login')
Traceback (most recent call last):
...
urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)>

Fetching the page using curl produces this output:
$  curl https://auth.nbnco.net.au/okta/login > /dev/null
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.

The page loads without error for me in Firefox and Chromium, so the certificate is treated differently by the browsers' certificate handling.
The sites SSL certificate is issued by Symantec.  It's possible that this behaviour relates to problems with Symantec certificate issuance in the past which has caused Chrome and Mozilla to announce that they will distrust SSL certificates from Symantec in 2018.
I don't think there is anything you can do in Twill to work around this problem.


text:
Q: Navigation bar color not changing on cordova I am new to Cordova and currently, I'm using this plugin Cordova Plugin to change the color of my navigation bar. As per the documentation, I have added the preferences in my config.xml file.
<preference name="NavigationBarBackgroundColor" value="#000000" />
<preference name="NavigationBarLight" value="true" />

and I have also tried changing using
NavigationBar.backgroundColorByName(String colorName, Boolean lightNavigationBar = false);

it doesn't work. The Splash screen has a black navigation bar however on the next page it turns to white.

Tried including it in document.addEventListener("deviceready", onDeviceReady, false); still not working
Any inputs will be helpful, Not sure where I'm going wrong.Thanks in advance
Navigation bar hide is working but unable to change the color

A: I have encountered this problem. I started studying the code of StatusBar and NavigationBar and found out that they are very similar. I do not know how Java works, but I saw a discrepancy and replaced it.
C:\projects\app-kit-cordovaReact\platforms\android\app\src\main\java\com\viniciusfagundes\cordova\plugin\navigationbar\NavigationBar.java
 //window.getClass().getDeclaredMethod - does not work

 window.getClass().getMethod("setNavigationBarColor", int.class).invoke(window,
 Color.parseColor(colorPref)); - works


text:
Q: How to call and render a template by button click listener I have created a template in html and I want to call it by using button click listener. Any idea?
   HTML
<template id="tem">
 <p>hi </p>
 </template>

A: const templateElement = document.getElementById("tem");
const templateCopy = document.importNode(templateElement.content, true);
// insert
document.body.appendChild(templateCopy);


text:
Q: How can I make an input label clickable? (initiate text input) I'm currently working on a project fiddling with animations on select and was creating a signup form (re-created it on my replit - https://replit.com/join/gzflphmalc-jeezgeorge
)
Everything seems to be working fine except for the fact that when I click on the name of the label (name, email, password) it doesn't initiate the text input.
How can I wrap the label with the input so that when I click on the name as well it will initiate the input.
Thanks in advance. :)

A: I don't have a Replit account so I can't see your project. But if I understand your question, you can use id and for HTML attributes for that:
<label for="name">First Name</label>
<input id="name" type="text" placeholder="e.g. John Doe" />

Once you click on the label First Name, it will focus on the text input.


text:
Q: Unity - How to check if there is a Tile of an specific Tilemap in the position x,y,z I made 4 TileMaps in the same Grid

Lvl1 = The Level Blocks/Tiles,
Lvl1 Dec = The Decoration of the Level,
Negative Parts = Parts where the Player cant Jump,
Positive Parts = [The red ones]Parts where the player stops the jump Animation

So that the thing is I want to check if there is a Positive Tile in a specific Position of that Tilemap, but my code does just checks for Colliders
if (TileChanger == Grass)
{
    Vector3 pos = Cam.ScreenToWorldPoint(Input.mousePosition);
    RaycastHit2D hitdown = Physics2D.Raycast(vecdown, Vector2.zero);
    if (hitdown != false && hitdown.collider != null)
    {
        PositiveParts.SetTile(vecInt, Positive);
        PositiveParts.SetTile(vecIntdown, null);
    }
    else
    {
        PositiveParts.SetTile(vecInt, Positive);
    }
}

So is there any code to get an specific Tile from a specific Tilemap?

A: Can't you just use the gameObject property of the collider to get the tile?
hitdown.collider.gameObject

Then check to see if this is a positive tile using your own validation.
EDIT:
If you just want a tile at a specific coordinate, you can use the Tilemap.GetTile method. Documentation can be found here:
Tilemap.GetTile


text:
Q: bootsrap: how to float right an element from navbar?

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                Toggle navigation

              </button>

Accueil

A propos

Contact

Vos données

Se déconnecter

Credits

I would like to make "Credits" float on right.
I used that:

Credits

But does not help !
fiddle on : http://jsfiddle.net/c8xtkz60/

A: I put together a bootply for you here. I would recommend reading bootstrap's example of this because using navbar-right is the solution you were looking for. Your main problem was the order of your
 tags you started setting them inside each other. Another problem was you were not using container-fluid which takes up full width of the viewport.

              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
                Toggle navigation

              </button>

Accueil

A propos

Contact

Vos données

Se déconnecter

Credits


text:
Q: Java reflection: add final modifier to a class field I'm looking for a way to make an object immutable dynamically by setting all properties of a POJO to be final. One way I thought of is to use Java Reflection to set the modifier to final.
Consider the following POJO:
public class Task {

   private String id;
   private String code;

   // getters and setters placed here

}

Using the above POJO example, I'd like to make id and code have a final modifier. By researching some examples on the internet, these examples refer to using bitwise operators to unset the final modifier.
e.g. the common line that does that is:
modField.setInt(idField, idField.getModifiers() & ~Modifier.FINAL);

However, is there an example of setting the FINAL modifier to a field?
thanks.
Based on the comments below, I set the final modifier by using the following line
modifiersField.setInt(idField, idField.getModifiers() | Modifier.FINAL);

Then by writing a short piece of code to do a test to see if the modifiers change:
Field idField = c.getClass().getDeclaredField("id");
System.out.println("Before = "+id.getModifiers());
id.setAccessible(true);
Field modField = Field.class.getDeclaredField("modifiers");
modField.setAccessible(true);
modField.setInt(id, id.getModifiers() | Modifier.FINAL);
idField.set(c, "DAVE");
modField.setAccessible(false);
idField.setAccessible(false);
Field f = c.getClass().getDeclaredField("id");
System.out.println("After = "+f.getModifiers());
System.out.println("RES = "+c.geId());    //prints "DAVE"

So by checking this, I can see that the value certainly changes for the ID (i.e. to "DAVE"), but the modifier both before the change and after the modifier change is set to 2 (which according to the docs refers to modifier "PRIVATE" being set. Maybe based on other peoples comments it's not possible see a field having final set to it?

A: It is highly advisable to immediately change the .class instead of modify the loaded class. Especially for final constants. For this one can use a byte code manipulation library. The backdraw is the latest java version that the library can handle.
Final constants are special in that they are invisibly imported, copied to the immporting class. A huge disadvantage is that the compiler can no longer detects when the constant value in the original class is modified.
Making the fields final dynamically not optimize the code (as above, or in A+B), but rather only catch errors assigning from other classes.
You will have your valid reason. Assume you have foo-1.2.jar, creating foo-const-1.2.jar. Why not have foo-const-1.2-src.zip or such, and work with final refactored sources? Some code checkers (SonarLint?) detect exposed public fields as bad style.
So you can automate this, writing a script (say in java). But code checkers often also provide a refactoring out of the box.

*

*Let SonarLint run to detect which rule detects exposal of fields.

*Customize SonarLint/SonarCube for just that rule.

*Maybe you can per click refactor all fields.

*Otherwise collect those spots and write your own refactoring. Backing up the origina source.

You might even want to do a name refactoring converting fooBar into FOO_BAR.


text:
Q: Elasticsearch _reindex API not copying documents I'm trying to upgrade an old 1.5 elastic index to 6.0, according to docs (https://www.elastic.co/guide/en/elasticsearch/reference/6.0/reindex-upgrade.html)
I can create a new index in 6.0 and then use reindex from remote using reindex from remote (https://www.elastic.co/guide/en/elasticsearch/reference/6.0/reindex-upgrade-remote.html)
Both of these instances are running inside docker containers I just wanted to test this in local before actually doing it in production
I can see there are documents indexed in my old index.
curl -XGET 'http://localhost:9200/old_index/_search?pretty'
{
  "took" : 8,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : 1.0,
    "hits" : [ {
      "_index" : "old_index",
      "_type" : "item",
      "_id" : "92",
      "_score" : 1.0,
      "_source":{"user_id":3,"slug":"asdfaisjeilej","name":"lake.jpgasdad","item_type":"image","created_at":"2018-01-23T18:11:30Z","deleted_at":null,"content_length":1252171}
    }]}
}

After creating a new index (new_index) in my elasticsearch 6.0 instance, with a slightly diff mapping (change string types to text), I then proceed to reindex from remote using the following command. (note than my other instance is running in port 9400)
curl -XPOST 'localhost:9400/_reindex?pretty' -H 'Content-Type: application/json' -d'
{
  "source": {
    "remote": {
      "host": "http://localhost:9200"
    },
    "index": "old_index"
  },
  "dest": {
    "index": "new_index"
  }
}

I get the following response
{
  "took" : 136,
  "timed_out" : false,
  "total" : 0,
  "updated" : 0,
  "created" : 0,
  "deleted" : 0,
  "batches" : 0,
  "version_conflicts" : 0,
  "noops" : 0,
  "retries" : {
    "bulk" : 0,
    "search" : 0
  },
  "throttled_millis" : 0,
  "requests_per_second" : -1.0,
  "throttled_until_millis" : 0,
  "failures" : [ ]
}

So basically, documents from old_index are not being copied to new_index, and I have no idea why this is happening. Is there a step I'm missing, I'm following elasticsearch docs exactly as they read apparently.

A: As I mentioned, I also had the same issue while migrating from Elasticsearch-2 to Elasticsearch-6 after I tested the remote-reindexing in staging environment without dockers.
My workaround was to create an instance of the old version (not on docker), load it from backup and reindex from it to elasticsearch 6 instance that not running on docker.
If you still want to run elasticsearch 6 on docker you can always mount the data to your container.
Hope you find it helpful.


text:
Q: FIXED Send POST request to server from client, Springboot I am trying to send a post request, but springboot doesnt seem to recieve it.
My code:
Serverside reader
@RestController
public class MessageService {
    @PostMapping(path = "/online")
    public ResponseEntity<?> getResponse(){
        System.out.println("Post Recieved");
        return new ResponseEntity<>(HttpStatus.OK);
    }
}

Client
private String url = "http://127.0.0.1:8090";
public static void main(String[] args) throws IOException {
    SpringApplication.run(Client.class, args);
    new StartupService().init();
}
public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}

StartupService/ POST Sender
public void init() throws IOException {
       String query = "Body";
        Client client = new Client();
        HttpURLConnection urlConn;
        URL mUrl = new URL(client.getUrl()+ "/online");
        urlConn = (HttpURLConnection) mUrl.openConnection();
//query is body
        urlConn.addRequestProperty("Content-Type", "application/" + "POST");
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-Length", Integer.toString(query.length()));
        urlConn.getOutputStream().write(query.getBytes(StandardCharsets.UTF_8));
        System.out.println("Post Sent");
    }

I tried sending a POST request via Postman, which worked as expected and gave me the console output. But the POST from code isn't recieved from the server.

A: FIXED: I used a simpler method to send a POST:
javaClient userClient = new Client();
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
  .uri(URI.create(userClient.getUrl()+ "/online"))
  .POST(HttpRequest.BodyPublishers.ofString(query))
  .build();

HttpResponse<String> response = client.send(
  request,
  HttpResponse.BodyHandlers.ofString()
);

System.out.println(response.body());

System.out.println("Post Sent");


text:
Q: Cross Database Permissions SQL Server In an MS SQL 2005 instance there are two databases.
A specific user has execute rights on the dbo schema for both of these databases.
In database A I have a stored procedure which contains a select statement on a table in database B.
Are the dbo schema execute permissions sufficient for this call, or will the user have to have select access on the table in database B?
We use stored procedures for all database access and would prefer the user only have execute rights.

A: If cross db ownership chaining is enabled and the owner of stored procedure in A is also the owner of tables in B (same SID, not just same name) then the EXECUTE permission is sufficient.
If either of these is not true then the current executing login must also have an user in B with SELECT permission on the table. The alternative is to use code signing which can give a more granular control, allowing the user to select from the table only when executing the procedure.

A: No, you must also grant SELECT on the schema or the specific objects in question.  Granting EXECUTE on the schema just allows the user to do just that.  You must also have the permissions to perform the underlying taks within the stored procedure.


text:
Q: Print evaluation of function calls and iterators I would like to understand the way Python evaluates function calls inside print statements or, more particulary, what does the call for
next(some_iter) return? A mutable reference to the element in the next position or just a copy of the element in the next position when some_iter was last evaluated?
The following code:
def foo(val, arr=set()):
    arr.add(val)
    return arr

print(foo(1))
print(foo(2))
print(foo(1), foo(3), foo(0))

Returns the output:
{1}
{1, 2}
{0, 1, 2, 3} {0, 1, 2, 3} {0, 1, 2, 3}

Python calls the function three times, holding what seems to be a reference to arr, then, since sets are mutable, the output is as can be seen above. foo(1) return value was not saved, that is {1, 2} when it is called in order of the print statement.
However
lst = [1, 2, 3, 4]
def bar(a):
    a = lst
    a[0] = 17
    return a
x = iter(lst)
y = iter(lst)
print(next(x), bar(lst), next(y), next(x))
print(lst)

Would print
1 [17, 2, 3, 4] 17 3
[17, 2, 3, 4]

I would have expected
17 [17, 2, 3, 4] 17 3
[17, 2, 3, 4]

That is for next to hold a reference to the first element of lst, which would later be changed to 17, and for that reference to be printed as 17 eventually, but it is computed first returning 1.
Why does it not happen? In what way is the next() or iters different?


text:
Q: Remove IDENTITY from a partitioned table In https://stackoverflow.com/a/26048363/143768, a clever way of eliminating the IDENTITY property from a table was provided using the magic of partition switching.  This approach, however, does not work if your table is already partitioned.  (And, in fact, this method is more applicable to very large multi-terabyte tables, which are likely are already partitioned.)
Since I am working in exactly this situation — trying to eliminate the IDENTITY attribute on some very large tables — does anyone know how to adapt this solution to already-partitioned tables?
EDIT: This is actually more complicated than I originally envisioned.  There is at least one index that is not partitioned.  When I try traditional partition switching:
ALTER TABLE [dbo].[era_adj] SWITCH PARTITION 1 TO [dbo].[tmp_ms_xx_era_adj] PARTITION 1;
. . .
ALTER TABLE [dbo].[era_adj] SWITCH PARTITION 57 TO [dbo].[tmp_ms_xx_era_adj] PARTITION 57;

I get the error:
Msg 7733, Level 16, State 4, Line 21
'ALTER TABLE SWITCH' statement failed. The table 'ERADev.dbo.era_adj' is partitioned while index 'PK_era_adj' is not partitioned.

So now I also need to figure out how to partition my indexes...


text:
Q: Disable hover popup outlook When i hover over an email contact, it produces a popup. How can I stop outlook
from doing this
I tried file, options, general, user interface options, dont show screentips;
but it seems that is not the option that controls it.

A: Here is a REG file that covers Outlook 2013 and 2010:
Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Policies\Microsoft\Office\15.0\Common\ContactCard]
"TurnOffHoverFunctionality"=dword:1

[HKEY_CURRENT_USER\Software\Policies\Microsoft\Office\14.0\Common\ContactCard]
"TurnOffHoverFunctionality"=dword:1

http://leeowens337.blogspot.com/2010/10/outlook-2010-contact-card-hover-over.html


text:
Q: Best practice for data streaming #bigquery How would you go for real time data streaming from a PostgreSQL DB on GCS to BQ?
Google has literally a ton of options and products on the left panel menu and from what i could find online, i saw that Datastream and Dataflow might be the way, but that example I found is with data from an oracle DB.
Would a database already on GCS only need dataflow?
I'm confused, the available material doesn't say much (at least to me, maybe it's my limitation) and i need to find a solution as I'm totally new to Google products.
Any help would be greatly appreciated.
Thanks.


text:
Q: Extend Google Forms (Custom Functions) I ran into a bit of a problem here while creating a Google Form for work appraisals. I have the basic form for employees to fill out all set up but I need a second form for the heads of department to fill in employee scores.
Simply put:

*

*User completes form

*Completed form is forwarded to head of department for review

*HoD finishes "grading" said form and submits to HR

*Results are tabulated into Google Sheets for further use

Can this be solved with functions or add-ons?

A: As per stackoverflow rules: https://stackoverflow.com/help/on-topic

Questions asking us to recommend or find a book, tool, software
  library, tutorial or other off-site resource are off-topic for Stack
  Overflow as they tend to attract opinionated answers and spam.
  Instead, describe the problem and what has been done so far to solve
  it.

Having said that, I will be brief.
Yes. What you would need is just one form with a special workflow and the use of just one add-on.
I have prepared a functioning Testing Form for you. Please have look.
Make a note that the emailing ability has been disabled for obvious reasons.
Also. In the form a hint is provided for a password asked. Similar hint should be avoided in your working form.
PS: What to do when someone answers your question (accepting and/or upvoting) it.


text:
Q: Maximal subgroups of order $pq^2$ in finite simple groups This question is moved from math stackexchange, seems like it is a more advanced question. Here the link from the original question: https://math.stackexchange.com/questions/3415338/maximal-subgroups-of-order-pq2-in-finite-simple-groups
It is a well-known result in elementary group theory that if $q^{2}\mid (p-1)$, then there are two non-isomorphic nonabelian groups of the form $\mathbb{Z}_{q^{2}}\ltimes\mathbb{Z}_{p}$. One has a cyclic subgroup of order $pq$ while in the other one the subgroup of order $pq$ is nonabelian. Now my question:
Is there any finite simple group $G$ with a maximal subgroup $M\cong\mathbb{Z}_{q^{2}}\ltimes\mathbb{Z}_{p}$ such that the subgroup of order $pq$ in $M$ is abelian?
As far as I searched in ATLAS there is not such an example but I need a proof.

A: No there is no such simple group.
Suppose that $G$ is simple and has $M$ as a maximal subgroup. Let $P \in {\rm Syl}_q(M)$ and $Z=Z(M)$. So $|P|=q^2$ and $|Z|=q$ with $Z < P$. Since $M$ is maximal in $G$ and $M$ is not normal in $G$, we have $M = N_G(Z)$.
Now $N_G(Z)$ contains the centre of a Sylow $q$-subgroup $R$ of $G$ containing $P$, and since $Z$ is the only subgroup of $P$ of order $q$, we must have $Z \le Z(R)$, and so $R=P$.
Also, $N_G(P) \le N_G(Z) = M$, so $N_G(P) = N_M(P) = P$. But now by Burnside's Transfer Theorem $G$ has a normal $q$-complement in $G$, contradicting its simplicity.


text:
Q: I want to append to echo statement in one line in UNIX read Name?" Enter Full name "

First= echo $Name | cut -d ' ' -f1

I am using this command to cut Full name, but it automatically print first name. which  I don't want.
I want an output like
James, This is prime number.

A: In the shell I use (bash on MacOS), this following works.
read -p "Enter full name " first last

echo Hi $first, you are the man

Please specify what shell you are using.
Another thing to note, is that in order to assign to the variable 'First' in your question, in bash you need to do surround the command with backticks `` or the $() construction, as follows.
First=$(echo $Name | cut -d ' ' -f1)


text:
Q: Protect uploaded files I have build a website based on php/joomla. It is running on a WAMP server.
Users can upload files/images to their own account, and the files are all saved as:
public_html/userfiles/0001.jpg
public_html/userfiles/0002.jpg
public_html/userfiles/0003.jpg
...

For the sake of privacy, I want to avoid none-registered users or users without permission to access files from other users. Right now, anyone can access all images by entering the filename in the browser address bar.
I need an extremely high level of protection, so my question is: Can I solve this by apache settings? Or should I use fx server site AES encryption and then ask for password at client-site and run descryption with something like crypto-js?

A: Not really good with .htaccess but you can use the following code:
RewriteCond %{HTTP_COOKIE} allow!=true
RewriteRule (.*) http://domain.com/404.html [L,QSA]

What this will do is it will redirect anyone with a cookie allow not set to domain.com/404.html
You should also set http cookie to true while setting it.

A: This will prevent images being accessed via url, but will still display from html/php file. (change localhost to whatever your host is)
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC]
RewriteRule \.(gif|jpg)$ - [F]

A: You can do like this,
1. Prevent direct access of .jpg using .htaccess
.htaccess
<FilesMatch "\.(jpg|jpeg)$">   #all file extensions you want to restrict.
Deny from all
</FilesMatch>

2. Retrive image using .php script.
get_picture.php
//check here user login
//if not logged-in
// exit();

//proceed if logged-in.

//get picture file path from DB.
$file_path="this/path/will/be/from/db/user_xyz.jpg"

header("content-type: image/jpg"); //set mime type respective to file type

readfile(file_path);

die();

3. how to use in
HTML
<img src="get_picture.php" style="height:100px;width:100px;" />


text:
Q: How to drop UITableViewCell to bottom of UITableView. A UITableView which have UITableViewCell of 20 rows, each row do have one button on it, click button I want to drop the UITableViewCell to bottom to UITableView.
Is there any delegate method which do for it.
Your feedback will be appreciated.

A: Yes, there is a method on tableview
- (void)moveRowAtIndexPath:(NSIndexPath*)indexPath
               toIndexPath:(NSIndexPath*)newIndexPath

You can read more https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/#//apple_ref/occ/instm/UITableView/moveRowAtIndexPath:toIndexPath:

A: Yes, there is one!
Use below delegate methods for that:
have to return YES to allow moving of tableView row in canMoveRowAtIndexPath delegate method as per your requirement,
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) // Don't move the first row
      return NO;

   return YES;
}

Then, use moveRowAtIndexPath delegate method to Updating the data-model array for the relocated row accordingly,
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
      toIndexPath:(NSIndexPath *)toIndexPath
{

      //Updating the data-model array
}

Like moveRowAtIndexPath in button click,
- (void)btnClick:(UIButton*)sender
{
    UITableViewCell *cell = (UITableViewCell *)sender.superview;
    NSIndexPath *indexpath = [tableView indexPathForCell:cell];

    //Change accordindly as per requirement
    [tableView moveRowAtIndexPath:[NSIndexPath indexPathForItem:indexpath.row inSection:indexpath.section] toIndexPath:[NSIndexPath indexPathForItem:0 inSection:indexpath.section]];

}

Also, read Apple documentation for same:
https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/TableView_iPhone/ManageReorderRow/ManageReorderRow.html


text:
Q: Is it possible to lock all new and existing WordPress posts to one specific author? I have a case where there will be multiple users writing, editing, and publishing posts. All these posts should always have the same user as the author, a catch-all user if you will.
Is it possible to programmatically set the author for every new post to this user, no matter which user is logged in? I think I will be able to figure out how to remove the ability to change author on posts, but I am kind of stuck on this one question.
If someone could point me in the right direction I would be very thankful!

A: This is untested, but you could use the wp_insert_post_data filter to change the post author to a specific value whenever a post is inserted or updated:
add_filter(
    'wp_insert_post_data',
    function( $data ) {
        if ( 'post' === $data['post_type'] ) {
            $data['post_author'] = 2; // Replace with desired author's user ID.
        }

        return $data;
    }
);

Just be aware that if posts are being created by users who do not have the edit_others_posts capability, such as Authors and Contributors, then they will experience unusual behaviour, because they will not have permission to do anything with the post once it has been saved. So they could see an error when the post page reloads after pressing Publish, for example.


text:
Q: Symfony2.5 + FOSUserBundle check path apparently not found I started a new Symfony app on which I use the FOSUserBundle.
I installed it, loaded the bundle and configured it.
Here's my configuration.yml:
fos_user:
    db_driver: orm
    firewall_name: main
    user_class: Myapp\UserBundle\Entity\User

and my security.yml:
security:
    encoders:
        FOS\UserBundle\Model\UserInterface: sha512

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username
        in_memory:
            memory: ~

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        default:
            anonymous: ~

        main:
            pattern: ^/
            form_login:
                login_path: fos_user_security_login
                check_path: fos_user_security_check
                provider: fos_userbundle
                csrf_provider: form.csrf_provider
                default_target_path: /
            logout:       true
            anonymous:    true

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, role: ROLE_ADMIN }

Now, when I go to localhost/myapp/web/app_dev.php/login, I get the following Error 500 after I try to login (I have no problem accessing the login form, this comes after I submit):

You must configure the check path to be handled by the firewall using form_login in your security firewall configuration

It seems to me that form_login is configured in my security firewall configuration... what am I missing?

A: I am thinking that you didn't import FOSUserBundle's routing file. Did you?
In case didn't this is how you do it:
http://symfony.com/doc/current/bundles/FOSUserBundle/index.html#step-6-import-fosuserbundle-routing-files
Other than that, what is the purpose of that default firewall? It could be intercepting the security component when it tries to "find the correct firewall to use".


text:
Q: What to do if logfile has rotated? If I am continually parsing a log file and I detect that it has rotated, what is the best practice for handling this?

*

*Update my internal hashmap to reflect a new filePointer (end of
rotated file)

*Or should I update the hashmap to 0 so it can read the
rotated file from the start

My concern is that in the case of an anomaly in situation no. 2 mentioned above, I may indirectly parse a large file from the start and put significant load on the host.
However if I use no. 1 I may miss something critical that I was parsing the log file for.
This is the code that I've put together.
currentFilePointer = util.FileManagement.getLastFilePointerFromFile(file.getName());
lastFilePointer = Long.parseLong(lastReadFiles_.get(file.getName()).toString());

if (currentFilePointer < lastFilePointer) // file has grown
{
     processLineByLine(file.getName(), currentFilePointer, lastFilePointer);
} else if (currentFilePointer > lastFilePointer) // file has been rotated
{
     lastReadFiles_.put(file.getName(), currentFilePointer); // Option 1
 }

A: From the code you posted, I can't see any Hashmap... Hard to tell which solution is better :)
Here's a snippet of code I used to "tail" a file, which also supports rotates (to be run in a separate Thread):
@Override
public void start() {
    File file = ...
    long filePointer = 0;
    try {
        while (running) {
            Thread.sleep(updateInterval);
            long len = file.length();
            if (len < filePointer) {
                // File was rotated
                filePointer = 0;
            } else if (len > filePointer) {
                // File must have had something added to it!
                RandomAccessFile raf = new RandomAccessFile(file, "r");
                raf.seek(filePointer);

                // Here you can read the next lines using for example a BufferedReader

                filePointer = raf.getFilePointer();
                raf.close();
            }
        }
    } catch (Exception e) {
        // ...
    }
}

A: I think that your issues is how to manage log files in general. Such operations can be done using script language like bash or some general script language like python. An extensive tutorial for using java is managing Logs for the Java Subsystems.


text:
Q: How to fill down in Numbers without dragging? I have a 20,000 line spreadsheet in Apple Numbers, and I need to fill a column with data. I don't want to sit there dragging down the fill handle for thousands of rows.
How can I fill the whole column with a value?

A: Found a way.

*

*Select the column

*Deselect the header row (Cmd click on the header
row cell)

*Table Menu > Autofill Cells > Autofill Down

This will not infer a pattern. (ex 1,2,3 it will just copy down 1,1,1)
If you're expect it to interpolate, you have to click-drag.
It will fill down formulas and they will be correct.

A: It is late for response here.
I have a file with 65500 rows which I need to add sequence of numbers (1,2,3,etc) to it. This is how you do it.
Row 1, column 1 type 1
In Row 2, column 2 type use formula to add the value of number 1 ( check the attachment)
Now do this as @Joshua Dance suggested.

*

*Select the column

*Deselect the header row and the row 1 (Cmd click on the header
row cell)

*Table Menu > Autofill Cells > Autofill Down

Cheers

A: To expand upon the above answers, if you would like to do this using only the keyboard, you can simulate the Ctrl-D and Ctrl-R shortcuts from Excel by adding a keyboard shortcut to that menu item in System Preferences.
This is how:

*

*Open System Preferences > Keyboard

*Under the Shortcuts tab, click the + button.

*In the resulting sheet, select Numbers.app for the Application.

*For Menu Title, enter Autofill Down, exactly as it is in the menu item.

*For Keyboard Shortcut, press the key combination you want to assign, e.g. Ctrl-D or Ctrl-R.

A: Filling a column can use the shortcut combination "option + command + \".
Steps:

*

*Select the column you want to fill in.

*Unselect the first cell.

*Press "option + command + \" at the same time.


text:
Q: Change all values that satisfy different conditions in pandas dataframe      A      B  C   D
0  foo    one  0   0
1  bar    one  1   2
2  foo    two  2   4
3  pak  three  3   6
4  foo    two  4   8
5  bar    two  5  10
6  foo    one  6  12
7  dop  three  7  14
8  foo    one  0   0
9  bar    one  1   2
10 pak    two  2   4
11 bar  three  3   6

I need to multiply C and D columns with a weight but weight are different for A column values. For foo it's 2, for bar it's 1,5, and for pak it's 3,4 and for dop it's 2,3. In reality those conditions are 15 and the data is huge so I can't use for loop.

A: Using Series.map:
conditions = {
    'foo': 2,
    'bar': 1.5,
    'pak': 3.4,
    'dop': 2.3

}

weights = df['A'].map(conditions)

df['result'] = df['C'] * df['D'] * weights


text:
Q: Makefile improvement when intermediate files do not really change I have a Makefile like this
all: *.foo
    ./finalstep *.foo > $@

%.foo: %.bar
    ./secondstep < $< > $@

%.bar: %.baz
    ./firststep < $< > $@

The thing is that often changes in a .baz file are minor in the sense that the .bar file produced after the change is the same (content-wise, or as would be detected by diff) as before the change.
Since secondstep and finalstep (and possible some more intermediate steps) are expensive it would be preferable if the lack of change in the .bar files could be detected and thus the invocation of secondstep (and maybe even finalstep) spared. Is there any way to achieve this?
My attempt to do something like this is as follows:
%.bar: %.baz
    touch $@; cp $@ $@.backup; ./firststep < $< > $@

%.foo: %.bar
    diff -q $< $<.backup || ./secondstep < $< > $@

But this has a lot of drawbacks (and does not work correctly if one invokes make with arguments).
Is there any better method? Basically, make should consider two different filetimes for .bar files: One that gets updated each time firststep is run and that is used to determine whether .bar itself needs to be remade. Another that is only updated when a run of firststep results in a net change of content of the file and that is used to determine whethr .foo needs to be remade ...

A: I think you should experiment with something like this (not tested):
all: %.foo
    ./finalstep %.foo > $@

%.foo: %.bar
    @if [[ -f $< && -f $<.backup ]]; then   \
        if diff -q $< $<.backup; then       \
            echo "IDENTICAL => do nothing"; \
        else                                \
            echo "DIFFERENT => proceed";    \
            ./secondstep < $< > $@;         \
        fi;                                 \
    else                                    \
        echo "NOT FOUND => proceed";        \
        ./secondstep < $< > $@;             \
    fi;                                     \
    cp $< $<.backup

%.bar: %.baz
    ./firststep < $< > $@;

Basically, the intention of the big recipe is to handle all the relevant combinations of $< and $<.backup (in the same subshell!):

*

*both files present and equal (diff returns 0) => do nothing

*both files present and differ (diff returns 1) => execute

*one of the files not present => execute

Whatever is the above choice, make a backup at the end.


text:
Q: .htaccess rules being overriden I am currently having an issue with a website I am working on. I am forwarding one URL to another URL.
In my root folder, I have the following code:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.domaina.com
RewriteRule ^(.*) http://www.domainb.com/$1 [R=301,L]

It's redirecting traffic as it is supposed to, except in one directory on the website > /shop
In the /shop directory, there is also an .htaccess file and it seems to be cancelling out what I have set in the root. Here are the contents of the .htaccess in the /shop directory:
RewriteEngine On
RewriteBase /shop/

RewriteRule ^enclosures-enclosure-guidelines-c-229_675.html$
/resources#nema-guidelines [L,R=301,NE]

#RewriteRule ^category/(.*)$ index.php?$cPath=$2
RewriteRule ^mc/(.*)$ mc.php?keywords=$1

RewriteRule ^(.*)-c-(.*)-p-(.*)$ product_info.php?cPath=$2&products_id=$3&%{QUERY_STRING}
RewriteRule ^(.*)-p-(.*)$ product_info.php?products_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-c-(.*)$ index.php?cPath=$2&%{QUERY_STRING}
RewriteRule ^(.*)-c2-(.*)$ index2.php?cPath=$2&%{QUERY_STRING}

RewriteRule ^(.*)-c-(.*)-p-(.*).html$ product_info.php?cPath=$2&products_id=$3&%{QUERY_STRING}
RewriteRule ^(.*)-p-(.*).html$ product_info.php?products_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-c-(.*).html$ index.php?cPath=$2&%{QUERY_STRING}
RewriteRule ^(.*)-m-(.*).html$ index.php?manufacturers_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-pi-(.*).html$ popup_image.php?pID=$2&%{QUERY_STRING}
RewriteRule ^(.*)-t-(.*).html$ articles.php?tPath=$2&%{QUERY_STRING}
RewriteRule ^(.*)-a-(.*).html$ article_info.php?articles_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-pr-(.*).html$ product_reviews.php?products_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-pri-(.*).html$ product_reviews_info.php?products_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-i-(.*).html$ information.php?info_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-links-(.*).html$ links.php?lPath=$2&%{QUERY_STRING}

Any help would be appreciated.

A:
it seems to be cancelling out what I have set in the root"

That's how .htaccess files work. From the docs:

The configuration directives found in a .htaccess file are applied to
  the directory in which the .htaccess file is found, and to all
  subdirectories thereof. However, it is important to also remember that
  there may have been .htaccess files in directories higher up.
  Directives are applied in the order that they are found. Therefore, a
  .htaccess file in a particular directory may override directives found
  in .htaccess files found higher up in the directory tree. And those,
  in turn, may have overridden directives found yet higher up, or in the
  main server configuration file itself.

A: Inside shop/.htaccess you can use this directive at the top:
RewriteOptions InheritBefore

This forces the current configuration to inherit the configuration of the parent and applies parent rules before current .htaccess rules.
If you are on older Apache i.e. < 2.4 then use:
RewriteOptions Inherit

though remember that parent config will be applied after current set.
Check official doc for more details


text:
Q: Let u and v be two verticies in the tournament T. Let u and v be two verticies in the tournament T. Prove that if U and V do not lie  on a  common cycle then the out degree  of u does not equal the outdegree of v.
So I will try to do the contra positive. So assume that the out degree of u equal the out degree of v.
The we assume (u,v) is an arc in the tournament T. The since $deg^+(v)=deg^+(u)$ there must also be be a (v,u) arc in the tournament. Hence u,v lie on a common cycle.
The only thing which confuses me is that in a tournament you can only have (u,v) or (v,u) as an but not both.

A:
since $\deg^+(v)=\deg^+(u)$ there must also be be a $(v,u)$ arc in the tournament.

Why is that so? What theorem/argument are you using? Just having $\deg^+(v)=\deg^+(u)$ doesn't seem to imply that $(v,u)$ is also an arc in the tournament (in fact this isn't the case precisely because of your "confusion", i.e., in a tournament, you cannot have both $u\rightarrow v$ and $v\rightarrow u$)

Here's one approach to prove it:
Let the tournament $T$ be on $n$ vertices.
WLOG say $u\rightarrow v$ and assume that $u,v$ have equal outdegrees.
Now, define $I(u):=\{x\in T\mid x\rightarrow u\}$ and $O(v):=\{x\in T\mid v\rightarrow x\}$. We also define $O(u)$ and $I(v)$ analogously. Note that $\deg^+(u)=|O(u)|$ (analogously for $v$)
Can you show that $I(u)\cap O(v)$ is non-empty? (if it is non-empty, say $w\in I(u)\cap O(v)$, then $v\rightarrow w\rightarrow u\rightarrow v$ forms a directed cycle)
Hint: Suppose it is empty and obtain a contradiction.
Hint #2: Every vertex other than $u$ must either be in $I(u)$ or $O(u)$ (analogously for $v$) since $T$ is a tournament.

A: As the previous answer by Prasun Biswas suggests , consider w.l.o.g, that you have $u\rightarrow v$(which means $u$ beat $v$ in the tournament). Consider all the people beaten by $v$, which number $deg^{+}(v)$. If even one of them, say $w$, beats $u$, then we get the cycle $u\rightarrow v\rightarrow w \rightarrow u$, and we are done. Otherwise, if all of these people beaten by $v$ are also beaten by $u$, then $deg^{+}(u)\geq deg^{+}(v)+1$, since $u$ had also beaten $v$, which gives a contradiction.


text:
Q: How much torque does it take to turn a doorknob? How much torque does it take to turn a doorknob?  I'm not looking for an exact answer, just a ballpark for someone who doesn't have a sense of everyday amounts of torque.
Here's a very ordinary picture of a very ordinary doorknob, the type I'm imagining for this question:

A: Hanging my iPhone with case (0.16 kg), on a lever arm 12 cm from the center of the door knob just starts turning it. Therefore,
$$m\cdot g\cdot L = 0.19 \mathrm{\,Nm}.$$

A: How about 5 inch-pounds max (0.56 Nm). It would take a weight of 1 pound hung at a distance of 5 inches to turn some doorknobs. Of course it really varies with the strength of the return spring, the friction and the amount of travel the latch needs.

A: There is so many different variables in play to really give any answer, how old is the door noob, was there a bit of paint in the door nob assembly from the last time it was painted, has the components worn out or have started to oxidize, just to many different variables that I want to be able to give you an answer.


text:
Q: How to optimize a SQL Server query with repetitive sub queries I am restrained to a legacy database structure and require some stats results.  The following query works, but is inefficient and slow ...
SELECT various, other, native, columns,
    (SELECT client FROM clients WHERE id = clientid) AS client,
    (SELECT name FROM categories WHERE id = (SELECT categoryid FROM clients WHERE id = clientid)) AS category,
    (SELECT fullname FROM staff WHERE id = producerid) AS producer,
    ISNULL((SELECT SUM(amount) FROM JobsVoiceWork v WHERE v.jobid = j.id),0) AS voicecosts,
    (SELECT COUNT(*) FROM Scripts s WHERE s.jobid = j.id) AS numberofscriptscompleted,
    ISNULL((SELECT SUM(duration) FROM TimeLog WHERE jobid = j.id),0)/60 AS totaltime,
    ISNULL((SELECT SUM(duration)  FROM TimeLog WHERE jobid = j.id AND jobeditid = 3 AND jobpart = 'Add'),0)/60 AS PartAdd,
    ISNULL((SELECT SUM(duration)  FROM TimeLog WHERE jobid = j.id AND jobeditid = 3 AND jobpart = 'Update'),0)/60 AS PartUpdate,
    ISNULL((SELECT SUM(duration)  FROM TimeLog WHERE jobid = j.id AND jobeditid = 3 AND jobpart = 'Produce'),0)/60 AS PartProduce,
    ISNULL((SELECT SUM(duration)  FROM TimeLog WHERE jobid = j.id AND jobeditid = 3 AND jobpart = 'Amend'),0)/60 AS PartAmend,
    ISNULL((SELECT SUM(duration)  FROM TimeLog WHERE jobid = j.id AND jobeditid = 4),0)/60 AS EditProducerError,
    ISNULL((SELECT SUM(duration)  FROM TimeLog WHERE jobid = j.id AND jobeditid = 8),0)/60 AS EditVoiceError,
    ISNULL((SELECT SUM(duration)  FROM TimeLog WHERE jobid = j.id AND jobeditid = 1),0)/60 AS EditClientError,
    ISNULL((SELECT SUM(duration)  FROM TimeLog WHERE jobid = j.id AND jobeditid = 2),0)/60 AS EditEntryError,
    ISNULL((SELECT SUM(duration)  FROM TimeLog WHERE jobid = j.id AND jobeditid = 5),0)/60 AS EditPronunciation,
    ISNULL((SELECT SUM(duration)  FROM TimeLog WHERE jobid = j.id AND jobeditid = 6),0)/60 AS EditRemixRequest,
    ISNULL((SELECT SUM(duration)  FROM TimeLog WHERE jobid = j.id AND jobeditid = 7),0)/60 AS EditRevoiceRequest
FROM Jobs j

I have show a simplified version of the query, but I have included the repetitive sub queries to clearly demonstrate the inefficiency.  I have tried various table join scenarios, but I cannot improve performance.
It looks like it should be possible to improve.  Is there a way?

A: You can use CASE statements to eliminate the redundant subqueries, something like:
SELECT various, other, native, columns,
    (SELECT client FROM clients WHERE id = clientid) AS client,
    (SELECT name FROM categories WHERE id = (SELECT categoryid FROM clients WHERE id = clientid)) AS category,
    (SELECT fullname FROM staff WHERE id = producerid) AS producer,
    ISNULL((SELECT SUM(amount) FROM JobsVoiceWork v WHERE v.jobid = j.id),0) AS voicecosts,
    (SELECT COUNT(*) FROM Scripts s WHERE s.jobid = j.id) AS numberofscriptscompleted,
    ISNULL(SUM(t.duration),0)/60 AS totaltime,
    ISNULL(SUM(CASE WHEN  t.jobeditid = 3 AND t.jobpart = 'Add' THEN t.duration ELSE 0 END),0)/60 AS PartAdd,
    ISNULL(SUM(CASE WHEN  t.jobeditid = 3 AND t.jobpart = 'Update' THEN t.duration ELSE 0 END),0)/60 AS PartUpdate,
    ISNULL(SUM(CASE WHEN  t.jobeditid = 3 AND t.jobpart = 'Produce' THEN t.duration ELSE 0 END),0)/60 AS PartProduce,
    ISNULL(SUM(CASE WHEN  t.jobeditid = 3 AND t.jobpart = 'Amend' THEN t.duration ELSE 0 END),0)/60 AS PartAmend,
    ISNULL(SUM(CASE WHEN  t.jobeditid = 4 THEN t.duration ELSE 0 END),0)/60 AS EditProducerError,
    ISNULL(SUM(CASE WHEN  t.jobeditid = 8 THEN t.duration ELSE 0 END),0)/60 AS EditVoiceError,
    ISNULL(SUM(CASE WHEN  t.jobeditid = 1 THEN t.duration ELSE 0 END),0)/60 AS EditClientError,
    ISNULL(SUM(CASE WHEN  t.jobeditid = 2 THEN t.duration ELSE 0 END),0)/60 AS EditEntryError,
    ISNULL(SUM(CASE WHEN  t.jobeditid = 5 THEN t.duration ELSE 0 END),0)/60 AS EditPronunciation,
    ISNULL(SUM(CASE WHEN  t.jobeditid = 6 THEN t.duration ELSE 0 END),0)/60 AS EditRemixRequest,
    ISNULL(SUM(CASE WHEN  t.jobeditid = 7 THEN t.duration ELSE 0 END),0)/60 AS EditRevoiceRequest
    FROM Jobs j
    LEFT JOIN Timelog t
       ON j.id = t.jobid

A: Try this one -
SELECT various, other, native, columns,
    c.client,
    c2.name AS category,
    s.fullname AS producer,
    ISNULL(v.amount, 0) AS voicecosts,
    s3.numberofscriptscompleted,
    ISNULL(SUM(t.duration),0)/60 AS totaltime,
    ISNULL(SUM(CASE WHEN t.jobeditid = 3 AND t.jobpart = 'Add' THEN t.duration END),0)/60 AS PartAdd,
    ISNULL(SUM(CASE WHEN t.jobeditid = 3 AND t.jobpart = 'Update' THEN t.duration END),0)/60 AS PartUpdate,
    ISNULL(SUM(CASE WHEN t.jobeditid = 3 AND t.jobpart = 'Produce' THEN t.duration END),0)/60 AS PartProduce,
    ISNULL(SUM(CASE WHEN t.jobeditid = 3 AND t.jobpart = 'Amend' THEN t.duration END),0)/60 AS PartAmend,
    ISNULL(SUM(CASE WHEN t.jobeditid = 4 THEN t.duration END),0)/60 AS EditProducerError,
    ISNULL(SUM(CASE WHEN t.jobeditid = 8 THEN t.duration END),0)/60 AS EditVoiceError,
    ISNULL(SUM(CASE WHEN t.jobeditid = 1 THEN t.duration END),0)/60 AS EditClientError,
    ISNULL(SUM(CASE WHEN t.jobeditid = 2 THEN t.duration END),0)/60 AS EditEntryError,
    ISNULL(SUM(CASE WHEN t.jobeditid = 5 THEN t.duration END),0)/60 AS EditPronunciation,
    ISNULL(SUM(CASE WHEN t.jobeditid = 6 THEN t.duration END),0)/60 AS EditRemixRequest,
    ISNULL(SUM(CASE WHEN t.jobeditid = 7 THEN t.duration END),0)/60 AS EditRevoiceRequest
FROM Jobs j
JOIN clients c ON j.id = c.clientid
JOIN categories c2 ON c2.id = c.clientid
JOIN staff s ON j.id = s.producerid
LEFT JOIN (
     SELECT v.jobid, amount = SUM(amount)
     FROM JobsVoiceWork v
     GROUP BY v.jobid
) v ON v.jobid = j.id
JOIN (
     SELECT s.jobid, numberofscriptscompleted = COUNT(*)
     FROM Scripts s
     GROUP BY s.jobid
) s3 ON s3.jobid = j.id
LEFT JOIN Timelog t ON j.id = t.jobid
--GROUP BY ...

A: I'm not going to promise that this is better, it might well be worse - but its a different approach, that may help. Give it a whirl, and see if it is of any use.
First, I'm compiling a temporary table, summing duration for all values of jobs.id + timelog.jobeditid + if jobeditid is 3, timelog.jobpart:
SELECT j.id, tl.jobeditid, case when tl.jobeditid = 3 then tl.jobpart else '' end as [JobPart], (Sum(tl.duration)/60) as AdjTotalDuration
INTO #t
FROM Jobs J CROSS JOIN TimeLog tl
GROUP BY j.id, tl.jobeditid, case when tl.jobeditid = 3 then tl.jobpart else '' end;

Now i've simplified your query considerably, using this temporary table in a number of different ways; I've also moved most of the subqueries in the select clause into joined tables in the from clause:
SELECT various, other, native, columns, c.Client, cg.name as [Category], s.fullname as Producer,
  isnull(v.TotalAmount, 0) as voicecosts, (SELECT COUNT(*) FROM Scripts s WHERE s.jobid = j.id) AS numberofscriptscompleted,
  isnull((SELECT SUM(AdjTotalDuration) FROM #t WHERE jobid = j.id),0) AS TotalTime,
  t3a.AdjTotalDuration as PartAdd,
  t3u.AdjTotalDuration as PartUpdate,
  t3p.AdjTotalDuration as PartProduce,
  t3m.AdjTotalDuration as PartAmend,
  t4.AdjTotalDuration  as EditProducerError,
  t8.AdjTotalDuration  as EditVoiceError,
  t1.AdjTotalDuration  as EditClientError,
  t2.AdjTotalDuration  as EditEntryError,
  t5.AdjTotalDuration  as EditPronunciation,
  t6.AdjTotalDuration  as EditRemixRequest,
  t7.AdjTotalDuration  as EditRevoiceRequest
FROM Jobs j
  join clients c on j.ClientID = c.ID
  join categories cg on c.CategoryID = cg.ID
  join staff s on j.ProducerID = s.ID
  left join (select jobid, sum(amount) as TotalAmount from JobsVoiceWork group by jobid) v on j.id = v.jobid
  left join (select * from #t where id = j.id and jobeditid = 3 and jobpart = 'Add') t3a
  left join (select * from #t where id = j.id and jobeditid = 3 and jobpart = 'Update') t3u
  left join (select * from #t where id = j.id and jobeditid = 3 and jobpart = 'Produce') t3p
  left join (select * from #t where id = j.id and jobeditid = 3 and jobpart = 'Amend') t3m
  left join (select * from #t where id = j.id and jobeditid = 4) t4
  left join (select * from #t where id = j.id and jobeditid = 8) t8
  left join (select * from #t where id = j.id and jobeditid = 1) t1
  left join (select * from #t where id = j.id and jobeditid = 2) t2
  left join (select * from #t where id = j.id and jobeditid = 5) t5
  left join (select * from #t where id = j.id and jobeditid = 6) t6
  left join (select * from #t where id = j.id and jobeditid = 7) t7;

Does this improve it at all? Does it make it worse?
If it does improve it, please mark as answer.
Regards
John


text:
Q: Merge rows using awk I have a input file which has large data in below pattern. some part of data is shown below:
Data1
C
In;
CP
In;
D
In;
Q
Out;
Data2
CP
In;
D
In;
Q
Out;
Data3
CP
In;
CPN
In;
D
In;
QN
Out;

I want my output as
Data1(C,CP,D,Q)
In C;
In CP;
In D;
Out Q;
Data2 (CP,D,Q)
In CP;
In D;
Out Q;
Data3 (CP,CPN,D,QN)
In CP;
In CPN;
In D;
Out QN;

How can I do this.

A: $ cat tst.awk
BEGIN { FS="[[:space:];]+" }
{ rec[++nf] = $1 }
$1 == "Out" {
    printf "%s(", rec[1]
    for (i=2; i<=nf; i+=2) {
        printf "%s%s", (i>2 ? "," : ""), rec[i]
    }
    print ")"

    for (i=2; i<=nf; i+=2) {
        print rec[i+1], rec[i] ";"
    }

    delete rec
    nf = 0
}

$ awk -f tst.awk file
Data1(C,CP,D,Q)
In C;
In CP;
In D;
Out Q;
Data2(CP,D,Q)
In CP;
In D;
Out Q;
Data3(CP,CPN,D,QN)
In CP;
In CPN;
In D;
Out QN;

A: Try this...
awk 'BEGIN {RS="\n\n";} {for(i=1;i<=NF;i++) if ($i ~ "Data") print $i; else if ($i ~ "In;") print "In " $(i-1)";" ; else if ($i ~ "Out") print "Out " $(i-1)";"}'  a.txt

A: gawk '
    BEGIN { FS = "\n"; RS = ";\n" }
    function output() {
        print data ")"
        for (i=1; i<=c; i++) print inout[i]
        delete inout
        c=0
    }
    NF == 3 {
        if (NR > 1) output()
        data = $1 "(" $2
        inout[++c] = $3 " " $2 ";"
    }
    NF == 2 {
        data = data "," $1
        inout[++c] = $2 " " $1 ";"
    }
    END {output()}
' file

Data1 (C,CP,D,Q)
In C;
In CP;
In D;
Out Q;
Data2 (CP,D,Q)
In CP;
In D;
Out Q;
Data3 (CP,CPN,D,QN)
In CP;
In CPN;
In D;
Out QN;

A: Invoking GNU sed with extended regexp mode -E, we can print the ports and also their types as shown. For more info.
you can lookup the manpages (man sed)
or the Gnu sed manual (info sed)
$ sed -Ee '
  /\n/{
    /\n.*\n/{P;D;}
    p;$d;g
  }
  :loop
    $break;N
  /;(\n[^;]+){2}$/!bloop
  :reak
  h;s/;[^;]+$/;/
  s/\n[^\n;]+;//g
  s/\n/(/;y/\n/,/;s/$/)/p
  g;s/.*;\n//
  x;s/;[^;]+$/;/
  s/\n([^\n]+)(\n[^\n;]+)/\2 \1/g
  D
' file

Results:
Data1 (C,CP,D,Q)
In C;
In CP;
In D;
Out Q;
Data2 (CP,D,Q)
In CP;
In D;
Out Q;
Data3 (CP,CPN,D,QN)
In CP;
In CPN;
In D;
Out QN;


text:
Q: Cannot retrieve cookie Using FormsAuthentication, I am creating a FormsAuthenticationTicket, encrypting, adding this to a cookie using Response.Cookies.Add(authCookie).  I then do a redirect using Response.Redirect to the original page that was requested.  There is code in the Global.asax in the Application_AuthenticateRequest method that looks to retrieve the cookie - HttpCookie authCookie = Context.Request.Cookies[cookieName].  For some reason, however, when it hits the Global.asax code after the redirect is called, there are no cookies in the collection.  At this point, I am a bit stumped as to why it is losing the cookie from the collection.  Any thoughts as to why this would happen?  Right now, I am just working within localhost.
Login Page Code:
    string adPath = "LDAP://ldapserveraddress";

    LdapAuthentication adAuth = new LdapAuthentication(adPath);
    try
    {
        if (true == adAuth.IsAuthenticated("ES", txtUsername.Text, txtPassword.Text))
        {
            string groups = adAuth.GetGroups();

            //Create the ticket, and add the groups.
            bool isCookiePersistent = chkPersist.Checked;
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
                      txtUsername.Text, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups);

            //Encrypt the ticket.
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

            //Create a cookie, and then add the encrypted ticket to the cookie as data.
            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

            if (true == isCookiePersistent)
                authCookie.Expires = authTicket.Expiration;

            //Add the cookie to the outgoing cookies collection.
            Response.Cookies.Add(authCookie);

            string redirect = FormsAuthentication.GetRedirectUrl(txtUsername.Text, false);
            //You can redirect now.
            Response.Redirect(redirect,false);
        }
        else
        {
            errorLabel.Text = "Authentication did not succeed. Check user name and password.";
        }
    }
    catch (Exception ex)
    {
        errorLabel.Text = "Error authenticating. " + ex.Message;
    }
}

Global.asax Code (Application_AuthenticateRequest):
    string cookieName = FormsAuthentication.FormsCookieName;
    HttpCookie authCookie = Context.Request.Cookies[cookieName];

    if (null == authCookie)
    {
        //There is no authentication cookie.
        return;
    }
    FormsAuthenticationTicket authTicket = null;
    try
    {
        authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    }
    catch (Exception ex)
    {
        //Write the exception to the Event Log.
        return;
    }
    if (null == authTicket)
    {
        //Cookie failed to decrypt.
        return;
    }
    //When the ticket was created, the UserData property was assigned a
    //pipe-delimited string of group names.
    string[] groups = authTicket.UserData.Split(new char[] { '|' });
    //Create an Identity.
    GenericIdentity id = new GenericIdentity(authTicket.Name, "LdapAuthentication");
    //This principal flows throughout the request.
    GenericPrincipal principal = new GenericPrincipal(id, groups);
    Context.User = principal;
}`

A: I was able to resolve my issue by adjusting the data that was being stored in the userData of the FormsAuthenticationTicket.  It appears as though the amount of data that I was trying to insert exceeded a maximum.  Once I removed, everything works as expected.


text:
Q: What are the minimum system requirements for ubuntu 12.04 desktop?
Possible Duplicate:
What are the minimum system requirements for 12.04 LTS?

Sir,
    I am a LINUX beginner. I want to use ubuntu 12.04 desktop version on my system. So I want to know the minimum system and internet requirements. I have WINDOWS XP SP2, 1GB of RAM, 160GB HD and a 256kbps bandwidth dial up connection. Are these enough to use ubuntu 12.04 desktop?? Please let me know.

A: According to Ubuntu the requirements for Ubuntu Desktop are,

1. 700 MHz processor (about Intel Celeron or better)
2. 512 MiB RAM (system memory)
3. 5 GB of hard-drive space (or USB stick, memory card or external drive but see LiveCD for an alternative approach)
4. VGA capable of 1024x768 screen resolution
5. Either a CD/DVD drive or a USB port for the installer media
6. Internet access is helpful

For requirements for other types are give here.