text:
Q: What's the maximum number of wifi connections for a single WiFi router? We've got a Draytek 2829VN Wifi router and I'm wondering how many concurrent connections I should expect a router of this kind to cope with?  We are looking to connect 60 iPads!
I'd also be interested in knowing what might happen when it starts to reach capacity?
Not looking for details specifically for this model, but in general.
Thanks!
UPDATE
Thanks for everyone's help!
We ended up going with 3 wired Cisco AP's, sharing a single SSID across 3 channels.
The venue already has WiFi running across channels 1,6 & 11 (the default it seems) so we've opted for channels 3, 8, and 13 which seems to be working very well, with around 20 iPads per AP.
The iPads then picked up the signal almost immediately, something they were taking in excess of 2 minutes to do when running on channels 1,6,11 due to interference.
Lesson learned : don't assume that setting up WiFi for large numbers of people is easy!

A: Concurrent connections are dictated by 2 things, bandwidth & resource,
On the resource front it would be best to ask the vendor, the cpu & memory of he hardware could be a limiting factor in the supported concurrent connections.
Bandwidth is the major limiting factor, whilst you may connect @ 54mb/s remember if you users are contenting with 50 others all over the 100mb/s Ethernet attached to the access point their actual available bandwidth becomes 2mb/s.
As you start to reach capacity you will find:
Bandwidth: The Ethernet connection is always transferring the maximum available for the connections (i.e. 100mb.s)
Resource: assuming someone isn't attempting to crack your network by spamming de-auth packets you will see a lot of "broadcasts" from the AP, as it tries to reconnect with dropped clients.

A: I don't see that model specifically, but similar model lines look like they're a SOHO class routers. The price on those models makes them look like a step above home routers, but I'd be wary of their limits.
If you're pushing 60+ devices through a wireless system simultaneously, I'd really strongly consider getting a dedicated access point and a separate router. Combo router/switch/wireless AP's in my experience tend to get glitchy and have issues with maintaining connections or having a subcomponent die and require a reboot, killing everything until it restarts.
They also tend to have limits in their routing tables that start giving odd behavior for things like web browsing or computers that get booted off the network.
If I had to guess, you're overpushing that router. Suggest getting separate, higher-end systems.

A: As others have said, you're probably "oversubscribing" the wifi router. Wifi is a shared medium so all 60 clients are sharing and contending for the 54Mbps (assumed) bandwidth available through the wifi link. That's somewhat analogous to connecting 60 wired clients to a hub and uplinking that via a single 10, 100, or 1000Mbps link to your core switch, but in addition you've also got signal quality and potential interference issues to deal with as well.

A: I should add that bandwidth is not an important parameter for consideration. It is obvious to divide bandwidth on number of clients but real hardware has various limitations.
Like count of hardware encryption modules (it can be around 32 or 50/64). See https://superuser.com/a/639007/49345
Manufacturer for home end products like D-Link recommends only 15 simultaneous connections.
NETGEAR home routers can accommodate up to 32 clients per wireless band. If your router is dual band, the total wireless clients your router can handle is 64 (32 for the 2.4GHz and 32 for the 5GHz)
Statistics on Cisco 1142 and 3502I access points:
Protocol / bandwidth / # of Clients per AP

802.11b    600 kbps    13
802.11g    600 kbps    43
802.11n (1 Spatial Stream)
           600 kbps    43
802.11n (2 Spatial Streams)
           600 kbps    273

and they tell about 30-40 clients per AP.

A: While Oneiroi's answer starts to get you there. There are a few flaws that deserved more than a comment on his answer.
First, the bandwidth you are actually contending for isn't the back end ethernet link, but the wireless link speed. So on a 54 mbps router you would be contending for that 54 mbps. At  60 clients that would be about 900kbps each, not counting TCP overhead, counting TCP overhead you are already down to ~720kbps.
Secondly, you still have to deal with signal strength issues, which depending on your location could greatly effect throughput.
Thirdly, you have to deal with interference between those 60 radios all trying to broadcast. Years ago when I was working on planning an 802.11b wireless network the engineer we talked to said the rule of thumb was about 10-12 clients per AP for best performance, you can probably move that up to 20-25 (pure off the cuff number)with today's newer technologies. But that still doesn't get you to 60.
I would suggest that you take a look at some pure Wireless APs (not routers) and do a site survey to find the optimal placements for them.


text:
Q: AEM Solr integration I'm following this mini tutorial on how to integrate Solr on a local AEM instance.
I get stuck on point 5: whene I try to connet to localhost:8080/solr/ I receive the following error code:
{msg=SolrCore 'collection1' is not available due to init failure: Could not load core configuration for core collection1,trace=org.apache.solr.common.SolrException: SolrCore 'collection1' is not available due to init failure: Could not load core configuration for core collection1
at org.apache.solr.core.CoreContainer.getCore(CoreContainer.java:753)
at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:307)
at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:207)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:583)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1125)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1059)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:485)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:290)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:248)
at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:606)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:535)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.solr.common.SolrException: Could not load core configuration for core collection1
at org.apache.solr.core.ConfigSetService.getConfig(ConfigSetService.java:66)
at org.apache.solr.core.CoreContainer.create(CoreContainer.java:554)
at org.apache.solr.core.CoreContainer$1.call(CoreContainer.java:261)
at org.apache.solr.core.CoreContainer$1.call(CoreContainer.java:253)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
... 1 more
Caused by: java.lang.RuntimeException: java.nio.charset.MalformedInputException: Input length = 1
at org.apache.solr.schema.IndexSchema.<init>(IndexSchema.java:168)
at org.apache.solr.schema.IndexSchemaFactory.create(IndexSchemaFactory.java:55)
at org.apache.solr.schema.IndexSchemaFactory.buildIndexSchema(IndexSchemaFactory.java:69)
at org.apache.solr.core.ConfigSetService.createIndexSchema(ConfigSetService.java:89)
at org.apache.solr.core.ConfigSetService.getConfig(ConfigSetService.java:62)
... 9 more
Caused by: java.nio.charset.MalformedInputException: Input length = 1
at java.nio.charset.CoderResult.throwException(CoderResult.java:277)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:338)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:154)
at java.io.BufferedReader.readLine(BufferedReader.java:317)
at java.io.BufferedReader.readLine(BufferedReader.java:382)
at org.apache.lucene.analysis.util.WordlistLoader.getLines(WordlistLoader.java:223)
at      org.apache.lucene.analysis.util.AbstractAnalysisFactory.getLines(AbstractAnalysisFactory.java:256)
at org.apache.lucene.analysis.util.AbstractAnalysisFactory.getWordSet(AbstractAnalysisFactory.java:244)
at org.apache.lucene.analysis.core.StopFilterFactory.inform(StopFilterFactory.java:99)
at org.apache.solr.core.SolrResourceLoader.inform(SolrResourceLoader.java:675)
at org.apache.solr.schema.IndexSchema.<init>(IndexSchema.java:166)
... 13 more
,code=500}

Does anyone have got any idea on how to solve it?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Current exciting topics in graph theory What is new in the world of graph theory in the past few years?  Beyond the basics?

