text:
Q: Unused results from Entity Framework database call Any decent compiler should eliminate dead code, at least to a certain extent. However, I am curious how a compiler (specifically MSBuild) handles a situation like the following:
// let's assume LazyLoadingEnabled = false;
var users = db.Users.ToList();
// more code that never touches 'users'

Since LazyLoadingEnabled = false, will the compiled code:

*

*Eagerly load the results from the database call

*Make the call to the database without storing the results
or

*Never make the call to begin with?
I was cleaning up some old code at work and I found several cases of this occurring, so I'm curious as to whether we've been wasting resources or not.
It feels like the right answer is number 3, but I haven't found any solid evidence to back up my claims. Thank you for your help!

A: The answer is #1.
Not only will this execute the database query to select all the records from the Users table, but it will fetch all those records and construct entities for each of those records in the Users table.  Very expensive if you have many records.  Of course, the GC will eventually collect the wasted resources.
If you want to prove the above for yourself, just add the following line after you create your DbContext to log the SQL being executed:
db.Database.Log = s => Console.WriteLine(s);

BTW, the LazyLoadingEnabled setting has no effect on the observed behavior.  The LazyLoadingEnabled setting determines if navigational properties are eagerly loaded or not.  In this case, db.Users is not a navigational property, so it has no effect.


text:
Q: GeoFire alternative for static locations I want to query for locations near by the user from Firebase.
I stumbled over GeoFire and, while it does work, I am unsure if it is the best way to go. As far as I understand the main idea of GeoFire is that the locations are moving and updated to the user. In my case they are static, so it is probably a bit of an overkill.
Is there another solution to query near by locations from firebase, without using serverside logic and downloading a lot more data than needed?

A: You can use geoFire to get the locations of things around the user for one time. The way to do that is by
1- running a geoQuery and get all the keys around.
2- then removing all the listeners on the geoQuery.
To remove listeners after you get the locations, in android for example, call geoQuery.removeAllListeners(); in onGeoQueryReady() function

redpajama_set_name: RedPajamaStackExchange


text:
Q: 2 images in a row. Subcaption package give me errors, Subfig too , ¿solution? I have a big .tex that runs well without errors
I´m trying to put 2 images in a row,
I tried subcaption packaes and only adding to my code
\usepackage{subcaption} gives me this errors

