text:
Q: Odd behavior when using uppercase(combined with underscore) for column names in Hibernate(deployed on JBoss 5.1.0), for MySql DB I'm trying to specify column name using the @Column annotation:
@Column(name="ID") //also tried with @Column(name="[ID]") and @Column(name=""\ID"\")
private int id;

@Column(name="TINY_IMAGE")
private String tinyUrl;

But, the hibernate (or MySQL?) gives the names 'id' and 'tinyUrl' for the above mentioned
columns, respectively.
However, when I use the code bellow, columns' names in the join table are just fine (SHOE_ID and ARTICLE_ID):
@JoinTable(name="SHOE_ARTICLE",
        joinColumns={@JoinColumn(name="SHOE_ID")},
        inverseJoinColumns={@JoinColumn(name="ARTICLE_ID")})

Here is the content of persistence.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

         version="2.0">
   <persistence-unit name="YSPers">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <jta-data-source>java:/ySDS</jta-data-source>
      <properties>
         <property name="hibernate.dialect"
                  value="org.hibernate.dialect.MySQLDialect"/>
         <property name="hibernate.hbm2ddl.auto" value="update"/>
         <property name="hibernate.show_sql" value="false" />
         <property name="hibernate.format_sql" value="false"/>
         <!-- property name="hibernate.hbm2ddl.auto" value="create-drop"/-->
      </properties>
   </persistence-unit>
</persistence>

How can I tell hibernate to use "name" property of @Column annotation for the column name?

A: It looks like you might have mixed annotations on both fields and getters in the class hierarchy.
Make sure to put you annotations in on place. The target (field or getter) scanned by Hibernate depends on where you put the @Id annotation: make sure you put your @Column annotations on the same target. I usually recommend the getter for various reasons.
By the way, the way to quote a column name is by using backticks @Column(name="`MY_ID`")


text:
Q: AS3 return dropped object to initial location I am using codes from http://hub.tutsplus.com/tutorials/create-a-drag-and-drop-puzzle-in-actionscript-30--active-2920 to make a drag and drop decoration game. I am trying to make it so that when the dropped object is dragged out of target location (which is an outline of the shape in my case), it goes back to initial location... basically reversing the drag and drop. I've been messing around with really random codes and so far this line is the closest to what I want but I don't think the code is right and also it doesnt return to initial location, it just goes to the side of the stage.
so, I added the else if line to stopDragObject which got the object to be removed from target location, but it randomly goes to the side of the stage, and not initial location:
private function stopDragObject(evt:MouseEvent):void {
        if (evt.target.hitTestObject(getChildByName(evt.target.name + "Target"))) {
            evt.target.x = getChildByName(evt.target.name + "Target").x;
            evt.target.y = getChildByName(evt.target.name + "Target").y;

        }  else if (evt.target.x = null) {
            evt.target.x = xPos;
            evt.target.y = yPos;
        }

        evt.target.stopDrag();
    }

Solved
after reading the lesson from below,  I ended up with this and it works perfectly! (not exactly the way like the lesson but at least it works...)
private function stopDragObject(evt:MouseEvent):void {
        if (evt.target.hitTestObject(getChildByName(evt.target.name + "Target"))) {
            evt.target.x = getChildByName(evt.target.name + "Target").x;
            evt.target.y = getChildByName(evt.target.name + "Target").y;

        }  else {
            evt.target.x = getChildByName(evt.target.name + "Int").x;
            evt.target.y = getChildByName(evt.target.name + "Int").y;
        }

        evt.target.stopDrag();
    }

I added a initial object so the object could only be either at target or initial :)

A: I will try to teach neither provide code.
Lets draw two rectangles:
var s1:Sprite = new Sprite()
var s2:Sprite = new Sprite()
with (s1)
{
    graphics.beginFill(0xfcaaaa, .7)
    graphics.drawRect(0, 0, 400, 400)
    graphics.endFill()
}
with (s2)
{
    graphics.beginFill(0x00aaaa, .7)
    graphics.drawRect(0, 0, 30, 30)
    graphics.endFill()
}
addChild(s1)
addChild(s2)

Is't that simple? You see that s1 is much bigger than s2 (dimentions: 400, 400 vs 30, 30 ) Now place s2 to the center of our big s1:
s2.x = 200;
s2.y = 200;

We will use s1 for the boundaries of s2 movings.
This code is a simplest solution for dragging our s2 rectangle (Sprite):
s2.addEventListener(MouseEvent.MOUSE_DOWN, onDown)
s2.addEventListener(MouseEvent.MOUSE_UP, onUp)

function onDown(e:MouseEvent):void
{
    (e.currentTarget as Sprite).startDrag();
}

function onUp(e:MouseEvent):void
{
    (e.currentTarget as Sprite).stopDrag();
}

Now, the basic solution for returning our Sprite to the starting position: hitTestObject will return true, if Sprite s2 is still located in the area of Sprite s1. More helpful functions here. Lets check it. Change onUp function this way:
function onUp(e:MouseEvent):void
{
    var s:Sprite = (e.currentTarget as Sprite);
    s.stopDrag();
    if (!s.hitTestObject(s1))
    {
        s.x = 200;
        s.y = 200;
    }
}

You see that now s2 gets returned to the starting position if it gets dragged out from the area of s1.

Now the main part:
What to do, if you can't predict the starting position of the object? Now, when we know how to deal with already known coordinates, this is the challange. I assume that there are several implementations of this functionality exist. One of the best way is to set additional parameters e.g. startingX and startingY for the dragging object when starting drag. E.g. in our example when onDown function gets called. I guess you dealing with Sprites or MovieClips and don't have the ability to do this.
Lets go another way and use Dictionary object. Dictionary is some kind of traditional Hash Map with the ability to use objects as keys.

Hash map is kind of storage, where you can put any value mapped by a key, provided by you. In actionscript 3 we have Object as a limited implementation of Hash Map. Why use it? In two words because it's simple and fast. But with Object we can't use other Objects as keys, only strings ints numbers etc..

var sites:Object = new Object();
sites['stackoverflow'] = "http://stackoverflow.com/"
trace(sites.stackoverflow) // outputs-> http://stackoverflow.com/

With Dictionary we can use Objects as keys.
Lets create it:
var startCoordinates:Dictionary = new Dictionary();

To save coordinates, we need x and y property.

FYI: new Object() is equivalent of {}
var capitals:Object = new Object();
capitals['Italy'] = 'Rome';

is equivalent of
var capitals:Object = {Italy: 'Rome'};

To save current position we will use this code:
var s:Sprite = (e.currentTarget as Sprite);
startCoordinates[s] = { x: s.x, y: s.y };

And the whole code in our example will look like this:
var s1:Sprite = new Sprite()
var s2:Sprite = new Sprite()
addChild(s1)
addChild(s2)
with (s1)
{
    graphics.beginFill(0xfcaaaa, .7)
    graphics.drawRect(0, 0, 400, 400)
    graphics.endFill()
}
with (s2)
{
    graphics.beginFill(0x00aaaa, .7)
    graphics.drawRect(0, 0, 30, 30)
    graphics.endFill()
}
s2.x = 200;
s2.y = 200;
s2.addEventListener(MouseEvent.MOUSE_DOWN, onDown)
s2.addEventListener(MouseEvent.MOUSE_UP, onUp)

var startCoordinates:Dictionary = new Dictionary()

function onDown(e:MouseEvent):void
{
    var s:Sprite = (e.currentTarget as Sprite);
    startCoordinates[s] = { x: s.x, y: s.y };
    s.startDrag();
}