A: Here(Douglas West's website) is a good site that lists some open problems. Also, see this related question about the relationship between graph theory and homology.


text:
Q: Struct methods as FFI callbacks I'm working on a plugin for an existing host application. The application provides a native C SDK that I connect to from Rust with FFI bindings generated with bindgen. The SDK relies heavily on callback functions to inform my plugin of state changes and user interactions.
My plugin on the Rust side is basically a structholding the relevant data. All functionality is built into methods of this struct.
My challenge are those function callbacks needed by the SDK.
I can easily create static functions and hand them over to the host application:
// function to set callback function in FFI lib
fn set_callback(callback_fn: fn(usize)) {
    let ptr = callback_fn as *const ();
    unsafe {
        // transmute the fn ptr into a C-style fn
        std::mem::transmute::<*const (), Option<unsafe extern "C" fn(usize)>>(ptr);
        // this can now be handed over as the callback via FFI
        // ...
    }
}

// Rust function to be used as callback
fn my_callback(val: usize) {
    println!("{}", val);
}

set_callback(my_callback);

Those functions just don't have access to my struct and thus the data and functionality stored there. So I need to use methods of my struct.
If I convert those static functions into methods of my struct, I can't use them as callback anymore:
struct dummy {}

impl dummy {
    fn set_callback(&mut self, callback_fn: fn(usize)) {
        let ptr = callback_fn as *const ();
        unsafe {
            // transmute the fn ptr into a C-style fn
            std::mem::transmute::<*const (), Option<unsafe extern "C" fn(usize)>>(ptr);
            // this can now be handed over as the callback via FFI
            // ...
        }
    }
    fn my_callback(&self, val: usize) {
        // do something
    }

    fn init(&mut self) {
        self.set_callback(self.my_callback);
    }
}

let mut dummy_instance = dummy {};
dummy_instance.init();

error[E0615]: attempted to take value of method `my_callback` on type `&mut dummy`
   --> src/main.rs:18:36
    |
 18 |             self.set_callback(self.my_callback);
    |                                    ^^^^^^^^^^^ method, not a field
    |
help: use parentheses to call the method
    |
 18 |             self.set_callback(self.my_callback(_));
    |                                               ^^^

Seems that I'd have to use a closure encapsulating that function call. This creates the next obstacle for me, as I can't easily hand over that closure via FFI to call from C. I could wrap it like this:
use std::ffi::c_void;

type Callback<T> = unsafe extern "C" fn(*mut c_void, x: T) -> T;

fn c_like_closure<F, T>(_: &mut F) -> Callback<T>
where
    F: FnMut(T) -> T,
{
    unsafe extern "C" fn invoke<Q, S>(state: *mut c_void, x: S) -> S
    where
        Q: FnMut(S) -> S,
    {
        let func = &mut *(state as *mut Q);
        func(x)
    }

    invoke::<F, T>
}

struct Dummy {}

impl Dummy {
    fn my_callback(&self, val: usize) -> usize {
        val
    }
}

fn main() {

    let mut my_plugin = Dummy {};
    let mut cb = |val: usize| my_plugin.my_callback(val);

    let fn_ptr = c_like_closure(&mut cb);
    let g = unsafe { fn_ptr(&mut cb as *mut _ as *mut c_void, 123) };
}

The caveat is, that I'd have to somehow hand over the context. And the SDK I have to use doesn't offer any function parameters that would allow me top pass the context back and forth.
I've found libfficrate that seems to be able to wrap a closure and hand it over via FFI. The above example can be altered as following:
use libffi::high::arity1::Closure1;
...
fn main() {

    let mut my_plugin = Dummy {};
    let mut cb = |val: usize| my_plugin.my_callback(val);

    let closure = Closure1::new(&cb);
    let fn_ptr = closure.code_ptr();
    unsafe {
        fn_ptr(123);
    }
}

Nice!
Until I try to do it from inside my struct, within my init_pluginmethod. There I can't easily create a closure using self:
struct Dummy {
    closure: Option<Box<Fn(usize) -> usize>>,
}

impl Dummy {
    fn my_callback(&self, val: usize) -> usize {
        println!("{}", val);
        val
    }

    fn init_plugin(&mut self) {
        self.closure = Some(Box::new(|val: usize| self.my_callback(val)));
    }
}

error[E0759]: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
  --> src/main.rs:64:38
   |
63 |     fn init_plugin(&mut self) {
   |                    --------- this data with an anonymous lifetime `'_`...
64 |         self.closure = Some(Box::new(|val: usize| self.my_callback(val)));
   |                                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...is captured here, requiring it to live as long as `'static`

Looks like I'm stuck on my path with closures… The only other option I see would be some static intermediate functions that get a reference to my plugin struct from somewhere and then call the methods on that like this:
let my_plugin = Dummy{};

Dummy::my_callback(my_plugin, 123);

But that would require my_pluginto become a global variable, which doesn't sound too convincing to me…
It's quite obvious, that I'm not the only one, trying to work with callbacks via FFI. I wonder how this can be solved without giving up on Rust's principles and advantages.


text:
Q: PHP to C# conversion. Taking user input / manipulating user input I am required to learn C#/ASP.NET.  I have been googling but I can't find any tutorial.
Right now I have an HTML form in ASP.NET
How do I manipulate the user input and display them back?
In PHP I would write this:
if (isset($_POST['fname'])){
$name = $_POST['fname'];

echo $name;
}

How do I do the same in  C#/ ASP.NET?

A:     if (!String.IsNullOrEmpty(Request.Form["fname"]))
    {
        var name = Request.Form["fname"];
        Response.Write(name);
    }

A: Quickly written out of my head, it would look something like this:
protected void ButtonClick(object sender, EventArgs e)
{
    string name = Request.Form["fname"];
    //Or with a TextBox
    string name = fnameTextBox.Text;

    if(!String.IsNullOrEmpty(name))
    {
        Response.Write(name);
    }
}

A: put this code in aspx page:
<asp:TextBox runat="server" id="txtfname" />
<asp:Button runat="server" id="btnSubmit" Text="Save" OnClick="btnSubmit_Click"/>

and your aspx.cs page:
protected void btnSubmit_Click(object sender, EventArgs e)
{
    string fname = txtfname.Text;
    //save to db or whatever code here
}


text:
Q: Limited number of SQL Query selectors I can't figure out what is wrong with my query. I have three elements that control the order of posts: quartier, block and number. And it is working well.
I want to add a fourth named street. When I do so, nothing is fetched. I thought maybe there is a problem with street, but if for example I leave street but remove block, it is working again and uses street appropriately.
My conclusion is that the database only accepts a limited number of selectors per query. Is that true? Or am I missing something?
$query = "SELECT `wp_posts`.`post_title` , `wp_posts`.`ID` , `end`.`meta_value` AS `enddate` , `start`.`meta_value` as `startdate`, `quartier`.`meta_value` AS `thequartier`, `street`.`meta_value` AS `thestreet`, `number`.`meta_value` AS `thenumber`, `block`.`meta_value` AS `theblock`
        FROM `wp_posts` , `wp_postmeta` AS `end` , `wp_postmeta` AS `start` , `wp_postmeta` AS `quartier`, `wp_postmeta` AS `street`, `wp_postmeta` AS `number`, `wp_postmeta` AS `block`

        WHERE `wp_posts`.`post_type` = 'listing'

        AND `wp_posts`.`ID` = `end`.`post_id`
        AND `wp_posts`.`ID` = `start`.`post_id`
        AND `wp_posts`.`ID` = `quartier`.`post_id`
        AND `wp_posts`.`ID` = `street`.`post_id`
        AND `wp_posts`.`ID` = `block`.`post_id`
        AND `wp_posts`.`ID` = `number`.`post_id`

        AND `end`.`meta_key` = 'theend'
        AND `end`.`meta_value` >= '".time()."'

        AND `start`.`meta_key` = 'thestart'
        AND `start`.`meta_value` <= '".time()."'

        AND `quartier`.`meta_key` = 'quartier'
        AND `street`.`meta_key` = 'street'
        AND `number`.`meta_key` = 'number'
        AND `block`.`meta_key` = 'block'

        AND `wp_posts`.`post_status` = 'publish'

        GROUP BY `wp_posts`.`ID`
        ORDER BY `thequartier` + 0 ASC";
        $calendar = $wpdb->get_results($query, ARRAY_A);

        foreach ($calendar as $key => $row) {
            $thequartier[$key]  = $row['thequartier'];
            $thestreet[$key] = $row['thestreet'];
            $theblock[$key] = $row['theblock'];
            $thenumber[$key] = $row['thenumber'];
        }

        // Sort the data with volume descending, edition ascending
        array_multisort($thequartier, SORT_ASC, $theblock, SORT_ASC, $thestreet, SORT_ASC, $thenumber, SORT_ASC, $calendar);

Update: I found the solution for my problem, adding the following line to allow the excessive amount of selectors:
$wpdb->query("SET SQL_BIG_SELECTS=1");


text:
Q: Oracle - spool to CSV file, but Excel splits "$10,000" into two columns I have a command as follows:
SPOOL &&p_CSVfile

SELECT
  YEAR || ', ' ||
  TO_CHAR(AMOUNT, '$9,999,999,999.99')
FROM TABLE

SPOOL OFF

...and values in the AMOUNT field can contain commas. When this file is opened in Microsoft Excel, the AMOUNT field is treated as two separate fields if it contains a comma. Is there a simple way around this that I am not aware of, or will I have to change my delimiter?

A: A CSV wraps each comma separated value in double quotes.  Are each of your values in double quotes?  If not,
Consider: (copy and paste below to notepad save as a csv)
"This is a","test"
"This is,a","test"
10,000,500
"$10,000","500"
"And she said, ""Hello my love""","end"

Lines 1,2,4,5 only result in 2 columns.  Line 3 results in 3.  Quotes matter.

So... To resolve add begin/end " to each of your values being output (what is " chr(34)?)
SELECT chr(34) || YEAR || chr(34) ||',' ||
       chr(34) || AMOUNT ||chr(34)
FROM TABLE

if your exported string data has quotes in it... simply double them up to escape properly.

A: Wrap your value in double quotes '"' || Amount || '"'.
Full Example
SPOOL &&p_CSVfile

SELECT
  '"' || YEAR || '","' || AMOUNT || '"'
FROM TABLE

SPOOL OFF

If you don't need commas in a specific field, you can also REPLACE them, i.e. REPLACE(Amount,',','').


text:
Q: Unable to reproduce NewtonSoft deserialization error locally I'm getting following error in deserializing a json object : (Using JSON.NET)

Cannot create an abstract class.
  at System.Runtime.Serialization.FormatterServices.nativeGetUninitializedObject(RuntimeType type)
  at ReadDataSourceBaseFromJson(XmlReaderDelegator ,  XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString[] )

And exact line giving the error is:
return _serializer.ReadObject(stream); // _serializer is DataContractJsonSerializer

I can not reproduce this issue in my local machine, or in the stage machine in hosted environment. JSON is deserialized perfectly
However the issue is reproducible consistently in the QA and production environment. I've tried with

*

*QA database

*QA code in release mode, including all DLLs

*QA web configs

But still can't produce. JSON object is stored in database and I'm trying to serialize it into classes.
What else I can do to reproduce the issue?
EDIT
Code leading up to the error line is:
var json = JObject.Parse(definition);
var foo = json.GetValue("outerRoot").ToString();
var dataDefinition = _serializer.Deserialize(foo);

And Deserialize function is
public returnType Deserialize(string serializedData)
        {
            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(serializedData)))
            {
                return (returnType)_serializer.ReadObject(stream);
            }
        }

So I am using JSON.Net to strip out the outer most node and deserializing what's inside.

A: When I encounter something that only happens on PROD I will set the application to run on Local IIS instead of IIS Express.  This requires that you have IIS installed on your development machine, however this allows you to debug locally and hit the site from a remote computer to cause the error.

A: In your code where you instantiate the DataContractJsonSerializer, you will be specifying the deserializing type.
The code will look something like this:
_serializer = new DataContractJsonSerializer(typeof(MyType));

It appears that the type that you have specified for deserialization has the abstract keyword.
public abstract class MyType

In C# you can't instatiate abstract classes, only non-abstract classes, i.e. classes that inherit from them.

A: This was Framework 4.0 issue, and fixed in Framework 4.5 WCF JSON Deserialization Issues with Whitespace
Solution was to upgrade Framework. Or what dbc said in the comments


text:
Q: Choppy scrolling on new retina mac book pro My new mac has:

2.2GHz Quad-core Intel Core i7, Turbo Boost up to 3.4GHz 16GB 1600MHz DDR3L SDRAM 256GB PCIe-based Flash Storage Intel Iris Pro Graphics
  Force Touch trackpad Backlit Keyboard (English) & User's Guide
  Accessory Kit