and then readin this post
subcaption: `caption' package not loaded
I use this
\usepackage[caption=false]{subfig}

and.... ERROR too.
so,... how can I put 2 images in a row?


text:
Q: Is there any way to specify "any character but [aeiou]" in a PHP regular expression? I am developing a C# Web Service whose responses are always collections of things. Since I am too lazy and do not want to explicitly define collections of things, I implemented a generic class representing a collection of things that can be serialized using XML.
Now, ASP.NET usually gives horrible names to generics, such as CollectionOfOrdenPago (in Spanish, "orden de pago" means "payment order") or PageOfLineaDetalleReporte (in Spanish, "línea de detalle de reporte" means "report detail line"). I wanted to give my collections more sensible names like OrdenesPago ("payment orders") or LineasDetalleReporte ("report detail lines"), so I defined the following method:
internal static string Pluralize(string input)
{
    int i = 0;
    while (++i < input.Length)
        if (!char.IsLower(input[i]))
            break;

    StringBuilder builder = new StringBuilder(input);
    if ("aeiou".IndexOf(input[i - 1]) == -1)
        builder.Insert(i++, 'e');
    builder.Insert(i, 's');

    return builder.ToString();
}

This Web Service is consumed by a PHP website, which I am developing as well. Since pluralizing a noun does not seem to be a good reason to call the C# Web Service, I reimplemented the Pluralize function in PHP:
function pluralize($element) {
    return preg_replace_callback('/^([A-Z][a-z]*)([A-Z]|$)/', function($args) {
        // If the first word ends in consonant, append "e" first. After that, append "s".
        return preg_replace('/([B-DF-HJ-NP-TV-Z])$/i', '\1e', $args[1]) . "s{$args[2]}";
    }, $element);
}

But I am still not happy. The term [B-DF-HJ-NP-TV-Z] is ugly. As in the C# method, I would like to specify "a character not in [aeiou]" as a term. Is that possible?

A: Sure. A caret (^) negates a character class:
/[^aeiou]/i

A: First, your string needs to be in Normalization Form D.  Otherwise you will miss things like María, Ángeles, Argüelles,  and Bogotá.  Here's an example in Perl:
#!/usr/bin/env perl
use utf8;
use strict;
use warnings;
use Unicode::Normalize qw(NFD NFC);
binmode(STDOUT, ":utf8") || die;
my @names = qw(María Ángeles Argüelles Bogotá cáñamo);
for my $orig ("@names", @names) {
    my $nfd = NFD($orig);
    $nfd =~ s/( (?: (?! [aeiou] ) (?= \pL ) \X ) +)/<$1>/xig;
    print NFC($nfd), "\n";
}

When run, that prints out this:
<M>a<r>ía Á<ng>e<l>e<s> A<rg>üe<ll>e<s> <B>o<g>o<t>á <c>á<ñ>a<m>o
<M>a<r>ía
Á<ng>e<l>e<s>
A<rg>üe<ll>e<s>
<B>o<g>o<t>á
<c>á<ñ>a<m>o

I don't how to pull in the needed NFD function in PHP, but the  rest should be completely transferable once you figure that part out.

A: Use a negated character class
[^AEIOU]

instead of [B-DF-HJ-NP-TV-Z].
N.B. as per @fireeyedboy's comment, this regex matches non-alphabetic characters as well.


text:
Q: Magento2 migration problem I have problem when migration data from magento1 to magento2.
It show Record structure does not contain field "is_configurable":

However, I checked magento1 data and map-eav.xml, map-customer.xml and add ignore:
<ignore>
            <field>eav_attribute.is_configurable</field>
        </ignore>

File config:
    <?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xs:noNamespaceSchemaLocation="../../config.xsd">
    <steps mode="settings">
        <step title="Settings Step">
            <integrity>Migration\Step\Settings\Integrity</integrity>
            <data>Migration\Step\Settings\Data</data>
        </step>
        <step title="Stores Step">
            <integrity>Migration\Step\Stores\Integrity</integrity>
            <data>Migration\Step\Stores\Data</data>
            <volume>Migration\Step\Stores\Volume</volume>
        </step>
    </steps>
    <steps mode="data">
        <step title="Data Integrity Step">
            <integrity>Migration\Step\DataIntegrity\Integrity</integrity>
        </step>
        <step title="EAV Step">
            <integrity>Migration\Step\Eav\Integrity</integrity>
            <data>Migration\Step\Eav\Data</data>
            <volume>Migration\Step\Eav\Volume</volume>
        </step>
        <step title="Customer Attributes Step">
            <integrity>Migration\Step\Customer\Integrity</integrity>
            <data>Migration\Step\Customer\Data</data>
            <volume>Migration\Step\Customer\Volume</volume>
        </step>
        <step title="Map Step">
            <integrity>Migration\Step\Map\Integrity</integrity>
            <data>Migration\Step\Map\Data</data>
            <volume>Migration\Step\Map\Volume</volume>
        </step>
        <step title="Url Rewrite Step">
            <integrity>Migration\Step\UrlRewrite\Version191to2000</integrity>
            <data>Migration\Step\UrlRewrite\Version191to2000</data>
            <volume>Migration\Step\UrlRewrite\Version191to2000</volume>
        </step>
        <step title="Log Step">
            <integrity>Migration\Step\Log\Integrity</integrity>
            <data>Migration\Step\Log\Data</data>
            <volume>Migration\Step\Log\Volume</volume>
        </step>
        <step title="Ratings Step">
            <integrity>Migration\Step\Ratings\Integrity</integrity>
            <data>Migration\Step\Ratings\Data</data>
            <volume>Migration\Step\Ratings\Volume</volume>
        </step>
        <step title="ConfigurablePrices step">
            <integrity>Migration\Step\ConfigurablePrices\Integrity</integrity>
            <data>Migration\Step\ConfigurablePrices\Data</data>
            <volume>Migration\Step\ConfigurablePrices\Volume</volume>
        </step>
        <step title="OrderGrids Step">
            <integrity>Migration\Step\OrderGrids\Integrity</integrity>
            <data>Migration\Step\OrderGrids\Data</data>
            <volume>Migration\Step\OrderGrids\Volume</volume>
        </step>
        <step title="Tier Price Step">
            <integrity>Migration\Step\TierPrice\Integrity</integrity>
            <data>Migration\Step\TierPrice\Data</data>
            <volume>Migration\Step\TierPrice\Volume</volume>
        </step>
        <step title="SalesIncrement Step">
            <integrity>Migration\Step\SalesIncrement\Integrity</integrity>
            <data>Migration\Step\SalesIncrement\Data</data>
            <volume>Migration\Step\SalesIncrement\Volume</volume>
        </step>
        <step title="PostProcessing Step">
            <data>Migration\Step\PostProcessing\Data</data>
        </step>
    </steps>
    <steps mode="delta">
        <step title="Customer Attributes Step">
            <delta>Migration\Step\Customer\Delta</delta>
            <volume>Migration\Step\Customer\Volume</volume>
        </step>
        <step title="Map Step">
            <delta>Migration\Step\Map\Delta</delta>
            <volume>Migration\Step\Map\Volume</volume>
        </step>
        <step title="Log Step">
            <delta>Migration\Step\Log\Delta</delta>
            <volume>Migration\Step\Log\Volume</volume>
        </step>
        <step title="OrderGrids Step">
            <delta>Migration\Step\OrderGrids\Delta</delta>
            <volume>Migration\Step\OrderGrids\Volume</volume>
        </step>
        <step title="SalesIncrement Step">
            <delta>Migration\Step\SalesIncrement\Delta</delta>
            <volume>Migration\Step\SalesIncrement\Volume</volume>
        </step>
    </steps>
    <source>
        <database host="localhost" name="xxxxxx_m1" user="root" password="xxxxxx"/>
    </source>
    <destination>
        <database host="localhost" name="xxxxxx" user="root" password="xxxxx"/>
    </destination>
    <options>
        <map_file>etc/opensource-to-opensource/1.9.2.4/map.xml</map_file>
        <eav_map_file>etc/opensource-to-opensource/map-eav.xml</eav_map_file>
        <eav_document_groups_file>etc/opensource-to-opensource/eav-document-groups.xml</eav_document_groups_file>
        <eav_attribute_groups_file>etc/opensource-to-opensource/eav-attribute-groups.xml</eav_attribute_groups_file>
        <log_map_file>etc/opensource-to-opensource/map-log.xml</log_map_file>
        <log_document_groups_file>etc/opensource-to-opensource/log-document-groups.xml</log_document_groups_file>
        <settings_map_file>etc/opensource-to-opensource/settings.xml</settings_map_file>
        <customer_map_file>etc/opensource-to-opensource/map-customer.xml</customer_map_file>
        <customer_document_groups_file>etc/opensource-to-opensource/customer-document-groups.xml</customer_document_groups_file>
        <customer_attribute_groups_file>etc/opensource-to-opensource/customer-attribute-groups.xml</customer_attribute_groups_file>
        <delta_document_groups_file>etc/opensource-to-opensource/deltalog.xml</delta_document_groups_file>
        <order_grids_document_groups_file>etc/opensource-to-opensource/order-grids-document-groups.xml</order_grids_document_groups_file>
        <map_document_groups>etc/opensource-to-opensource/map-document-groups.xml</map_document_groups>
        <class_map>etc/opensource-to-opensource/class-map.xml</class_map>
        <tier_price_map_file>etc/opensource-to-opensource/map-tier-price.xml</tier_price_map_file>
        <stores_map_file>etc/opensource-to-opensource/map-stores.xml</stores_map_file>
        <!--
        In case bulk_size=0 it will be auto-detected for every document.
        -->
        <bulk_size>0</bulk_size>
        <!--
        Set direct_document_copy = 1 for better performance.
        NOTE: 'source' and 'destination' databases MUST be placed on the same MySQL instance
        and 'destination' user MUST be granted with 'SELECT' permissions on 'source' database
         -->
        <direct_document_copy>0</direct_document_copy>
        <source_prefix />
        <dest_prefix />
        <auto_resolve_urlrewrite_duplicates>0</auto_resolve_urlrewrite_duplicates>
        <log_file>migration.log</log_file>
        <progress_bar_format>%percent%% [%bar%] Remaining Time: %remaining%</progress_bar_format>
        <upgrade_customer_password_hash>1</upgrade_customer_password_hash>
        <edition_migrate>opensource-to-opensource</edition_migrate>
        <edition_number>1.9.2.4</edition_number>
        <init_statements_source>SET NAMES utf8;</init_statements_source>
        <init_statements_destination>SET NAMES utf8;</init_statements_destination>
        <crypt_key>ee8c2f57c8e64cc641ed58cccf7b31eb</crypt_key>
    </options>
</config>

But it isnt help. can you please help me?


text:
Q: Java8 using enum values in interface's default methods I'm exploring possibilities of static and default methods introduced in java 8.
I've an interface that has 2 default methods that do construct a command, that I run on server through ssh to do some simple tasks remotely. Moving mouse requires 2 arguments: x and y position of the mouse.
public interface Robot {

    default String moveMouse(int x, int y) {
        return constructCmd("java -jar move_mouse.jar " + x + " " + y);
    }

    default String clickLeft() {
        return  constructCmd("java -jar click_left.jar");
    }

    static String constructCmd(String cmd) {
        return "export DISPLAY=:1.0\n" +
                "cd Desktop\n" +
                cmd;
    }
}

I've multiple enums with values preset, I could potently combine all enums into one and not use interface what so ever, however that enum would contain hundreds or thousands of values and I want to keep it somewhat organised, so I've split evertying in multiple enums.
I want all enums to share same methods so I figured I'll give default methods in an interface a shot.
public enum Field implements Robot {

    AGE_FIELD(778, 232),

    NAME_FIELD(662, 280);

    public int x;
    public int y;

    Field(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

So I can get String commands by:
Field.AGE_FIELD.clickLeft();
Field.AGE_FIELD.moveMouse(Field.AGE_FIELD.x, Field.AGE_FIELD.y);

However moveMouse looks really bad to me and I think it should be somehow possible to use enum's values by default.
Anyone has a a nice solution for such problem?

A: The problem is your architecture. On the one hand, you have a layer that actually executes the mouse-movement (represented by your Robot interface). Now, you need a layer that produces mouse-movement and sends it to a Robot to execute this mouse-movement. Let's call the interface defining this layer MouseTarget (fits your example nicely):
public interface MouseTarget {
    int getTargetX();
    int getTargetY();

    default void moveMouseHere(Robot robot) {
        robot.moveMouse(this.getTargetX(), this.getTargetY());
    }
}

This interface represents one mouse-movement to one target. As you see the moveMouseHere(Robot robot) method expects a Robot to send the movement to (which does the actual work). Now, all what is left is to adapt your Fields enum:
public enum Fields implements MouseTarget {

    AGE_FIELD(778, 232), NAME_FIELD(662, 280);

    public int targetX;
    public int targetY;

    Fields(int targetX, int targetY) {
        this.targetX = targetX;
        this.targetY = targetY;
    }

    @Override
    public int getTargetX() {
        return targetX;
    }

    @Override
    public int getTargetY() {
        return targetY;
    }
}

A: As you may want to have several implementations of Robot, I would clearly not proceed as you do, I would rather provide a Robot instance to the methods of your enum instead of implementing the interface Robot, it would then be much more flexible and easier to test.
The enum Field
public enum Field {

    ...

    public String moveMouse(Robot robot) {
        return robot.moveMouse(x, y);
    }

    public String clickLeft(Robot robot) {
        return robot.clickLeft();
    }
}

Even if it is not strictly the Strategy pattern, it is globably the same approach.


text:
Q: Var does not update I want to save the url of the current tab but when I execute the code it doesn't save the url in the variable.
/* global var */
var currentURL;

function getCurrentURL() {
  chrome.tabs.query({ active: true, currentWindow: true}, function(tabs) {
    var tab = tabs[0];
    currentURL = tab.url;
  });
}

function addChannel() {

}

document.addEventListener('DOMContentLoaded', function () {
  getCurrentURL();
  console.log(currentURL);
  if (currentURL !== "https://www.youtube.com/channel/*") {
    document.getElementById('addChannel').remove();
  }
  else {
    document.getElementById('addChannel').addEventListener('click',
  function() {addChannel();});
  }
})


text:
Q: For every $x,y,z \in[2,7] $ and $x+y+z=12$, prove that $x^3+y^3+z^3\leq 316+x^2+y^2+z^2$ I have tried to use the majorization inequality to approach this question.
I have both $x^3$ and $x^2$ is convex in the region $[2,7]$ since there second derivatives are positive on this interval.
After I rewrite the equation, I have $(x^3-x^2)-(y^3-y^2)-(z^3-z^2)\leq 316$
So, I wonder if I can first say something about $g(x)=x^3-x^2$ by the majorization inequality then generalize to y and z cases.
I would appreciate if someone can help.

A: Solution with use of the majorization inequality.
Wlog $x\geq y\geq z$. Then we have
\begin{align}x&\leq 7\\
x+y&\leq 10\\
x+y+z&=12
\end{align}
so $(x,y,z) \preceq (7,3,2)$. Since $g$ in convex on $[2,7]$ we have  $$g(x)+g(y)+g(z)\leq g(7)+g(3)+g(2) = 316$$

A: HINT( for another way).
For $(x,y,z)=(2,3,7)$ (and any of the six permutations) we have exactly $x^3+y^3+z^3= 316+x^2+y^2+z^2$.
Fixing $z=7$ we have to prove $x^3+y^3\le 22 + x^2+y^2$ in which the equality is reached at $(x,y)=(2,3)$ so we must take $z\lt7$. An easy calculation more and we are done.


text:
Q: How to use Button with Behavior in Silverlight Legend? I'm trying to use a button with behavior in the MapLayerTemplate of an Esri Silverlight SDK 2.1 legend.
When I click the button and then drag on the map, the map pans instead of showing a selection rectangle.
The behavior code is pulled from this sample, while the legend is from this sample.
If I put the same xaml code within the layoutroot, it works as expected - I see a selection rectangle and the selection completes successfully.
<esri:Legend x:Name="MyLegend" Map="{Binding ElementName=MyMap}"
            LayerIDs="ProjectPolys,AssetPoints,AssetLines,BaseLayers,WaterInfrastructure,SewerInfrastructure"
            LayerItemsMode="Tree"
            ShowOnlyVisibleLayers="False"
            Refreshed="Legend_Refreshed">
    <esri:Legend.MapLayerTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
            <CheckBox Content="{Binding Label}"
                    IsChecked="{Binding IsEnabled, Mode=TwoWay}"
                    IsEnabled="{Binding IsInScaleRange}">
                </CheckBox>
                <Button Content="Select">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="Click">
                            <esriBehaviors:SpatialQueryAction
                                DrawMode="Rectangle"
                                LayerID="MyGraphicsLayer"
                                Url="http://hq-gis-01/ArcGIS/rest/services/WaterInfrastructure2/MapServer/15"
                                Symbol="{StaticResource GraphicsLayerFillSymbol}"
                                TargetName="MyMap" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </Button>
                <Slider Maximum="1" Value="{Binding Layer.Opacity, Mode=TwoWay}" Width="50" />
            </StackPanel>
        </DataTemplate>
    </esri:Legend.MapLayerTemplate>
    <esri:Legend.LayerTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Label}"
            IsChecked="{Binding IsEnabled, Mode=TwoWay}"
            IsEnabled="{Binding IsInScaleRange}" >
            </CheckBox>
        </DataTemplate>
    </esri:Legend.LayerTemplate>
</esri:Legend>

Update:
Following Seth's suggestion I tried wiring the trigger in the code-behind.  I get the same results.  The code behind approach fails for the button in the datatemplate, but works for the one on a stackpanel sibling to the map.
private void Assign_Behavior_Click(object sender, RoutedEventArgs e)
{
    var button = sender as Button;
    ESRI.ArcGIS.Client.Actions.SpatialQueryAction sqa = new ESRI.ArcGIS.Client.Actions.SpatialQueryAction();
    sqa.DrawMode = DrawMode.Rectangle;
    sqa.LayerID = "MyGraphicsLayer";
    sqa.Url = @"http://hq-gis-01/ArcGIS/rest/services/WaterInfrastructure2/MapServer/15";
    sqa.Symbol = LayoutRoot.Resources["GraphicsLayerFillSymbol"] as Symbol;
    sqa.TargetName = "MyMap";

    var et = new System.Windows.Interactivity.EventTrigger("Click");
    et.Actions.Add(sqa);
    var triggerColl = System.Windows.Interactivity.Interaction.GetTriggers(button);
    triggerColl.Add(et);
}

I'm beginning to think this is not an Esri issue - I can't find an example anywhere showing how to attach trigger actions from buttons in a datatemplate.

A: I was able to replicate this issue, it may be a bug with ESRI's API.  You can put a Click event in the Select button to hit the code-behind and then use this technique to call the action:
http://forums.arcgis.com/threads/3696-Measure-Action-in-Code?p=11969&viewfull=1#post11969
As Dominique states, it's probably not recommended to use Actions in the code-behind, however in this case, I don't see any alternative.


text:
Q: Ruby Newbie strftime Time.Now I have the following written in ruby
t = Time.now
    t.strftime("%Y-%d-%m")

SCHEDULER.every '1m', :first_in => 0 do |job|
  send_event('gmail_gh', {current: gmail.inbox.count(:after => Date.parse(t)), older: gmail.inbox.count})

But i get this error
scheduler caught exception:
can't convert Time into String
/var/dashing/cdmdash/jobs/gmail_gh.rb:21:in `parse'
/var/dashing/cdmdash/jobs/gmail_gh.rb:21:in `block in <top (required)>'
/usr/local/rvm/gems/ruby-1.9.3-p327/gems/rufus-scheduler-2.0.17/lib/rufus/sc/jobs.rb:231:in `call'
/usr/local/rvm/gems/ruby-1.9.3-p327/gems/rufus-scheduler-2.0.17/lib/rufus/sc/jobs.rb:231:in `trigger_block'
/usr/local/rvm/gems/ruby-1.9.3-p327/gems/rufus-scheduler-2.0.17/lib/rufus/sc/jobs.rb:191:in `block in trigger'
/usr/local/rvm/gems/ruby-1.9.3-p327/gems/rufus-scheduler-2.0.17/lib/rufus/sc/scheduler.rb:416:in `call'
/usr/local/rvm/gems/ruby-1.9.3-p327/gems/rufus-scheduler-2.0.17/lib/rufus/sc/scheduler.rb:416:in `block in trigger_job'