function onUp(e:MouseEvent):void
{
    var s:Sprite = (e.currentTarget as Sprite);
    s.stopDrag();
    if (!s.hitTestObject(s1))
    {
        s.x = startCoordinates[s].x;
        s.y = startCoordinates[s].y;
    }
    delete startCoordinates[s];
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does this make my R session abort? I'm trying to implement named-list calling in Rcpp
in R
b<-list("bgroups"=c(1,1,1,1,0,0,0,0))
> b$bgroups
[1] 1 1 1 1 0 0 0 0

cppFunction(
  "
NumericVector split(Rcpp::List & b){
  Rcpp::NumericVector c= b['bgroups'];
  return c;
}")

split(b)

But this causes my R session to abort.
I'm trying to implement this procedure as illustrated in one of Dirk's presentations, but I'm missing something.

This is an extension of my question

A: The following works:
b<-list("bgroups"=c(1,1,1,1,0,0,0,0))
b$bgroups
#[1] 1 1 1 1 0 0 0 0

Rcpp::cppFunction(
  '
NumericVector split(Rcpp::List & b){
  Rcpp::NumericVector c = b["bgroups"];
  return c;
}')

split(b)
#[1] 1 1 1 1 0 0 0 0

In C++, ' is used to quote a character, while " is used to quote strings. My compiler warns me about this:
warning: character constant too long for its type
   Rcpp::NumericVector c= b['bgroups'];
                            ^~~~~~~~~

Generally it is a good idea to take compiler warnings seriously.


text:
Q: bash file looping and passing contents to java call I have the following bash script and it isn't quite working right.  The objective here is to move XMLs from /source to /active folders, then call a java script and pass in XML file contents as argument, then move active file from /active to /archive folder.
Any help is greatly appreciated!
#!/bin/bash
JAVA_HOME=/usr/lib/jvm/jdk1.6.0_02
CLASSPATH=/tracking/lib/tracking_client.jar: .
FILES=/tracking/source/*
for f in $FILES
do
  filename=$(basename "$f")
  cd /tracking/source/
  mv /tracking/source/${filename} /tracking/active/${filename}
  cd /tracking/active/
  $JAVA_HOME/bin/java -cp $CLASSPATH TrackClient  ## need to pass XML file contents in to java call as argument
  mv /tracking/active/${filename} /tracking/archive/${filename}
done
exit 0

A: Use $() to insert the result of a command into the command.
$JAVA_HOME/bin/java -cp $CLASSPATH TrackClient  "$(cat "/tracking/active/${filename}")"


text:
Q: AWS SES - Check which verified email is causing the limits to exceed I have configured my AWS SES account to have an email sending quota as follows. But given the last 24 hours, this quota has exceeded, causing SES to reject sending emails.
Sending Quota:  send 127500 emails per 24 hour period
Quota Used: 100% as of 2019-10-08 10:06 UTC+5:30

I have around 5 verified emails, connected to different services. Is there a way to check which email address has caused the quota to be exceeded? (May be with a different permission for my role)
PS: Checking application logs of each service is not an option.

A: There isn't a way to see the separated statistics but you can configure SNS to get the notification for each mail. See the Documentation.
You can configure the notifications for each mail from the console > email addresses > select an email > see details > notification > edit configuration. Before doing this, you should have an SNS topic and just select that topic. From the notification, you can save them to DB or somewhere, count the number of emails where the email is sent from what email.


text:
Q: How do I recreate my particular Excel output in R? Below is my R code, but I couldn't decipher the "result" part. It doesn't work the way I want (see the Excel image below).
library(tidyverse)

Question_No <-c(1,1,1,1,1,10,10,10,10,10,11,11,11,11,11)

Reply<-c("never","few","medium","much","complete",
         "never","few","medium","much","complete",
         "never","few","medium","much","complete")

Number_of_Answers<- c(7,1,12,13,18,6,2,12,10,21,6,2,13,11,19)

aa<- data.frame(Question_No,Reply,Number_of_Answers)

replace<- function(x)
{Replys=x['Reply']
if(Replys=="few"){return(2)}
else if(Replys=="much"){return(4)}
else if(Replys=="never"){return(1)}
else if(Replys=="medium"){return(3)}
else {return(5)}}

Replys<- apply(aa,MARGIN = 1,FUN = replace)

aa['Replys']<-Replys

aa= mutate(aa,NA_R = aa$Replys * aa$Number_of_Answers)

aa$result = ifelse(aa$Question_No==1, sum(aa$NA_R) ,"n")

View(aa)

My aim is to use R to reproduce the result in EXCEL shown in the picture below.
Thank you for the help.
Image of Excel output I'm trying to reproduce


text:
Q: Неопределенный оператор delete Код
class Test {};

void setup() {
    Test * t = new Test();
    delete t;
}

Компилирую скетч для Ардуино на cmake + avr. На строчке с delete Получаю ошибку

undefined reference to `operator delete(void*, unsigned int)'

это что такое? Зачем компилятор (а вернее линковщик) требует переопределения оператора delete да еще и с такими параметрами?
Содержимое CMakeList.txt
cmake_minimum_required(VERSION 2.8.4)
set(CMAKE_TOOLCHAIN_FILE ${CMAKE_SOURCE_DIR}/cmake/ArduinoToolchain.cmake)
set(CMAKE_CXX_STANDARD 17)
set(PROJECT_NAME Controller)

set(${PROJECT_NAME}_BOARD uno)
# set(ARDUINO_CPU)
project(${PROJECT_NAME})

include_directories(${PROJECT_SOURCE_DIR})
file(GLOB SRC_FILES ${PROJECT_SOURCE_DIR}/*.cpp)
file(GLOB HDR_FILES ${PROJECT_SOURCE_DIR}/*.h)

set(${PROJECT_NAME}_SRCS ${SRC_FILES})
set(${PROJECT_NAME}_HDRS ${HDR_FILES})

set(${PROJECT_NAME}_PORT COM4)

generate_arduino_firmware(${PROJECT_NAME}
        SRCS ${${PROJECT_NAME}_SRCS}
        HDRS ${${PROJECT_NAME}_HDRS}
        )

print_board_list()
print_programmer_list()

A: Это происходит, так как avr-g++ не поддерживает libstdc++
Из avr-libc FAQ

Can I use C++ on the AVR?
Basically yes, C++ is supported (assuming
your compiler has been configured and compiled to support it, of
course). Source files ending in .cc, .cpp or .C will automatically
cause the compiler frontend to invoke the C++ compiler. Alternatively,
the C++ compiler could be explicitly called by the name avr-c++.
However, there's currently no support for libstdc++, the standard
support library needed for a complete C++ implementation. This imposes
a number of restrictions on the C++ programs that can be compiled.
Among them are:

*

*Obviously, none of the C++ related standard functions, classes, and
template classes are available.

*The operators new and delete are not implemented, attempting to use them will cause the linker to complain
about undefined external references. (This could perhaps be fixed.)

*Some of the supplied include files are not C++ safe, i. e. they need
to be wrapped into extern "C" { . . . } (This could certainly be
fixed, too.)

*Exceptions are not supported. Since exceptions are
enabled by default in the C++ frontend, they explicitly need to be
turned off using -fno-exceptions in the compiler options. Failing
this, the linker will complain about an undefined external reference
to __gxx_personality_sj0. Constructors and destructors are supported
though, including global ones.

When programming C++ in space- and runtime-sensitive environments like
microcontrollers, extra care should be taken to avoid unwanted side
effects of the C++ calling conventions like implied copy constructors
that could be called upon function invocation etc. These things could
easily add up into a considerable amount of time and program memory
wasted. Thus, casual inspection of the generated assembler code (using
the -S compiler option) seems to be warranted.

Библиотека arduino содержит реализацию new/delete(файлы new.cpp и new.h), но используемый Вами скрипт ArduinoToolchain.cmake не подключает их при сборке библиотеки arduino core
Вы можете попробовать другую реализацию Arduino Toolchain для cmake
Например, https://github.com/a9183756-gh/Arduino-CMake-Toolchain
Пример файл проекта для cmake:
cmake_minimum_required(VERSION 3.10)

project(test_uno CXX)

add_executable(test_uno main.cpp)

target_link_arduino_libraries(test_uno PRIVATE core)

target_enable_arduino_upload(test_uno)

Параметры cmake:
cmake \
   -DCMAKE_TOOLCHAIN_FILE=/path/to/Arduino-toolchain.cmake \
   -DARDUINO_BOARD="avr.uno" \
   /path/to/sources.dir

//main.cpp
#include <Arduino.h>

class Test {};

void setup() {
    Test * t = new Test();
    delete t;
}

void loop() {}

A: В C++14 появился перегруженный оператор delete
void operator delete  ( void* ptr, std::size_t sz ) noexcept;

который удаляет память указанного размера. В ардуиновской библиотеке определены только такие варианты
void * operator new(size_t size);
void * operator new[](size_t size);
void * operator new(size_t size, void * ptr) noexcept;
void operator delete(void * ptr);
void operator delete[](void * ptr);

Я понизил в CMakeLists.txt версию с++ до 11
set(CMAKE_CXX_STANDARD 11)

и все стало компилироваться


text:
Q: Openlayers- Show another Image Layer based on zooming region Is it possible in OpenLayers to open another Image layer (OpenLayers.Layer.Image) from a base Image Layer based on certain predefined regions on the base Image Layer. For example if I have five regions set in my base Image Layer on zooming to any one region will open the respective Image layer and zooming out will bring back the base Image Layer?
If yes can you point some samples or method how to achieve this.

A: I have no knowledge of such feature - different image layers based on regions. But maybe you'd be interested in self-hosted custom tiles? Here's some information of how it is set. The idea is: you create tile images (e.g. 256x256px) from your images and you just create many zoom levels from one big image. But at the areas of your interest, you change the tile images, that are present there. Downside is amount of actions, you have to do: you have to cut all your images to tiles (or not, if using big tiles), resize images for different zoom levels by hand, configure zoom levels and finally - change the tiles with regions of your interest. Needs some image editing, but should work.

A: After a lot of trial and error, I found its possible in Openlayers using OpenLayers.Layer.Image to the map layer. Then creating a vector overlay layer denoting circles (OpenLayers.Layer.Vector("Overlay")) and adding it to the map as overlay layer.
Then I register zoomend event of the map. Based on the getZoom() method I have the control to change the image using map.setBaseLayer(imageLayer2)


text:
Q: Adding height with jquery to a div with !important in css I'm making a button that adds to the height of a div, but since I'm making some responsive styles I have in the style sheet the height with !important and after I press the button, the height it's not adding.
Here's my code:
$("#mailDiv").height("+=70");

style:
#mailDiv{height: 300px !important;}

I hope you guys can help me

A: you can use .attr then add style attribute and add your extra height like this to style attribute :
"height:"+($("#mydiv").height()+extra)+'px!important'

you can see demo here

A: Use this:
$("#mailDiv").attr('style', 'height: ' + parseInt($("#mailDiv").height() + 70) +'px !important;')

See JSFiddle to see in action: http://jsfiddle.net/kbf7s20r/


text:
Q: Does TypeScript have something like C#'s dynamic type? Does TypeScript have something like C#'s dynamic type?
I need that dynamic aspect because TypeScript has the any type. Inside, I upload one JSON file, and I would like to access in some variable to their values of JSON class mapped to model.
watch here
Is it possible in TypeScript?
My code:
loadData(index: any) {
    this._service.GetTreeViewModel(index).subscribe((items) => {
        this.items = items[0].**items**;
     });
}

It is giving me a compilation error:

ERROR in C:/_PRJ/mappingtools/src/app/iui-Tools/Tree/Tree.component.ts (42,21): Type 'any[]' cannot be converted to type 'items'.)
  C:/_PRJ/mappingtools/src/app/iui-Tools/Tree/Tree.component.ts (42,21): Type 'any[]' cannot be converted to type 'items'.
    Property 'items' is missing in type 'any[]'.)

And my object is:
{
    id:1,
    items: [...]
}

I can't access items when I do something like x.items.


text:
Q: regex letters only keypress as event I wonder what seems to be the problem in here.
$("#city_field").bind({
  keypress: function(event){
    var  regex = /^[a-zA-ZäöüÄÖÜ]/;
    if (regex.test($("#city_field").val())==true) {
    $('.r_validation').html('').css('background-color', '');
    } else {
        $('.validation').html("TEST").css('background-color', 'red');
    }
  }
});

Whenever I input letters it is valid, then when I input numbers the red validation notice appears. Everything is fine at this point, not until I entered numbers after letters. The following should be invalid, but in my current script it is seen as valid:

*

*foo1212

*foo,

*foo, [with space after comma]

What I really want to validate is to ONLY accept letters and dash (-), nothing more other than that.
Thanks.
EDIT
For the record, the last comment of  @Adam Rackis solved the issue, I ended up with this working code.
$(function(){
  $("#city_field").bind("keyup",
    function(event) {
      var regex = /^[a-zA-ZäöüÄÖÜ]+$/;
      if (regex.test($("#city_field").val())==true) {
        $('.validation').html('').css('background-color', '');
      } else {
          $('.validation').html("TEST").css('background-color', 'red');
      }
  });
});

A: Your regex is matching only one character.  You need to put that input over a Kleene closure, then put an end of string marker:
/^[a-zA-ZäöüÄÖÜ]*$/;

Or if you want to make sure there's at least one character, you'd use the positive closure:
/^[a-zA-ZäöüÄÖÜ]+$/;

Which produces:
var r = /^[a-zA-ZäöüÄÖÜ]+$/;

console.log(r.test('Foo'));    //true
console.log(r.test('Foo123')); //false
console.log(r.test('foo,'));   //false
console.log(r.test('foo, '));  //false
console.log(r.test('foo '));   //false

DEMO
ALSO, make sure you catch the keyup event, since keypress fires before the text in your textbox updates, so you're always validating one character behind.

So on your Regex:
/^[a-zA-ZäöüÄÖÜ]/;

When testing Foo123 the F would be consumed, and that's it.  Done.


text:
Q: Wordpress Custom Post Type Post not showing I'm having a hard time figuring out what could be the issue. I have a Custom Post Type 'Booking'. Even there are post inserted to it, posts are not showing and only 'No Bookings found' is visible. You will notice the labels 'Mine' and 'All' which contains the number of post has value on it.  Please help. I attached the screenshot.

function aviators_booking_create_post_type() {
$labels = array(
    'name'               => __( 'Booking', 'aviators' ),
    'singular_name'      => __( 'Booking', 'aviators' ),
    'add_new'            => __( 'Add New', 'aviators' ),
    'add_new_item'       => __( 'Add New Booking', 'aviators' ),
    'edit_item'          => __( 'Edit Booking', 'aviators' ),
    'new_item'           => __( 'New Booking', 'aviators' ),
    'all_items'          => __( 'All Booking', 'aviators' ),
    'view_item'          => __( 'View Booking', 'aviators' ),
    'search_items'       => __( 'Search Booking', 'aviators' ),
    'not_found'          => __( 'No Bookings found', 'aviators' ),
    'not_found_in_trash' => __( 'No Bookings found in Trash', 'aviators' ),
    'parent_item_colon'  => '',
    'menu_name'          => __( 'Bookings', 'aviators' ),
);

$capabilities = array(
    'publish_posts' => 'publish_for_subscriber',
    'edit_posts' => 'edit_for_subscriber',
    'edit_published_posts' => 'edit_published_for_subscriber',
    'edit_others_posts' => 'edit_others_for_subscriber',
    'delete_posts' => 'delete_for_subscriber',
    'delete_others_posts' => 'delete_others_for_subscriber',
    'read_private_posts' => 'read_private_for_subscriber',
    'read_post' => 'read_for_subscriber'
);

register_post_type( 'booking',
        array(
            'labels'              => $labels,
            'supports'            => array( 'title', 'author' ),
            'public'              => true,
            'exclude_from_search' => true,
            'show_in_nav_menus'   => false,
            'capability_type' => 'for_subscriber',
            'capabilities' => $capabilities,
            'menu_position'       => 32,
            'menu_icon'           => get_template_directory_uri() . '/aviators/plugins/faq/assets/img/faq.png',
        )
    );
}

add_action( 'init', 'aviators_booking_create_post_type' );

A: Something similar happened to me a while ago, it gone well after I used this functon.
flush_rewrite_rules();

Try after the closure of the register_taxonomy
Like this
register_post_type( 'booking',
    array(
        'labels'              => $labels,
        'supports'            => array( 'title', 'author' ),
        'public'              => true,
        'exclude_from_search' => true,
        'show_in_nav_menus'   => false,
        'capability_type' => 'for_subscriber',
        'capabilities' => $capabilities,
        'menu_position'       => 32,
        'menu_icon'           => get_template_directory_uri() . '/aviators/plugins/faq/assets/img/faq.png',
    )
);
flush_rewrite_rules();

For further details check on Codex Function Reference/flush rewrite rules


text:
Q: How do I allow access to GCE to only the dev that created the server? Right now everyone can access absolutely any server in GCE so long as they have GCE access. The gcloud comput ssh command can ssh into any server.
How do I make sure that only the person that created the server has access?

A: It is possible to implement access control to instances based on GCE IAM roles via OS Login:

After you enable OS Login on one or more instances in your project,
  those instances accept connections only from user accounts who have
  the necessary IAM roles in your project or organization:
As an example, you might grant instance access to your users with the
  following process:

*

*Grant the necessary instance access roles to the user. Users must have the following roles:

*

*The iam.serviceAccountUser role.

*One of the following login roles:

*

*The compute.osLogin role, which does not grant administrator permissions

*The compute.osAdminLogin role, which grants administrator permissions

But note that not all GCE image families have OS Login support:

The following image families do not yet support OS Login:

*

*All project coreos-cloud (CoreOS) image families

*Project suse-cloud (SLES) image family sles-11

*All Windows Server and SQL Server image families


text:
Q: Crazy pattern in the simple continued fraction for $\sum_{k=1}^\infty \frac{1}{(2^k)!}$ The continued fraction of this series exhibits a truly crazy pattern and I found no reference for it so far. We have:
$$\sum_{k=1}^\infty \frac{1}{(2^k)!}=0.5416914682540160487415778421$$
But the continued fraction is just beautiful:
[1, 1, 5, 2, 69, 1, 1, 5, 1, 1, 12869, 2, 5, 1, 1, 69, 2, 5, 1, 1, 601080389, 2, 5, 2, 69, 1, 1, 5, 2, 12869, 1, 1, 5, 1, 1, 69, 2, 5, 1, 1, 1832624140942590533, 2, 5, 2, 69, 1, 1, 5, 1, 1, 12869, 2, 5, 1, 1, 69, 2, 5, 2, 601080389, 1, 1, 5, 2, 69, 1, 1, 5, 2, 12869, 1, 1, 5, 1, 1, 69, 2, 5, 1, 1, 23951146041928082866135587776380551749, 2, 5, 2, 69, 1, 1, 5, 1, 1, 12869, 2, 5, 1, 1, 69, 2, 5, 1, 1, 601080389, 2, 5, 2, 69, 1, 1, 5, 2, 12869, 1, 1, 5, 1, 1, 69, 2, 5, 2, 1832624140942590533, 1, 1, 5, 2, 69, 1, 1, 5, 1, 1, 12869, 2, 5, 1, 1, 69, 2, 5, 2, 601080389, 1, 1, 5, 2, 69, 1, 1, 5, 2,...]
All of these large numbers are not just random - they have a simple closed form:
$$A_n= \left( \begin{array}( 2^n \\ 2^{n-1}  \end{array} \right) -1$$
$$A_1=1$$
$$A_2=5$$
$$A_3=69$$
$$A_4=12869$$
$$A_5=601080389$$
And so on. This sequence is not in OEIS, only the larger sequence is, which contains this one as a subsequence https://oeis.org/A014495

What is the explanation for this?
Is there a regular pattern in this continued fraction (in the positions of numbers)?

Is there generalizations for other sums of the form $\sum_{k=1}^\infty \frac{1}{(a^k)!}$?

Edit
I think a good move will be to rename the strings of small numbers:
$$a=1, 1, 5, 2,\qquad b=1, 1, 5, 1, 1,\qquad c=2,5,1,1,\qquad d=2, 5, 2$$
As a side note if we could set $1,1=2$ then all these strings will be the same.
Now we rewrite the sequence. I will denote $A_n$ by just their indices $n$:

$$[a, 3, b, 4, c, 3, c, 5, d, 3, a, 4, b, 3, c, 6, d, 3, b, 4, c, 3, d, 5, a, 3, a, 4, b, 3, c, 7, \\ d, 3, b, 4, c, 3, c, 5, d, 3, a, 4, b, 3, d, 6, a, 3, b, 4, c, 3, d, 5, a, 3, a,...]$$

$$[a3b4c3c5d3a4b3c6d3b4c3d5a3a4b3c7d3b4c3c5d3a4b3d6a3b4c3d5a3a,...]$$
Now we have new large numbers $A_n$ appear at positions $2^n$. And postitions of the same numbers are in a simple arithmetic progression with a difference $2^n$ as well.
Now we only have to figure out the pattern (if any exists) for $a,b,c,d$.

The $10~000$ terms of the continued fraction are uploaded at github here.

I also link my related question, from the iformation there we can conclude that the series above provide a greedy algorithm Egyptian fraction expansion of the number, and the number is irrational by the theorem stated in this paper.

A: actually your pattern is true and it is relatively easy to prove. Most of it can be found in an article from Henry Cohn in Acta Arithmetica (1996) ("Symmetry and specializability in continued fractions") where he finds similar patterns for other kind of continued fractions such as $\sum \frac{1}{10^{n!}}$. Curiously he doesn't mention your particular series although his method applies directly to it.
Let $[a_0,a_1,a_2,\dots,a_m]$ a continued fraction and as usual let
$$ \frac{p_m}{q_m} = [a_0,a_1,a_2,\dots,a_m] $$
we use this lemma from the mentioned article (the proof is not difficult and only uses elementary facts about continued fractions):
[Folding Lemma]
$$ \frac{p_m}{q_m} + \frac{(-1)^m}{xq_m^2} = [a_0,a_1,a_2,\dots,a_m,x,-a_m,-a_{m-1},\dots,-a_2,-a_1] $$
This involves negative integers but it can be easiy transformed in a similar expresion involving only posive numbers using the fact that for any continued fraction:
$$ [\dots, a, -\beta] = [\dots, a-1, 1, \beta-1] $$
So
$$ \frac{p_m}{q_m} + \frac{(-1)^m}{xq_m^2} = [a_0,a_1,a_2,\dots,a_m,x-1,1,a_m-1,a_{m-1},\dots,a_2,a_1] $$
With all this consider the write the $m$th partial sum of your series as
$$ S_n = \sum_{k=1}^n \frac{1}{2^k!} = [0,a_1,a_2,\dots,a_m] = \frac{p_m}{q_m}$$
Where we can take always $m$ even (ie if $m$ is odd and $a_m>1$ then we can consider instead the continued fraction $[0,a_1,a_2,\dots,a_m-1,1]$ and so on).
Now $q_m = 2^n!$ we see it using induction on $n$: it is obvious for $n=1$ and if $S_{n-1} = P/2^{n-1}!$  then
    $$ S_n = \frac{P}{2^{n-1}!} + \frac{1}{2^n!} = \frac{P (2^n!/2^{n-1}!) + 1}{2^n!} $$
now any common factor of the numerator and the denominator is has to be a factor of $2^{n-1}!$ dividing also $P$, but this is impossible as both are coprime so $q_m = 2^n!$ and we are done.
Using the "positive" form of the folding lemma with $x = \binom{2^{n+1}}{2^n}$ we get:
$$ \frac{p_m}{q_m} + \frac{(-1)^m}{\binom{2^{n+1}}{2^n}(2^n!)^2} =
\frac{p_m}{q_m} + \frac{1}{2^n!} =
[0,a_1,a_2,\dots,a_m,\binom{2^{n+1}}{2^n}-1,1,a_m-1,a_{m-1},\dots,a_1] $$
And we get the "shape" of the continued fraction and the your $A_m$. Let's see several steps:
We start with the first term wich is
$$ \frac{1}{2} = [0,2] $$
as $m$ is odd we change and use instead the continuos fraction
$$ \frac{1}{2} = [0,1,1] $$
and apply the last formula getting
$$ \frac{1}{2}+\frac{1}{2^2!}  = [0,1,1,5,1,0,1] $$
We can dispose of the zeros using the fact that for any continued fraction:
$$ [\dots, a, 0, b, \dots] = [\dots, a+b, \dots ] $$
so
$$ \frac{1}{2}+\frac{1}{2^2!}  = [0,1,1,5,2] $$
this time $m$ is even so we apply again the formula getting
$$ \frac{1}{2}+\frac{1}{2^2!}+\frac{1}{2^3!} = [0,1,1,5,2,69,1,1,5,1,1] $$
again $m$ is even (and it will always continue even as easy to infer) so we apply again the formula getting as the next term
$$ \frac{1}{2}+\frac{1}{2^2!}+\frac{1}{2^3!}+\frac{1}{2^4!} = [0,1,1,5,2,69,1,1,5,1,1,12869,1,0,1,5,1,1,69,2,5,1,1] $$
and we reduce it using the zero trick:
$$ \frac{1}{2}+\frac{1}{2^2!}+\frac{1}{2^3!}+\frac{1}{2^4!} = [0,1,1,5,2,69,1,1,5,1,1,12869,2,5,1,1,69,2,5,1,1] $$
from now it is easy to see that the obtained continued fraction always has an even number of terms and we always have to remove the zero leaving a continued fraction ending again in 1,1. So the rule to obtain the continued fraction from here to an arbitrary number of termes is repeating the follewing steps: let the shape of the last continued fraction be $[0,1,1,b_1,\dots,b_k,1,1]$ then the next continued fraction will be
 $$[0,1,1,b_1,\dots,b_k,1,1,A_n,2,b_k,\dots,b_1,1,1 ]$$
from this you can easily derive the patterns you have found for the position of apperance of the different integers.

A: I have computed $10~000$ entries of the continued fraction, using Mathematica (the number itself was evaluated with $100~000$ digit precision).
The results show that the pattern is very simple for the most part.
First, we denote again:
$$A_n= \left( \begin{array}( 2^n \\ 2^{n-1}  \end{array} \right) -1$$
The computed CF contains $A_n$ up to $n=13$, and the formula is numerically confirmed.
Now the positions of $A_n$ go like this ($P_n$ is the position of $A_n$ in the list of all CF entries):
$$P_2=P(5)=[3,8,13,18,23,28,\dots]$$
$$P_3=P(69)=[5,16,25,36,45,56,\dots]$$
$$P_4=[11,30,51,70,91,110,\dots]$$
$$P_5=[21,60,101,140,181,220,\dots]$$
$$P_6=[41,120,201,280,361,440,\dots]$$
But all these are just a combination of two arithmetic progressions for even and odd terms!
The first two terms are a little off, but the rest goes exactly like $P_4,P_5$, meaning for $n \geq 4$ we can write the general position for $A_n$ ($k=0,1,2,\dots$):

$$p_k(A_n)= \begin{cases} 5 \cdot 2^{n-3}(1+2 k)+1,\qquad k \text{ even} \\ 5 \cdot 2^{n-3}(1+2 k),\qquad \qquad k \text{ odd} \end{cases}$$

As special, different cases, we have:

$$p_k(5)=3+5 k,\qquad k=0,1,2,\dots$$
$$p_k(69)= \begin{cases} 2(3+5 k)-1,\qquad k \text{ even} \\ 2(3+5 k),\qquad \qquad k \text{ odd} \end{cases}$$

For $P_1=1$ and for $2$ I can't see any definite pattern so far.

Basically, we now know the explicit expression for every CF entry and all of its positions in the list, except for entries $1$ and $2$.

It's enough now to consider the positions of $2$, then we just fill the rest of the list with $1$. The positions of $2$ start like this:
[4, 12, 17, 22, 24, 29, 37, 42, 44, 52, 57, 59, 64, 69, 77, 82, 84, 92, 97, 102, 104, 109, 117, 119, 124, 132, 137, 139, 144, 149, 157, 162, 164, 172, 177, 182, 184, 189, 197, 202, 204, 212, 217, 219, 224, 229, 237, 239, 244, 252, 257, 262, 264, 269, 277, 279, 284, 292, 297, 299, 304, 309, 317, 322, 324, 332, 337, 342, 344, 349, 357, 362, 364, 372, 377, 379, 384, 389, 397, 402, 404, 412, 417, 422, 424, 429, 437, 439, 444, 452, 457, 459, 464, 469, 477, 479, 484, 492, 497, 502, 504, 509, 517, 522, 524, 532, 537, 539, 544, 549, 557, 559, 564, 572, 577, 582, 584, 589, 597,...]
So far I have found four uninterrupted patterns for $2$:
$$p_{1k}(2)=4+20k,\qquad k=0,1,2,\dots$$
$$p_{2k}(2)=17+20k,\qquad k=0,1,2,\dots$$
$$p_{3k}(2)=29+40k,\qquad k=0,1,2,\dots$$
$$p_{4k}(2)=12+40k,\qquad k=0,1,2,\dots$$
Edit
Discounting these four progressions the rest of the sequence is very close to $20k$, but some numbers are $20k+2$, while some $20k-1$ with no apparent pattern:
[22,42,59,82,102,119,139,162,182,202,219,239,262,279,299,322,342,362,379,402,422,439,459,479,502,522,539,559,582,599,619,642,662,682,699,722,742,759,779,802,822,842,859,879,902,919,939,959,982,1002,1019,1042,1062,1079,1099,1119,1142,1162,1179,1199,1222,1239,1259,1282,1302,1322,1339,1362,1382,1399,1419,1442,1462,1482,1499,1519,1542,1559,1579,1602,1622,1642,1659,1682,1702,1719,1739,1759,1782,1802,1819,1839,1862,1879,1899,1919,1942,1962,1979,2002,2022,2039,2059,2082,2102,2122,2139,2159,2182,2199,2219,2239,2262,2282,2299,2322,2342,2359,2379,2399,2422,2442,2459,2479,2502,2519,2539,2562,2582,2602,2619,2642,2662,2679,2699,2722,2742,2762,2779,2799,2822,2839,2859,2882,2902,2922,2939,2962,2982,2999,3019,3039,3062,3082,3099,3119,3142,3159,3179,3202,3222,3242,3259,3282,3302,3319,3339,3362,3382,3402,3419,3439,3462,3479,3499,3519,3542,3562,3579,3602,3622,3639,3659,3679,3702,3722,3739,3759,3782,3799,3819,3839,3862,3882,3899,3922,3942,3959,3979,4002,4022,4042,4059,4079,4102,4119,4139,4162,4182,4202,4219,4242,4262,4279,4299,4319,4342,4362,4379,4399,4422,4439,4459,4479,4502,4522,4539,4562,4582,4599,4619,4642,4662,4682,4699,4719,4742,4759,4779,4799,4822,4842,4859,4882,4902,4919,4939,4959,4982,5002,...]

The $10~000$ terms of the continued fraction are uploaded at github here. You can check my conjectures or try to obtain the full pattern.

I would also like some hints and outlines for a proof of the above conjectures.

I understand that it's quite likely that any of the patterns I found break down for some large $k$.


text:
Q: html - Abnormal behavior of hyperlinks I have created a div in which I have put some hyperlinks. On those, I have added some styling that when I hover over them they get an underline, pretty simple. But when I try to hover over them an unusual small line appears.
Here is the jsFiddle.
HTML:

        HOME
        ABOUT US
        PORTFOLIO
        CONTACT US

CSS:
html, body{
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
}

#header {
    width: 100%;
    height: 30%;
    background-image: url(http://www.7daysinhavana.com/wordpress/wp-content/themes/7days/images/commun/back_header_global.jpg);
    font-family: 'GarageGothicBlackRegular';
    word-spacing: 20px;
    font-size: 25px;
    text-align: center;
    position: relative;
}

#header-links-holder {
    position: absolute;
    width:100%;
    bottom: 0px;
}

#header a {
    color: black;
    text-decoration: none;
}

#header a:hover{
    text-decoration: underline;
}

.no-spacing {
    word-spacing: 0px;
}

Try hovering over the HOME link and see the result.
How can I fix this error?

A: It's a typo, you are not closing your a tag
HOME

Demo
Always use validator to avoid such errors and use debugging tools like firebug

Note: Also view source of your HTML documents, as far as I know,
  Firefox will highlight stray tags in red

A: Here's your problem:
HOME

You forgot the closing
    HOME


text:
Q: is there a way to do session manage using sinatra framework with cloudfoundry? none of the tutorials I found online seem to cover this. I mean that do but I'm not seeing what they say I should be seeing when I do the check. is this because I'm on the cloudfoundry platform? if you could direct me to some literature or give me a hint that would be great! I am trying to implement session control by some storing information in a cookie,review that cookie, and compare it to a session table in my db each time the user makes a HTTP request.

A: This is pretty straight forward. Just make sure you have sessions enabled in Sinatra and use the session_id as a key in your database. I created a little example at https://gist.github.com/danhigham/4943057
The example gets a tweet from twitter as json and retrieves a collection from Redis using the session_id as a key, adds the tweet to the collection as json and then stores it back in the same record.
I have also pushed the example to http://session-tweet.cloudfoundry.com


text:
Q: unable to push the vagrant image to atlas I have used the ubuntu/trusty64 image for creating the vm. I added few installation and now I want to store the new image in the atlas public account. But I am not able to push the image to atlas. I tried the vagrant push but I am getting following error message.
subh@ubuntu_14$ vagrant push atlas
error archiving: No VCS found for path: /Users/subh/subh_mac/vagrant/ubuntu_14

My push scheme is following in VagrantFile :
config.push.define "atlas" do |push|
     push.app = "subh/ovs_docker"  # this box does not exist in my atlas account
end

Please let me know, how could I push the image to my Atlas account using vagrant push.

A: did you ensure that you have the repo initialized within git, and have performed one commit?
An example, which would add all the files to the repo, then commit the files to your newly initialized repo.
git init
git add *
git commit -am "new init, first commit, vagrant"
vagrant push

A: Within your vagrantfile, you should specify where the push will go...
For example:
 config.push.define "ftp" do |push|
  push.host = "ftp.company.com"
  push.username = "username"
  push.password = "mypassword"
end


text:
Q: What does "**" mean in python? Simple program:
storyFormat = """
Once upon a time, deep in an ancient jungle,
there lived a {animal}.  This {animal}
liked to eat {food}, but the jungle had
very little {food} to offer.  One day, an
explorer found the {animal} and discovered
it liked {food}.  The explorer took the
{animal} back to {city}, where it could
eat as much {food} as it wanted.  However,
the {animal} became homesick, so the
explorer brought it back to the jungle,
leaving a large supply of {food}.

The End
"""

def tellStory():
    userPicks = dict()
    addPick('animal', userPicks)
    addPick('food', userPicks)
    addPick('city', userPicks)
    story = storyFormat.format(**userPicks)
    print(story)

def addPick(cue, dictionary):
    '''Prompt for a user response using the cue string,
    and place the cue-response pair in the dictionary.
    '''
    prompt = 'Enter an example for ' + cue + ': '
    response = input(prompt).strip() # 3.2 Windows bug fix
    dictionary[cue] = response

tellStory()
input("Press Enter to end the program.")

Focus on this line:
    story = storyFormat.format(**userPicks)

What does the ** mean? Why not just pass a plain userPicks?

A: '**' takes a dict and extracts its contents and passes them as parameters to a function. Take this function for example:
def func(a=1, b=2, c=3):
   print a
   print b
   print b

Now normally you could call this function like this:
func(1, 2, 3)

But you can also populate a dictionary with those parameters stored like so:
params = {'a': 2, 'b': 3, 'c': 4}

Now you can pass this to the function:
func(**params)

Sometimes you'll see this format in function definitions:
def func(*args, **kwargs):
   ...

*args extracts positional parameters and **kwargs extract keyword parameters.

A: **means kwargs. here is a good article about it.
read this: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/


text:
Q: Elasticsearch Index type doesn't changed after updating status I've made some _bulk insert successfully , now I'm trying to make query with date range and filter something like:
{
   "query": {
        "bool": {
            "must": [{
                "terms": {
                    "mt_id": [613]
                }
            },
            {
                "range": {
                    "time": {
                        "gt": 1470009600000,
                        "lt": 1470009600000
                    }
                }
            }]
        }
    }

Unfortunately I got no results , Now I noticed that the index mapping is created after bulk insert as following:
{
  "agg__ex_2016_8_3": {
    "mappings": {
      "player": {
        "properties": {
          "adLoad": {
            "type": "long"
          },
         "mt_id": {
           "type": "long"
          },
          "time": {
            "type": "string"
          }
        }
      },

As a solution I tried to change the index mapping with:
PUT /agg__ex_2016_8_3/_mapping/player
{
  "properties" : {
    "mt_id" : {
      "type" :    "long",
      "index":    "not_analyzed"
    }
  }
}

got
{
  "acknowledged": true
}

and PUT /agg__ex_2016_8_3/_mapping/player
{
  "properties" : {
    "time" : {
      "type" :    "date",
     "format" : "yyyy/MM/dd HH:mm:ss"
    }
  }
}

got:
{
   "error": {
      "root_cause": [
         {
            "type": "remote_transport_exception",
            "reason": "[vj_es_c1-esc13][10.132.69.145:9300][indices:admin/mapping/put]"
         }
      ],
      "type": "illegal_argument_exception",
      "reason": "mapper [time] of different type, current_type [string], merged_type [date]"
   },
   "status": 400
}

but nothing happened , and still doesn't get any results.
What i'm doing wrong ? ( I must work with http , not using curl)
Thanks!!

A: Try this:
# 1. delete index
DELETE agg__ex_2016_8_3

# 2. recreate it with the proper mapping
PUT agg__ex_2016_8_3
{
  "mappings": {
    "player": {
      "properties": {
        "adLoad": {
          "type": "long"
        },
        "mt_id": {
          "type": "long"
        },
        "time": {
          "type": "date"
        }
      }
    }
  }
}

# 3. create doc
PUT agg__ex_2016_8_3/player/104
{
  "time": "1470009600000",
  "domain": "organisemyhouse.com",
  "master_domain": "613###organisemyhouse.com",
  "playerRequets": 4,
  "playerLoads": 0,
  "c_Id": 0,
  "cb_Id": 0,
  "mt_Id": 613
}

# 4. search
POST agg__ex_2016_8_3/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "mt_Id": [
              613
            ]
          }
        },
        {
          "range": {
            "time": {
              "gte": 1470009600000,
              "lte": 1470009600000
            }
          }
        }
      ]
    }
  }
}


text:
Q: Custom validation for @PathVariable There is a controller accepting code as a path variable
@RestController
@RequestMapping(value = "/api/currency")
@Validated
public class CurrencyController {

    @GetMapping("/gif/{code}")
    public ResponseEntity<Map> getChangeGif(@PathVariable @Code String code){
        // some implementation
        return null;
    }
}

I want to use my own annotation to validate code as I want
@Target( { FIELD, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy =  CodeValidator.class)
public @interface Code {

    public String message() default "error message";

    public Class<?>[] groups() default {};

    public Class<? extends Payload>[] payload() default {};
}

And here is the validator
public class CodeValidator implements ConstraintValidator<Code, String> {
    @Override
    public void initialize(Code constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(String code, ConstraintValidatorContext context) {
        // validator implementation
        return false;
    }
}

For some reason when requests come, validation just skipps, and controller continue working without it


text:
Q: Split string into list of string I have a string which is 28000 lines long and is laid out like below:
List<string> sQuerys = new List<string>();

string FullFileQuery = " EXEC spDataCache_INS_XSCDV1P @Company = 'UKC                                ', @Country = 'AE                                 ', @Trade_Lane = 'ARABIAN GULF/MIDDLE EAST           ', @Trade_Region = 'INDIA/PAKISTAN/MIDDLE EAST         '
EXEC spDataCache_INS_XSCDV1P @Company = 'UKC                                ', @Country = 'AL                                 ', @Trade_Lane = 'MEDITERRANEAN                      ', @Trade_Region = 'EUROPE/MEDITERRANEAN               '
EXEC spDataCache_INS_XSCDV1P @Company = 'UKC                                ', @Country = 'AO                                 ', @Trade_Lane = 'WEST AFRICA                        ', @Trade_Region = 'AFRICA                             '
EXEC spDataCache_INS_XSCDV1P @Company = 'UKC                                ', @Country = 'AR                                 ', @Trade_Lane = 'EAST COAST SOUTH AMERICA           ', @Trade_Region = 'LATIN AMERICA                      '
EXEC spDataCache_INS_XSCDV1P @Company = 'UKC                                ', @Country = 'AU                                 ', @Trade_Lane = 'AUSTRALIA/NEW ZEALAND              ', @Trade_Region = 'FAR EAST AND OCEANIA               '"

I want to split the string every 15000th line and add to my list of string sQuerys.
So the 28000 lines will be split into 15000 lines and 13000 lines and added to the list. I am unsure on the quickest way to achieve this.
EDIT:
The code I have tried doing but I am stuck is below:
if (FullFileQuery.Split('\n').Length > 15000)
{
    //28000
    int numLines = FullFileQuery.Split('\n').Length;
    //LOOP TWICE.
    for (int i = 0; i < ((numLines / 15000) + 1); i++)
    {
        //NEED TO ADD TO sQuerys in here.
    }
}

A: You can use the Skip and Take Linq methods to do something like this:
int chunkSize = 15000;
var splitted = FullFileQuery.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
int chunks=splitted.Length/chunkSize; //Get number of chunks

for (int i=0;i<chunks;i++)
{
    sQuerys.Add(string.Join(Environment.NewLine,splitted
                            .Skip(i * chunkSize) //skip the already added lines
                            .Take(chunkSize))); //take the new lines
}

So basically first we split all the lines into splitted. Then we divide that splitted array length by the chunk size we want to get how many chunks are we going to get. Finally, we loop this number of chunks first using Skip to "jump" the lines we already added to the previous chunks and then Take to take the chunk.
Haven't tried it so comment if there is something not working.

A: You could use something like
class Program
{
    static void Main(string[] args)
    {
        var input = @"your long multiline string...";

        var list = new List<string>();
        var lines = input.Split('\n');
        var index = 0;
        var batchSize = 15000;
        while (index < lines.Count())
        {
            list.Add(string.Join(string.Empty, lines.Skip(index).Take(batchSize)));
            index += batchSize;
        }
    }
}

A: This extension method will batch any type of list into an IEnumerable of batches.
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source, int batchSize)
{
    var batch = new List<T>(batchSize);

    foreach (var item in source)
    {
        batch.Add(item);

        if (batch.Count == batchSize)
        {
            yield return batch;
            batch = new List<T>(batchSize);
        }
    }

    if (batch.Any())
    {
        yield return batch;
    }
}

You can use it like this:
var batchesOfLines = allLines.Batch(15000);


text:
Q: Laravel - Self referential relationship does not work I work with Laravel 8
In my database I have a Menu table with this data:
id  | id_parent | name         | route                 | routename            | term   | active
----------------------------------------------------------------------------------------
1   | NULL      | "Home"       | "/"                   | "home"               | "main" | 1
2   | NULL      | "Storage"    | "/storage"            | "storage"            | "main" | 1
3   | 2         | "Devices"    | "/storage/devices"    | "storage.devices"    | "main" | 1
4   | 2         | "New Device" | "/storage/new-device" | "storage.new-device" | "main" | 1

In my Menu Model I have this code:
public function parent()
{
    return $this->belongsTo('App\Models\Menu', 'id_parent');
}

public function children()
{
    return $this->hasMany('App\Models\Menu', 'id_parent');
}

And the function in my Controller looks like this:
static function getMenu($term)
{
    $id_userrole = Auth::user()->id_userrole;
    $route = \Request::route()->getName();
    $menu = Menu::select('name','route','routename')
    ->with('children')
    ->where([['term',$term], ['active',1],['id_parent',null]])
    ->whereHas('access', function($q) use ($id_userrole) {
        $q->where('id_userrole', $id_userrole)
        ->orWhere('id_userrole', 0);
    })
    ->get();
    dump($menu);

    foreach($menu as &$m) {
        $m->isActive = $route == $m->routename ? 1 : 0;

        foreach($m->children as &$m2) {
            $m2->isActive = $route == $m2->routename ? 1 : 0;
            $m->isActive = $m2->isActive;
        }
    }

    return ApiResource::collection($menu);
}

If i want to get children, the array is empty. This is my output:
{"data":[{"name":"Home","route":"\/","routename":"home","isActive":0,"children":[]},{"name":"Storage","route":"\/storage","routename":"storage","isActive":0,"children":[]}]}

What am I doing wrong?

A: The children relationship will work if model result has id column, you can test like this:
Menu::with('children')->all();

BTW, the parent relationship should be:
public function parent()
{
    return $this->belongsTo('App\Models\Menu', 'id', 'id_parent');
}

And if you want to get children's children's children...
public function descendants()
{
    return $this->children()->with('descendants');
}


text:
Q: Why BufferedImage is not working well?!! Is it because I misused it? I want to copy a gray image using BufferedImage from getRGB() to int[][] and then to setRGB(). The problem is that the size of image is different from the size of the one that the program outputs it. The original image has file size = 176 KB, whereas the output image has file size = 154 KB. I have to say that when you see the two image, all of the human-being would say it is the same, but in terms of binary bits, there are different in something that I would like to know.
Maybe some of you will say it doesn't matter, as long as image is the same when you look at it. In fact, during the processing of some noise project, this is a huge problem, and I suspect that this is the reason why I have the problem.
I just want to know if there are other method than BufferedImage to produce int[][] and then to create the output?
This is the code that I'm using:
public int[][] Read_Image(BufferedImage image)
{
  width = image.getWidth();
  height = image.getHeight();
  int[][] result = new int[height][width];
  for (int row = 0; row < height; row++)
     for (int col = 0; col < width; col++)
        result[row][col] = image.getRGB(row, col);
  return result;
}

public BufferedImage Create_Gray_Image(int [][] pixels)
{
    BufferedImage Ima = new BufferedImage(512,512, BufferedImage.TYPE_BYTE_GRAY);
    for (int x = 0; x < 512; x++)
    {
        for (int y = 0; y < 512; y++)
        {
            int rgb = pixels[x][y];
            int r = (rgb >> 16) & 0xFF;
            int g = (rgb >> 8) & 0xFF;
            int b = (rgb & 0xFF);

            int grayLevel = (r + g + b) / 3;
            int gray = (grayLevel << 16) + (grayLevel << 8) + grayLevel;
            Ima.setRGB(x, y, pixels[x][y]);
        }
    }
    return Ima;
}

 public void Write_Image(int [][] pixels) throws IOException
{
    File outputfile;
    outputfile = new File("Y0111.png");
    BufferedImage BI = this.Create_Gray_Image(pixels);
    ImageIO.write(BI, "png", outputfile);
    System.out.println("We finished writing the file");
}

See the figure, you see file size = 176 KB (this is the original image) and file size = 154 KB (this is the output image).

A: The difference of size is not a problem. It's certainly because of different compression/encoding.
A BufferedImage is in fact a 1D array of size width * height * channel. getRGB is not the easiest/fastest way to manipulate a BufferedImage. You can use the Raster (faster than getRGB, not the fastest, but it takes care of the encoding for you). For a gray level image:
int[][] my array = new int[myimage.getHeight()][myimage.getWidth()] ;
for (int y=0 ; y < myimage.getHeight() ; y++)
    for (int x=0 ; x < myimage.getWidth() ; x++)
        myarray[y][x] = myimage.getRaster().getSample(x, y, 0) ;

The opposite way:
for (int y=0 ; y < myimage.getHeight() ; y++)
    for (int x=0 ; x < myimage.getWidth() ; x++)
        myimage.getRaster().setSample(x, y, 0, myarray[y][x]) ;

The fastest way to do it is to use the DataBuffer, but then you have to handle the image encoding.


text:
Q: How to use Humanoid Model : Animator(property) in scripts using Unity Scriptable API I'm newbie at unity animations and stuff and I want to create a game scene in which at run time I would be able to move a humanoid 3D model and save the movement as an animation (.anim) file.
I may move the parts of the model by mouse or by mapping scrolling bars to animation property values, somehow.
To do all this I decided to go for the animators (properties) of a model. Kindly look at the picture in the link below to know exactly what I am talking about. (Wasn't able to post image since I'm new to stack overflow too)

I searched the unity Scriptable API for this but wasn't able to find the documentation on how to use the above mentioned property directly in your scripts so that animation curves can be generated from them.
Is it possible to do this?
Is there a better way to record animations of humanoid models at runtime (in-game mode)  or a better property for humanoid models to use?
Note: The whole animation process is to be handled through code.


text:
Q: How do I activate my virtual environment with cronjob? I am running a python script. The script requires environment variables that are defined in my virtaul environment's ~/.bash_profile
Here is my cronjob script, I edit it by SSHing to my EC2 instance and running:
crontab -e

*/1 * * * * cd /home/ec2-user/code/green_brick_django/pricecomparison_project/pricecomparison && /home/ec2-user/MYVENV/bin/python /home/ec2-user/code/green_brick_django/pricecomparison_project/pricecomparison/run_cronjob_script.sh > /tmp/cronlog.txt 2>&1

I keep getting a python error saying it can't find my ENVIRONMENT variables.
What am I doing wrong? Please help!
I've tried every single option listed here, multiple times over, in every which way I can think of. Please!
Cron and virtualenv

A: Cron started by system. It has minimal environment and nothing about your shell. Your command is unable to load the environment and result in python error. Load your it by updating your command like below.
*/1 * * * * $HOME/.bash_profile;/home/ec2-user/MYVENV/bin/python /home/ec2-user/code/green_brick_django/pricecomparison_project/pricecomparison/run_cronjob_script.sh > /tmp/cronlog.txt 2>&1
Go through Loading environment variables link for other options for loading your environment variables.
I hope this will help you.


text:
Q: How to control the unit of a time difference in R? I calculate some durations in R as shown below. Depending of the value of the duration, the unit can be minutes, hours, days, etc.:
library(lubridate)
start <- "2022-08-27 10:06:58"
end <- "2022-08-27 10:10:24"
start <- as_datetime(start)
end   <- as_datetime(end)
end - start
# Time difference of 3.433333 mins
start - Sys.time()
# Time difference of -3.136468 days

I want to always get the durations in minutes, how could I achieve that?

A: You do not need lubridate but you likely want an argument to difftime():
Code
start <- as.POSIXct("2022-08-27 10:06:58")
end <- as.POSIXct("2022-08-27 10:10:24")
difftime(end, start, unit="mins")

Output
> start <- as.POSIXct("2022-08-27 10:06:58")
> end <- as.POSIXct("2022-08-27 10:10:24")
> difftime(end, start, unit="mins")
Time difference of 3.43333 mins
>

And yup, likely a duplicate a few times over.


text:
Q: using es6 import syntax with typescript in the browser I am making simple web-app with typescript only (no module bundlers, ui framework or anything) In my app I am using one third party package I've downloaded using npm (that supports typescript)
In my main script.ts file I've imported it like
import * as Tone from 'tone';

But then I am getting the error
Uncaught ReferenceError: exports is not defined
    <anonymous> http://127.0.0.1:5500/dist/script.js:7

My tsconfig.js looks as follows:
{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "CommonJS",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    "outDir": "./dist",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */
    // "noUncheckedIndexedAccess": true,      /* Include 'undefined' in index signature results */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  }
}

What is the problem here?

A: export the module and in another script, you have to set the type attribute with module value for its script tag, after that you can import the module.
e.g:
export.js:
export function test(){console.log(123)}

import.js:
import {test} from "./export.js";

test();

index.html:
<script src="./import.js" type="module"></script>

console output: 123


text:
Q: android play games services "your application is incorrectly configured" just when I publish it I've been working on an android game that uses Google play services and it was working great on Eclipse ADT, correctly configured and all, but when I published it, I got the message "the application is incorrectly configured. Check that the package name and signing certificate match the client ID... ". But it worked on Eclipse, so what am I doing wrong? I really don't know how to explain any more than this, but can anyone help me?

A: found how to solve it: used the debug.keystore located in my .android folder when I was exporting my APK

A: After 4 hours of researching, i found the solution to fix this error successfully:
When developing, make sure you sign the SHA1 with you debug.keystore NOT release keystore.
 Good luck!


text:
Q: Accessing a given file by date on PowerShell I wrote this in PowerShell:
Ideally it should check $myDIRECTORY and get all the files that have been created during $myCreationTime, it works flawlessly, now I want to access the file, so I wrote a For-Each-Object{} to print the file:
    Get-ChildItem $myDIRECTORY  | Where-Object {
    $_.CreationTime.Date.ToString() -match $myCreationTime | ForEach-Object{
        Write-Host $_.ToString()
    }
}

However I get the boolean Match value, so:
False
False
True
False

How can I get the True file? $_.BaseName isn't working and it's unsurprisingly, I understand it's a boolean, so I don't even know why I tried it!

A: In your foreach loop you get only the result of the match operation.
Try it like that:
Get-ChildItem $myDIRECTORY  | ForEach-Object {
    If ($_.CreationTime.Date.ToString() -match $myCreationTime) {
        $_.BaseName
    }
}


text:
Q: Building Subversion on Windows 7 with Visual Studio 2010 I'm currently trying to build subversion 1.7.3 with Visual Studio 2010 SP1 on Windows 7 SP1.
I'm not really experienced in building open source software myself, but it's not always easy to find a complete binary package where I can find the right modules for. Therefore I thought I try building it myself. Now I'm stuck at executing the gen-make.py and can't find any solutions on the web.
The error is, I get an invalid syntax error:
File "gen-make.py", line 271
    except getopt.GetoptError, e:
                             ^
SyntaxError: invalid syntax

I don't think it has to do with the dependencies I submitted, because the same error is shown when I open the gen-make.py in IDLE.
I'm not experienced with python or compiling open source software myself. So I'm stuck and can't figure out what's going wrong.
I'm using Python 3.2.2.
I'm calling python with the following line:
F:\Open Source\subversion-1.7.3>python gen-make.py -t vcproj --vsnet-version=2010 --with-berkeley-db=..\bdb --with-openssl=..\openssl-1.0.0g --with-httpd=..\httpd-2.4.1 --with-neon=..\neon --with-serf=..\serf --with-sqlite=..\sqlite --with-zlib=..\zlib

Has anyone some clues what I am missing here?
====
Update:
I've tried it with Python 2.7. And the syntax error is gone. But nothing is perfect. ;)
Now I'm facing another problem: It says it can't find apr, I've downloaded apr yet having trouble getting it to work. I'm tired now and I think I'll come back tomorrow, looking into it.
The exact error is as follows:
ERROR: '..\httpd-2.4.1\srclib\apr\include\apr_version.h' not found.
Use '--with-apr' option to configure APR location.

Greetings,
Skalli

A: That's Python 2 syntax, run it with Python 2 instead.

A: I've never built Subversion on Windows. However, I know there's a major difference between Python 3.x syntax and Python 2.7.x syntax, and that one is not compatible with the other.
Were you told to use Python 3.x? Most people are still using Python 2.7.x, and I suspect that you need to use Python 2.7.x.


text:
Q: How to carry variables into different function First of all sorry for this heavy, blunt code.
I know there are some better and more eye-candy codes out there but I decided to write it by myself. I know there is a room for HUGE improvement but bear with me.
Almost all my code is working surprisingly except the score part.
Basically this is a Rock Paper Scissors game with recording the number of wins for player, for computer and total number of games.
I only couldn't pass the scores into another function. Can someone please let me know why I am getting this error when I am selecting "1 - Score" on repeat game function
Traceback (most recent call last):
  File "forweb.py", line 123, in <module>
    main_menu()
  File "forweb.py", line 27, in main_menu
    play_game()
  File "forweb.py", line 95, in play_game
    return player, computer, total, repeat_game()
  File "forweb.py", line 112, in repeat_game
    play_game()
  File "forweb.py", line 47, in play_game
    play_game()
  File "forweb.py", line 95, in play_game
    return player, computer, total, repeat_game()
  File "forweb.py", line 107, in repeat_game
    print("Total Game: "+ play_game(total))
NameError: name 'total' is not defined

note: please ignore "from game_text import game_information" since it is on another python file
import random
import sys
import os
import time
from game_text import game_information
os.system('clear')
name = input("Please write your name: ")

def main_menu():

  menu_selection_word = input("1-Help, 2-Play, 3-Quit \n"))
  try:
    menu_selection_int = int(menu_selection_word)
    print("you have selected: ", menu_selection_int)
  except ValueError:
    print(" Invalid selection")
    main_menu()

  if menu_selection_int == 1:
    os.system('clear')
    game_information()
    main_menu()
  elif menu_selection_int == 2:
    play_game()
  elif menu_selection_int == 3:
    game_quit()
  else:
    print("Invaild selection \n")
    main_menu()

def play_game(player=0,computer=0,total=0):
  total += 1
  player_selection_input = input("R-Rock, S-Scissors, P-Paper \n")

  if player_selection_input == "R" or player_selection_input == "r":
    print("You have selected Rock")
  elif player_selection_input == "S" or player_selection_input == "s":
    print("You have selected Scissors")
  elif player_selection_input == "P" or player_selection_input == "p":
    print("You have selected Paper")
  else:
    print("Invaild selection \n")
    play_game()

  comp_random = ["R", "r", "S", "s", "P", "p"]
  comp_selection = random.choice(comp_random)

  if comp_selection == "R" or comp_selection == "r":
    print("Computer Selected: Rock")
  elif comp_selection == "P" or comp_selection == "p":
    print("Computer Selected: Paper")
  else:
    print("Computer Selected: Scissors")

  if player_selection_input == "R" or player_selection_input == "r":
    if comp_selection == "S" or comp_selection == "s":
        print("Your Rock crushed computer's scissors! You Won!")
        player += 1
        time.sleep(1.5)
    elif comp_selection == "R" or comp_selection == "r":
        print("It is a tie!")
        time.sleep(1.5)
    else:
        print("Computer's Paper covered your Rock! You Lost!")
        computer += 1
        time.sleep(1.5)
  elif player_selection_input == "S" or player_selection_input == "s":
    if comp_selection == "S" or comp_selection == "s":
        print(" It is a tie!")
        time.sleep(1.5)
    elif comp_selection == "R" or comp_selection == "r":
        print("Computer's Rock crushed your Scissors. You Lost!")
        computer += 1
        time.sleep(1.5)
    else:
        print("Your Scissors cut computer's Paper. You Won!")
        player += 1
        time.sleep(1.5)
  elif player_selection_input == "P" or player_selection_input == "p":
    if comp_selection == "R" or comp_selection == "r":
        print("Your Paper covered computer's Rock. You Won!")
        player += 1
        time.sleep(1.5)
    elif comp_selection == "S" or comp_selection == "s":
        print("Computer's Scissors cut your Paper. You Lost!")
        computer += 1
        time.sleep(1.5)
    else:
        print(" It is a tie!")
        time.sleep(1.5)
  return player, computer, total, repeat_game()

def repeat_game():
  repeat_game_selection = input("1-Score, 2-New game, 3-Quit \n")

  try:
    repeat_game_select = int(repeat_game_selection)
  except ValueError:
    print(" Invalid selection")
    repeat_game()
  if repeat_game_select == 1:
    os.system('clear')
    print("Total Game: "+ play_game(total))
    Print("Player Win: "+ play_game(player))
    print("Computer Win: "+ play_game(computer))
  elif repeat_game_select == 2:
    print("New Game begins \n")
    play_game()
  elif repeat_game_select == 3:
    game_quit()
  else:
    print("Invaild selection \n")
    repeat_game()

def game_quit():
  os.system('clear')
  sys.exit("Thank you for Playing. See you next time!")

main_menu()

A: You want to pair
    return player, computer, total, repeat_game()

with a call like this:
    player, computer, total, repeat_game = play_game()

That is, if the public API returns four values, you will want to pick up those values.
Four is starting to become an inconveniently largish number.
You'd probably be better off defining a class and storing four object attributes,
such as self.player.


text:
Q: Problem about number 2 display on the 7-segment display Currently i am doing a project on blinking two LED at random interval of time and count the number of blinks in one minute. I encounter one problem which is when number 2 display on the 7-segment display, the number 2 display looks weird. I hope anyone can help me to solve this issue. I had also attached my circuit diagram and the picture with weird number 2 below.
const int a=5;
const int b=4;
const int c=1;
const int d=2;
const int e=3;
const int f=7;
const int g=8;
const int DP=0;
const int lowerThreshold = 150;
const int upperThreshold = 200;
const int ldrPin = A0; // select the input pin for the LDR
int ledPin = 9;    // select the pin for the LED
int ledPin2 = 10;
int counter = 0;
int analogValue = 0;
unsigned long int timer;

void setup() {
  // declare the ledPin as an OUTPUT
  pinMode(ledPin, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ldrPin, INPUT);
  pinMode(a,OUTPUT);
  pinMode(b,OUTPUT);
  pinMode(c,OUTPUT);
  pinMode(d,OUTPUT);
  pinMode(e,OUTPUT);
  pinMode(f,OUTPUT);
  pinMode(g,OUTPUT);
  pinMode(DP,OUTPUT);
  Serial.begin(9600);
  Serial.println("CLEARDATA");
  Serial.println("LABEL,Time,Timer,Count for LED,Count for LED2");
}

void loop() {
  timer = millis()/1000;
  analogValue = analogRead(ldrPin); // Reading LDR Input.
  digitalWrite(ledPin, HIGH);
  digitalWrite(ledPin2, HIGH);
  Serial.println("DATA,Time," + String(timer) + "," + String(counter) + "," + String(counter));
  if(counter == 10|| timer > 60)
  {
    digitalWrite(ledPin, LOW);
    digitalWrite(ledPin2, LOW);
    Serial.println("SAVEWORKBOOK");
    Serial.println("STOPLOGGING");
  }else
  {
    counter++;
  }
  delay(random(20,3000));
  digitalWrite(ledPin, LOW);
  digitalWrite(ledPin2, LOW);
  delay(random(20,3000));
  switch(counter)
  {
    case 0:
    digitalWrite(a, HIGH);
    digitalWrite(b, HIGH);
    digitalWrite(c, HIGH);
    digitalWrite(d, HIGH);
    digitalWrite(e, HIGH);
    digitalWrite(f, HIGH);
    digitalWrite(g, LOW);
    digitalWrite(DP, HIGH);
    break;

    case 1:
    digitalWrite(a, LOW);
    digitalWrite(b, HIGH);
    digitalWrite(c, HIGH);
    digitalWrite(d, LOW);
    digitalWrite(e, LOW);
    digitalWrite(f, LOW);
    digitalWrite(g, LOW);
    digitalWrite(DP, HIGH);
    break;

    case 2:
    digitalWrite(a, HIGH);
    digitalWrite(b, HIGH);
    digitalWrite(c, LOW);
    digitalWrite(d, HIGH);
    digitalWrite(e, HIGH);
    digitalWrite(f, LOW);
    digitalWrite(g, HIGH);
    digitalWrite(DP, HIGH);
    break;

      case 3:
      digitalWrite(a, HIGH);
      digitalWrite(b, HIGH);
      digitalWrite(c, HIGH);
      digitalWrite(d, HIGH);
      digitalWrite(e, LOW);
      digitalWrite(f, LOW);
      digitalWrite(g, HIGH);
      digitalWrite(DP, HIGH);
      break;

      case 4:
      digitalWrite(a, LOW);
      digitalWrite(b, HIGH);
      digitalWrite(c, HIGH);
      digitalWrite(d, LOW);
      digitalWrite(e, LOW);
      digitalWrite(f, HIGH);
      digitalWrite(g, HIGH);
      digitalWrite(DP, HIGH);
      break;

      case 5:
      digitalWrite(a, HIGH);
      digitalWrite(b, LOW);
      digitalWrite(c, HIGH);
      digitalWrite(d, HIGH);
      digitalWrite(e, LOW);
      digitalWrite(f, HIGH);
      digitalWrite(g, HIGH);
      digitalWrite(DP, HIGH);
      break;

      case 6:
      digitalWrite(a, HIGH);
      digitalWrite(b, LOW);
      digitalWrite(c, HIGH);
      digitalWrite(d, HIGH);
      digitalWrite(e, HIGH);
      digitalWrite(f, HIGH);
      digitalWrite(g, HIGH);
      digitalWrite(DP, HIGH);
      break;

      case 7:
      digitalWrite(a, HIGH);
      digitalWrite(b, HIGH);
      digitalWrite(c, HIGH);
      digitalWrite(d, LOW);
      digitalWrite(e, LOW);
      digitalWrite(f, LOW);
      digitalWrite(g, LOW);
      digitalWrite(DP, HIGH);
      break;

      case 8:
      digitalWrite(a, HIGH);
      digitalWrite(b, HIGH);
      digitalWrite(c, HIGH);
      digitalWrite(d, HIGH);
      digitalWrite(e, HIGH);
      digitalWrite(f, HIGH);
      digitalWrite(g, HIGH);
      digitalWrite(DP, HIGH);
      break;

      case 9:
      digitalWrite(a, HIGH);
      digitalWrite(b, HIGH);
      digitalWrite(c, HIGH);
      digitalWrite(d, HIGH);
      digitalWrite(e, LOW);
      digitalWrite(f, HIGH);
      digitalWrite(g, HIGH);
      digitalWrite(DP, HIGH);
      break;

      break;
  }
}

A: You're using pins 0 and 1 to drive your display ('dp' and 'c'), but these pins are also used for the Arduino's serial port (RX and TX).
This explains why segment "c" also lights up when displaying "2", as it is connected to your serial TX port and your program is sending output to it.
The solution is to use different (unused) pins for segments 'c' and 'dp', for example 11 and 12 as they don't seem to be used in your sketch.


text:
Q: PHP array print statement Here is my code:
        if(is_file($userName.".txt")) {
            $userDetails = explode(',', file_get_contents($userName.".txt"));
            print($userDetails[0]);
            if ($password == $userDetails[0]) {
                print('Correct login');
            } else {
                print('Incorrect login');
            }
        }

And I have the following file: Simon.txt with the following contents: simonpassword,4,1
If the $userName is 'Simon', when the code is run, how come 4 is printed out instead of simonpassword at the line: print($userDetails[0])?

A: <?
$userName = "Simon";
$password = "simonpassword";
if(is_file($userName.".txt")) {
        $userDetails = explode(',', file_get_contents($userName.".txt"));
        print($userDetails[0]);
        if ($password == $userDetails[0]) {
            print('Correct login');
        } else {
            print('Incorrect login');
        }
    }
?>

Here is Simon.txt
simonpassword,4,1

And it works.


text:
Q: SQL Server 2012 AlwaysOn performance best practice Is it best practice to have 2 Primary then 1 Secondary for SQL Server AlwaysOn Availability Groups?
My purpose for having 2 Primary instances is to balance the database load. (e.g. my db1 and db2 is on 1st Primary Server then my db3 and db4 is on 2nd Primary Server, then i will configure my AG to add db1 and db2 to 2nd Primary as passive and db3 and db4 to my 1st Primary Server as passive).
Will this improve the performance of my SQL Server?

A: AlwaysON in a roundabout way can help with overall performance but it does that by helping you scale out the reads to other nodes which then also help you with blocking/locking.
From how you described it you are spreading out your databases across 2 different instances, but then making replica's of each instance on the other database server.  Outside of locking/blocking benefits you won't get too much out of this, so no, I wouldn't consider this a 'best practice' for performance.  Your active production databases are still sharing server resources with the read only copies.  Thus, this isn't a 'best practice' for performance and AGs.  Also AG's represent a issue where you have to decide if you're willing to get data that's a little bit stale and near real time, or if you want to force performance loss on the master writer and keep the data on the secondary up to date.
If you're interested, here is how StackExchange uses AGs to give you a bit more idea of how enterprises use it.

A: If you take a look at this article http://solutioncenter.apexsql.com/performance-monitoring-of-alwayson-availability-groups-part-1/ - you will understand that AlwaysOn availability group performance is not linked with "performance" but with "reliability". AlwaysOn is the synergy of the best of clustering (FCI) and database mirroring, folded in the single feature - as analogy to this, look at this as RAID 1 which is there to keep your data safe, rather than RAID 0 which sacrifies reliability to gain some performance.
Unlike monitoring the Failover cluster or mirroring (where passive/secondary components are inactive), AlwaysOn Availability Group allows the direct interaction between a user and secondary databases, but ONLY for reading (not writing).
What's more - with AlwaysOn, the failover is possible for a single database, a group of databases or for the entire SQL Server instance. In addition, AlwaysOn availability group allows the user to create more than one failover target and to have the full control of the failover process.
So, by careful planning you can actually get some performance improvements, by distributing loads from primary to secondary etc. Anyway, I strongly advise you to monitor AlwaysOn metrics to get some insight in how your AlwaysOn AG behaves performance wise and if needed you can reconfigure your AG to squeeze out some better performance if possible.
You can use some SSMS built-in monitoring solutions via AlwaysOn dashboard or use T-SQL scripts for direct querying of the AlwaysOn dedicated DMVs (or Performance Monitor, but it's a bit tricky).
Create alerts and notification on AlwaysOn metrics that can help you to analyze the potential bottlenecks and performance problems, so that you can deal with them timely. Once you establish this well, it should help you in both fields - reliability and performance.


text:
Q: How to add set text bold, italic, super script and sub script in comment text in Word VBA? I want to format the comment text in Word Template using VBA. I can add simple text using following code. But I don't know how to format the text
CommentText = "Test Bold: Bold Text & vbNewLine & Test Italic: Italic Text & vbNewLine & Test Bold Italic: Bold Italic Text & vbNewLine &  Test Superscript: My BrandTM & vbNewLine & Test Subscript: H2O"
Selection.Comments.Add Range:=Selection.Range
With Selection
        .TypeText (CommentText)                        'Add comment text
End With

Output should be like following Image:

A: The code below will add your formatted comment to the selected text.  Tested in Word 2007, and functioning as expected.
By the way, in case you need to do something similar in the future, start recording a macro, add your comment, then stop recording. The resulting macro code should get you most of the way there.
Public Sub AddComment()

  Selection.Comments.Add Range:=Selection.Range

  With Selection
    .TypeParagraph

    .TypeText Text:="Test Bold: Bold Text"
    .MoveLeft Unit:=wdCharacter, Count:=9, Extend:=wdExtend
    .Font.Bold = wdToggle
    .EndKey Unit:=wdLine
    .Font.Bold = wdToggle

    .TypeParagraph

    .TypeText Text:="Test Italic: Italic Text"
    .MoveLeft Unit:=wdCharacter, Count:=11, Extend:=wdExtend
    .Font.Italic = wdToggle
    .EndKey Unit:=wdLine
    .Font.Italic = wdToggle

    .TypeParagraph

    .TypeText Text:="Test Bold Italic: Bold Italic Text"
    .MoveLeft Unit:=wdCharacter, Count:=16, Extend:=wdExtend
    .Font.Bold = wdToggle
    .Font.Italic = wdToggle
    .EndKey Unit:=wdLine
    .Font.Italic = wdToggle
    .Font.Bold = wdToggle

    .TypeParagraph

    .TypeText Text:="Test Superscript: My BrandTM"
    .MoveLeft Unit:=wdCharacter, Count:=2, Extend:=wdExtend
    .Font.Superscript = True
    .EndKey Unit:=wdLine
    .Font.Superscript = False

    .TypeParagraph

    .TypeText Text:="Test Subscript: H20"
    .MoveLeft Unit:=wdCharacter, Count:=1
    .MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
    .Font.Subscript = True
    .EndKey Unit:=wdLine
    .Font.Subscript = False
  End With

End Sub


text:
Q: How do I get around ini_set disabled when trying to autoload I'm writing a WordPress plugin that uses Raven, which uses autoload in the following way:
ini_set('unserialize_callback_func', 'spl_autoload_call');
spl_autoload_register(array(new self, 'autoload'));

However, some users of the plugin have ini_set disabled by their host providers, and an error gets thrown when the plugin is activated:
Warning: ini_set() has been disabled for security reasons in...
Is there a way I can get around using ini_set in this case?
I guess my real question is if ini_set necessary when using spl_autoload_register or not?

A: This answer states that you probably don't need to set unserialize_callback_func anymore when using spl_autoload_register().


text:
Q: get request data from Flask redirect I have to create a small web app in Flask which contains an API and also an interface and I'm facing the following problem:
This would be how i handle a GET request:
@app.route('/member/<id>', methods=['GET'])
def member_get(id):
    member = cursor.execute(f"select * from members where id={id}").fetchone()
    if member is not None:
        return to_json(member), 200
    else:
        return 'Not found', 404

And I would like to create some small forms with which I could do GET,POST,PUT,DELETE operations.
This would be how I get the data from the form:
@app.route('/dashboard', methods=['POST'])
def dashboard_post():
    id = request.form['get_id']
    return redirect(url_for("member_get",id=id))

My question is how can I get the data from the API method without actually redirecting to that page?
More precise, can I call somehow redirect(url_for("member_get",id=id)) and get the response data directly? (if I print the return of the redirect method it only shows the request status)
I assume one solution would be using the requests module, but is there a way to do it directly in Flask?

A: First of all, an API should always return a response in a format that is consistent and predictable. The code for member_get returns JSON in case of success but plain text in case of failure. This is not okay. You should return JSON always, with the appropriate HTTP status code. Here you are using 404 to express Not found, this is good.
You can use the jsonify function in Flask for that. And maybe normalize the response, so that is always has the same shape, whether the member ID is found or not.
Otherwise, parsing the response from your API will be harder because it is not consistent depending on the scenario.
Second point, if I understand it right: if you want to invoke the route '/member/' from within your API, you could simply do:
return member_get(id)

You call the function that is attached to the route, not the route itself. Of course you could actually fetch the page with the requests module but this is unnecessary, since the function is available internally.

A: Your question is not clear, but as I understand, (1) you think you have to get your form data from one view and send it to another view to do operations. (2) you are not familiar with flask request and flask-wtf. and maybe (3) looking for a way to do this without refreshing or redirecting the page.

*

*You don't need to separate your GET and POST methods. instead you can integrate both in one view.
@app.route('/member/<id>', methods=['GET', 'POST])

*To handling data, you can use flask request.
from flask import request

and access to data in your view like this:
id = request.form.get("idField")

but you can also use Flask-WTF to simply make and handle forms.
with Flask-WTF your view would be like this:
from app.forms import SearchForm

@app.route('/your-endpoint', methods=['GET', 'POST'])
def yourView():
    form = your_form()
    if form.validate_on_submit():
        id=form.idField.data
    return render_template('test.html', form=form)

the condition form.validate_on_submit() checks if you are submitting a from or you just opened it. if you submit a form and it's data are valid based on validators defined in your form, the code runs. else just renders the template and returns the page.
To learn how to make forms with Flask-WTF I recommend reading this article:

*If you don't want to refresh the page or redirect it after submitting the form, you can use AJAx on your page.


text:
Q: Why set a property both on the function and its prototype? I was trying to understand OOP model of JavaScript,  so I was reading this article:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
The following code was interesting:
function Person(gender) {
    this.gender = gender;
    alert('Person instantiated');
}

Person.prototype.gender = '';
var person1 = new Person('Male');
var person2 = new Person('Female');
//display the person1 gender
alert('person1 is a ' + person1.gender); // person1 is a Male

What was interesting and not clear to me is this line:
Person.prototype.gender = '';

I didn't understand so I tested the code both with that line and without it.
The code is working fine in both conditions.
So my question is:
Why did the author add that line?

A: You should not set data on the prototype. A lot of times people who come to JavaScript from classical languages attempt it to emulate classical inheritance, but the assymetric nature of the prototype chain (setting is always local but getting climbs up the chain) means that it's impractical. For more information about prototypical inheritance,  click here.
The prototype is for sharing functionality across instances. Put functions there instead. For sharing data, see this answer.
That article putting gender on the prototype is mistaken. This is why in ES6, maximally minimal classes set functions on the prototype, but not data members. See this article on why to avoid data on the prototype.
I've fixed the MDN article, nice catch.


text:
Q: Error in lda.default(x, grouping, ...) : variables appear to be constant within groups I'm trying to run a lda function but i get this error. My dataset has 388 observations and 1026 variables. The column Act has only "n" or "p", and the other columns have numbers. The code is:
dat<-bbb.fingerprints

head(dat)

N<-nrow(dat)

smp<-sample(1:N, N/3)

smp

train<-dat[-smp, ]

test<-dat[smp, ]

library(MASS)

lda.model <- lda(Act ~ . , data=train)

View(lda.model)

The error is:
Error in lda.default(x, grouping, ...) :
  variables   18   21   29   39   55   56   59   70   94  104  114  138  150  162  184  199  205  248  268  371  374  383  443  444  450  451  515  535  537  538  554  583  606  619  620  628  636  646  649  655  720  733  756  757  784  798  806  846  849  852  860  867  908  939  978  987  996 1000 1001 appear to be constant within groups

Can you help me pleaseeee?

A: Saw this on reddit:
if x is a data frame with the 17th column being the grouping variable and the rest are the features then run LDA using the following:
lda(x[,-17], grouping=x[,17])


text:
Q: Multiple instance of angular 4 directive called from a component mesed up the input values I have a component in angular 4 that is called three times. In template metadata I have a div with a directive with some bindings like this.
@import {gServ} from '../gServ.service';

@Component: ({
   selector: 'sr-comp',
   template: `<div gDirective [cOptions]="dataChart">`
})

export class SGComponent implements OnInit {
    @Input('report') public report: IReportInstance;
    cOptions:any;

    constructor(private gServ: gServ) {
    }

    ngOnInit(){

        this.cOptions = {};
        this.cOptions = this.gServ.objectMerge(this.gServ.defaultOpt, this.report.opt);

        //this.report.opt is binded to a component when is instantiated.
        //this.gServ.objectMerge is a function that merge the two objects
    }
}

this.cOptions change for every instance of the component, then in the directive I have this:
import { Directive, ElementRef, HostListener, Input, OnInit } from '@angular/core';

@Directive({
  selector: '[gDirective]'
})
export class SGDirective implements OnInit {
  public _element: any;
  @Input() public cOptions: string;

  constructor(public element: ElementRef) {
    this._element = this.element.nativeElement;
  }

  ngOnInit() {
    console.log(this.cOptions);
  }
}

The problem is that console.log(this.cOptions); always print the same object, even when component set cOptions with diferent values in ngOnInit method of the compnent.
Do you have some idea what is wrong?

A: Your component property binding [cOptions]="dataChart" doesn't look good, reason being your dataChart is not even defined. it should be like [DIRECTIVE_PROPERTY]="COMPONENT_PROPERTY" and your COMPONENT_PROPERTY is not even defined in SGComponent component class.
Your component class should be something like this:
@import {gServ} from '../gServ.service';

@Component: ({
   selector: 'sr-comp',
   template: `<div gDirective [cOptions]="Options">`
})

export class SGComponent implements OnInit {
    @Input('report') public report: IReportInstance;
    Options:any;

    constructor(private gServ: gServ) {
    }

    ngOnInit(){
        this.Options = {};
        this.Options = this.gServ.objectMerge(this.gServ.defaultOpt, this.report.opt);
    }
}

A: @Ashwani points out a valid problem with your code.  The way your template is wiring things up, nothing will ever be passed to the SGDirective input.
Another potential problem you could be running into has to do with the gServ code.  If gServ is a singleton (which is probably the case) and it is returning the same object to each of the SGComponents, then all the SGDirectives will have the same value.  A simple way to test this is to put {{Options | json}} in the SGComponent template.
To create a new instance of the gServ service for each SGComponent you can add a providers array to the @Component metadata.  It would look like this:
import {gServ} from '../gServ.service';

@Component({
   selector: 'sr-comp',
   template: `{{Options | json}}<div gDirective [cOptions]="Options"></div>`
   providers: [gServ],
})

export class SGComponent implements OnInit {
    @Input('report') public report: IReportInstance;
    Options:any;

    constructor(private gServ: gServ) {
    }

    ngOnInit(){
        this.Options = this.gServ.objectMerge(this.gServ.defaultOpt, this.report.opt);
    }
}

A: You have probably the same return/value at this.gServ.objectMerge) (you can test it wihtout calling the service, and passing each one one different objet make by you)

@import {gServ} from '../gServ.service';

@Component: ({
   selector: 'sr-comp',
   template: `<div gDirective [cOptions]="dataChart">`
})

export class SGComponent implements OnInit {
    //@Input('report') public report: IReportInstance;
    cOptions:any;

    constructor(private gServ: gServ) {
    }

    ngOnInit(){

        this.cOptions = {nicolas: 'nicolas1'}; //change this in the next component that use the directive

    }
}

If that is the case, your problem is that gServ is provide at the same rootComponent. with angular, service provider at the same rootComponent are singleton.
And use the same type in your directive and your component!!


text:
Q: What's the most efficient way of filtering an array based on the contents of another array? Say I have two arrays, items and removeItems and I wanted any values found in removeItems to be removed from items.
The brute force mechanism would probably be:
var animals = ["cow","dog","frog","cat","whale","salmon","zebra","tuna"];
var nonMammals = ["salmon","frog","tuna","spider"];
var mammals = [];
var isMammal;

for(var i=0;i<animals.length;i++){
   isMammal = true;
   for(var j=0;j<nonMammals;j++){
     if(nonMammals[j] === animals[i]){
       isMammal = false;
       break;
     }
   }
   if(isMammal){
     mammals.push(animals[i]);
   }
}

This is what? O(N^2)? Is there a more efficient way?

A: Basically what you want to do is efficiently compute the set difference S \ T. The (asymptotically) fastest way I know is to put T into a hashmap (that makes |T| steps) and go over each s in S (that makes |S| steps) checking wether s in T (which is O(1)). So you get to O(|T| + |S|) steps.

A: That's actually O(M * N).
Probably you could do better sorting the animals array first, then doing a binary search. You'll be able to reduce to O(N * log N) - well, that's if log N < M anyway.
Anyway, if you're working with JS and that runs client-side, then just try to keep amount of data at minimum, or their browsers will yell at you with every request.

A: With jQuery it's pretty easy:
function is_mammal(animal)
{
    return $.inArray(animal, nonMammals) == -1;
}

mammals = $.grep(animals, is_mammal);

See docs for $.grep and $.inArray.


text:
Q: PHP Countdown added two hours currentime=strtotime('22:00:00');
rem=currentime - strtotime('now'); //now is 20:00:00
remaining=date("H:i:s",rem);

My problem is, remaining shows 04:00:00 instead of 02:00:00
Is there any clue why it is? I also set date_default_timezone_set

A: Check your settings in php.ini file. There should be line similar to this one:
date.timezone = UTC
Try setting it to your time zone.