But when I scroll this (or other pdf) in safari link
it looks not smooth when you scroll it. But my mac book MacBook Pro (13-inch, Mid 2012) has smooth scrolling.
Actually on my new retina mac if I open gmail via safari and try to scroll over 20 emails in list it also stuck when scrolling. Like it's from 1995 years computer.
So I tried it on 10 computer in apple store and all of them have the same problem when scroll link above or gmail content in safari.
Why? (


text:
Q: Compiling code directly from .cpp files works. Making object files first and then linking, results in Multiple Definition of Function Error? # Compiler
CXX      := g++
CF       := -g

# c files
CFILES   := $(wildcard src/*.cpp)
SOURCES  := $(CFILES) # $(CFILES2) all CFILES

# o files
OBJECTS  := $(SOURCES:.cpp=.o)
OBJECTS_A:= $(SOURCES:.cpp=_a.o)

# Macros
MACRO = -D
INFO = -DINFO // optional
DCDREAD = -DDCDREAD
# More Macros
DEFAULT   = -DDEFAULT
CONTACT = -DDEFAULT -DCONTACT -DCONTACTPERSIST -DTENSION_COSTHETA
MTCONTACT = -DDEFAULT -DMTCON1 -DMTCON2
DCDCON = -DDCDREAD -DCONTACT -DCONTACTPERSIST -DTENSION_COSTHETA
DCDMT = -DDCDREAD -DMTCON1 -DMTCON2
CENMOV = -DDCDREAD -DMTCON1 -DCENTROIDMOVEMENT
ANGLE = -DDCDREAD -DINERTIA -DANGLE
ANG3 = -DDCDREAD -DMTCON1 -DANGLE3CENTROID

ang3o: $(OBJECTS_A)
    $(CXX) $(OBJECTS_A) -o test/$(EXEC)_dcd_angle3centroid
    cd test && ./$(EXEC)_dcd_angle3centroid mtonly_seamup.ref.pdb      mtonly_seamup_d1_indent.dcd 1 209 1
ang3: $(OBJECTS)
    $(CXX) $(SOURCES) $(CF) $(INC) $(LIB) $(ANG3) -o   test/$(EXEC)_dcd_angle3centroid
    cd test && ./$(EXEC)_dcd_angle3centroid mtonly_seamup.ref.pdb mtonly_seamup_d1_indent.dcd 1 209 1

# To obtain object files
$(OBJECTS_A) : $(SOURCES)
    $(CXX) $(CF) $(INC) $(LIB) $(ANG3) -c $< -o $@
%.o: %.cpp
    $(CXX) $(CC_FLAGS) $(INC) $(LIB) -c $< -o $@

I know the objects are unnecessary in the ANG3 rule. The  c files are compiled directly, the executable runs correctly! I'd like to switch to objects, an ANG3O rule.  HERE is my main question, am I trying to link .o files incorrectly at the end of the ANG3O rule?
ANG3 works.
ANG3O fails. Multiple Definitions of Function Error.
make ang3
g++ -g -O3 -Iinclude -pthread -c src/readfile.cpp -o src/readfile.o

g++ -g -O3 -Iinclude -pthread -c src/main.cpp -o src/main.o

g++ -g -O3 -Iinclude -pthread -c src/md.cpp -o src/md.o
g++ -g -O3 -Iinclude -pthread -c src/chain.cpp -o src/chain.o
g++ src/readfile.cpp src/main.cpp src/md.cpp src/chain.cpp  -g -Iinclude -pthread -DDCDREAD -DMTCON1 -DANGLE3CENTROID -o test/run_segment_dcd_angle3centroid

make ang3o
g++ -g -Iinclude -pthread -DDCDREAD -DMTCON1 -DANGLE3CENTROID -c     src/readfile.cpp -o src/readfile_a.o
g++ -g -Iinclude -pthread -DDCDREAD -DMTCON1 -DANGLE3CENTROID -c src/readfile.cpp -o src/main_a.o
g++ -g -Iinclude -pthread -DDCDREAD -DMTCON1 -DANGLE3CENTROID -c src/readfile.cpp -o src/md_a.o
g++ -g -Iinclude -pthread -DDCDREAD -DMTCON1 -DANGLE3CENTROID -c src/readfile.cpp -o src/chain_a.o
g++ src/readfile_a.o src/main_a.o src/md_a.o src/chain_a.o -o test/run_segment_dcd_angle3centroid

src/main_a.o: In function `ReadLines(Chain*)':
/home/d/sop_dev/contacts/segment/src/readfile.cpp:43: multiple     definition of `ReadLines(Chain*)'
                src/readfile_a.o:/home/d/sop_dev/contacts/segment/src/readfile.cpp:43:     first defined here
src/main_a.o: In function `ReadMolecularContent(char*)':
/home/d/sop_dev/contacts/segment/src/readfile.cpp:208: multiple     definition of `ReadMolecularContent(char*)'
        src/readfile_a.o:/home/d/sop_dev/contacts/segment/src/readfile.cpp:208:    first defined here
src/md_a.o: In function `ReadLines(Chain*)':
/home/d/sop_dev/contacts/segment/src/readfile.cpp:43: multiple     definition of `ReadLines(Chain*)'
    src/readfile_a.o:/home/d/sop_dev/contacts/segment/src/readfile.cpp:43:     first defined here
src/md_a.o: In function `ReadMolecularContent(char*)':
/home/d/sop_dev/contacts/segment/src/readfile.cpp:208: multiple     definition of `ReadMolecularContent(char*)'
    src/readfile_a.o:/home/d/sop_dev/contacts/segment/src/readfile.cpp:208:    first defined here
src/chain_a.o: In function `ReadLines(Chain*)':
/home/d/sop_dev/contacts/segment/src/readfile.cpp:43: multiple     definition of `ReadLines(Chain*)'
        src/readfile_a.o:/home/d/sop_dev/contacts/segment/src/readfile.cpp:43:     first defined here
src/chain_a.o: In function `ReadMolecularContent(char*)':
/home/d/sop_dev/contacts/segment/src/readfile.cpp:208: multiple     definition of `ReadMolecularContent(char*)'
    src/readfile_a.o:/home/d/sop_dev/contacts/segment/src/readfile.cpp:208:    first defined here
/usr/lib/gcc/x86_64-unknown-linux-gnu/5.2.0/../../../../lib/crt1.o: In     function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
Makefile:172: recipe for target 'ang3o' failed
make: *** [ang3o] Error 1

NOTES:
Related question: Error with multiple definitions of function
Possibly related: One definition rule and different class definitions in two translation units
However, in my situation:
the headers are in the include directory. The c files are in a src directory. All functions are declared in the headers. Only headers are included, no c/cpp files. Makefile examples seem to halt just before this level of complexity, the use of different define segments of code, and the need to compile objects with/without certain defined sections.

A: It helps to actually read the output.
g++ -g -Iinclude -pthread -DDCDREAD -DMTCON1 -DANGLE3CENTROID -c src/readfile.cpp -o src/readfile_a.o
g++ -g -Iinclude -pthread -DDCDREAD -DMTCON1 -DANGLE3CENTROID -c src/readfile.cpp -o src/main_a.o
g++ -g -Iinclude -pthread -DDCDREAD -DMTCON1 -DANGLE3CENTROID -c src/readfile.cpp -o src/md_a.o
g++ -g -Iinclude -pthread -DDCDREAD -DMTCON1 -DANGLE3CENTROID -c src/readfile.cpp -o src/chain_a.o

You're compiling the same C++ source file over and over again, then linking it to itself.
Your mistake is in the recipe to build objects. I'll leave you to read the documentation and find out why.


text:
Q: Changing the layer shape for CPTPlotSpaceAnnotation? I want to add a widget to my graph that a user can click and drag. I've managed to do this using CPTPlotSpaceAnnonation (because I also want it to also scroll with the data) and CPTBorderedLayer. The basic functionality works and now I want to improve the look of the widget. So far it's just a green circle.
The follow code generates the circle below, notice how the shadow is clipped to the rect of the layer and the border follows the layer and not the circle,

How can I stroke the circle and not the layer? I guess I can avoid clipping by making the frame of the layer larger. Is possible to use CAShapeLayer class with the Core Plot annotations? This would be an easy way of drawing the widgets.
// Add a circular annotation to graph with fill and shadow
annotation = [[CPTPlotSpaceAnnotation alloc]
                  initWithPlotSpace:graph.defaultPlotSpace
                    anchorPlotPoint:anchorPoint];

// Choosing line styles and fill for the widget
NSRect frame = NSMakeRect(0, 0, 50.0, 50.0);
CPTBorderedLayer *borderedLayer = [[CPTBorderedLayer alloc] initWithFrame:frame];

// Circular shape with green fill
CGPathRef outerPath = CGPathCreateWithEllipseInRect(frame, NULL);
borderedLayer.outerBorderPath = outerPath;
CPTFill *fill = [CPTFill fillWithColor:[CPTColor greenColor]];
borderedLayer.fill = fill;

// Basic shadow
CPTMutableShadow *shadow = [CPTMutableShadow shadow];
shadow.shadowOffset = CGSizeMake(0.0, 0.0);
shadow.shadowBlurRadius = 6.0;
shadow.shadowColor = [[CPTColor blackColor] colorWithAlphaComponent:1.0];
borderedLayer.shadow = shadow;

// Add to graph
annotation.contentLayer = borderedLayer;
annotation.contentLayer.opacity = 1.0;
[graph addAnnotation:annotation];

A: Don't set the border paths of the layer. Instead, just set the cornerRadius to half the width of the frame.
borderedLayer.cornerRadius = frame.size.width * 0.5;


text:
Q: Starcraft 2 -- DirectX 10 effects? I seem to recall rumors that Starcraft 2 looked better when using DirectX 10 over DirectX 9. Is this true, and if so can you give examples (preferably in screenshot form)?

A: So I think that this seems to be an appropriate discussion to the site, until you actually know the answer.  The answer itself actually has nothing to do with gaming and is more appropriate for Game-Dev or SO than here. Unfortunately, I don't think I can convince you that this question is inappropriate without first giving the answer.
DirectX10 has a demonstrably noticeable effect on Starcraft 2, unfortunately its not the sort of thing I can show you in a screenshot.
Starcraft 2 is one of the few games to have Pixel Shader 2.0 as a minimum requirement.  For those of you unaware of what a Pixel Shader is, it is a programmable piece of the graphics pipeline that allows developer code to run on the GPU.  These Pixel Shaders are usually used for such buzz words as: Phong Shading, Bump Mapping, Volumetric Shadows... but they're actually a lot more basic than that as they're actually your fragment rasterizers (OpenGL even calls these Fragment Shaders).

Now you may be thinking:
Wait a sec, Pixel Shader 2.0 debut on DirectX 9, not 10.  So why are we talking about it?
Since Stacraft requires Pixel Shader 2.0, more advanced effects provided in Pixel Shader 3.0 and 4.0 (DirectX 9c and 10 respectively) have to be reconstructed in Pixel Shader 2.0 and as a result have much poorer performance time (ie. slower) and will set back your frame rate.  By comparison these artifacts provided in Pixel Shader 4.0 will run smoother.  However, if you provide Pixel Shader 2.0 code to run on a Pixel Shader 4.0 you will actually see a decrease in performance as compared to native code.
So what does this mean for me as a Gamer?
Nothing.  If you were a game developer or a graphics programmer this is a really interesting conversation about trade offs in performance as compared to user base, and how trying to satisfy everyone you can end up with a poorer overall product; but you don't care about any of that because this is a gaming website.  Much the way a programmer doesn't care about trade offs in Monitors, he only cares about which one he's running on.
We've been kind of lax on the nature of questions we let into this site, and I think this really shows it.  However, that is a topic more appropriate for Meta so I won't discuss it here.

A: As far as I know, StarCraft II quality is not increased by using DirectX 10 as opposed to DirectX 9. I think XP users can crank up all settings to ultra as well.
I've found this teamliquid thread and this overclock.net thread that both mention the game is only a DX9 game.
Maybe the reason for that rumor is a Blizzard FAQ from 2007 (emphasis mine):

Will StarCraft II take advantage of DirectX 10? What other graphical goodies are included?
The game will be compatible with DirectX 10, and we're still considering whether there will be exclusive DirectX 10 graphic effects, but the graphics engine will also be very scalable to ensure that a wide range of different systems will be capable of running StarCraft II. The new engine is also capable of rendering very large units, as well as large numbers of units on screen together. Havok physics have been integrated into the engine for added realism as well.

The official recommended system requirements, by the way, implicitly say DX10 is needed:

PC Recommended Specifications:

*

*Windows Vista®/Windows® 7 <-- these OSes come with dx 10

*Dual Core 2.4Ghz Processor

*2 GB RAM

*512 MB NVIDIA® GeForce® 8800 GTX or ATI Radeon® HD 3870 or better <-- these cards support dx 10


text:
Q: Use the regular expression feature of Oracle to find all movies whose titles include three or more words What code should I use to only show titles with three or more words.
So far I have used
SELECT  title
FROM movie
WHERE REGEXP_LIKE (title, '\s+( )')

or would this code work? So far it has but is there another way?
SELECT  title
FROM movie
WHERE REGEXP_LIKE (title, '(\s[A-Z]*){2}')

A: Don't use regex! Instead return movies whose name has at least 2 spaces:
SELECT  title
FROM movie
WHERE title LIKE '% % %'

A: Depending on what you mean by a word, use
WHERE REGEXP_LIKE (title, '\S+(\s+\S+){2}')

Or,
WHERE REGEXP_LIKE (title, '\w+(\W+\w+){2}')

Or,
WHERE REGEXP_LIKE (title, '[[:alpha:]]+(\s+[[:alpha:]]+){2}')

Where:

*

*\S+  - word is non-whitespaces

*\w+ - word contains letters, digits and underscores

*\s+ - whitespaces

*[[:alpha:]]+ -  word contains letters

*{2} - two repetitions.


text:
Q: Allow console application to access Windows Authenticated web app I have a MVC web application which uses Windows Authentication. So we do things like System.Web.HttpContext.Current.User.Identity.Name
Now there is a console app I'm writing that would be run as part of a batch job. All this console app needs to do is call an ActionResult in the main web app which would then carry out some maintenance tasks.
Now, since the console app doesn't have an identity within the domain controller/Active Directory, the call using System.Net.WebClient().DownloadString() keeps throwing a 401 error.
My question is, is there a way to allow this application to call this link in the main web app without having to disable WindowsAuthentication in the web.config/IIS?
Any ideas/suggestions welcome.
All the console app contains is
static void Main(string[] args)
        {
            try
            {
                new System.Net.WebClient().DownloadString(System.Configuration.ConfigurationSettings.AppSettings["http://foo.com/"]);
            }
            catch
            {

            }
        }

A: Use UseDefaultCredentials:
        var client = new WebClient
                     {
                         UseDefaultCredentials = true
                     };
        client.DownloadString(address);

this will use whatever the console app is running as (which can be specified on the Scheduled Task settings).


text:
Q: Maximize flow through a multigraph, where edges can be added subject to restrictions I'm doing a course in algorithms and I'm stuck on this problem.
Given a set of vertices on a grid. Every vertex has a coordinate (x,y).
An source and a sink has been given.
From every vertex there can only be drawn 4 types of edges.
O1: The edge can be drawn from v1 to v2 if v1.x=v2.x or v1.y==v1.y.
O2: The edge can be drawn from v1 to v2 if the euclidean distance between v1 and v2 is the largest possible.
O3: The edge can be drawn from v1 to v2 if there's at least 2 vertices on the line segment between v1 and v2.
O4: The edge can be drawn from v1 to the sink.
Every vertex has a maximum number for each edge type that can be drawn from it.
Input example for one vertex:
0,1,4,0,2,0 - Is the vertex at coordinate 0,1 where the maximum number of type O1 edges that can be drawn is 4, type O2 is 0, type O3 is 2 and type O4 is 0.
The problem is to find the maximum flow of the graph.
My approach is that if I'm able to generate a weighted directed graph, I can apply Ford-Fulkerson and get the result.
I'm able to generate the graph with all possible edges, but I have no idea how to figure out which edges should be drawn to ensure maximum flow (the restriction on the number of edge types from a given vertex is what trips me up).
I assume that every edge have weight 1, in the resulting multigraph, thus making the maximum flow problem well defined.
Example:
0 1 4 0 2 0
2 2 1 2 3 4
4 1 3 1 1 0
4 3 1 0 0 1
6 4 0 0 1 1
9 1 1 0 0 2
9 4 2 0 0 1
9 3 0 0 0 0

Possible edges:

Drawn solution:

I know the answer to this instance of the problem is 5.

A: Nevermind my previous answer, think I got it:
Start with the complete graph
Re-write each node into five nodes, one input and then one output of each type
Add nodes from the input node to each output node depending on how many edges of that type the original node was allowed to have
Calculate max flow on the translated graph
So if in your original graph you had a node n with n.O1_out outgoing neighbors, n.01_limit limit, n.O2_out, n.O2_limit, etc, you'll translate that into:

*

*An input node n_input such that all nodes that previously had edges to n now have edges to n_input

*An output node n_O1_output such that n_O1_output has edges to all nodes previously in n.O1_out (repeat for O2, etc)

*n.O1_limit edges (or one edge with n.O1_limit weight) going from n_input to n_O1_output (repeat for O2, etc)

Sorry, this is a pain to describe clearly, but does that make sense?


text:
Q: Laravel 4 unable to join on multiple conditions using ->on( ) more than once In a nutshell I am trying to do a join with more than one condition.  We are using legacy Laravel 4, and the actual class I've tracked it to is Illuminate\Database\Query\Builder.  Here is what I am adding:
->leftJoin('node_fields AS visible_for_categories', function($join){
    $join->on('nv2.id',  '=', 'visible_for_categories.node_version_id');
    $join->on('visible_for_categories.name', '=', 'visible_for_categories');
})

It works fine with the first $join->on( ) call, but the page fails if the second on is called.  why is this and what is the proper way to do this in Laravel 4?

A: The way that worked for me on the above query is as follows:
->leftJoin('node_fields AS visible_for_categories', function($join){
    $join->on('nv2.id',  '=', 'visible_for_categories.node_version_id');
    $join->on('visible_for_categories.name', '=', DB::raw("'visible_for_categories'"));
})

The query builder will assume all three values in the on() function are fields, not strings, and will parse out the . period as well.
The general assumption is that JOINS will have the relational field joins to create structure, and the WHERE conditionals will provide the desired filter.  However anyone who's worked esp. with LEFT or RIGHT joins knows this is not always possible.
Be careful for SQL injection using DB::raw but in this case, an EAV table, we're dealing with a fixed string, not a variable.

A: Try
->leftJoin('node_fields AS visible_for_categories', function($join){
    $join->on('nv2.id',  '=', 'visible_for_categories.node_version_id')
    ->on('visible_for_categories.name', '=', 'visible_for_categories');
})


text: Q: Oracle Apex 20.2 (IR): How I can get selected row(s) and process its data through a function please somebody guide how to process selected row(s) from Interactive Report to execute a function one-by-one which return success/failure result (like update select employee's information etc.)


text:
Q: Why is the response empty when retrieving Github commit info with GraphQL (API V4)? with GraphQL API v4, I want to fetch commit infos (such as committer, committedDate ) on a file under designated release tag. But unfortunately, below script, I always get blank result with no errors. Nowadays, github cannot get commit info via GraphQL?
{'query': 'query($org_name: String!, $resp_name: String!){
             repository(owner: $org_name name: $resp_name){
                    object(expression: "bgi4004-ios-v1.0:proj.ios_mac/AppConfig.plist"){
                                                                                ... on Commit{
                                                                                committer{
                                                                                date
                                                                                user{
                                                                                name
                                                                                }
                                                                                }
                                                                                }
                                                                                id
                                                                                }
                                                                                }
                                                          }
                                                     }',
 'variables': {"org_name": "gz-project",
           "resp_name": "bgi4004-unity-cs"}'
}

Response:
{u'data': {u'repository': {u'object': {}}}}

Reference
https://developer.github.com/enterprise/2.13/v4/object/repository/


text:
Q: ServiceStack Validator - Request not injected I have a validator and I'm trying to use some session variables as part of the validation logic, however the base.Request is always coming back as NULL. I've added it in the lambda function as directed and also the documentation for Validation seems to be out of date as the tip in the Fluent validation for request dtos section mentions to use IRequiresHttpRequest, but the AbstractValidator class already implements IRequiresRequest.
This is my code:
public class UpdateContact : IReturn<UpdateContactResponse>
{
    public Guid Id { get; set; }

    public string Reference { get; set; }

    public string Notes { get; set; }

    public List<Accounts> Accounts { get; set; }
}

public class UpdateContactResponse : ResponseBase
{
    public Guid ContactId { get; set; }
}

public class UpdateContactValidator : AbstractValidator<UpdateContact>
{
    public UpdateContactValidator(IValidator<AccountDetail> accountDetailValidator)
    {
        RuleSet(ApplyTo.Post | ApplyTo.Put, () => {
            var session = base.Request.GetSession() as CustomAuthSession;
            RuleFor(c => c.Reference).Must(x => !string.IsNullOrEmpty(x) && session.Region.GetCountry() == RegionCodes.AU);
        });

        RuleFor(R => R.Accounts).SetCollectionValidator(accountDetailValidator);
    }
}

Is there something I'm missing?

A: Access to injected dependencies can only be done from within a RuleFor() lambda, delegates in a RuleSet() are executed on constructor initialization to setup the rules for that RuleSet.
So you need to change your access to base.Request to within RuleFor() lambda:
RuleSet(ApplyTo.Post | ApplyTo.Put, () => {
  RuleFor(c => c.Reference)
    .Must(x => !string.IsNullOrEmpty(x) &&
    (Request.GetSession() as CustomAuthSession).Region.GetCountry() == RegionCodes.AU);
});


text:
Q: DNS Server replication created duplicate A-Records I have a several Windows Server 2008 R2 DC/DNS servers locally, RODC's at the remote office, and a Windows Server 2012 DC/DNS server on Azure with a VPN tunnel established.
Earlier today I moved a webserver, changed the DNS records on one of the local DNS servers, and updated at the registrar. Everything worked as expected.
Then weird issues started popping up, some people being directed to the wrong server, others to the correct one.
After troubleshooting, I checked the local DNS server again and the records were still correct, until I hit refresh, and the old A-Records popped up in conjunction with the new ones.
The way these records are set up, is a forward lookup zone with one static A record using the parent domain for each zone.
So there ended up being two A-Records with different IP's for the URL's that I had changed earlier in the day, and the old records showed back up in DNS manager when I refreshed the screen. (I had checked several times previously without refreshing)
Fortunately this only affected internal users and not all of them at that, all external users were unaffected because the public DNS records are published through a registrar (GoDaddy, independent so unrelated).
What happened? And how can I prevent this from happening again?

A: Nope, that's not what happened. Assuming you're talking about AD Integrated zones, DNS records are objects in AD. Objects have a USN which is essentially a number that increments whenever a change to that object is made. If your tunnel "blipped" the USN would be incremented on your on-prem DCs and not on your Azure-hosted DC. This means that when it came back online, it would see that it had an older copy of the record and update inbound. It wouldn't replicate the old record outbound.
As to why it happened, it's really next to impossible to say without getting deep into your environment.

A: Since the old records reappeared in Windows DNS, one of two things are likely to be happening.
It's possible that AD auto-registration put the "old" records back once they were missing.  Machines will register all their addresses unless you disable it in the network adapter properties.
If not that, you have some kind of strange replication problem.  Replication in this way happens with other AD data, typically, so you can use repadmin to validate.  However, simple connectivity problems shouldn't cause this, because every record has a serial and attempts to replicate old records overtop new ones are ignored.
AD replication problems are by far the less likely scenario.


text:
Q: Get selected records in Crystal Reports from SQL Tables This might be a very small question for SQL and Crystal Experts.
For e.g. I have a Table of Names
ID    Name
1     John Smith
2     Boris Berker
3     Alex Mathew
4     John Abraham
5     Melisa Estate
6     Willam Schweizer

Now in crystal report I just want to display lets say ID-1,4 and 6.
How can I do it. I will get the final IDs to display in C# List. But then how to pass it as parameter to crystal reports.
I use selection formula of crystal reports.
{Name.ID}={ID}

where {Name.ID} is SQL Column and {ID} is crystal report parameter, but then it would display all the records. Is there a way such that I can pass my list to ID parameter of crystal reports.
I hope I am clear.
Thank you in advance

A: First of all in your Crystal Report you will need to amend your parameter to accept multiple values:

In your Selection Expert you need to use a formula and have the following:
{OBJECTNAME.COLUMN_NAME} = {?ID}
Then in your C# code you will need to iterate through the C# List and add each value to the Crystal Report parameter using AddCurrentValue


text:
Q: Azure traffic direction explanation I am really not clear what outbound(egress) and inbound(ingress) traffic means. I have two theories

*

*inbound just specifies that the origin is outside and target inside i.e. HTTP round trip to some VM hosted web is ingress, the response with HTTP 200 status goes the same established route back

*inbound is anything from internet and outbound is anything to internet. So HTTP roundtrip to azure VM is ingress and also egress (HTTP response), both of which can have different route(in case of asymmetric routing.
My question is if the VM does not have route back to internet, will it serve properly the HTTP or the response cannot reach the originator in internet?

A:
Inbound traffic originates from outside the network, while outbound
traffic originates inside the network.

My question is if the VM does not have route back to internet, will it serve properly the HTTP or the response cannot reach the originator in internet?
Assuming you have a web server running on it, you just need to configure on firewall rules to enable inbound / outbound traffic for port 80 and 443


text:
Q: Make Columns Rows in SQL I want to do a query in mysql on a table that has over 60 columns and list those columns vertically, so their values run horizontally.  Kind of like describe table, but have a couple rows listed after each column instead of the column's description.  The table I have has cryptic 4 letter column names and it's too hard to understand them through describe table and regular querying.  I want to describe table and get a couple row values after them.  Essentially just rotating the whole table 90 degrees counter-clockwise.
I've searched around and can't find a simple way to do this.
-- basically, this would do:
SELECT * FROM BIG_TABLE LIMIT 2 ROTATE_LEFT 90;

COLUMN 1 | VALUE_1 | VALUE_2
COLUMN 2 | VALUE_1 | VALUE_2
COLUMN 3 | VALUE_1 | VALUE_2
COLUMN 4 | VALUE_1 | VALUE_2
COLUMN 5 | VALUE_1 | VALUE_2
COLUMN 6 | VALUE_1 | VALUE_2
COLUMN 7 | VALUE_1 | VALUE_2
COLUMN 8 | VALUE_1 | VALUE_2

-- instead of the normal:
SELECT * FROM BIG_TABLE LIMIT 2;

COLUMN 1 | COLUMN 2 | COLUMN 3 | COLUMN 4 | COLUMN 5 | COLUMN 6 ....
VALUE_1  | VALUE_1  | VALUE_1  | VALUE_1  | VALUE_1  | VALUE_1  ....
VALUE_2  | VALUE_2  | VALUE_2  | VALUE_2  | VALUE_2  | VALUE_2  ....

A: Assuming the datatypes of all sixty columns are compatible, we could do something like this.
 SELECT c.colname

      , CASE c.colname
        WHEN 'c1' THEN v1.`c1`
        WHEN 'c2' THEN v1.`c2`
        WHEN 'c3' THEN v1.`c3`
        WHEN 'c4' THEN v1.`c4`
        WHEN 'c5' THEN v1.`c5`
        ...
        END AS `value 1`

      , CASE c.colname
        WHEN 'c1' THEN v2.`c1`
        WHEN 'c2' THEN v2.`c2`
        WHEN 'c3' THEN v2.`c3`
        WHEN 'c4' THEN v2.`c4`
        WHEN 'c5' THEN v2.`c5`
        ...
        END AS `value 2`

   FROM ( SELECT 1 AS seq, 'c1' AS colname
          UNION ALL SELECT 2, 'c2'
          UNION ALL SELECT 3, 'c3'
          UNION ALL SELECT 4, 'c4'
          UNION ALL SELECT 5, 'c5'
          ...
         ) c
  CROSS
   JOIN ( SELECT * FROM BIG_TABLE ORDER BY ... LIMIT 0,1 ) v1
  CROSS
   JOIN ( SELECT * FROM BIG_TABLE ORDER BY ... LIMIT 1,1 ) v2
  ORDER
     BY c.seq

Note that the column names (c1, c2, c3) need to be hardcoded, along with the order they should be returned.
If we need the column names to be dynamic, we would need a separate SQL statement to retrieve the list of column names (information_schema.columns), and then use the info retrieved to dynamically build a statement, like the one above.


text:
Q: Selenium WebDriver - Java : How to write webtable data into an excel file in Selenium WebDriver using Java? :) I am trying to write the web table data into an excel file using Selenium-WebDriver with Java. By the below code I was able to print only the last column data in the excel but not the entire webtable data. Could you please help me out here.....
import java.util.*;
import java.lang.*;
import  java.io.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class WebTableTOSpreedsheet
{
public static void main(String[] args) throws IOException
{
System.out.println("Hello Dear.....");
System.out.println();

WebDriver wb = new FirefoxDriver();
wb.navigate().to("http://www.w3schools.com/html/html_tables.asp");
wb.manage().window().maximize();
System.out.println(wb.getTitle() +" - WebPage has been launched");

List<WebElement> irows =   wb.findElements(By.xpath("//*[@id='main']/table[1]/tbody/tr"));
int iRowsCount = irows.size();
List<WebElement> icols =   wb.findElements(By.xpath("//*[@id='main']/table[1]/tbody/tr[1]/th"));
int iColsCount = icols.size();
System.out.println("Selected web table has " +iRowsCount+ " Rows and " +iColsCount+ " Columns");
System.out.println();

FileOutputStream fos = new FileOutputStream("D://Software//AutomationPractise//WebTableTOSpreedsheet.xlsx");

XSSFWorkbook wkb = new XSSFWorkbook();
XSSFSheet sheet1 = wkb.createSheet("DataStorage");

for (int i=1;i<=iRowsCount;i++)
{
for (int j=1; j<=iColsCount;j++)
{
if (i==1)
{
WebElement val= wb.findElement(By.xpath("//*[@id='main']/table[1]/tbody/tr["+i+"]/th["+j+"]"));
String  a = val.getText();
System.out.print(a);

XSSFRow excelRow = sheet1.createRow(i);
XSSFCell excelCell = excelRow.createCell(j);
excelCell.setCellType(XSSFCell.CELL_TYPE_STRING);
excelCell.setCellValue(a);

//wkb.write(fos);
}
else
{
WebElement val= wb.findElement(By.xpath("//*[@id='main']/table[1]/tbody/tr["+i+"]/td["+j+"]"));
String a = val.getText();
System.out.print(a);

XSSFRow excelRow = sheet1.createRow(i);
XSSFCell excelCell = excelRow.createCell(j);
excelCell.setCellType(XSSFCell.CELL_TYPE_STRING);
excelCell.setCellValue(a);

//wkb.write(fos);
}
}
System.out.println();
}
fos.flush();
wkb.write(fos);
fos.close();
}
}

Output:Webtable's data write issue in excel

A: You are creating new empty row for each cell in for (int j=1; j<=iColsCount;j++) loop. Move XSSFRow excelRow = sheet1.createRow(i); to loop iterating over i.
    for (int i = 1; i <= iRowsCount; i++) {
        XSSFRow excelRow = sheet1.createRow(i);
        for (int j = 1; j <= iColsCount; j++) {

For others, I had to add this to my code to execute properly:
    System.setProperty("webdriver.firefox.bin", "C:\\path\\to\\Mozilla Firefox\\firefox.exe");


text:
Q: For a group G, find all x such that $x^2=x$ Let G be a group.
Find all solutions x in G to the equation x^2 = x.
I do not understand where I need to start in solving the problem.

A: \begin{array}
\ x^2=x &\implies x^2 x^{-1} = xx^{-1} \\
&\implies x(xx^{-1})=e \\
&\implies xe=e \\
&\implies x = e
\end{array}
We used the fact that since $G$ is a group then $\forall x \in G$ there exists an element $x^{-1}\in G$ such that $xx^{-1}=e$, the property concerning identies, and that $G$ is associative. So all the properties!


text:
Q: Nice formatting for the results of a dice game simulation One of my Mathematica interests is in problems related to the formatting of  output. Getting nice formatting from Mathematica is often frustrating, but occasionally Mathematica will delight me by making a formatting task, which I anticipated would be difficult, easy. I want to share one such recent experience by posing it as a question.

Can you create a 10-row, 5-column table in Mathematica  presenting the results from running a dice game simulation in which a pair of dice is rolled 50 times?

The table should look like this:

Your solution may show a different sequence of dice rolls. Note that rolls of seven are highlighted in red. That feature must be reproduced.
I post this question, not because it is difficult (it isn't), but because I had fun with it myself. I will post my answer in 48 hours, providing nobody posts an equivalent answer beforehand.

A: When I posted this question, I said I wouldn't post my answer if someone else posted an equivalent one, but here I am doing it. Am I going back on my word?. The answer given by ssch is close enough to mine to qualify as equivalent for all practical purposes. However, although both our answers are based on the same insight: that no graphics are needed because the job can be done with Unicode text characters, I think the two implementations differ enough to justify showing my code.
My implementation is based on a styling function, which takes a pair of integers representing the dice roll and an integer giving the font size. It returns a Style expression that packages everything up nicely, all ready for the grid.
With[{faceZero = 16^^267f},
  diceStyle[{dots1_, dots2_}, fontSize_] :=
    Style[
      FromCharacterCode[faceZero + dots1] <> " " <> FromCharacterCode[faceZero + dots2],
      If[dots1 + dots2 == 7, Red, Black],
      fontSize]]

A little unit testing is always in order.
diceStyle[#, 36] & /@ {{1, 1}, {3, 4}} // FullForm

List[Style["\:2680 \:2680", GrayLevel[0], 36],
     Style["\:2682 \:2683", RGBColor[1, 0, 0], 36]]

Given this special styling for integer pairs, the grid I showed in my question can be generated quite concisely.
SeedRandom @ 1;
Grid[Table[diceStyle[RandomInteger[{1, 6}, 2], 36], {10}, {5}],
  Dividers -> All, Spacings -> {Automatic, {{.75}}}]

A: The power of Mathematica's syntax allows us to create dice in several different ways. Here's one way that I like:
dice[n_Integer] := dice[n, Black]
Format[dice[n_Integer, c_]] := With[{
    dots = {1 -> {5}, 2 -> {3, 7}, 3 -> {3, 5, 7}, 4 -> {1, 3, 7, 9},
            5 -> {1, 3, 5, 7, 9}, 6 -> {1, 2, 3, 7, 8, 9}} /.
            l : {__Integer} :> Sequence @@ Thread[l -> Graphics[{c, Disk[]}, ImageSize -> 16]],
    face = Partition[Range@9, 3]},

    Panel[Grid[face /. {n /. dots, _Integer -> Null}, ItemSize -> All]]
]

This gives a pretty nice looking set of die faces (since the display is entirely 2D, I didn't think it was worth the effort to construct a 3D die):
dice /@ Range@6 // Row

By keeping dice symbolic and only modifying the display via Format, we can utilize the structure for the kind of modifications you had in mind (e.g. coloring total 7 with red).
With this basic structure, the 50 rolls of a pair of dice can be simulated concisely as:
With[{trials = RandomInteger[{1, 6}, {10, 5, 2}]},
    Grid[trials /. l : {__Integer} :> Row[dice /@ l], Frame -> All]
] /. l : {dice[n_, _], dice[m_, _]} /; m + n == 7 :> (l /. Black -> Red)

A: We have unicode support so we can use the following strings: {"⚀", "⚁", "⚂", "⚃", "⚄", "⚅"}:
dice = FromCharacterCode /@ Range[9856, 9856 + 5];
Grid[Partition[RandomInteger[{1, 6}, {50, 2}], 5] /. {
   i : {__Integer} :> Style[
     Row[dice[[i]], Spacer[1]],
     {Large, Total[i] /. {7 -> Red, _ -> Black}}]}
 , Frame -> All]

A: After importing a free dice 3D model
{pd, vd} = Import["c:\\dice.stl", #] & /@ {"PolygonData", "VertexData"};
g2 = Translate[GraphicsComplex[vd, Polygon /@ pd], {-10, -37.5, -10}];
rv = {{0, 0, -1}, {0, -1, 0}, {0, 0, 1}, {0, 1, 0}, {-1, 0, 0}, {1, 0, 0}};
dice[x_List, n_Integer] :=
     Rasterize@(Graphics3D[{EdgeForm[None], Blue, Rotate[g2,{{0, 0, 1}, rv[[x]][[n]]}]},
                            Boxed -> False]/. Blue :> Red /; Tr@x == 7)
ri = RandomInteger[{1, 6}, {50, 2}];
GraphicsGrid[Partition[GraphicsRow[{dice[#,1], dice[#,2]}] & /@ ri, 5],
             Frame->All, ImageSize -> 700]

A: Here's one way, borrowing heavily from one of the Wolfram demonstrations.
dicelist[rb_] := {{rb, Disk[{0, 0}, 0.2]}, {rb, Disk[{0.6, 0.6}, 0.2], Disk[{-0.6, -0.6}, 0.2]}, {rb, Disk[{0, 0}, 0.2], Disk[{0.6, 0.6}, 0.2], Disk[{-0.6, -0.6}, 0.2]}, {rb, Disk[{0.6, 0.6}, 0.2], Disk[{-0.6, -0.6}, 0.2], Disk[{0.6, -0.6}, 0.2], Disk[{-0.6, 0.6}, 0.2]}, {rb, Disk[{0, 0}, 0.2], Disk[{0.6, 0.6}, 0.2], Disk[{-0.6, -0.6}, 0.2], Disk[{0.6, -0.6}, 0.2], Disk[{-0.6, 0.6}, 0.2]}, {rb, Disk[{-0.6, 0}, 0.2], Disk[{0.6, 0}, 0.2], Disk[{0.6, 0.6}, 0.2], Disk[{-0.6, -0.6}, 0.2], Disk[{0.6, -0.6}, 0.2], Disk[{-0.6, 0.6}, 0.2]}};
dice[i_, col_] := Graphics[{{White, EdgeForm[Directive[col, Thickness[0.02]]], Rectangle[{-1, -1}, {1, 1}]}, If[MemberQ[Range[1, 6], i], Part[dicelist[col], i], {}]}, ImageSize -> 50];

pair := (roll = RandomInteger[{1, 6}, 2];
  If[Total[roll] == 7, col = Red, col = Black]; dice[#, col] & /@ roll)

For example, simply typing pair creates a pair of dice that are red if the sum is seven and black otherwise. These can be put into a table:
GraphicsColumn[Table[GraphicsRow[ Flatten[{pair, , pair, , pair, , pair, , pair}]],{i,10}]]

A: Using the same (well slightly modified) Wolfram demonstrations code as bill s
dicelist = {{Disk[{0, 0}, 0.2]}, {Disk[{0.6, 0.6}, 0.2],
    Disk[{-0.6, -0.6}, 0.2]}, {Disk[{0, 0}, 0.2],
    Disk[{0.6, 0.6}, 0.2],
    Disk[{-0.6, -0.6}, 0.2]}, {Disk[{0.6, 0.6}, 0.2],
    Disk[{-0.6, -0.6}, 0.2], Disk[{0.6, -0.6}, 0.2],
    Disk[{-0.6, 0.6}, 0.2]}, {Disk[{0, 0}, 0.2],
    Disk[{0.6, 0.6}, 0.2], Disk[{-0.6, -0.6}, 0.2],
    Disk[{0.6, -0.6}, 0.2],
    Disk[{-0.6, 0.6}, 0.2]}, {Disk[{-0.6, 0}, 0.2],
    Disk[{0.6, 0}, 0.2], Disk[{0.6, 0.6}, 0.2],
    Disk[{-0.6, -0.6}, 0.2], Disk[{0.6, -0.6}, 0.2],
    Disk[{-0.6, 0.6}, 0.2]}};

Dice[i_, colour_] :=
  Graphics[{{White, EdgeForm[Directive[colour, AbsoluteThickness[2]]],
      Rectangle[{-1, -1}, {1, 1}]}, colour, Part[dicelist, i]},
   ImageSize -> 25];

I then create the dice rolls:
tmp = Fold[Partition[#1, #2] &, RandomChoice[Range[6], 100], {2, 5}]

and display them in a way that has each dice "aligned" left and right within a grid element with the space between the dice much larger than the spacing between the grid elements (as per picture in the question):
Grid[
 Map[If[Total[#] == 7,
    Row[{Dice[#[[1]], Red], Dice[#[[2]], Red]}, Spacer[15]],
    Row[{Dice[#[[1]], Black], Dice[#[[2]], Black]}, Spacer[15]]] &,
  tmp, {2}],
 Frame -> All,
 FrameStyle -> AbsoluteThickness[2],
 Spacings -> {1, 1}]

Possible tweeks include adjusting the divider thickness in the grid and the Row spacer. Personally I prefer thinner lines and frames around the dice but am trying to match the example in the question. This is with AbsoluteThickness[0.5]

A: Another dice:
dots = {{{2, 2}}, {{0.85`, 0.85`}, {3.15`, 3.15`}}, {{0.85`, 0.85`}, {2, 2},
    {3.15`, 3.15`}}, {{0.85`, 3.15`}, {0.85`, 0.85`}, {3.15`, 3.15`}, {3.15`, 0.85`}},
    {{0.85`, 3.15`}, {0.85`, 0.85`}, {2, 2}, {3.15`, 3.15`}, {3.15`, 0.85`}},
    {{0.85`, 3.15`}, {0.85`, 0.85`}, {3.15`, 3.15`}, {3.15`, 0.85`}, {0.85`, 2}, {3.15`, 2}}};

dice[i_, color_: GrayLevel[0]] :=
  Graphics[
    {GrayLevel[0.94], EdgeForm[color], Polygon[{{0, 0}, {0, 4}, {4, 4}, {4, 0}}],
    {color, EdgeForm[color], Disk[#, 0.45] & /@ dots[[i]]}}, ImageSize -> 30]

twoDice[{i_, j_}] /; (i + j == 7) := Row[{dice[i, Red], dice[j, Red]}, Spacer[5]]
twoDice[{i_, j_}] := Row[{dice[i], dice[j]}, Spacer[5]]

role := twoDice[RandomChoice[Range[6], 2]]

Grid[Table[role, {i, 10}, {j, 5}], Frame -> All, Spacings -> {2, 1}, FrameStyle -> GrayLevel[.8]]


text:
Q: How do I locate an external device through terminal? I am an intern at a company which built a speaker with an internal DSP chip which includes a microphone to record audio, as well as way to produce pink noise. We plug the speaker into a computer via a usb drive and we can extract the recorded audio onto the computer for desired research involving RT-60 measured with impulse response.
On my coworker's PC, he typed 'cmd -qY' into his shell interface and was able to access the speaker in order to extract the recorded audio files from the speaker. This code is a prompt through micropython and he was allowed to type in other code in order to register the speaker as an external hard-drive and then upload files from the speaker. I am having trouble getting this to work on my Mac, for when I type that prompt in Terminal my computer says "-bash: cmd: command not found." My computer is also not registering the speaker as an external device, which I believe to be the root of the problem, as well as my lack of knowledge regarding the difference between PC and Mac command interfaces.

A: I resolved my problem by downloading CoolTerm, an application for Mac. I go to the options on CoolTerm and select the port that I want, which shows up as a USB when I have the speaker plugged in. From there, I go to Terminal in the options menu and click 'Line Mode' So I can type in code in CoolTerm. I go back to the main Cool Term interface and click connect. Then I enter in the line the desired prompts (which were written by my coworker and have no application outside this use) and wait a bit and then my speaker shows as an external hard-drive from which I can take files. I think the important lesson to draw from this is to bear in mind that CoolTerm is a very useful tool for external devices whose software were designed on a PC and may not be compatible with Mac and identified as external hard-drives. CoolTerm is a great application for this purpose and I recommend it to anyone having issues with viewing external devices on their computer.


text:
Q: How to hide a tooltip with a javascript if statement? I've created a tooltip that appears with all the text in my word tree and now I want to hide it from 5 categories with a javascript if statement.

A: If the tooltip is because of title attribute and not something custom made then you can just remove title attribute with below line
$('.targetElement').removeAttr('title');
on the other hand, if the tooltips are custom created then you'll need to handle mouse-hover event and check if it has to be hidden then hide it


text:
Q: Parsing a MS Word generated XML file in C# So I have a client (this could only come from the government) who has a bunch of MS Word docs they want entered into a database, and short of manual entry, I feel like converting them to XML and parsing them using a utility program would be the best course of action.
I have a utility to do this using code found here on stackoverflow:
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
object oMissing = System.Reflection.Missing.Value;

DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("\\testfiles"));
FileInfo[] wordFiles = dirInfo.GetFiles("*.doc");

word.Visible = false;
word.ScreenUpdating = false;

XmlDocument xmlDoc = new XmlDocument();

foreach(FileInfo wordFile in wordFiles)
{
    Object filename = (Object)wordFile.FullName;
    Document doc = word.Documents.Open(ref filename, ref oMissing,
         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
         ref oMissing, ref oMissing, ref oMissing, ref oMissing);

    doc.Activate();

    object outputFileName = wordFile.FullName.Replace(".doc", ".xml");
    object fileFormat = WdSaveFormat.wdFormatXML;

    doc.SaveAs(ref outputFileName, ref fileFormat, ref oMissing,
         ref oMissing, ref oMissing, ref oMissing, ref oMissing,
         ref oMissing, ref oMissing, ref oMissing, ref oMissing,
         ref oMissing, ref oMissing, ref oMissing, ref oMissing);

    object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
    ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
    doc = null;

    xmlDoc.Load(outputFileName.ToString());
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
    nsmgr.AddNamespace("w", "http://schemas.microsoft.com/office/word/2003/wordml");

    XmlNodeList node = xmlDoc.SelectNodes("//w:document/descendant::w:t|//w:document/descendant::w:p|//w:document/descendant::w:tab", nsmgr);
}

((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
word = null;

Now, my XML file(s) look like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<?mso-application progid="Word.Document"?>
<w:wordDocument xmlns:aml="http://schemas.microsoft.com/aml/2001/core"
            xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
            xmlns:ve="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:o="urn:schemas-microsoft-com:office:office"
            xmlns:v="urn:schemas-microsoft-com:vml"
            xmlns:w10="urn:schemas-microsoft-com:office:word"
            xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml"
            xmlns:wx="http://schemas.microsoft.com/office/word/2003/auxHint"
            xmlns:wsp="http://schemas.microsoft.com/office/word/2003/wordml/sp2"
            xmlns:sl="http://schemas.microsoft.com/schemaLibrary/2003/core"
            w:macrosPresent="no"
            w:embeddedObjPresent="no"
            w:ocxPresent="no"
            xml:space="preserve">
<w:ignoreSubtree w:val="http://schemas.microsoft.com/office/word/2003/wordml/sp2"/>
<o:DocumentProperties>
  ...
</o:DocumentProperties>
<w:fonts>
  ...
</w:fonts>
<w:lists>
  ...
</w:lists>
<w:styles>
  ...
</w:styles>
<w:shapeDefaults>...</w:shapeDefaults>
<w:docPr>...</w:docPr>
<w:body>
  <w:p wsp:rsidR="00B01775" wsp:rsidRDefault="00B01775">
    <w:pPr>
      <w:tabs>
        <w:tab w:val="left" w:pos="3312"/>
        <w:tab w:val="left" w:pos="4032"/>
        <w:tab w:val="left" w:pos="5616"/>
      </w:tabs><w:ind w:right="-576"/>
    </w:pPr>
  </w:p>
  <w:p wsp:rsidR="00B01775" wsp:rsidRDefault="00B01775">
    <w:pPr>
      <w:jc w:val="center"/>
      <w:rPr>
        <w:b/>
      </w:rPr>
    </w:pPr>
    <w:r>
      <w:rPr>
        <w:b/>
      </w:rPr>
      <w:t>blah blah blach this is sample text</w:t>
    </w:r>
  </w:p>
  <w:p wsp:rsidR="00B01775" wsp:rsidRDefault="00B01775">
    <w:pPr>
      <w:jc w:val="center"/>
    </w:pPr>
    <w:r>
      <w:rPr>
        <w:b/>
      </w:rPr>
      <w:t>More sample text</w:t>
    </w:r>
  </w:p>
  <w:p wsp:rsidR="00B01775" wsp:rsidRDefault="00B01775"/>
  <w:p wsp:rsidR="00B01775" wsp:rsidRDefault="00B01775"/>
  <w:p wsp:rsidR="00B01775" wsp:rsidRDefault="00B01775"/>
  <w:p wsp:rsidR="00B01775" wsp:rsidRDefault="00B01775"/>
  <w:p wsp:rsidR="00B01775" wsp:rsidRDefault="00B01775">
    <w:r>
      <w:t>Sample Header</w:t>
    </w:r>
  </w:p>
  <w:p wsp:rsidR="00B01775" wsp:rsidRDefault="00B01775"/>
  <w:p wsp:rsidR="00B01775" wsp:rsidRDefault="00B01775">
    <w:pPr>
      <w:pStyle w:val="BodyText"/>
    </w:pPr>
    <w:r>
      <w:rPr>
        <w:snapToGrid w:val="off"/>
      </w:rPr>
      <w:t>Sample Body text.......</w:t>
    </w:r>
  </w:p>
 </w:body>
</w:wordDocument>

I'm no pro, but I think I'm following the letters of the law pretty well here by declaring the namespace manager correctly, so why then, am I getting a null return on the node(s) I am trying to select?
XmlNodeList node = xmlDoc.SelectNodes("//w:document/descendant::w:t|//w:document/descendant::w:p|//w:document/descendant::w:tab", nsmgr);

Am I missing something?

A: I looks like you have the wrong node name in your XPath expression. Replace all occurrences of  w:document with w:wordDocument. So it should be:
XmlNodeList node = xmlDoc.SelectNodes("//w:wordDocument/descendant::w:t|//w:wordDocument/descendant::w:p|//w:wordDocument/descendant::w:tab", nsmgr);


text:
Q: Is there a way to move this .logout to the right side?

    body {
      background-color:olive;
      margin:0;
    }

    nav {
      background-color:aqua;
    }

    #container{
      max-height:1800px;
      display:flex;
      flex-direction:row;

    }

     a {

      background-color:chocolate;
      padding:7px;
      border-radius:10px;
      text-decoration:none;
    }

    #container > a:hover{
      opacity:0.5;
    }

    #item-2, #item-3, #item-1, #item-0 {
     align-self:flex-start;
     margin-top:5px;
    }

    #logout {
     align-self:flex-end;
    }

    }
    /* nav is finally done after 1.5 hours lol and another 30mins  */

    #bear-nest {
      display:flex;
      flex-direction:row;
      justify-content:flex-end;
      align-items:center;
    }

    img {
      border-radius:20%;
     display: block;
margin-left: auto;
margin-right: auto;}

    #bear > p {
      text-align:center;
      margin-left:auto;
      margin-right:auto;
      width:70%;
    }

    hr {
      border: 1px solid black;
    }

    .middle {
      display:flex;
      justify-content:center;
     align-self:flex-start;
    }

    }

    Main
    Information
    Contacts
    Media
    Log out