I think it has something to do with the t variable and it not being a truing, I am new to Ruby so I am abit stuck

A: If you look at the gem documentation, you will see that the :after and :before params take in a date in the format of YYYY-MM-DD.
From the gem Readme:
gmail.inbox.count(:after => Date.parse("2010-02-20"), :before => Date.parse("2010-03-20"))
gmail.inbox.count(:on => Date.parse("2010-04-15"))

Your code is passing in YYYY-DD-MM which is likely causing the error.
Edit
When you call strftime on a datetime object, it doesn't modify the object - only returns the string notation based on format you give.
As a result, the Date.parse(t) is still getting Time.now was a parameter.
Try this:
t = Time.now.strftime("%Y-%m-%d")
Date.parse(t)


text:
Q: Do we need common tags across the different sites? It seems that some tags like "US" or should it be "USA" are needed for lots of sites, there are lot of other examples.
This may be impossible to sort out for the old sites, but I think we can do something simple for the new sites.
What if the tag surjection list on new sites that you get when to go to tag a question contained all the tags that are used on more than one other site with a usage of 0 – would this be enough to guild people to make the same tag chooses?

A: This could lead very far. It would be nice for the case you brought up, US vs USA. It even would be nice for sites with overlapping areas of interest. Why should sql-server-2005 not be tagged the same on SO, SF, SU, WebApps, and site alike?
Yet CSI on a crime or TV site means something totally different from CSI on a site about horses, java is obvious, and their synonym lists would be hardly overlapping. Thus a tag usage on other sites could be very misleading.
So this would probably end in a system to decide on neighborhood of sites and therefore probability of same semantic meaning of overlapping tags.

A: Tagging conventions should be up to the individual communities. Tagging is ad hoc, by design. Something you design for everyone to use, might not be what another site needs.
Take math.SE, for instance. They are talking about using an entirely different tagging convention (employing standard prefixes in their tags). If we imposed our "common tags" on them, their tagging methodology would be full of unnecessary exceptions imposed by the system.
Area 51 is designed to create sites with overlapping groups of experience between sites, so no one site is created in isolation. That group of experienced users would most likely carry over any de facto standards used in other systems.


text:
Q: How do you reference a Macro Enabled Excel workbook and run VBA code in Python? I have built an optimization model in Excel which I am trying to loop through for several observations and store the optimal outputs for each. I have a dataset that I am trying to read into python and then have a loop put in the input values to the Excel sheet, run solver/VBA code, and then return the output for each observation.
Below is the dataset that I have with my input values, followed by the current code that I am trying to use. I current have this code below, which I got from this post https://stackoverflow.com/a/19743828/11046221, as it appears to have gotten me the furthest. However I tried to find how to reference the "Module" name and was not able to get it to work, so I saw further in the post to reference the sheet name, which did not work either, both resulting in the error message:
"Cannot run the macro 'P:/optimization_model_reference.xlsm!Excel_Model.run_solver_v2'. The macro may not be available in this workbook or all macros may be disabled."
obs var1    var2    var3
0   27  80  100 125
1   35  56  93  128
2   42  48  89  108
3   53  70  91  109
4   59  73  86  89

if os.path.exists("P:/optimization_model_reference.xlsm"):
    xl=win32.Dispatch("Excel.Application")
    xl.Workbooks.Open(os.path.abspath('P:/optimization_model_reference.xlsm'), ReadOnly=1)
    xl.Application.Run("P:/optimization_model_reference.xlsm!Excel_Model.run_solver_v2")  #This I have in the format ("file_name!sheet_name.macro_name")
    xl.Application.Quit()
    del xl


text:
Q: VB.NET LINQ Group By Multiple Columns I have the following LINQ code which has a syntax error and i've no idea how to fix it
         Dim query =
        From row In mainDatatable.AsEnumerable

    'the syntax Error is in the following line
      Group row By new  { row.Field(Of Double)("cprice") , row.Field(Of Integer)("ccategory")}
Into ProductGroups
    '**************************

                Dim grpNumber = 1
                For Each grp In query
                    For Each row In grp.ProductGroups
                        row.SetField("gnum", grpNumber)
                    Next
                    grpNumber += 1
                Next

            End Sub

so what am i doing wrong?
Here is how the table looks like and i want to group by the columns cprice and ccategory
+---------------+---------------+-----------+------+
| Product Name  | cprice        | ccategory | gnum |
+---------------+---------------+-----------+------+
| Skirt Red     |            99 |         1 |      |
| Jeans Blue    |            49 |         2 |      |
| Jeans Black   |            49 |         2 |      |
| Skirt Blue    |            99 |         1 |      |
| T-shirt White |            20 |         2 |      |
| T-shirt Green |            20 |         2 |      |
| Jeans Grey    |            49 |         2 |      |
+---------------+---------------+-----------+------+

A: Try this:
new with { Key.Price = row.Field(Of Double)("cprice") ,
           Key.Category = row.Field(Of Integer)("ccategory")

Uisng the Key modifier, this creates an anonymous type that implements equality based on equality of its members.


text:
Q: Linq 3 value choices in column I am having a bit trouble with understanding Linq.
 with the following linq in vb.net:
    Dim qeurySearch = (From P In DB.table1
      Where P.number = searchInput And P.valueCol = 2 OrElse
      P.valueCol= 3 OrElse P.valueCol = 4
      Select P.number , P.valueCol
      ).ToList

What i get from this is 4 records... all of them of which are not the searchInput.
So lets say searchinput is "102" and the valueCol which is in the same table has a value of "1". Then what i expect is that it won't work, it would give me no records. But thats wrong.
What happens is that it completely ignores my searchInput in the WHERE clause and gives the P.valueCol = 4  records. As if that one is the only WHERE clause.
Does anyone know how I can filter my query in the right way ? By giving the P.Number and that this column can only have a P.valueCol of 1,2 or 3.

A: I suspect this is a precedence issue. I don't know the VB precedence rules, but I suspect your query is being treated as:
Where P.number = (searchInput And P.valueCol = 2) OrElse
                 P.valueCol= 3 OrElse P.valueCol = 4

I suggest you change the code to:
Where P.number = searchInput AndAlso (P.valueCol = 2 OrElse
                                      P.valueCol = 3 OrElse
                                      P.valueCol = 4)

A: Try including some brackets:
If you think of your query in terms of words you might say:

Where number is equal to searchinput and valuecol is one of 2,3 or 4

This gives a good idea of where your brackets should be:
Dim qeurySearch = (From P In DB.table1
  Where P.number = searchInput
  And (P.valueCol = 2 OrElse P.valueCol= 3 OrElse P.valueCol = 4)
  Select P.number , P.valueCol
  ).ToList

In more depth this comes down to something called logical operator precedence. This is the order in which the logical operators in your query are considered. A fairly normal standard for this is that NOT is considered first, followed by AND and then OR. For example see the MSDN page on the topic for MS SQL.
In your case this means that the condition containing the AND is checked first:
P.number = searchInput And P.valueCol = 2
before the following OR sections are checked.


text:
Q: User regex in Jmeter While loop I have Jmeter while loop having regular expression extractor as post processor
Regular expression variable reference name is : CFM
It extracts: (<\S+\s\S+)(\s+)(.*?hv_saw_)(.*?label1)("\s+\w+=")(Current Fiscal YTD)(.*?>)
$4$ value is .*?label1
$6$  value is Current Fiscal YTD

Now I want to use $4 and $6 template in while loop but not able to do so..
Here is what i am doing:
While loop :${__javaScript((${CFY_g4}.match(/.*?label1/) != "$4",))}
I want unless my $4 template .match or .contains while loop continues to run

A: Wooohuuu!!!
I researched further and came across Mozilla developers website that answers my questionrealted to fidning start and end of my variables. here is what i did:
My Javascript code inside while loop for $4 and $6 template:
${__javaScript(! "${CFY_g4}".endsWith('label1') || (! "${CFY_g6}".match('Current Fiscal YTD')) )}


text:
Q: Is it possible to group cups print jobs so they will not be interrupted by other users print jobs? I am working on printing very large images on a custom type printer, in linux, using cups.
Because of memory limitations, the images are broken in chunks. Each chunk is sent to printer using cupsPrintFile() function - that sets, among othe options, feed and cut to be done only on the last image. The intent is to have all the smaller images sent to create the original large image.
My question is, how to group the print jobs to avoid other users printing to the same printer to send jobs in-between the chunks of the same image ?
(I am aware that printer protocols are doing the exact opposite, optimizing resources they allow different jobs to be processed out of sequence... But in this case, that would be very bad).
(An alternative is to use the cupsPrintFiles that sends all required files as a single job - the problem is hat they all have the same print options, and I cannot figure out how I could set a different page size for the last file, which will be smaller).
If there are any cups commands that allow print jobs to be grouped would be great, because I can try to find the equivalent c++ commands or just try to run the terminal commands from a shell inside the code...

A: I used the 2dir script to create a virtual printer, then combined the resulting print jobs.


text:
Q: How do I vertically align the content in these grid cells in a bootstrap grid? I've got a basic bootstrap grid with two rows and I'm trying to align the content vertically in these cells but no matter what I try the content doesn't seem to budge..
I've tried adding various classes to the rows and container div, i.e. align-middle, align-items-center but nothing seems to do anything.

< BACK TO HOMEPAGE

          Preview text

            Preview text

            Preview text

            Preview text

            Preview text

            6

            7

            <button type="button" class="btn btn-dark">Play Video</button>

            1

            Preview text

            Preview text

            Colour

            Preview text

A: Change

To

Here's a JSFiddle with that change. I've added a border to each div, so you can see that it is centered vertically. http://jsfiddle.net/bqfa74y0/
If you want the lower row to be centered vertically, just add align-items-center to the class of the row.

I would also strongly recommend that you change:

< BACK TO HOMEPAGE

To

< BACK TO HOMEPAGE

Because < has a special meaning in HTML (it's for starting/ending tags), so using it as text could have unexpected consequences.

A: Did you mean this?

 .menu-bar{
  length: 200px;
  width: 100%
}

 .col{
  display: inline-block;
  width: 11%;
  margin-left: auto;
margin-right: auto;
  text-align: center;
  height: 50px;
}

 BACK TO HOMEPAGE

          Preview text

            Preview text

            Preview text

            Preview text

            Preview text

            6

            7

            <button type="button" class="btn btn-dark">Play Video</button>

            1

            Preview text

            Preview text

            Colour

            Preview text


text:
Q: Is it possible to open a terminal from an ongoing subprocess in Python? I am using the subprocess module in Python to navigate and run commands on behalf of a user.
I now want to be able to open the terminal session so that the user can enter their own commands.
I have used Tmux and Screen to create a shared terminal session and I have had no luck.
When initiating the shared terminal session with Tmux through the subprocess module I get the error:
"Open terminal failed: not a terminal"
and with Screen, I get the error:
"Must be connected to a terminal"
Any help would be greatly appreciated.


text:
Q: asp.net viewstate encryption I have a few questions about when and how viewstate is encrypted in asp.net 3.5.
For instance, if I have a machinekey entry in my web.config like:

            decryptionKey="AutoGenerate,IsolateApps"
            validation="AES"
            decryption="Auto" />
Is viewstate encrypted at this point? Or do I need to specify the viewStateEncryptionMode in the page section also?
Also, is it possible to encrypt a formsauthentication cookie, but not encrypt viewstate at the same time?
Thanks for any help.

A: The controls on the page can request that encryption be used for the ViewState, but even this request can be overridden by the page setting.
The ViewStateEncryptionMode enumeration has three values: Auto, Always, and Never. The default value is Auto.
ViewStateEncryptionMode.Auto
In this mode, ASP.NET will encrypt the ViewState for a page if any control on the page requests it. Note that this means all of the ViewState is encrypted, not just the ViewState for the control that requests it. A large part of the performance cost associated with encryption is in the overhead. So encrypting the whole ViewState is faster than doing separate encryption operations if more than one control makes the request.
ViewStateEncryptionMode.Never
As you would expect, in this mode ASP.NET will not encrypt the ViewState, even if the application is set for encryption and controls on the page have requested it. If you know that no data involved in the page needs to be encrypted, then it may be safe to set the mode to Never. However, at this point it is rare for the documentation about a control to disclose what is being saved in ViewState, so you will want to be careful if there is a chance that sensitive data could be exposed.
ViewStateEncryptionMode.Always
In this mode, ASP.NET does not wait for a control in the page to request encryption. ViewState is always encrypted. When working with sensitive data, it is a good practice to utilize encryption.
Source: http://msdn.microsoft.com/en-us/library/aa479501.aspx


text:
Q: Go Concurrency Pattern- will this leave hanging goroutines? In Rob Pike's Google IO talk on Go Concurrency Patterns, he presented this code as an example of how to pick the fastest responder from a number of replica servers:
func First(query string, replicas ...Search) Result {
    c := make(chan Result)
    searchReplica := func(i int) { c <- replicas[i](query) }
    for i := range replicas {
        go searchReplica(i)
    }
    return <-c
}

Question: Won't this leave N-1 of the replica goroutines blocking on a channel write?
In the discussion after the talk, one of the audience members seems to be asking this question, but got kind of a handy-wavy response.
I'd be inclined to change the 3rd line to something like this:
searchReplica := func(i int) {
   select {
      case c <- replicas[i](query):
      default: // non-blocking write
 }
}

A: You are correct. But that doesn't fit on a single slide. He was talking about concurrency patterns, not necessarily the code to do it.
Of course, I still wouldn't have put that code on a slide...


text:
Q: how to save/fetch non English characters into core data? I have successfully added and fetched some data using core data. my entity attribute has the following scheme: productName, price and quantity.
price and quantity are displayed correctly in the console. On the other hand, product name is written in Arabic and therefore it is displayed in weird characters like: "\U062c\U064a\U0628 \U0627\U0644\U062a\U0627\U062c\U0631";
save to core data code:
   @IBAction func submitOrderButton(_ sender: UIButton) {

    let newItem =  NSEntityDescription.insertNewObject(forEntityName: "OrderDetail", into: context)
    newItem.setValue(String(self.productName.text!), forKey: "productName")
    newItem.setValue(Int(self.productPrice.text!), forKey: "price")
    newItem.setValue(self.orderQuantity, forKey: "quantity")

    do{
        try context.save()
    }
    catch{
        // display in a uialert message
        print("error has occured")
    }
    print("\(orderQuantity) items of this product")

}

fetch from core data code:
    func fetchOrderDetails(){

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context =  appDelegate.persistentContainer.viewContext
    let fetchedOrders = NSFetchRequest<NSFetchRequestResult>(entityName: "OrderDetail")
    fetchedOrders.returnsObjectsAsFaults = false

    do{
        let result = try context.fetch(fetchedOrders)
        if result.count > 0{
            print()
        }
    }
    catch{

    }
}

output in console:
<OrderDetail: 0x604000480af0> (entity: OrderDetail; id: 0xd000000000040000 <x-coredata://109134CB-DCF5-45D8-9298-E8B43C51E5DA/OrderDetail/p1> ; data: {
price = 3;
productName = "\U062c\U064a\U0628 \U0627\U0644\U062a\U0627\U062c\U0631";
quantity = 2;
  })

Thanks!
UPDATE
All I did was access the attributes and then I could either assign it to a label or print it in the console. Both worked.
Below is the code I added:
        do{
        let result = try context.fetch(fetchedOrders)
        if result.count > 0{
          // added code
            var tempProd = result[0] as! NSManagedObject
            productName.text = "\(tempProd.value(forKey: "productName"))"

            for data in result as! [NSManagedObject]{
                print(data.value(forKey: "productName") as! String)

            }
           // end of added code
        }
    }


text:
Q: Sync only some folders from My Documents to OneDrive I have the default OneDrive with 5GB, and I sync My Documents folder to it.
The issue occurs when I get too much data in My Documents and I want to deselect some folders from syncing. But as I see, these deselected folders simply disappear from My Documents and are nowhere to be found in my computer. I also noticed that OneDrive actually cancelled the default My Documents path and created one of its own which is incredibly frustrating.
Is there a way to sync all my Documents folder to OneDrive but some specific folders that I select?


text:
Q: indicator for increase over time I'm trying to create an indicator for value increase over time within a group. In particular, I'm trying to flag certain grp if value ever increases by 50% over time.
I have a raw data that looks like:
id    grp     value_dt    value
--------------------------------
1      1      11/20/20     1.4
1      1      11/21/20     0.8
1      1      11/24/20     2.8
1      1      11/25/20     2.5
1      2      11/29/20     1.5
1      2      12/1/20      1.6
2      1      11/21/20     0.8
2      2      11/26/20     0.9
2      3      12/1/20      0.9
2      3      12/3/20      2.8

You can see that for id = 1 and grp = 1, the value fluctuates as it increases and decreases over time, but because it had increase over time between 11/21/20 and 11/24/20 from 0.8 to 2.8 (greater than 50% increase), I want to flag the whole grp 1. I want my output to look like:
id    grp     val_ind
-----------------------
1      1         1
1      2         0
2      1         0
2      2         0
2      3         1

I can only think of using min and max (something like below), which doesn't include the 'over the time' factor in...
select id,
grp,
min(value) as min_grp,
max(value) as max_grp,
(max_grp - min_grp) as val_diff,
case when val_diff >= min_grp * 1.5 then 1 else 0 end as val_ind

If anyone can offer their advice, I will greatly appreciate it!

A: I think you want to know if at any point at time there is an increase of 50% , you flag that group. if yes , here is how you can do it,
you need to use cte and window functions :

; WITH cte AS (
SELECT *
, CASE WHEN  COALESCE(LEAD(value) OVER (PARTITION BY id, grp ORDER BY value_dt),0)  >= value* 2 THEN 1 ELSE 0 END val_ind
FROM  ttt
)

SELECT
id , grp , MAX(val_ind) val_ind
FROM cte
GROUP BY
id , grp

id | grp | val_ind
-: | --: | ------:
 1 |   1 |       1
 1 |   2 |       0
 2 |   1 |       0
 2 |   2 |       0
 2 |   3 |       1

db<>fiddle here


text:
Q: Pandas DataFrame filling in a column incorrectly -- Strange behavior I get different results in a for loop from print and df.at. Can this be explained?
import pandas as pd
data = [['A', []], ['B', []], ['C', []], ['D', []]]
df = pd.DataFrame(data, columns = ['Act', 'PreviousActs'])

actssofar = []

for i, row in df.iterrows():
 actssofar.append(row['Act'])
 print (i, actssofar)
 df.at[i,'PreviousActs'] = actssofar

Now, the output of the print function in the for loop is this:
0 ['A']
1 ['A', 'B']
2 ['A', 'B', 'C']
3 ['A', 'B', 'C', 'D']

But the output of the dataframe is this:

Acts
PreviousActs

A
A, B, C, D

B
A, B, C, D

C
A, B, C, D

D
A, B, C, D

Logically, shouldn't it show the same step-by-step appending behavior as the print function, since we are filling the dataframe with the same value?

A: If I understand correctly, the problem is that, when the loop finishes, your dataframe contains ['A', 'B', 'C', 'D'] for all rows.This happens because you are passing the list as "reference", which means all rows are storing the same list. You should add a list() call to create a new list everytime you assign it to the dataframe.
import pandas as pd
data = [['A', []], ['B', []], ['C', []], ['D', []]]
df = pd.DataFrame(data, columns = ['Act', 'PreviousActs'])

actssofar = []

for i, row in df.iterrows():
 actssofar.append(row['Act'])
 print (i, actssofar)
 df.at[i,'PreviousActs'] = list(actssofar)

Updated answer that makes use of mutability and is more memory efficient as it only creates one list.
import pandas as pd
data = [['A', []], ['B', []], ['C', []], ['D', []]]
df = pd.DataFrame(data, columns = ['Act', 'PreviousActs'])

actssofar = []

for i, row in df.iterrows():
 actssofar.append(row['Act'])
 print (i, actssofar)
 df.at[i,'PreviousActs'] = actssofar[:i+1]

A: You need to copy the list before putting it in the DataFrame. It's a mutable object, and what you are currently storing in the DataFrame is a reference to the original list, not a copy of it. Every element in the PreviousActs column is the same list.


text:
Q: Integer/Long from excel seen inside (VBA's and c++'s) VARIANT as a double I have the following c++ code :
#include <OAIdl.h> // for VARIANT, BSTR etc

__declspec(dllexport) void __stdcall updatevar(VARIANT * x)
{
    double nb = 3.0;
    ++nb;
}

with a function doing (almost) nothing (to avoid warnings)
and a .def file :
LIBRARY   tmp0
EXPORTS
   updatevar   @1LIBRARY

I compile this with visual studio 2013 into a dll that I reference as follows in excel-2013's VBA :
Declare Sub updatevar Lib "C:\path\to\thedll.dll" (ByRef x As Variant)

and that I use like this :
Public Sub DoIt()

    Dim r As Range
    Set r = ActiveWorkbook.Sheets("Sheet1").Range("B2:C4")
    Dim var As Variant
    var = r.Value
    Call updatevar(var)

End Sub

where the 6-cells excel range B2:C4 contains strings, dates, doubles and ints/longs.
I put a breakpoint in c++ code to inspect the variant pointed to that I receive, as remarked that the type of its 6 elements is always rightly resolved  : dates go to a vt (variant type VT_DATE) equal to 7, doubles to a vt (variant type VT_R8) equal to 5, strings go to a vt (variant type VT_BSTR) of 8, except for ints/longs, that are mapped to VT_R8 and treated as doubles.
At the beginning I thought it was a c++ problem but, already inspecting the range r in the VBA code, and its Value2 field, showed to me that all ints/longs were treated in VBA as Variant/Double and not Variant/Long, and I have no idea why this is happening.
Note. I put c++ and dll tags as the people interested in these tags may also help given the context involving exchanging VARIANT's between c++ and VBA.
Remark. "Downcasting" from double to int is not an option, especially as VARIANT is supposed to know about ints/longs (VT_I4 = 2 and VT_I4 = 3 do exist.)


text:
Q: Address Firebase object by child value, and then modify that object? I'm facing a little difficulty finding information about how to modify objects in Firebase Realtime Database. I'm adding items into my database in real-time, so I won't know ahead of time what the object key is. As you know, the database structure looks like this:

Say I want to address a child of "testing", whose category is "social", what I do is this:
firebase.database().ref("testing").orderByChild("category").equalTo("social")

But how exactly can I then address this child so as to update this entire child (including all the fields - "category", "date", etc.) or even delete it? Thanks so much for any help!

A: To update (or delete) a node in Firebase you must know the complete path to that node. If you don't know the complete path, you can use a query to determine the node(s) matching a certain condition.
So in your case you'll need to execute the query, loop over the results, and update each child node in turn. In code:
let query = firebase.database().ref("testing").orderByChild("category").equalTo("Social");
query.once("value").then((results) => {
  results.forEach((snapshot) => {
    snapshot.ref.update({ propertyToUpdate: "new value" });
  });
});

If you want to delete the matching node(s), the innermost line would be: snapshot.ref.remove().


text:
Q: Web Api, How to return enum text value instead of enum index value from HttpResponseMessage I notice that my Web Api method that return HttpResponseMessage convert enum value to int (order of value). But I would like to return enum text value.
return Request.CreateResponse(HttpStatusCode.OK, new {MyEnum.Someting, MyEnum.Someting2});

What should I setup for it ?

A: You can use the Enum.GetName method
return Request.CreateResponse(HttpStatusCode.OK, new {Enum.GetName(typeof(MyEnum), 0), Enum.GetName(typeof(MyEnum), 1)});

If this is what you are looking for ? https://msdn.microsoft.com/en-us/library/system.enum.getname(v=vs.110).aspx

A: This will return the name of a value defined in MyEnum:
return Request.CreateResponse(HttpStatusCode.OK,
    new string[] {MyEnum.Someting.ToString(), MyEnum.Someting2.ToString()});

If you have a number of variables of type MyEnum, then you can simply to a ToString on those variables:
MyEnum var1 = MyEnum.Something;
MyEnum var2 = MyEnum.Something2;

return Request.CreateResponse(HttpStatusCode.OK,
       new string[] {var1.ToString(), var2.ToString()});

If you wanted to return the names of each value defined in MyEnum you can use:
return Request.CreateResponse(HttpStatusCode.OK, Enum.GetNames(typeof(MyEnum)));

A: return Request.CreateResponse(HttpStatusCode.OK, new { TextValueOfSomething = MyEnum.Someting.ToString(), TextValueOfSomething2 = MyEnum.Someting2.ToString() });

You can't return new {MyEnum.Something.ToString(), MyEnum.Something2.ToString()} because you can't declare an anoymous object in this way. If you just want an array of strings then you would use new[] {MyEnum.Something.ToString(), MyEnum.Something2.ToString()}.

A: If you are returning and receiving the data in Json, you can use StringEnumConverter. Defining a model like this:
class Output
{
    [JsonProperty(ItemConverterType = typeof(StringEnumConverter))]
    public MyEnum[] Enums { get; set; }
}

public HttpResponseMessage Get()
{
    return Request.CreateResponse(HttpStatusCode.OK, new Output { Enums = new MyEnum[] { MyEnum.Someting, MyEnum.Someting2 } }); ;
}

Allows you instruct the json serializer to converts enums to and from its name string value.
Moreover, if you do not want to define the output model, in your WebApiConfig.Register(config) method, you can add this lines and also works:
var jsonFormatter = config.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());