The American black bear

The American black bear (Ursus americanus) is a medium-sized bear native to North America. It is the continent's smallest and most widely distributed bear species. Black bears are omnivores, with their diets varying greatly depending on season and location. They typically live in largely forested areas, but do leave forests in search of food. Sometimes they become attracted to human communities because of the immediate availability of food. The American black bear is the world's most common bear species.

    It is listed by the International Union for Conservation of Nature (IUCN) as a least-concern species, due to its widespread distribution and a large population estimated to be twice that of all other bear species combined. Along with the brown bear, it is one of only two of the eight modern bear species not considered globally threatened with extinction by the IUCN. American black bears often mark trees using their teeth and claws as a form of communication with other bears, a behavior common to many species of bears.

Asian black bear

The Asian black bear (Ursus thibetanus, previously known as Selenarctos thibetanus), also known as the moon bear and the white-chested bear, is a medium-sized bear species native to Asia and largely adapted to arboreal life.[2][3] It lives in the Himalayas, in the northern parts of the Indian subcontinent, Korea, northeastern China, the Russian Far East, the Honshū and Shikoku islands of Japan, and Taiwan. It is classified as vulnerable by the International Union for Conservation of Nature (IUCN), mostly because of deforestation and hunting for its body parts.[1]

The species is morphologically very similar to some prehistoric bears, and is thought by some scientists to be the ancestor of other extant bear species (aside from pandas and spectacled bears).[2] Though largely herbivorous, Asian black bears can be very aggressive toward humans, who frequently trap or kill them for traditional medicine.[4]

Yes , I know that margin-left:auto   would help this but I was wondering if there's an alternative to it? I know about justify-content / align-items / align-self . But none of them seem to push the log out button to the end. So whats going on here? I cannot figure this out so any advice on why it doesnt seem to work would be appreciated. Thanks.


text:
Q: Sync all RealtimeDB data to the Google's sheet columns For every time im adding, or editing a product through my app, I am trying to write Firebase RealtimeDB data into a Google Sheets spreadsheet through Google Appscript.
This is what my RealtimeDB looks like

And this is my goal for every product (ignore the blue box)

This is what i have done so far but i do not know how to handle the sheet ranges and add the data in those specific positions.
url="https://inventory-c1e.firebaseio.com/Items.json?&auh=pur6Ka8wYVAd"
xpath="OMCPC150C/itembarcode"   //here im trying something but dont know how to continue for all DB values
function addProduct() {
  var sheet = SpreadsheetApp.getActiveSheet();
  sheet.appendRow([IMPORTJSON()]);
}
function IMPORTJSON(){

  try{

    var res = UrlFetchApp.fetch(url);
    var content = res.getContentText();
    var json = JSON.parse(content);

    var patharray = xpath.split("/");
    //Logger.log(patharray);

    for(var i=0;i<patharray.length;i++){
      json = json[patharray[i]];
    }

    //Logger.log(typeof(json));

    if(typeof(json) === "undefined"){
      return "Node Not Available";
    } else if(typeof(json) === "object"){
      var tempArr = [];

      for(var obj in json){
        tempArr.push([obj,json[obj]]);
      }
      return tempArr;
    } else if(typeof(json) !== "object") {
      return json;
    }
  }
  catch(err){
      return "Error getting data";
  }

}