and for .Net Core Web API use this:

public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc().AddJsonOptions( op => {
      op.SerializerSettings.Converters.Add(new StringEnumConverter());
  });

A: You could add the following helper method:
public static class Enums
{
    public static string GetDescription(this Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attributes != null && attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }

Then include descriptions in your enum, such as this:
public enum MyEnum
{
    [Description("Something 1")]
    Something1 = 1,
    [Description("Something 2")]
    Something2 = 2
}

And finally simply call:
return Request.CreateResponse(HttpStatusCode.OK, new
{
    MyEnum.Something1.GetDescription(),
    MyEnum.Something2.GetDescription()
});

A: I've created an extension for enums :
public static class EnumExtension
{
    public static string GetDescription(this Enum @enum)
    {
        FieldInfo fi = @enum.GetType().GetField(@enum.ToString());

        if (null != fi)
        {
            object[] attrs = fi.GetCustomAttributes
                (typeof (DescriptionAttribute), true);
            if (attrs != null && attrs.Length > 0)
                return ((DescriptionAttribute) attrs[0]).Description;
        }
        return null;
    }

    public static IEnumerable<TEnum> GetAllValues<TEnum>()
    {
        return Enum.GetValues(typeof(TEnum)).Cast<TEnum>();
    }
}

Your Enum :
public enum MyEnum
{
    [Description("foobar1 text")]
    foobar1= 1,
    [Description("foobar2 text")]
    foobar2= 2,
    [Description("foobar3 text")]
    foobar3= 3,
    [Description("foobar4 text")]
    foobar3= 4
}

Then call like this :
 MyEnum.foobar2.GetDescription()

Should return foobar2 text
Other solution is :
Enum.GetName(typeof(MyEnum.foobar2))

to return foobar2


text:
Q: Simplifying Floor/Ceiling expressions I'm working with symbolic expressions using Floor and Ceiling, and I'm unable to get Simplify to evaluate them.  For instance, I would expect:
Assuming[Element[n,Integers], Simplify[Ceiling[n/2] + Floor[n/2] == n]
to result in True, but it doesn't. (FullSimplify doesn't work either.)
There is a work-around using Resolve given in the comment to this question.
However, I would like to somehow implement Assuming and Simplify to achieve the same result.  Is this possible?  It seems such a simple, obvious expression.
Edit: Here is a more complex comparison that I haven't been able to resolve even using the work-around linked above.
Assuming[Element[n, Integers] && n > 0, Simplify[Ceiling[-(1/2) + 1/2 Sqrt[33 + 8 n]] == Floor[1/2 + 1/2 Sqrt[25 + 8 n]]]]

A: You could take a brute-force approach and provide your own transformation function to handle that case:
Assuming[Element[n, Integers],
  Simplify[
    Ceiling[n/2] + Floor[n/2] == n,
    TransformationFunctions -> {Automatic, ReplaceAll[Ceiling[a_] + Floor[a_] :> 2 a]}
  ]
]

(* Out: True *)


text:
Q: Unit test serilog configuration I have a piece of code for setting up serilog based on some custom configuration combined with hosting environment. E.g. the application writes to one sink in development and another sink in production.
I'm trying to figure out how to write tests for this piece of code. Basically, I want to write a test that checks that a sink only is added if the environment name is set to a given value, and that the sink configuration, like log file path, respects the custom configuration that I provide.
But I haven't had any luck finding any way of getting values out of the LoggingConfiguration...
Anyone knows if this is possible?

A: Unfortunately Serilog does not expose the list of Sinks that have been configured, so your only option at the moment would be to use Reflection.
If you poke around Serilog's source code, you'll see that it groups all configured sinks into an instance of an internal class SafeAggregateSink which is responsible emitting the logs to the different sinks setup, and holds an array with all the configured sinks in a private field called _sinks.
Here is a simple example:
var log = new LoggerConfiguration()
    .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Verbose)
    .WriteTo.File(path: "log.txt", restrictedToMinimumLevel: LogEventLevel.Verbose)
    .CreateLogger();

var aggregateSinkFieldInfo = log.GetType()
    .GetField("_sink", BindingFlags.Instance | BindingFlags.NonPublic);

var aggregateSink = (ILogEventSink)aggregateSinkFieldInfo?.GetValue(log);

var sinkEnumerableFieldInfo = aggregateSink?.GetType()
    .GetField("_sinks", BindingFlags.Instance | BindingFlags.NonPublic);

var sinks = (ILogEventSink[])sinkEnumerableFieldInfo?
    .GetValue(aggregateSink);

if (sinks != null)
{
    foreach (var sink in sinks)
    {
        Console.WriteLine(sink.GetType().FullName);
    }
}

This should output:
Serilog.Sinks.SystemConsole.ConsoleSink
Serilog.Sinks.File.FileSink

N.B.: Keep in mind that Serilog wraps sinks in some cases, so you might need to handle that, before you can find the sink you're looking for. For example, if you restrict the minimum level of a sink, your sink will be wrapped into a RestrictedSink, so you'll have to get a hold of its _sink field to get the "real" sink you're looking for.