So please kindly guide me on how to continue


text:
Q: Sortable Java collection without duplicates I am searching for sortable (I mean sorting after initialization and many times using Comparator) Java class collection without duplicates. Is there any more pure solution than writing code which will opaque and prevent for example some ArrayList for adding another object with the same value that already exists?
Edit 1:
I should add some explanation about sorting. I need to sort this set of values many times with different comparators (diversity of implementations).

A: Use a Set! The common implementations are HashSet and TreeSet. The latter preserves the order of items as it implements SortedSet.

A: Set Interface---->SortedSet Interface----->TreeSet Class
Set Interface---->HashSet Class
Set Interface---->LinkedHashSet Class

You can Use TreeSet. It will remove duplicates.
TreeSet implements SortedSet Interface so that it will sort the elements entered
        SortedSet s=new TreeSet();
        s.add(12);
        s.add(12);
        s.add(1);
        s.add(56);
        s.add(6);
        s.add(47);
        s.add(1);
        System.out.println(s);

Output
[1, 6, 12, 47, 56]

A: Use Set for unique elements.. You can always use Collections.sort() to sort any collection you use

A: This is a set.
usage:
Collection collection = new HashSet();

A: It might be best to extend a standard collection or implement one from scratch. Eg:
class SetList<E> extends ArrayList<E> {
  boolean add(E e) {
    if (contains(e)) {
      return false;
    } else {
      super.add(e);
      return true;
    }
  }