text:
Q: How to set up geotools/geoscript for logstash on an offline linux box? I'm currently a 2nd year comp sci student working out an independent project as a trial for my final year work, and have been having some issues with configuring an ELK stack to work with geoserver logs using the contrib wms.rb filter. The main purpose of what I'm trying to do is have the bounding box of a WMS request sent to elasticsearch as a geo_shape.
I haven't been able to work out how to use the geoscript plugin, given that the only help I've seen has been variations of "...using the geoscript (Gem/Wrapper) to the Geotools java library..." I was wondering if anyone could give me an idiots guide to setting up the geotools java library, and then how to actually get geoscript from it?
I've tried the official geotools installation guide and it doesn't seem particularly suitable for what I'm trying to do.
Do I have to have maven installed for this? I only meant it to be a small piece of work so was hoping to do it without having to learn how to use maven.
I've attempted a few workarounds and none of them have come to anything. I was hoping there would be a more straightforward solution given that when I can't find an existing forum thread for something its usually because I'm missing something obvious.
(I'm having to work on a linux (centos 6) box with no internet connection, just to make this even easier.)
I'm not totally computer illiterate but the simpler the response the better.
Cheers for any help, I'm at my wits' end.
And apologies if this was the wrong place to post it, it's on several forums as I've tried to hedge my bets.

A: Looking at the home of GeoScript shows where to download the 4 different versions:

*

*Python

*JavaScript

*Scala

*Groovy

From your question it's not clear which one you are using but each of them should download all the necessary GeoTools jars that you need to get going.


text:
Q: Why am I getting these errors in my Server/Client Chatroom program? I've been working on this program for a few hours now, so I'm pretty brain-dead and cannot figure out why I'm getting these errors. Being fairly new to Java programming doesn't help my case much either.
On line 27 - "error: method Add in class ClientManager cannot be applied to given types;"
On line 34 - "error: cannot find symbol"
Also line 34 - "error: cannot find symbol"
On line 42 - "error: cannot find symbol"

Now here are segments of my code for those particular lines:
Line 27 - CM.Add();
Line 34 - MyClient Client = new MyClient(Socket, CM);
Line 42 - Client.SendToAllClients(S);

Here's my full code for the Server class. The client class works perfectly.
import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Server
{

    public static void main(String[] args) throws Exception
    {
        new MyServer().start();
    }
}

class MyServer extends Thread
{
    ServerSocket SS = new ServerSocket(11200);
    Socket S;
    ClientManager CM = new ClientManager();

    public void run()
    {
        while(true)
        {
            S = SS.accept();
            CM.Add();
        }
    }
}

class MyClient extends Thread
{
    MyClient Client = new MyClient(Socket, CM);
    Scanner S;

    public void run()
    {
        while(true)
        {
            S = new Scanner(System.in);
            Client.SendToAllClients(S);
        }
    }

    public void Send(String S)
    {
        PrintWriter.println(S);
    }
}

class ClientManager
{
    MyClient[] X = new MyClient[15];
    int num = 0;

    public synchronized void Add(MyClient C)
    {
        X[num] = C;
        num++;
        C.start();
    }

    public synchronized void SendToAllClient(String S)
    {
        int i;
        for(i = 0;i < num;i++);
        {
            X[i].Send(S);
        }
    }
}

Update: I'm not sure what parameter needs to go in CM.Add();

A: I can tell you the reason why you are getting these errors. You need to understand it and then make changes according to what you need.
Line 27 - CM.Add();
In your ClientManager class, the signature of method is public synchronized void Add(MyClient C) So you can see, it needs one parameter i.e. object of class MyClient but when you are calling this method then you are not passing any parameter.
MyClient Client = new MyClient(Socket, CM);
In this line you are trying to create object of class MyClient and passing two arguments Socket and CM objects but in your class MyClient you have not created any such constructor which will accept two parameters, by default there will be only default constructor, which can be called something like new MyClient(); if you want to pass parameters then you need to create a parameterized constructor your self.
Client.SendToAllClients(S);
Here Client is object of class MyClient and the method SendToAllClients(s) is present in ClientManager class, you if you want to call this method then you need an object of ClientManager class, you cannot call it with the object of MyClient.

Apart from it I would like to tell you, you are not following naming conventions of Java. It is a good practice to follow naming conventions, it helps others to understand your code easily. Check this link


text:
Q: How To Get to Every single HTML file in a URL So my code works but only for one url. (for example I used http://www.ancient-hebrew.org/m/dictionary/1000.html)
However I would like to apply every single html file URL to my code. Which can be found here (https://www.ancient-hebrew.org/m/dictionary/).
from bs4 import BeautifulSoup
import re
import urllib

def getImage(_list):
    images = []
    # adds the url
    for image in _list:
        images.append(re.sub(
            r"..\/..\/", r"http://www.ancient-hebrew.org/", image['src']))
    return images

def getAudioFile(_list):
    audio = []
    # removes a tab character + adds the url
    for l in _list:
        audio.append("http://www.ancient-hebrew.org/m/dictionary/" +
                     l['href'].replace("\t", ''))
    return ''.join(audio)

def getHebrewWord(_list):
    hebrew = []
    for f in _list:
        hebrew.append(f.string.strip())
    return ''.join(hebrew)

url = 'http://www.ancient-hebrew.org/m/dictionary/1000.html'
file_name = str(re.search(r'(\d+).\w+$', url).group(1)) + ".txt"
raw_html = urllib.urlopen(url).readlines()
_list = []
_dict = {}
_ignore = {'audioURLs': '', 'pronuncation': [],
           'imageURLs': [], 'hebrewWord': ''}
for line in raw_html:
    number = 1
    html = BeautifulSoup(line, 'lxml')

    # Image Files URLs
    images = getImage(html.find_all('img', src=re.compile('.jpg$')))

    # Audio File URLs
    audioFile = getAudioFile(html.find_all('a', href=re.compile('.mp3$')))

    # Hebrew Words
    hebrewWords = getHebrewWord(html.find_all('font', face="arial", size="+1"))

    # Pronunciations
    pronunciation = [item.next_sibling.strip()
                     for item in html.select('img + font')]

    # Output: {'audioURLs': '', 'pronuncation': [], 'imageURLs': [], 'hebrewWord': ''}
    dictionary = {
        'audioURLs': audioFile,
        'pronuncation': pronunciation,
        'imageURLs': images,
        'hebrewWord': hebrewWords
    }
    if dictionary != _ignore:
        _list.append(dictionary)

with open(file_name, 'w') as f:
    for item in _list:
        f.write("%s\n" % item)

So In the end I would like to write them to as many files. What would be an easy way to do this.

A: Seems to me you made it somewhat unnecessarliy complicated (and - cardinal sin! - used regex on html D:). I tried to simplify parts of it - getting the links for the images and sounds and inserting them into lists. Note that, for various reasons, I changed some of the variable names you used - but it should be relatively easy to fit everything into your structure and extend it to get the word itself:
from bs4 import BeautifulSoup as bs
import requests

url = 'http://www.ancient-hebrew.org/m/dictionary/1000.html'
raw_html = requests.get(url)

soup = bs(raw_html.content, 'lxml')

image_list = []
audio_list = []

images = soup.find_all ('img')
audios = soup.find_all ('a',href=True)

for image in images:
    if 'jpg' in image['src']:
        image_link = "http://www.ancient-hebrew.org/"+image['src'].replace('../../','')
        image_list.append(image_link)

for audio in audios:
    if 'mp3' in audio['href']:
        audio_link = "http://www.ancient-hebrew.org/m/dictionary/"+audio['href'].replace("\t", '')
        audio_list.append(link)

etc.


text:
Q: How does one find all objects that contain "blah" in Elasticsearch? I have been using wildcard like so: *blah* But, the docs state that you shouldn't start out a wildcard value with * because it can increase iterations required and slow down search performance.
Also, there is no indication in the docs as to whether or not wildcard is intended to be case-insensitive. I noticed that when I searched for a lowercase "a" I got back everything that had both "a" or "A", but when I searched for a capital "A", so literally *A*, I got back no results at all.
I want this specific search to behave exactly like e.g., Django's ORM would behave if I used filter(title__icontains='blah'), including case-insensitivity. So, if I say get me all records that contain the word 'the' in the title, I would expect anything with "the" (case-insensitive) in the title to be returned.

A: I don't know how you would get around the cautionary approach of using the wildcard query, so here's what that would look like, in case you were just having trouble with the syntax:
GET /_search
{
  "query": {
    "wildcard": {
      "title": {
        "value": "*elved*",
        "boost": 1.0,
        "rewrite": "constant_score"
      }
    }
  }
}

I just tested this type of query on my own search index, and searching for *oam* correctly matched "foaming" in product titles.

And as for the case-insensitivity, that should be handled out-of-the-box, as long as you're using one of the built-in analyzers (e.g. Standard or English).  But if you're using a custom analyzer, then you'll just need to make sure to include the lowercase filter, along with whatever other filters you want to run the terms through.
PUT index_name
{
  "settings": {
    "analysis": {
      "analyzer": {
        "my_custom_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase"
          ]
        }
      }
    }
  }
}

If you're not specifying an analyzer in your field mapping, then I believe it uses standard by default, which includes lowercase filtering.


text:
Q: How to extern a global two-dimensional array? I want to extern a global two-dimensional array:
float buffer[10][10];

I know that "extern float buffer[];" would work for an array with a single dimension, however I do not know how to extern an array with two dimensions.
Thanks in advance.

A: You could just declare it as:
In a header file put:
extern float buffer[10][10];

In one source file put:
float buffer[10][10];


text:
Q: Inverse and multiplication of (symmetric, positive definite) Toeplitz matrices Let $A \in \mathbb R^{n \times n}$ and $B \in \mathbb R^{n\times k}$ be two Toeplitz matrices, with $A$ symmetric and positive definite.
I am searching for an elegant proof (or a counterexample) for the following two statements

*

*$A^{-1}$ is symmetric and Toeplitz as well

*$AB$ is Toeplitz

I played around with a few random numerical examples and it seems to hold. However, I was not able to get a simple proof and I was a bit reluctant to start digging in indices. Any hint is appreciated.

A: For any invertible matrix $X$, we have $(X^{-1})^T=(X^T)^{-1}$. So, if $X$ is symmetric, $(X^{-1})^T=(X^T)^{-1}=X^{-1}$ and hence $X^{-1}$ is symmetric. Now your $A$ is symmetric and invertible. Hence its inverse is symmetric. This has nothing to do with the property that $A$ is Toeplitz.
The inverses or products of positive definite Toeplitz matrices are not Toeplitz in general. Examples:
\begin{align*}
&\begin{pmatrix}3&2&1\\2&3&2\\1&2&3\end{pmatrix}^{-1}
=\frac18\begin{pmatrix}5&-4&1\\-4&8&-4\\1&-4&5\end{pmatrix},\\
&\begin{pmatrix}3&2&1\\2&3&2\\1&2&3\end{pmatrix}^2
=\begin{pmatrix}14&14&10\\14&17&14\\10&14&14\end{pmatrix}.
\end{align*}
I am surprised to read that $A^{-1}$ and $AB$ are Toeplitz in all your random numerical examples.


text:
Q: multiple points with UIBezierPath in UIView , what formula to apply? I'm working on an app on IOS with Xcode (objective-c)
Here is the problem :
I'm working on a new way to show some statistics based on some frequency in a day, every hours.
Here is what i'm trying to achieve:

What you see is sort of clock on a 24 hour basis (top = 0 o'clock, each 15 degrees is an hour)
Each hour i have a distance from the center of the circle.
Those values are known, what I have hard time to achieve, is the curves themselves !
Indeed, In an UIView, I think i need to use UIBezierPath to draw the curves, but i have no clue on what formula I need to apply in order to make the graph passing through all the points ?
I hope I am clear with this question. Don't hesitate to ask me to clarify myself !
Thanks again, and see ya later !


text:
Q: Xamarin - Update Observable Collection Not Working I have a Xamarin project in which I have a Cart Page. I'm trying to update the data whenever I click on an add or remove button but it doesn't. Here's the code
public class CartViewModel : BindableObject
    {
....

private ObservableCollection<OrderDisplay> _ordersList;
        public ObservableCollection<OrderDisplay> OrdersList
        {
            get => _ordersList;
            set
            {
                _ordersList = value;
                OnPropertyChanged();
            }
        }

And then I have AddTotal where I try to update it. It is called when pressing the add or remove button
 private async void AddTotal(OrderDisplay oCart, int quantity)
        {
            decimal total = 0;
            int index = 0;

            if (oCart != null)
            {
                foreach (OrderDisplay obj in OrdersList)
                {
                    if (obj.Id == oCart.Id)
                    {
                        break;
                    }
                    index += 1;
                }
                OrdersList[index].Quantity = quantity;
                OrdersList[index].Total = quantity * OrdersList[index].Price;
                //OrdersList = null;
                //OrdersList = tempOrdersList;

                var order = await _apiService.GetOrderById(OrdersList[index].Id, token);
                order.Data.Quantity = OrdersList[index].Quantity;
                var orderUpdated = await _apiService.UpdateOrder(Convert.ToString(order.Data.Id), token, order.Data);

                if (!orderUpdated)
                {
                    await _messageService.ShowMessageAsync("Error", "Ha ocurrido un error.", "Ok", "");
                    return;
                }
            }

            foreach (OrderDisplay order in OrdersList)
            {
                total = order.Total + total;
            }

            LblTotalCart = string.Format("{0:N2}€", total);

        }

For context here is the view

I don't know how to do it. Please help.
EDIT
I tried doing it with INotifyPropertyChanged but gives me NullReference. I don't know if this is correct
public class OrderDisplay : INotifyPropertyChanged
    {
        //public int Id { get; set; }
        //public int Quantity { get; set; }
        //public decimal Price { get; set; }
        //public decimal Total { get; set; }
        //public CrProduct Product { get; set; }

        private int id;
        public int Id
        {
            get { return id; }
            set
            {
                id = value;
                OnPropertyChanged("Id");
            }
        }

        public int quantity;
        public int Quantity
        {
            get { return quantity; }
            set
            {
                quantity = value;
                OnPropertyChanged("Quantity");
            }
        }

        public decimal price;
        public decimal Price
        {
            get { return price; }
            set
            {
                price = value;
                OnPropertyChanged("Price");
            }
        }

        public decimal total;
        public decimal Total
        {
            get { return total; }
            set
            {
                total = value;
                OnPropertyChanged("Total");
            }
        }

        public CrProduct product;
        public CrProduct Product
        {
            get { return product; }
            set
            {
                product = value;
                OnPropertyChanged("Product");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }

A: INotifyPropertyChanged is the mechanism that the UI uses to determine when it needs to update a bound property.  If you are changing property P on class X, then X needs to implement INotifyPropertyChanged and raise a PropertyChanged event when P is modified.
an ObservableCollection<T> only raises events when items are removed or added from the collection.  It does not raise events when individual properties on the class T are modified.


text:
Q: More / less links not work in internet explorer I have problems with the function of show more/less text in all internet explorer. Internet explorer don't hide the text, but it is visible all the time. Does anyone know why? In newer safari, chrome, opera, firefox work fine.

function moreLess(initiallyVisibleCharacters) {
 var visibleCharacters = initiallyVisibleCharacters;
 var paragraph = $(".text")

 paragraph.each(function() {
  var text = $(this).text();
  var wholeText = text.slice(0, visibleCharacters) + "... MORE" + "" + text.slice(visibleCharacters, text.length) + " LESS"

  if (text.length < visibleCharacters) {
   return
  } else {
   $(this).html(wholeText)
  }
 });
 $(".more").click(function(e) {
  e.preventDefault();
  $(this).hide().prev().hide();
  $(this).next().show();
 });
 $(".less").click(function(e) {
  e.preventDefault();
  $(this).parent().hide().prev().show().prev().show();
 });
};

moreLess(300);

A: Please check the version of the JQuery reference you've referred, I think perhaps the issue is related to the JQuery version. You could also use F12 developer tools to verify whether it contains JavaScript error.
I've made some tests according to your code. And I've found that when using the latest version of Jquery(such as:jquery-3.3.1), the text will be visible all the time in IE8 and older versions. The console bar will show the an error in the following picture.
the console error
This is because latest versions of jQuery do not support older versions of IE, you should try to use an older version of jQuery like below.

And it may work well, you could see from the capture.
the running result
Last but not at least, do not forget to add .ready() function in your code.
$(document).ready(function () {
   function moreLess(initiallyVisibleCharacters) {
            .................
   }
})


text:
Q: Where should I plug in my custom DefaultContractResolver JSON.NET? I have a WebAPI 2.0 project in ASP.Net in which I implemented a custom DefaultContractResolver so that I can control how my entities are serialized to JSON using JSON.Net; however I am unsure about how can I tell the framework to use my custom implementation. I'd also like to know if its possible to change the ContractResolver for a specific controller / action.
Thanks!
--- Edit 03/07/2014
I've already figured out how to use my custom implementation by creating a new ConfigSettings object and manually parsing the object; However the resulting JSON is serialized twice (it has extra \r\n characters). This is caused because the webAPI controller by default serializes the response, So i'd like to change to override that behavior... Is this the right way to go?

A: I just went through the pains of figuring that out myself and I needed one that works per-request. You can use that approach and just return the same media formatter. I found setting a formatter on GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver a bit unreliable for per-request needs, even though I tried handling the per-request needs in one single instance of that class. You can, however try setting your ContractResolver instance there, somewhere in App_Start code
I ended up creating a custom JsonMediaTypeFormatter that checks if there is a configured ContractResolver for the request, you can just return one and the same resolver:
public class DynamicJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, System.Net.Http.HttpRequestMessage request, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
{
// shown is getting the current formatter, but you can return an instance you prefer
  var formatter = base.GetPerRequestFormatterInstance(type, request, mediaType) as JsonMediaTypeFormatter;

// Here I had more code to get the resolver based on request, skipped
  ((JsonMediaTypeFormatter)formatter).SerializerSettings.ContractResolver = <YourContractResolverInstance>;
    return formatter;
}
}

I presume you've figured that part out already but your contract resolver can override `CreateProperties' and have your own logic decide what json properties will be present and what names will they use (added for completeness and benefit of other readers):
public class DynamicContractResolver : DefaultContractResolver
{
...
 protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization){
  ...
}

A: I ended up changing the return type of my method like this:
Asume we have this simple Foo class:
public class Foo
{
    public string Bar {get; set;}
}

with ASP WebApi 2.0 the scaffolded controller method for GET will look like this:
// GET api/Foo
public IQueryable<Foo> GetFoos()
{
    var foos = GetAListOfFoosFromSomewhere() //returns an IQueryable<Foo>
    return Foos
}

Note that the framework automagically serializes Foos to JSON.
So what I did was change the method to this:
// GET api/Foo
public HttpResponseMessage GetFoos()
{
    var foos = GetAListOfFoosFromSomewhere(); //returns an IQueryable<Foo>
    var settings = new JsonSerializerSettings()
    {
     ContractResolver= new MyCustomContractResolver(), //Put  your custom implementation here
     //Also set up ReferenceLoopHandling as appropiate
    };
    var jsoncontent = JsonConvert.SerializeObject(foos, settings);
    var response = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent(jsoncontent, Encoding.UTF8, "application/json")
    };
    return response;
}

In my solution I added a convience method to create the HttpResponseMessage so it looks a bit like this:
public HttpResponseMessage GetFoos()
{
    var foos = GetAListOfFoosFromSomewhere() //returns an IQueryable<Foo>
    return CreateResponse(foos);
}

This post by mercury2269 was really helpful.


text:
Q: HTML Cell Button I've a problem where I can't get my cell look like a button. I use a table as navbar, and I want the cell to be a button.
For the HTML part:

                Site Header

Head

                Home
                Producten
                Diensten
                Over ons
                Informatie
                Contact

Help much appreciated

A: Since you didn't put your CSS here or how you would want to see it, I have assumed the simplest.
This, at the roughest level, emulates what you might want to do.
CSS :
td {
    background:#bada55;
    color:#fff;
    border:10px solid #fff;
    padding:4px 10px;
}

Here it is... http://jsfiddle.net/550k4gm4/3/


text:
Q: How to log out of GitHub API I make simple GitHub example app. I created a login function, but not a sign out function. How to create a log out function?
I've been using this API
https://docs.github.com/en/rest/reference/apps#delete-an-app-authorization
Only this error popped up.
{"message":"Not Found","documentation_url":"https://docs.github.com/rest"}


text:
Q: Customize Camera Frame before capture I know there are many threads in relation to this topic as to how to customize the size of the window/frame of the camera (Is aspect ratio the correct term?) that shows preview of the image/environment before committing it (or clicking it) as an image.
I have tried this, this, this,this & especially another one from user Carlos, link for which I am unable to retrieve.
Thing is i just know the following lines of codes:
 camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent cam = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cam, CAMERA_REQUEST);
        }

    });

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_REQUEST) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        thumbView.setImageBitmap(photo);

         }
    }

That's it. I have tried typing from above links inside onCreate() but I have no clue.
Please guide from basics as to what will help me achieve a camera screen with a contracted square frame?

A: Unfortunately, you cannot control the camera screen with your approach.
You are launching the Camera Intent. This means that your app asks the system to perform the image capture for you, and the system will choose one of the registered apps that are willing to fulfill such task. More often than not, the system will launch the stock Camera app (the application that is preinstalled on the device), but a) different devices come with different preinstalled cameras and b) there are hundreds of custom camera apps on the Play Store.
There is no way to control this huge diversity of apps. There is only some hope that they will all respect the contract as defined on Android Developers page. But actually some of the apps ignore even these most basic requirements.


text:
Q: How to design database for movies? I am using TMDB api to get a list of popular, upcoming, top-rated and now-playing movies separately. I want to store them locally in a database which is updated daily. Each returned movie have a unique id. So, I want to store popular movies in a table named popular, upcoming movies in a table named upcoming and vice versa. If I follow this approach I will be creating four tables with same attributes but I can keep the movieId distinct to avoid redundancy like when the database is updated.
On the other hand if I create a single table then I cannot have movieId as distinct because a movie can be both popular and upcoming which will lead to redundancy when I update my database.Is there any way that a movie is only inserted in database if the movie with same id and same tag(popular, top-rated, upcoming, now-playing) is not present in the database?
How can I design my database so that I can easily get different list of movies from database as recieved from api?

A: Use one table: movies.  Create a unique index on two fields.  This will only allow one occurrence of this unique ID per type of movie: external_id and type:
CREATE TABLE `movies` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `external_id` INT NOT NULL,
  `type` ENUM('popular', 'upcoming', 'top-rated', 'now-playing') NOT NULL,
  `name` VARCHAR(45) NULL,
  `genre` VARCHAR(45) NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `external_id_type_idx` (`external_id` ASC, `type` ASC));

With this table structure you could use INSERT IGNORE statements when attempting to add movies:
INSERT IGNORE INTO `movies` (`external_id`, `type`, `name`, `genre`) VALUES (?, ?, ?, ?);

INSERT IGNORE will attempt to insert a record but if a constraint causes it to fail it will just be ignored(nothing will be inserted, updated, etc). See https://stackoverflow.com/a/548570/416412
To get a different list of movies(upcoming in this example), filter by type:
SELECT * FROM `movies` WHERE `type` = 'upcoming';

A: *

*At minimum for a best practice, you should use two tables. 'Movies' and 'MovieType'. They can contain any number of columns but I will focus on the required ones here.

*'MovieType' stores the details of the type of the movie. Columns will be MovieTypeId (primary key) and MovieTypeDescription (not null) - varchar - size depends. Store values such as (1, 'Popular'), (2, 'Upcoming') etc. in this table.

*'Movies' stores the details of movies. Columns will be MovieId (not null) - int - auto increment, MovieName (not null) - varchar - size depends, MovieTypeId (not null) - tinyInt.

*You need to add 2 more CONSTRAINTS for Movies table. First is, MovieTypeId will be a foreign key referring to the MovieTypeId column in the MovieType table. 2nd will be a Composite Unique Key that combines (MovieId and MovieTypeId).