  void add(int index, E e) { .. }

  void addAll(..) {..}

  void addAll(..) {..}
}

And then you've got Collections.sort as previously stated. I would want to double-check everything though -- I can just imagine library methods making false assumptions about SetList because it extends ArrayList, leading to disaster. Read the javadocs of ArrayList, List, and Collection for a start, and really consider doing one from scratch.


text:
Q: View behaves differently when called from WillResignActive than DidBecomeActive I reset my UI with this method:
func resetUI () {
    self.position = 0.0
    self.percent2 = 0.0
    self.tableView.setContentOffset( CGPoint(x: 0, y: 0) , animated: true)
}

And then have a background overlay that animates with:
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let height: CGFloat = scrollView.bounds.size.height
    self.position = max(scrollView.contentOffset.y, 0.0)
    self.percent2 = min(position / height, 0.99)
    alphaView?.alpha = percent2
    extraView?.alpha = percent2
}

But when I call resetUI from UIApplicationWillResignActive it works great, when I call it from UIApplicationDidBecomeActive it doesn't work great because the blur effect doesn't show up when you scroll anymore.
Any ideas why this would happen?  I'm not sure why this would work perfect in UIApplicationWillResignActivebut not UIApplicationDidBecomeActive.
Here's how the overlay gets set up, if needed:
     let overlay = UIVisualEffectView()
     overlay.effect = UIBlurEffect(style: .extraLight)
     overlay.alpha = 1.0
     overlay.frame = self.view.bounds
     alphaView?.addSubview(overlay)

Here's how I'm being notified of the the UIApplication details, if needed:
    NotificationCenter.default.addObserver(
        self,
        selector: #selector(resetUI),
        name: NSNotification.Name.UIApplicationDidBecomeActive,
        object: nil)


text:
Q: CSS Grid: 50% height not working on second column I'm trying to get the rows in the second column of a css grid structure to be 50% in height.
I have this code:
grid-template-areas: "green red"
                     "green blue";
grid-template-rows: 100% 50%;
grid-template-columns: 1fr 300px;

However, the first row in that column is larger. This is the result:

I tried adding:
#page > .red { max-height: 50%; }

but this gave me:

How do I get the two rows in the second column to be 50% height?
JSFIDDLE: https://jsfiddle.net/busr380n/13/

#page > .green {
  grid-area: green;
  background-color: green;
}

#page > .red {
  grid-area: red;
  background-color: red;
}

#page > .blue {
  grid-area: blue;
  background-color: blue;
}

#page {
  display: grid;
  width: 100%;
  height: 250px;

  grid-template-areas: "green red"
                       "green blue";
  grid-template-rows: 100% 50%;
  grid-template-columns: 1fr 300px;

}

#page > .red { max-height: 50%; }

A: This is your code:
grid-template-areas: "green red"
                     "green blue";
grid-template-rows:  100% 50%;

You've created two rows. But you've given the first row 100% height of the grid container. This forces the second row to exist outside of the container.
Try this instead:
grid-template-areas: "green red"
                     "green blue";
grid-template-rows:  50% 50%;

No need for the max-height on the grid item.

#page {
  display: grid;
  height: 250px;
  grid-template-areas: "green red"
                       "green blue";
  grid-template-rows: 50% 50%;
  grid-template-columns: 1fr 300px;
}

#page > .green {
  grid-area: green;
  background-color: green;
}

#page > .red {
  grid-area: red;
  background-color: red;
}

#page > .blue {
  grid-area: blue;
  background-color: blue;
}


text:
Q: Syncing Notes with Gmail & iCloud In the Mail, Contacts & Calendars Preference pane, you can have Notes synchronize with a Gmail account.
I've already got it setup to work nicely with iCloud, but..
Where do I go in Gmail to read these Notes? They don't appear under the "notes" label.

A: Your notes can synchronize with Gmail or iCloud, not both as far as I can tell.
To sync a note with Gmail do the following

*

*Set up your account and check the notes box in the Mail, Contacts & Calendars preference pane.

*Go to notes in Mountain Lion

*Go to View -> Show Folders List -- or -- click the folders list icon in the bottom left side of the Notes window

*From here you should be able to select your Gmail account instead of iCloud and create a new note

*Within Gmail you should have a folder called "Notes" and your newly created note should be inside


text:
Q: Can we minimise the risk of using xp_cmdshell? Using xp_cmdshell can be quite helpful and sometimes possibly the only answer to some scenarios. I've read some posts on the internet that enabling xp_cmdshell might jeopardize the security of the database/server.
My question is that, is there anything we can do to reduce the risk? For example can we set some restrictions/applying users role, etc providing safeguards to mitigate the risk?
Thanks.

A: Well, you could not grant execute on it explicitly to end users (deny it even), and only enable it in stored procedures that use EXECUTE AS with some login that does have execute permissions. Then grant execute on only that stored procedure to the user that needs to run the command.
First, make sure xp_cmdshell is enabled for the instance:
EXEC sp_configure 'show advanced options', 1;
GO
RECONFIGURE WITH OVERRIDE;
GO
EXEC sp_configure 'xp_cmdshell', 1;
GO
RECONFIGURE WITH OVERRIDE;
GO
EXEC sp_configure 'show advanced options', 0;
GO
RECONFIGURE WITH OVERRIDE;

Now depending on operating system and SQL Server service account, you may need to set up a proxy account (and to do this, thanks to UAC, you may need elevation and launch SSMS as an administrator):
EXEC master..sp_xp_cmdshell_proxy_account 'Domain\User', 'Password';

Then create a wrapper in your database that does whatever you need it to do (this is just a sample of a VERY generic wrapper that doesn't really protect you from anything; only using it to demonstrate):
USE yourdb;
GO
CREATE PROCEDURE dbo.uxp_cmdshell
  @cmd VARCHAR(2048)
WITH EXECUTE AS OWNER
AS
BEGIN
  EXEC master.dbo.xp_cmdshell @cmd;
END
GO

Now give your user or role permissions to execute the procedure:
GRANT EXECUTE ON dbo.uxp_cmdshell TO [your_user_or_role!];

Now when your_user logs in, and tries to execute willy-nilly calls to xp_cmdshell:
EXEC master.dbo.xp_cmdshell 'dir c:\';

They will get:

Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1
The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.

However if they pass the same command to your new procedure:
EXEC dbo.uxp_cmdshell 'dir c:\';

It will work just fine (assuming your proxy account is set up correctly and/or the SQL Server service account has adequate permissions).
This can take some work, but effectively this allows you to control exactly what your users can do with xp_cmdshell.

A: You can also setup a proxy account using sp_xp_cmdshell_proxy_account to allow non-administrators to use xp_cmdshell.  This will allow you to setup a less privileged Windows account rather than xp_cmdshell always using the SQL Server service account.  This is similar to setting up proxy accounts for SQL Agent jobs.


text:
Q: WPF Menu not staying at that the top OK here is my code :
<Window x:Class="Baileys.test"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Baileys"
    mc:Ignorable="d"
    Title="Bailey" Height="750" Width="832.579">

<Grid Margin="0,0,4.6,6.8" Height="716" VerticalAlignment="Bottom">
    <DockPanel>
        <Menu DockPanel.Dock="Top">
            <MenuItem Header="_File">
                <MenuItem Header="_New"/>
                <MenuItem Header="_Play"/>
                <MenuItem Header="_Save"/>
                <MenuItem Header="_Exit"/>
            </MenuItem>
        </Menu>
        <StackPanel></StackPanel>
    </DockPanel>
    <local:CustomChartControl x:Name="Chart_Copy1" HorizontalAlignment="Left" Height="102" Margin="9,332,-5,0" VerticalAlignment="Top" Width="789" BarsColor="SkyBlue" DataSource="C:\\data3.txt" RenderTransformOrigin="0.5,0.5">
        <local:CustomChartControl.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform AngleY="0.15" AngleX="-0.139"/>
                <RotateTransform/>
                <TranslateTransform Y="1.16" X="-0.346"/>
            </TransformGroup>
        </local:CustomChartControl.RenderTransform>
    </local:CustomChartControl>
    <local:CustomChartControl x:Name="Chart_Copy" HorizontalAlignment="Left" Height="86" Margin="9,221,-5,0" VerticalAlignment="Top" Width="789" BarsColor="SkyBlue" DataSource="C:\\data3.txt" RenderTransformOrigin="0.5,0.5">
        <local:CustomChartControl.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform AngleY="0.15" AngleX="-0.139"/>
                <RotateTransform/>
                <TranslateTransform Y="1.16" X="-0.346"/>
            </TransformGroup>
        </local:CustomChartControl.RenderTransform>
    </local:CustomChartControl>
    <local:CustomChartControl x:Name="Chart" HorizontalAlignment="Left" Height="102" Margin="9,117,-5,0" VerticalAlignment="Top" Width="789" BarsColor="SkyBlue" DataSource="C:\\data3.txt" RenderTransformOrigin="0.5,0.5">
        <local:CustomChartControl.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform AngleY="0.15" AngleX="-0.139"/>
                <RotateTransform/>
                <TranslateTransform Y="1.16" X="-0.346"/>
            </TransformGroup>
        </local:CustomChartControl.RenderTransform>
    </local:CustomChartControl>
</Grid>

when I make my screen bigger, the menu is not at the top anymore...
Why?
why doesn't it not stay at the very top ?
ok I just updated, my code but it is still now staying at the top.
when I make my screen bigger, there is a big white gap from the very top to the menu

A: Try using DockPanel and dock it to the Top of your window.
<DockPanel VerticalAlignment="Top" Grid.Column="0" Grid.Row="0">
    <Menu DockPanel.Dock="Top">
        <MenuItem Header="_File">
            <MenuItem Header="_New"/>
            <MenuItem Header="_Play"/>
            <MenuItem Header="_Save"/>
            <MenuItem Header="_Exit"/>
        </MenuItem>
    </Menu>
</DockPanel>


text:
Q: How to attach Click event dynamically to multiple buttons? I'm trying to develop Keno Game in C#, so I have 80 buttons where each of them has the numbers from 1-80 like this:

So what I want to do is that each user should choose 10 numbers (not less, not more) and when a button is being clicked the background color of the button turns green, but I want to know how can that be done without calling the event on each button. These numbers should be saved on the database.
I have tried adding the buttons on a array and looping through the array like this:
var buttons = new[] { button1, button2, button3, button4, button5, ..... };
foreach (var button in buttons)
{
    if (button.Focused)
    {
        button.BackColor = Color.Green;
    }
}

A: You can assign the same event handler to each button:
foreach (var button in buttons) {
    button.Click += (sender, e) => {
        ((Button)sender).BackColor = Color.Green;
    };
}

If you want to add to all buttons on the form, you can call this in the form constructor:
int counter = 0;
public Form1()
{
    InitializeComponent();
    foreach (var c in Controls)
    {
        if (c is Button)
        {
            ((Button)c).Click += (sender, e) =>
            {
                if (counter >= 10) return;
                Button b = (Button)sender;
                b.BackColor = Color.Green;
                counter += 1;
            };
        }
    }
}


text:
Q: The file was not uploaded. Magento 2 custom module I'm trying to upload image in my custom module but I always getting the "The file was not uploaded." error. I trace the code and all I can say is the $this->uploader->create() is not working.
Here my sample code.
<?php

/**
 * Grid Admin Cagegory Map Record Save Controller.
 * @category  Webkul
 * @package   Testing_Basic
 * @author    Webkul
 * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Testing\Basic\Controller\Adminhtml\Contact;

use Magento\Framework\App\Action\Context;
use Testing\Basic\Model\ContactFactory;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Magento\Framework\Image\AdapterFactory;
use Magento\Framework\Filesystem;

class Save extends \Magento\Backend\App\Action
{
    /**
     * @var \Testing\Basic\Model\ContactFactory
     */
    var $contactFactory;

    protected $uploaderFactory;
    protected $adapterFactory;
    protected $fileSystem;
    protected $allowedExtensions = ['jpg', 'jpeg', 'png'];
    protected $fileId = 'your_file_id';
    protected $oldImage = null;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Testing\Basic\Model\ContactFactory $contactFactory
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\Filesystem\DirectoryList $dir,
        UploaderFactory $uploaderFactory,
        Filesystem $fileSystem,
        \Testing\Basic\Model\ContactFactory $contactFactory,
        AdapterFactory $adapterFactory
    ) {
        parent::__construct($context);
        $this->_dir = $dir;
        $this->uploaderFactory = $uploaderFactory;
        $this->contactFactory = $contactFactory;
        $this->fileSystem = $fileSystem;
        $this->adapterFactory = $adapterFactory;
    }

    /**
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function execute()
    {
        $data = $this->getRequest()->getPostValue();
        $img = $this->getRequest()->getFiles();
        /* var_dump($img);die; */
        if (!$data) {
            $this->_redirect('contact/contact/addrow');
            return;
        }
        if(isset($_FILES['img_title']['name']) && (file_exists($_FILES['img_title']['tmp_name'])))
        {
            $destinationPath = $this->getDestinationPath();
            try{
                $imageAdapter = $this->adapterFactory->create();
                $uploaderFactory = $this->uploaderFactory->create(['fileId' => 'image'])
                    ->setAllowCreateFolders(true)
                    ->setAllowRenameFiles(true)
                    ->setAllowedExtensions($this->allowedExtensions)
                    ->addValidateCallback('custom_image_upload',$imageAdapter,'validateUploadFile');
                var_dump('asdad');die;
                $mediaDirectory = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA);
                $destinationPath = $mediaDirectory->getAbsolutePath('');
                $result = $uploaderFactory->save($destinationPath);
                if (!$result) {
                    throw new LocalizedException(
                        __('File cannot be saved to path: $1', $destinationPath)
                    );
                }
                $imagePath = $result['file'];
                var_dump($imagePath);die;
                $data['img_title'] = $imagePath;
            } catch (\Exception $e) {
                var_dump($e->getMessage());die;
            }
        }
        try {
            $rowData = $this->contactFactory->create();
            $rowData->setData($data);
            if (isset($data['id'])) {
                $rowData->setEntityId($data['id']);
            }
            $rowData->save();
            $this->messageManager->addSuccess(__('Row data has been successfully saved.'));
        } catch (\Exception $e) {
            $this->messageManager->addError(__($e->getMessage()));
        }
        $this->_redirect('contact/contact/index');
    }

    /**
     * @return bool
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Testing_Basic::save');
    }

    public function getDestinationPath()
    {
        return $this->fileSystem
            ->getDirectoryWrite(DirectoryList::MEDIA)
            ->getAbsolutePath('/');
    }
}

A: I think you use wrong AdapterFactory.Try this code
<?php
namespace YourNamespace\YourModule\Controller;

use Magento\Framework\App\Action\Context;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;

class YourController extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $messageManager;

    /**
     * @var \Magento\Framework\Filesystem $filesystem
     */
    protected $filesystem;

    /**
     * @var \Magento\MediaStorage\Model\File\UploaderFactory $fileUploader
     */
    protected $fileUploader;

    public function __construct(
        Context $context,
        ManagerInterface $messageManager,
        ...
        Filesystem $filesystem,
        UploaderFactory $fileUploader
    )
    {
        $this->messageManager       = $messageManager;
        ...
        $this->filesystem           = $filesystem;
        $this->fileUploader         = $fileUploader;

        $this->mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);

        parent::__construct($context);
    }

    public function execute()
    {
        // your code

        $uploadedFile = $this->uploadFile();

        // your code
    }

    public function uploadFile()
    {
        // this folder will be created inside "pub/media" folder
        $yourFolderName = 'your-custom-folder/';

        // "my_custom_file" is the HTML input file name
        $yourInputFileName = 'my_custom_file';

        try{
            $file = $this->getRequest()->getFiles($yourInputFileName);
            $fileName = ($file && array_key_exists('name', $file)) ? $file['name'] : null;

            if ($file && $fileName) {
                $target = $this->mediaDirectory->getAbsolutePath($yourFolderName);

                /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */
                $uploader = $this->fileUploader->create(['fileId' => $yourInputFileName]);

                // set allowed file extensions
                $uploader->setAllowedExtensions(['jpg', 'pdf', 'doc', 'png', 'zip']);

                // allow folder creation
                $uploader->setAllowCreateFolders(true);

                // rename file name if already exists
                $uploader->setAllowRenameFiles(true);

                // rename the file name into lowercase
                // but this one is not working
                // we can simply use strtolower() function to rename filename to lowercase
                // $uploader->setFilenamesCaseSensitivity(true);

                // enabling file dispersion will
                // rename the file name into lowercase
                // and create nested folders inside the upload directory based on the file name
                // for example, if uploaded file name is IMG_123.jpg then file will be uploaded in
                // pub/media/your-upload-directory/i/m/img_123.jpg
                // $uploader->setFilesDispersion(true);

                // upload file in the specified folder
                $result = $uploader->save($target);

                //echo '<pre>'; print_r($result); exit;

                if ($result['file']) {
                    $this->messageManager->addSuccess(__('File has been successfully uploaded.'));
                }

                return $target . $uploader->getUploadedFileName();
            }
        } catch (\Exception $e) {
            $this->messageManager->addError($e->getMessage());
        }

        return false;
    }
}