You are done.
Now you can store values such as
(Movie1, 1)
(Movie2, 2)
in the Movies table. A duplicate entry would throw an error. Of course, based on the API, you would like to handle it beforehand.
NOTE: I would personally prefer NOT to auto-increment MovieTypeId in the MovieType table because the category of the movies may change anytime including scrapping off from 10 categories to just 1 during which you will face problems.


text:
Q: Change 'not programming related' to 'not computer related' Now that we have SuperUser, the "not programming related" reason is no longer a valid reason to close a question - questions that are not programming related but are computer related should be moved instead. But because the option remains, people seem to feel justified in closing questions without moving them anyway sometimes.
As such, I suggest changing "not programming related" to "not computer related" - this will help reinforce the fact that questions not related to programming, but which are computer related, do have somewhere to go now. Alternately, "not programming related" should bring up a confirmation to suggest moving to superuser, serverfault, or meta if the question is appropriate for one of those.
Edit: If questions don't deserve to be migrated, they should be closed, sure - but not with "not programming related". Just thing: how do we close bad questions that are programming related? Use one of the other close reasons available, or edit the question to be better. And certainly leave a comment.
At the very least, if you use another close reason, the questioner might get a better idea of why their question was bad. If you just say "not programming related", they might never find out where their question should go, and might never know why their question was unacceptable.
Finally, from a philosophical perspective, anything computer related is theoretically on-topic somewhere in the SO family. Whether it's a good question is completely orthogonal to this - but since it's on topic, closing it for 'off topic' is false. Think: If the question was submitted to SU in the first place would you close it? If so, use that close reason.

A: In such a case, people should just use the "belongs on superuser.com" close reason. There's no reason to change the "not programming related" close reason. Each one serves a function.
I'll give two examples:

*

*This question is not programming-related, but should be moved to SuperUser, so the "belongs on superuser.com" close reason should have been used.

*This question is not programming-related, in my opinion. Some could make the argument that it is somehow programming or computer related, since it is dealing with programmers, but really it doesn't address programming. Sure, you could use other close reasons (like subjective and argumentative), but NPR is most appropriate and sends the most direct message about why the question doesn't really fit on SO. The question also doesn't really fit anywhere else on SF or SU either.
EDIT: An alternative suggestion is to adjust the NPR close reason to be specific for each site, indicating that it specifically doesn't belong on that site (and is not worthy of migration either):

*

*"not programming related" on SO

*"not server related" on SF

*"not computer related" on SU

*"not SO related" on MSO

IMO, this would be more informative, since it indicates exactly why a question was closed for that particular site.

A: I agree with this. I've seen several questions recently closed as "not programming related", when they should have been migrated to SU or SF. I think that we may have some users who are not up to date on the close reasons.

A: I would suggest that the language be "not appropriate for any SO site".  This makes it clear that it is completely unwanted.

A: If the users feel it is best moved, it will most likely get moved to another place (if it is better suited there). Otherwise some things just deserve to die. If we did what you said, most people would instinctively choose SuperUser ("Hey, it's computer related HURR!") and we can all watch SuperUser become the trash can that a lot of people predicted at the start.
I don't want to see that happen.

A: Looks like "not programming related" was removed at some point...


text:
Q: Nest can't resolve dependencies of the AuthService (?, JwtService) I am having some problems with the test generated by default by nest js. I make sure my services are not circularly declared and are both fully exported service and imported module. I have tried other similar stack questions but it doesn't seem to be my case. Please tell me how to fix it. Thanks
here is my repository: https://github.com/ThanhDeveloper/NestJsApp
My auth controller:
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Post('login')
  @UseGuards(AuthGuard('local'))
  @ApiBody({ type: LoginUserDto })
  @UseInterceptors(TransformInterceptor)
  @HttpCode(200)
  async login(@Request() req) {
    return await this.authService.login(req.user);
  }

  @Post('register')
  @UseInterceptors(TransformInterceptor)
  async signUp(@Body() registerUserDto: RegisterUserDto) {
    return await this.authService.register(registerUserDto);
  }
}

My auth service:
export class AuthService {
  constructor(
    private readonly userService: UsersService,
    private readonly jwtService: JwtService,
  ) {}
}

auth.module.ts:
@Module({
  imports: [
    PassportModule,
    UsersModule,
    JwtModule.register({
      secret: JWTKEY,
      signOptions: { expiresIn: TOKEN_EXPIRATION },
    }),
  ],
  providers: [AuthService, LocalStrategy, JwtStrategy],
  controllers: [AuthController],
})
export class AuthModule {}

user.module.ts:
@Module({
  controllers: [UsersController],
  providers: [UserProfile, UsersService, ...usersProviders],
  exports: [UsersService],
})
export class UsersModule {}

app.module.ts
@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    DatabaseModule,
    UsersModule,
    AuthModule,
    CrawlersModule,
    AutomapperModule.forRoot({
      options: [{ name: 'classMapper', pluginInitializer: classes }],
      singular: true,
    }),
  ],
})
export class AppModule {}

err log:

A: UsersService has a UserRepository injection. So if you want to test your controller or service that imports(or uses) UsersService, you must inject it or use repository mocking.

A: *

*change auth.controller.spec.ts to

*

*change auth.service.spec.ts to

*

*change users.controller.spec.ts to

*

*change users.service.spec.ts to

All your errors will be gone


text:
Q: Battery notification in every application that is running Is it possible to have a battery notification in every application that is running?
For example: If I'm going to run an application like Angry Birds, is it possible to have some sort of a notification that will tell me if there is enough time to continue playing it?
This is one of the objectives in our thesis.

A:
If I'm going to run an application like Angry Birds, is it possible to have some sort of a notification that will tell me if there is enough time to continue playing it?

You can play Angry Birds for a second, a minute, an hour, a day, a week, a month, etc. There is no defined "enough time to continue playing it".
Moreover, it is impossible to state definitively how much power a process will run in the future.
Now, you could create some code that attempts to measure historical power consumption of an application (and how the user uses it, which may vary from person to person). You could use that information to make some educated guesses about how long the user could keep using that app. And you could find a way to present that information to the user.
All of that will require, at minimum, custom firmware. It is also very possible that it will require custom hardware that has fine-grained power consumption data collection, such as the Qualcomm MDP.


text:
Q: Material Design in Angular won't work I have a problem with Angular Material including.
I've installed angular-material with bower in my angular project and included scripts and stylesheet.
Angular is v1.4.1 and Angular Material 0.10.0. Is there any wrong dependency?

var app = angular.module('startApp', ['ngMaterial'
  ]);

app.controller('MainController', ['$scope',
  function($scope) {
    $scope.title = 'Web page';
    $scope.array = [{
        name: 'data 1',
        duration: '01:42',
        creationdate: new Date('2014', '03', '08')
      },
      {
        name: 'data 2',
        duration: '00:58',
        creationdate: new Date('2014', '03', '08')
      },
      {
        name: 'data 3',
        duration: '02:45',
        creationdate: new Date('2014', '03', '08')
      }];
  }]);

<!doctype html>

    <meta charset="utf-8">
    <title>web page</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

    <link rel="stylesheet" href="bower_components/angular-material/angular-material.css">

    <link rel="stylesheet" href="styles/main.css">

  <md-button>asd</md-button>

 {{title}}

{{data.name}}

{{data.duration}}

{{data.creationdate | date}}

A: Clean up your javascript libraries, the order is important!

*

*jQuery.js

*angular.js

*all angular sub modules

*your application scripts

var app = angular.module('startApp', ['ngMaterial'
  ]);

app.controller('MainController', ['$scope',
  function($scope) {
    $scope.title = 'Web page';
    $scope.array = [{
        name: 'data 1',
        duration: '01:42',
        creationdate: new Date('2014', '03', '08')
      },
      {
        name: 'data 2',
        duration: '00:58',
        creationdate: new Date('2014', '03', '08')
      },
      {
        name: 'data 3',
        duration: '02:45',
        creationdate: new Date('2014', '03', '08')
      }];
  }]);
<!doctype html>

    <meta charset="utf-8">
    <title>web page</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/0.10.0/angular-material.min.css">

  <md-button>asd</md-button>

 {{title}}

{{data.name}}

{{data.duration}}

{{data.creationdate | date}}


text:
Q: SQL Server : first business day of month How can I incorporate a holiday table into the SQL below? The result returns the first business day, but since 1/1/18 was a Monday holiday I need business day 2.
DECLARE @DATE DATETIME;
SET @DATE = '1/1/2018';

SELECT
    CASE
       WHEN DATENAME(WEEKDAY, DATEADD(mm, DATEDIFF(MM, 0, @DATE), 0)) = 'Saturday'
          THEN DATEADD(mm, DATEDIFF(MM, 0, @DATE), 0) + 2
       WHEN DATENAME(WEEKDAY, DATEADD(mm, DATEDIFF(MM, 0, @DATE), 0)) = 'Sunday'
          THEN DATEADD(mm, DATEDIFF(MM, 0, @DATE), 0) + 2
       WHEN DATENAME(WEEKDAY, DATEADD(mm, DATEDIFF(MM, 0, @DATE), 0)) = 'Monday'
          THEN DATEADD(mm, DATEDIFF(MM, 0, @DATE), 0) + 1
       ELSE DATEADD(mm, DATEDIFF(MM, 0, @DATE), 0)
   END;

A: I think this will help you, you can check this sqlscript as you mention, I am given a 3 different dates to check proper answer :
Declare @date date = '01/01/2018' --getdate()

SELECT CASE
        WHEN DATENAME(WEEKDAY, dateadd(mm, DATEDIFF(MM, 0, @date), 0)) = 'Saturday'
            THEN dateadd(mm, DATEDIFF(MM, 0, getdate()), 0) + 2
        WHEN DATENAME(WEEKDAY, dateadd(mm, DATEDIFF(MM, 0, @date), 0)) = 'Sunday'
            THEN dateadd(mm, DATEDIFF(MM, 0, @date), 0) + 1
        ELSE dateadd(mm, DATEDIFF(MM, 0, @date), 0)
        END

set @date = '04/01/2018' --getdate()

SELECT CASE
        WHEN DATENAME(WEEKDAY, dateadd(mm, DATEDIFF(MM, 0, @date), 0)) = 'Saturday'
            THEN dateadd(mm, DATEDIFF(MM, 0, getdate()), 0) + 2
        WHEN DATENAME(WEEKDAY, dateadd(mm, DATEDIFF(MM, 0, @date), 0)) = 'Sunday'
            THEN dateadd(mm, DATEDIFF(MM, 0, @date), 0) + 1
        ELSE dateadd(mm, DATEDIFF(MM, 0, @date), 0)
        END

set @date = '09/01/2018' --getdate()

SELECT CASE
        WHEN DATENAME(WEEKDAY, dateadd(mm, DATEDIFF(MM, 0, @date), 0)) = 'Saturday'
            THEN dateadd(mm, DATEDIFF(MM, 0, getdate()), 0) + 2
        WHEN DATENAME(WEEKDAY, dateadd(mm, DATEDIFF(MM, 0, @date), 0)) = 'Sunday'
            THEN dateadd(mm, DATEDIFF(MM, 0, @date), 0) + 1
        ELSE dateadd(mm, DATEDIFF(MM, 0, @date), 0)
        END

Please refer :- First business day of the current month - SQL Server