text:
Q: Does the AWS SDK for NodeJS update the token from AWS_WEB_IDENTITY_TOKEN_FILE in EKS? I have a simple application running in EKS/Kubernetes using a service account, that service account uses the IAM Role Role_A
Within the application container is possible to see the AWS_WEB_IDENTITY_TOKEN_FILE and AWS_ROLE_ARN environment variables (via env | grep 'AWS')
Getting the content of the AWS_WEB_IDENTITY_TOKEN_FILE, I got a JWT with exp set to 24h from the iss.
With this context, my application uses this token to assume a role that has access to S3 resources.
My application has this piece of code:
const s3 = new AWS.S3();
const params = {Bucket: 'some-bucket', Key: 'some-file'}
const response = await s3.getObject(params).promise();
const fileContent = response.Body.toString('utf-8');

My question is: does the call new AWS.S3() deal with the token exp being used to assume the role? or it will receive a 403 error when the time is over?


text:
Q: Error in APEX SQL I am working on Oracle 11g. I have created a table STUDENTS using APEX in my port: 8080 . After that when I use SQLPLUS in cmd and write SELECT * FROM STUDENTS it shows TABLE OR VIEW DOES NOT EXIST. What am I doing wrong here?

A: Ok...When you created the table using APEX, what schema was it created in?  When you connect via SQL*Plus, are you logging in as the same user who owns the table?
If not, you'll need to grant select on the table to the user that wants to access the table, and also either specify the owner when referencing the table in your select statement, or create a synonym, or use alter session set current_schema statement.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add 30 minutes in time object in python 3? I converted this string into an object:
import datetime
date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')

when I print the time object using this:
print(date_time_obj.time())

Now I need to add 30 minutes to the time. Can someone show me how ? I tried this with no luck
updated_time = date_time_obj.time()+ timedelta(minutes=30)

A: You should get rid of time() function since date_time_obj is already a valid datetime.datetime object (timedelta works with datetime.datetime, not datetime.time)
updated_time = date_time_obj + timedelta(minutes=30)
print(updated_time)

The above code would successfully give us datetime.datetime(2018, 6, 29, 8, 45, 27, 243860)


text:
Q: Purpose of __name__ in TypeVar, NewType In the typing module, both TypeVar and NewType require as a first positional argument, a string to be used as the created object's __name__ attribute. What is the purpose of __name__ here?
Considering that this is a compulsory argument, I would expect it to be something essential. In PEP-484 where type hinting was introduced, the argument is normally set as a string of the variable name assigned to the object:
T = TypeVar('T', int, float, complex)

But, I can't really tell how this end up being used in typing.py in CPython. Replacing the string with indeed any other string does not appear to break anything in my tests.

A: The __name__ attribute is the associated typename that the IDE, for example, will use in its type hints. Given the following toy code:
T = TypeVar('not_T', int, float)
def test_func(arg: T): pass

Calling the function with something incorrect like test_func('not_a_number') would result in a type hint like this:
Expected type 'not_t', got 'str' instead

As far as the python interpreter is concerned, no restrictions are set on conformity between type.__name__ and the name tag you use to handle it, but other third-party tools such as mypy might not accept differing variable name and __name__, which is also a requirement in the intitial typing PEP-484:

The argument to TypeVar() must be a string equal to the variable name to which it is assigned. Type variables must not be redefined.

For an additional use case, you can also check the types in the __annotations__ member of any object where it is used to type hint, e.g.
print(test_func.__annotations__)
>> {'arg': ~not_T}

And use that to implement further type checking or handling in your code - in which case your TypeVar.__name__s better be meaningful :)


text:
Q: Redis ZRANGEBYLEX Escape Characters I have few items in my sorted set that look this way:
> zrangebylex search - +
1) "abcdefghijkl"
2) "[asd](asd)"
3) "[zxy](zxc)"

How can i retrieve the second item only using the the first two characters '[a' ?
I am trying to implement an auto-complete system and these special characters are posing a problem when i tried them in redis-cli.
I have tried the following commands but they don't work (with/without quotes) :
zrangebylex search ([a "([a\xff"
zrangebylex search (\[a "([a\xff"

A: redis-cli needs the quotes, but other than that all should be working as expected. Here's the output of my session:
127.0.0.1:6379> zadd search 0 abcdefjhijkl
(integer) 1
127.0.0.1:6379> zadd search 0 "[asd](asd)"
(integer) 1
127.0.0.1:6379> zadd search 0 "[zxy](zxc)"
(integer) 1
127.0.0.1:6379> ZRANGEBYLEX search - +
1) "[asd](asd)"
2) "[zxy](zxc)"
3) "abcdefjhijkl"
127.0.0.1:6379> ZRANGEBYLEX search "([a" "([a\xff"
1) "[asd](asd)"

```


text:
Q: BeforeClass using Spring transactional tests I'm using the Spring transactional test classes to do unit testing of my DAO code. What I want to do is create my database once, before all the tests run.  I have a @BeforeClass annotated method but that runs before Spring loads up the application context and configures the jdbcTemplate, thus I don't actually have a connection to the DB at that time.  Is there a way to run my DB setup once after the context loads but before the tests start running?
This thead asks the same question but the accepted solution seems to just be "don't do that".  I'm inclined to say this just seems like it isn't doable.

A: my solution, a bit complicated but i needed it for an test framework :-)
do not be afraid of the german javadocs, the method names and bodies should be enough to get  it
FIRST create Annotation to mark Class or method for database work (create table and/or insert statements)

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface SchemaImport {

    /**
     * Location der Schemadatei(en). Die Datei darf nur SQL Statements enthalten.
     * Wird keine Location gesetzt, greift der Defaultwert.
     * @return String
     */
    String[] locationsBefore() default {"input/schemas/before.sql"};

    /**
     * Location der Schemadatei(en). Die Datei darf nur SQL Statements enthalten.
     * Wird keine Location gesetzt, greift der Defaultwert.
     * @return String
     */
    String[] locationsAfter() default {"input/schemas/after.sql"};

    /**
     * Ein SchemaImport findet nur bei passender Umgebungsvariable statt, mit diesem
     * Flag kann dieses Verhalten geändert werden.
     * @return boolean
     */
    boolean override() default false;
}

SECOND create listener which looks for the annotation, AbstractTestExecutionListener
is a Spring Framework Class from

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>org.springframework.test</artifactId>
            <version>2.5.6</version>
        </dependency>

public class SchemaImportTestExecutionListener extends AbstractTestExecutionListener
        implements ApplicationContextAware {

    /**
     * Standard LOG Definition.
     */
    private static final Logger LOG = LoggerFactory.getLogger(
            SchemaImportTestExecutionListener.class);
    /**
     * Datasource Name - gemeint ist der Name der Datasource Bean bzw. die ID.
     */
    private static final String DATASOURCE_NAME = "dataSource";
    /**
     * JDBC Template.
     */
    private SimpleJdbcTemplate simpleJdbcTemplate;
    /**
     * Flag um festzustellen ob prepareTestInstance schon gerufen wurde.
     */
    private boolean isAlreadyPrepared = false;

    /**
     * Standard Constructor, laut API von konkreten Implementierungen für
     * TestexecutionListener erwartet, es geht aber auch ohne.
     */
    public SchemaImportTestExecutionListener() {
    }

    /**
     * Für jede Testklasse die mit der {@link SchemaImport} Annotation ausgezeichnet
     * ist, wird ein entsprechender SchemaImport durchgeführt.
     *
     * Der SchemaImport findet pro Klasse exakt einmal statt. Diese Verhalten
     * entspricht der BeforeClass
     * Annotation von JUnit.
     *
     * Achtung mit Nutzung von Schemaimport auf Klassenebene ist kein
     * Rollback möglich, stattdessen SchemaImport auf Methodenebene nutzen.
     *
     * @param testContext
     * @throws java.lang.Exception
     */
    @Override
    public void prepareTestInstance(TestContext testContext) throws Exception {
        final SchemaImport annotation = AnnotationUtils.findAnnotation(testContext.getTestClass(), SchemaImport.class);
        if ((annotation != null) && !isAlreadyPrepared && (isPropertyOrOverride(annotation))) {
            executeSchemaImports(testContext, annotation.locationsBefore(), true);
            isAlreadyPrepared = true;
        }
    }

    /**
     * Für jede Testmethode mit {@link SchemaImport} werden die angegebenen
     * Schema Dateien als SQL ausgeführt.
     *
     * @param testContext
     * @throws java.lang.Exception
     */
    @Override
    public void beforeTestMethod(TestContext testContext) throws Exception {
        // nur für Methoden mit passender Annotation Schemaimport durchführen
        final SchemaImport annotation = AnnotationUtils.findAnnotation(testContext.getTestMethod(), SchemaImport.class);
        if (annotation != null) {
            executeSchemaImports(testContext, annotation.locationsBefore(), true);
        }
    }

    @Override
    public void afterTestMethod(TestContext testContext) throws Exception {
        // nur für Methoden mit passender Annotation Schemaimport durchführen
        final SchemaImport annotation = AnnotationUtils.findAnnotation(testContext.getTestMethod(), SchemaImport.class);
        if (annotation != null) {
            executeSchemaImports(testContext, annotation.locationsAfter(), false);
        }
    }

    /**
     * Prüfen ob passende Umgebungsvariable gesetzt wurde. Diese kann durch
     * entsprechendes Setzen des Flags an der Annotation überschrieben werden.
     * @return
     */
    private boolean isPropertyOrOverride(SchemaImport annotation) {
        String prop = System.getProperty(TYPEnviroment.KEY_ENV);
        if (StringUtils.trimToEmpty(prop).equals(TYPEnviroment.EMBEDDED.getEnv())) {
            LOG.info("Running SchemaImport, Enviroment is set:'" + prop + "'");
            return true;
        } else {
            if (annotation.override()) {
                LOG.warn(
                        "Running SchemaImport, although Enviroment is set:'" + prop + "'");
                return true;
            } else {
                LOG.warn(
                        "Not Running SchemaImport cause neither Environment or SchemaImport.override are set.");
                return false;
            }
        }
    }

    /**
     * Hilfesmethode die eigentlichen SchemaImport kapselt.
     *
     * @param testContext
     * @param locations
     */
    private void executeSchemaImports(TestContext testContext, String[] locations, boolean checkLocations) {
        // für jede Datei SchemaImport durchführen, korrekte Reihenfolge
        // ist durch Entwickler zu gewährleisten
        if (locations.length > 0) {
            for (String location : locations) {
                if (StringUtils.trimToNull(location) != null) {
                    if (isResourceExistant(location, checkLocations)) {
                        LOG.info("Executing Schema Location: '" + location + "'");
                        SimpleJdbcTestUtils.executeSqlScript(getJdbcTemplate(
                                testContext), new ClassPathResource(location),
                                false);
                    } else {
                        LOG.warn(
                                "Schema Location '" + location + "' for SchemaImport not found.");
                    }
                } else {
                    throw new RuntimeException("SchemaImport with empty Locations in:'" + testContext.getTestClass().getSimpleName() + "'");
                }
            }
        }
    }

    /**
     *
     * @param resource
     * @return
     */
    private boolean isResourceExistant(String resource, boolean checkLocations) {
        try {
            new ClassPathResource(resource).getInputStream();
            return true;
        } catch (IOException ex) {
            if (checkLocations) {
                throw new RuntimeException(ex);
            } else {
                return false;
            }
        }
    }

    /**
     * Hilfsmethode um an ein JdbcTemplate heranzukommen.
     *
     * @param TestContext
     * @return SimpleJdbcTemplate
     */
    private SimpleJdbcTemplate getJdbcTemplate(TestContext context) {
        if (this.simpleJdbcTemplate == null) {
            this.simpleJdbcTemplate = new SimpleJdbcTemplate(getDataSource(
                    context));
        }
        return this.simpleJdbcTemplate;
    }

    /**
     * Hilfsmethode um an die Datasource heranzukommen.
     *
     * @param testContext
     * @return DataSource
     */
    private DataSource getDataSource(TestContext testContext) {
        return (DataSource) testContext.getApplicationContext().getBean(
                DATASOURCE_NAME, DataSource.class);
    }

    /** {@inheritDoc} */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

THIRD add the listener to the test execution

@ContextConfiguration(locations = {"classpath*:spring/persistence/*.xml"})
@Transactional
@TestExecutionListeners({
    TransactionalTestExecutionListener.class,
    SchemaImportTestExecutionListener.class})
public abstract class AbstractAvHibernateTests extends AbstractAvTests {

    /**
     * SimpleJdbcTemplate für Subclasses verfügbar.
     */
    @Autowired
    protected SimpleJdbcTemplate simpleJdbcTemplate;
}

in use

@SchemaImport(locationsBefore={"schemas/spring-batch/2.0.0/schema-hsqldb.sql"})
public class FooTest extends AbstractAvHibernateTests {
}

its important to note - beware of thread problems while using testNg parallel testing, for this to work there should be some 'synchronized' markers for the getJdbcTemplate / dataSource Methods in the listener
ps:
the code for the test base class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:spring/*.xml"})
@TestExecutionListeners({
    DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    LogDurationTestExecutionListener.class,
    LogMethodNameTestExecutionListener.class})
public abstract class AbstractAvTests implements ApplicationContextAware {

    /**
     * Logger für Subclasses verfügbar.
     */
    protected final Logger LOG = LoggerFactory.getLogger(getClass());
    /**
     * {@link ApplicationContext} für Subclasses verfügbar.
     */
    protected ApplicationContext applicationContext;

    /** {@inheritDoc } */
    @Override
    public final void setApplicationContext(final ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
}

LogDurationTestExecutionListener and LogMethodNameTestExecutionListener are custom listeners not provided by spring, but not needed for the schemaImport to work properly

A: I'd second the advice that you should make each of your tests autonomous and therefore do all your setup with @Before rather than with @BeforeClass.
If you wish to stick with your approach just use the @Before method and have a simple boolean check to see if the setup has already been completed. e.g.
 if(!databaseSetup) {
    ...set up the database
    databaseSetup=true;
    }

Not too fancy but it will work!
See my answer here for an example spring transaction test with annotations using dbunit.
Hope this helps!

A: I don't know what unit testing framework you are using but for JUnit, you can make your test class subclass AbstractTransactionalJUnit4SpringContextTests which has an executeSqlScript method this can either be run in a beforeclass or beforemethod method. My preference is to use BeforeMethod as this means that each of my unit tests are autonomous, even if it means my unit tests run a bit slower.

A: Try using your old methods instead of the fancy annotations.
@BeforeClass
    public static void beforeClass() {
        ApplicationContext context = new ClassPathXmlApplicationContext(
        "applicationContext.xml");
                  [...]
    }


text:
Q: Why parent div isn't getting expected height I've implemented a template with static heights. I've changed it's content height to fit to child heights, but parent  and parent
 aren't getting the autocalculated height.
Why?
I'm getting insane with this issue.
HTML:

...

...

...

...

CSS:
#sidebar{
    float: none;
    height: auto;
    width: 22%;
    padding: 1% 0 0 2%;
}
.seccion-productos {
    position: relative;
    width: 100%;
}
#grid-selector {
    width: 78%;
    position: absolute;
    top: 0;
    left: 22%;
    right: 0;
    display: flex;
    vertical-align: middle;
}
#grid {
    width: 78%;
    height: auto;
    top: 90px;
    left: 22%;
}

Undesired Result, parent content doesn't fit child content

I am just asking what things can make this happen and what should I do to solve it. Or if i'm missing something. Or where I have to look.
You also can see full code in here:
https://randal-es.000webhostapp.com/php/paginas/productos.php

A: @Arngue, as @Johannes says, if you put a child element with absolute positioning it won't affect the parent element even if the parent element has position relative. The only thing that the parent's relative position affects is the origin of coordinates for absolute positioning. You need to change the position definition for #grid-selector otherwise it will always break your layout.

A: The position: absolute; of the #grid-selector element takes it out of the size calculation context for the parent. Change that to relative


text:
Q: html_attr "href" returns only one result in rvest My goal is to exact urls from a wiki page and there is a table of congress members and I want to exact their own wiki urls.
My input is like:
url_congress <- "https://en.wikipedia.org/wiki/List_of_current_United_States_senators"
mynodes <- html_node(congress, ".fn a")
urls <- html_attr(mynodes, name = "href")
urls

However, it only selected the first url instead of all urls:
[1] "/wiki/Richard_Shelby"

What should I do if I want to select all urls in the table?

A: I should change the code to html_nodes instead of html_node !


text:
Q: Fallback - redirect to a new domain using apache vhost configuration This is a followup question on https://stackoverflow.com/posts/47547418
I wanted my requests from
somedomain.com/loadproduct?product=dell-inspiron-15
to be selectively redirected to
someotherdomain.com/dell-inspiron-15
but at the same time I want to make sure if something goes wrong with the new domain, users are still able to use old domain by adding /old in the url.
For example if users uses
somedomain.com/old/loadproduct?product=dell-inspiron-15
then they should not be redirected to someotherdomain but should be served through a valid url somedomain.com/loadproduct?product=dell-inspiron-15
but if they use
somedomain.com/loadproduct?product=dell-inspiron-15
they should be redirected.
Currently my vhost configuration looks like below. It redirects to someotherdomain for selected products but there is no fallback configuration.
Listen 12567
NameVirtualHost *:12567

<VirtualHost *:12567>
    ServerName somedomain.com
    ProxyPreserveHost On

    RewriteEngine On
    RewriteCond %{QUERY_STRING} (?:^|&)product=(Dell-Inspiron-15) [NC,OR]
    RewriteCond %{QUERY_STRING} (?:^|&)product=(Dell-Inspiron-16) [NC,OR]
    RewriteCond %{QUERY_STRING} (?:^|&)product=(Dell-Inspiron-17) [NC]
    RewriteRule ^/?loadproduct$ http://someotherdomain.com/%1? [R=301,L,NC]
</VirtualHost>

Any leads here is really appreciated.

A: Modify your RewriteCond conditions and add one where it says not to accept /old/ in the path (URI).  So:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^.*/old/.*$ [NC]
RewriteCond %{QUERY_STRING} (?:^|&)product=(Dell-Inspiron-15) [NC,OR]
RewriteCond %{QUERY_STRING} (?:^|&)product=(Dell-Inspiron-16) [NC,OR]
RewriteCond %{QUERY_STRING} (?:^|&)product=(Dell-Inspiron-17) [NC]
RewriteRule ^/?loadproduct$ http://someotherdomain.com/%1? [R=301,L,NC]

In the first line, no need to specify [AND], as it is implicit.  The ! character negates the match.
Disclaimer: I have not tested this on a real Apache, but I am pretty sure it is ok.


text:
Q: jquery guillotine plugin with ajax image update I am using jquery guillotine plugin for zoom and resize and i am updating image src through ajax call but on change i am not getting cordinate basicaly guillotine('getData') returning nothing,below is my my code which i am using.
jQuery(document).ready(function(){
       picture = jQuery('#sample_picture');
       picture.guillotine('fit');
       picture.on('load', function(){
        picture.guillotine({eventOnChange: 'guillotinechange'});
        var img = jQuery(this);
        img.guillotine({eventOnChange: 'guillotinechange'});
       // Remove any existing instance
       if (img.guillotine('instance')) img.guillotine('remove');
               img = jQuery('#sample_picture');
               img.guillotine({width: 387, height:594});
               img.guillotine('fit');
       if (! img.data('bindedBtns')) {
               img.data('bindedBtns', true)
               jQuery('#fit').click(function(){ img.guillotine('fit'); });
               jQuery('#zoom_in').click(function( { img.guillotine('zoomIn'); });
               jQuery('#zoom_out').click(function(){ img.guillotine('zoomOut'); });
       }
       var data = img.guillotine('getData');
        if(data){
               for(var key in data) {alert(data['key']); jQuery('#'+key).html(data[key]); }
        }
        // Bind button actions
        jQuery('#rotate_left').click(function(){ img.guillotine('rotateLeft'); });
        jQuery('#rotate_right').click(function(){ img.guillotine('rotateRight'); });
        jQuery('#fit').click(function(){ img.guillotine('fit'); });
        jQuery('#zoom_in').click(function(){ img.guillotine('zoomIn'); });
        jQuery('#zoom_out').click(function(){ img.guillotine('zoomOut'); });
           // Update data on change
           img.on('guillotinechange', function(ev, data, action) {
          data.scale = parseFloat(data.scale.toFixed(4));
          for(var k in data) { jQuery('#'+k).html(data[k]); }
        });
      });
});

A: I guess you already read this answer but it seems like you've just pasted conflicting code from different sources.
On the third line you atempt to fit the image even before having an instance of the plugin and later you instantiate it three times on the same image:

*

*picture.guillotine({eventOnChange: 'guillotinechange'})

*img.guillotine({eventOnChange: 'guillotinechange'})

*img.guillotine({width: 387, height:594})
You also bind buttons to actions (rotate, zoom, etc.) and parse data twice.
I would sujest to start with something simpler like Guillotine's own example and only when you get that working move on to something more complex like loading images over AJAX and swaping the src attribute.


text:
Q: SVG gradients not getting rendered when using it from external SVG-sprite file The gradients only functions properly when I include the svg sprite as code in the same file which defeats the purpose of having an svg sprite in the first place. I read from a different post from 3 years ago where someone said its bugged but surely there must be a fix for this?
How the sprite is formed:<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="display:none"> <symbol id="backpack" viewBox="0 0 177.4 181.2"> <defs>(some code)</defs> (some paths) </symbol></svg>
The use of the sprite in index.html
        <svg class="nav-icon" id="nav-backpack">
        <use href="svgNew/sprites/icons-nav-elementArt.svg#backpack"></use>
    </svg>

How it renderds from external file
How it renders if I keep the svg sprite in the same document

A: I found a fix quick fix. In the SVG sprite, take all of the defs from the symbol tags and put them at the top of the SVG sprite. Then change the style of the SVG to visibility:hidden and it should work. It does however not work on google chrome due to some bug.


text:
Q: How to highlight the menu item for the sort type of data on the page? In this site I would like to highlight the type of sort on the menu. I found many source to do this with css or javascript but I could not understand them enough to apply them to this site (they seem to be for pull-down menus). Can you direct me about how to do this with the css that I have now for this page? It is just one page, sorted 5 different ways. My main.css is below. Thanks!
.admin-content {width: 95%;
margin-top: 0px
margin-bottom: auto;
margin-right: 5px;
margin-left: 5px;
padding: 0px;}

.image-submit {width: 550px; margin-top: 0px margin-bottom: auto; margin-right: 50px; margin-left: 70px; padding: 15px;}

.image-page {width: 90%; padding: 15px;}

body { font-size: small; font-family: Verdana, Helvetica, sans-serif; }

a:link { color:#000000; text-decoration:none; }
a:visited { color:#000000; text-decoration:none; }
a:hover { text-decoration: underline; color: #0066CC; }
a:active { text-decoration: none }

tr {font-size: small; font-family: Verdana, Helvetica, sans-serif; }

.small {color: #808080; font-size: x-small; }
.xxsmall {color: #808080; font-size: xx-small; line-height:60%}
.small-tags {font-size: x-small; }
.large {color: #0033FF; font-size: 130%; }
.smaller-line-height {line-height:10%}
.medium {font-size: medium; }

Update
I updated the script according to Alon's answer but this is not working. What am I doing wrong?
I added the js to the header:

...
self.response.out.write("""""")
...

changed the urls:
self.response.out.write("""

sort by:  color |
number of attorneys |
number of partners |
number of associates |
associate salary |

""")

and I added the .active { color:red; } to main.css.
.active { color:red; }

But this is not working as expected. Is .active { color:red; } conflicting with a:active { text-decoration: none } in the css? I removed a:active { text-decoration: none } but it didn't make a difference.

A: your html should be
  number of attorneys |
    number of partners |
    number of associates |
    associate salary |

your javascript code should be something like
var url = window.location.href,
    sort_by = url.split("=");
if (sort_by.length == 2) {
   document.getElementById(sort_by[1]).className = "active";
}

you should also add class active to your css with the highlight style
.active { color:red; }


text:
Q: Regular Expression for username and password? I am trying to use a regular expression for name field in the asp.net application.
Conditions:name should be minimum 6 characters ?
I tried the following
"^(?=.*\d).{6}$"

I m completely new to the regex.Can any one suggest me what must be the regex for such condition ?

A: You could use this to match any alphanumeric character in length of 6 or more: ^[a-zA-Z0-9]{6,}$. You can tweak it to allow other characters or go the other route and just put in exclusions. The Regex Coach is a great environment for testing/playing with regular expressions (I wrote a blog post with some links to other tools too).

A: What about
^.{6,}$

What's all the stuff at the start of yours, and did you want to limit yourself to digits?

A: NRegex is a nice site for testing out regexes.
To just match 6 characters, ".{6}" is enough

A: In its simplest form, you can use the following:
.{6,}

This will match on 6 or more characters and fail on anything less. This will accept ANY character - unicode, ascii, whatever you are running through. If you have more requirements (i.e. only the latin alphabet, must contain a number, etc), the regex would obviously have to change.

A: Look at Expression library and choose user name and/or password regex for you. You can also test your regex in online regex testers like RegexPlanet.
My regex suggestions are:
 ^[a-zA-Z][a-zA-Z0-9._\-]{5,}$

This regex accepts user names with minimum 6 characters, starting with a letter and containing only letters, numbers and ".","-","_" characters.
Next one:
 ^[a-zA-Z0-9._\\-]{6,}$

Similar to above, but accepts ".", "-", "_" and 0-9 to be first characters too.
If you want to validate only string length (minimum 6 characters), this simple regex below will be enough:
 ^.{6,}$


text:
Q: I can´t post data using an api in Angular 10 I had this form with a validation that was working fine, the next step was using the post action of an api, but the tutorials I´ve seen have small differences and none seems to work, so ¿how can I use the post action passing first for the validation?
The comentented code is what I´ve tried.
ingresarservicio.component.html

    <form (ngSubmit)="onSubmit()" [formGroup]="form">

                Técnico
                <input type="text" class="form-control" id="tecnico" name="tecnico" formControlName="tecnico" [(ngModel)]="servicioSettings.tecnico">

                Servicio
                <input type="text" class="form-control" id="servicio" formControlName="servicio" [(ngModel)]="servicioSettings.servicio">

                Semana del año
                <input type="number" class="form-control" id="semanaDelAno" formControlName="semanaDelAno" [(ngModel)]="servicioSettings.semanaDelAno">

                Día de la semana
                <input type="text" class="form-control" id="diaDeLaSemana" formControlName="diaDeLaSemana" [(ngModel)]="servicioSettings.diaDeLaSemana">

                Hora Inicial
                <input type="number" class="form-control" id="horaInicial" formControlName="horaInicial" [(ngModel)]="servicioSettings.horaInicial">

                Hora Final
                <input type="number" class="form-control" id="horaFinal" formControlName="horaFinal" [(ngModel)]="servicioSettings.horaFinal">

            <button type="submit" class="btn btn-primary" [disabled]="myForm.invalid">Enviar</button>
        </form>

ingresarservicio.component.ts

    export class IngresarsrevicioComponent implements OnInit {

      servicioSettings: ServicioSettings = {
        tecnico: null,
        servicio: null,
        semanaDelAno: null,
        diaDeLaSemana: null,
        horaInicial: null,
        horaFinal: null
      };

      myForm: FormGroup;
      //dataService: DataService;

       constructor(private formBuilder: FormBuilder, private dataService: DataService)  {
          this.myForm = this.formBuilder.group({
          //this.form = this.formBuilder.group({
            tecnico: ['', Validators.required],
            servicio: ['', Validators.required],
            semanaDelAno: ['', Validators.required],
            diaDeLaSemana: ['', Validators.required],
            horaInicial: ['', Validators.required],
            horaFinal: ['', Validators.required]
          });

          // form = new FormGroup ({
          //   tecnico: new FormControl('', Validators.required)
          // });
       }

      ngOnInit(): void {
      }

      onSubmit(form: NgForm) {
        console.log('in onSubmit ', form.valid)
        this.dataService.postServicioSettingsForm(this.servicioSettings).subscribe(
          result => console.log('success ', result),
          error => console.log('error ', error)
        );
      }

      // submit() {
      //   if (this.myForm.valid) {
      //     console.log(this.myForm.value)
      //   }
      //   else{
      //     alert("FILL ALL FIELDS")
      //   }
      // }

    }

data.service.ts

    constructor(private http: HttpClient) { }

      postServicioSettingsForm(servicioSettings: ServicioSettings): Observable<any> {
        return this.http.post('https://localhost:44309/api/Servicio/PostServicio', servicioSettings);
    }

I have the api in my localhost

A: Please replace [formGroup]="form" with [formGroup]="myForm".

A: i suppose formGroup Property in html file is different with in ts file.
i cant dedicate use case of servicioSettings and ngModels , if you want set default value to form set in constractor or you can use patchValue.
this.myForm.patchValue(servicioSettings);

<form (ngSubmit)="onSubmit()" [formGroup]="myForm">

            Técnico
            <input type="text" class="form-control" id="tecnico" formControlName="tecnico">

            Servicio
            <input type="text" class="form-control" id="servicio" formControlName="servicio" >

            Semana del año
            <input type="number" class="form-control" id="semanaDelAno" formControlName="semanaDelAno">

            Día de la semana
            <input type="text" class="form-control" id="diaDeLaSemana" formControlName="diaDeLaSemana">

            Hora Inicial
            <input type="number" class="form-control" id="horaInicial" formControlName="horaInicial">

            Hora Final
            <input type="number" class="form-control" id="horaFinal" formControlName="horaFinal">

        <button type="submit" class="btn btn-primary" [disabled]="myForm.invalid">Enviar</button>
    </form>

export class IngresarsrevicioComponent implements OnInit {

  servicioSettings: ServicioSettings = {
    tecnico: null,
    servicio: null,
    semanaDelAno: null,
    diaDeLaSemana: null,
    horaInicial: null,
    horaFinal: null
  };

  myForm: FormGroup;

   constructor(private formBuilder: FormBuilder, private dataService: DataService)  {
      this.myForm = this.formBuilder.group({
        tecnico: [servicioSettings.tecnico, Validators.required],
        servicio: [servicioSettings.servicio, Validators.required],
        semanaDelAno: [servicioSettings.semanaDelAno, Validators.required],
        diaDeLaSemana: [servicioSettings.diaDeLaSemana, Validators.required],
        horaInicial: [servicioSettings.horaInicial, Validators.required],
        horaFinal: [servicioSettings.horaFinal, Validators.required]
      });
   }

  ngOnInit(): void {
  }

  onSubmit() {
    if (this.myForm.valid) {
        this.dataService.postServicioSettingsForm(this.myForm.value).subscribe(
            result => console.log('success ', result),
            error => console.log('error ', error)
        );
    }
  }
}


text:
Q: nearest/equal sum combination if a list of items - LINQ I have a list of items that contains the above properties.
Id
Amount
PackageNbr
What I need to accomplish, is to get from this list, the items that have the NEAREST OR EQUAL sum of Amount to a specific value; but a condition should always be valid which is that the items returned should be from different PackageNbr.
For example.
listOfItems:
╔══════╦══════════╦═════════════╗
║ ID   ║  amount  ║  packageNbr ║
╠══════╬══════════╬═════════════╣
║   1  ║      10  ║          1  ║
║   2  ║       7  ║          1  ║
║   3  ║       4  ║          1  ║
║   4  ║       6  ║          2  ║
║   5  ║       5  ║          2  ║
║   6  ║       3  ║          2  ║
║   7  ║      10  ║          3  ║
║   8  ║       9  ║          3  ║
║   9  ║       3  ║          4  ║
║  10  ║       2  ║          5  ║
╚══════╩══════════╩═════════════╝

for the value 21, id of returnedItems are : 1 - 6 - 8
for the value 14, id of returnedItems are : 3 - 7
for the value 11, id of returnedItems are : 4 - 9 - 10
I think the above can be achieve by getting all the sum combination (that have different PackageNbr), and after that we can get the NEAREST OR EQUAL.
Any idea how to accomplish this task ?
I did surf the web and didn't find a way to do it using linq.
Any help would be appreciated.
Regards

A: I think your problem maps to the well known problem in computer science called Subset Sum Problem
To make it short if you do not have additional constraints and have to find all possible combinations you end up with an exponential algorithm.
Now to a practical solution:

*

*If you have one dataset which is rarely changing and you need to query it multiple times with different sums, just build a table of all combinations with corresponding sums. Sort it by sums and use binary search to get results for a concrete sum.

*If your dataset is almost the same, but changing relatively frequently, you still can create a sorted data structure with all combinations and corresponding sums once. But then you need to keep it up to date after each add or remove in your original dataset. This will be still cheaper than regenerating it over again.

*If you always have a new dataset and new query value you end-up with one of solutions described in wiki article.

This is a sample implementation of option 1.
It uses NUGet of combinatorics library to generate combinations.
        //Dataset
        var items = new[] {
            new Item {Id=1, Amount=10, PackageNr=1},
            new Item {Id=2, Amount=7, PackageNr=1},
            new Item {Id=3, Amount=4, PackageNr=2},
            new Item {Id=4, Amount=3, PackageNr=2},
            new Item {Id=5, Amount=8, PackageNr=3},
            new Item {Id=6, Amount=9, PackageNr=3},
            new Item {Id=7, Amount=10, PackageNr=4},
        };

        //Building a table
        var stack = new List<Tuple<int, int[]>>();
        for(int count=1; count <= items.Count(); count++) {
            stack.AddRange(
             new Combinations<Item>(items, count)
                .Where(combination => !combination
                                        .GroupBy(item => item.PackageNr)
                                        .Where(group => group.Count() > 1)
                                        .Any())
                .Select(combination => new Tuple<int, int[]>(
                                        combination.Sum(item=>item.Amount),
                                        combination.Select(item=>item.Id).ToArray())));
        }

        var table =
            stack
            .OrderBy(tuple => tuple.Item1)
            .ToArray();
        var index = table.Select(i => i.Item1).ToArray();

        //Print the table
        foreach (var row in table)
        {
            Console.WriteLine(" {0} ->  {1}", row.Item1, string.Join(",", row.Item2));
        };

        //Binary search in the table.
        Console.WriteLine("Number to search for:");
        int number;
        int.TryParse(Console.ReadLine(), out number);

        var position = Array.BinarySearch(index, number);
        if (position >= 0) Console.WriteLine("Exact match {0}", string.Join(",", table[position].Item2));
        else Console.WriteLine("Best match {0}", string.Join(",", table[~position].Item2));
        Console.ReadKey();
    }


text:
Q: Help with Limits $$\lim_{x\to\infty}\sqrt{(x^2 + ax)} - \sqrt{(x^2 - ax)} = 4$$
Problem: Solve for a.
I'm taking AP Calculus next year and I wanted to get a bit ahead over the summer, but I got stuck on this problem.
I really don't know how to go about this problem, so all I've done (which is probably wrong) is rewrite it so it looks like $\displaystyle \lim_{x\to\infty} (x^2+ax)^{\frac12} - \lim_{x\to\infty}(x^2 - ax)^{\frac12} = 4$ and try to solve for a by squaring both sides and treating it as a binomial. Was I going in the right direction? What should I do?

A: Answer without details
We multiply by the conjugate and using that
$$\sqrt{x^2\pm ax}\sim_\infty x$$
then the limit becomes
$$\lim_{x\to\infty}\frac{2ax}{2x}=\boxed{a=4}$$

A: Well you can do it that way also
$$x^2+ax-2\sqrt{x^4-a^2x^2}+x^2-ax=16\\x^2-\sqrt{x^4-a^2x^2}=8\\x^2-8=\sqrt{x^4-a^2x^2}\\x^4-16x^2+64=x^4-a^2x^2\\64=(a^2-16)x^2$$
Since $x\to \infty$ means that $a^2-16=0$ otherwise it can't be equal to a finite number,now if $a=-4$ clearly the first square root is smaller than second so $a=4$

A: HINT
As the others have mentioned multiply by the conjugate which is
$$\frac{\sqrt{x^2+ax}+\sqrt{x^2-ax}}{\sqrt{x^2+ax}+\sqrt{x^2-ax}}$$
so you will have something like:
$$\lim_{x\to\infty}\left(\sqrt{(x^2 + ax)} - \sqrt{(x^2 - ax)}\right) \cdot \frac{\sqrt{x^2+ax}+\sqrt{x^2-ax}}{\sqrt{x^2+ax}+\sqrt{x^2-ax}} = 4$$
The reason you want to do this is so that you can get rid of the pesky square roots which simplifies the question a lot. Try it.


text:
Q: Scrot command - how to save only thumbnail I'm using scrot to take screenshots from terminal.
However when I want to generate thumbnailed version using parameter -t, I got two files: screenshot.png and screenshot-thumbnail.png.
How can I get only thumbnailed version - screenshot-thumbnail.png because I have no need for screenshot.png.

A: When you use the -t switch, it will generate a thumbnail too, not only a thumbnail. You could however extend your command with the -e 'rm $f' this will execute the remove command on the original filename, leaving you with only the thumbnail.
scrot -t '%Y-%m-%d_$wx$h.png'

would become
scrot -t '%Y-%m-%d_$wx$h.png' -e 'rm $f'


text:
Q: Magento 2 which of the elements automatically render their children in layout Xml? Which two elements automatically render their children in Xml?

*

*<block class="\Magento\Framework\View\Element\AbstractBlock" name="shop.info.details"/>

*<block class="\Magento\Framework\View\Element\Template" name="shop.info.details"/>

*<container name="shop.info.details"/>

*<block class="\Magento\Framework\View\Element\Text\ListText" name="shop.info.details"/>

A: 3 and 4 I'd say.
Abstract block will not work as its class cannot be instantiated.
Template is likely the most commonly used but it does not render its children unless the template dictates it


text:
Q: How to update sql table column value dynamicllay based on another value? I have one table with the following structure and some values :
PK_ID      Webinar_Name                   Start_Date                          Is_Active
1                                 w1                               3/1/2016                              True
2                                w2                                1/7/2016                            True
3                                w3                                   4/9/2016                             True
Now i want the Is_Active column value to be updated dynamically (i.e : NOT after update,insert and delete) based on the date.. if its matches the current date so the Is_Active column value will set to be false.
I've tried to use triggers but it should be after some action like insert and update which is conflicts with my requirements.
I appreciate any help . thanks

A: It looks like you should be able to use a computed column for this, though I've never tried it.
https://msdn.microsoft.com/en-GB/library/ms188300.aspx
I guess it'd look something like this:
ALTER TABLE webinars ADD ActiveFlag AS
    CASE WHEN Start_Date = CAST(GetDate() AS date) THEN 'True'
    ELSE 'False' END

A: Use a computed column:
alter table t add Is_Active as (case when cast(start_date as date) = cast(getdate() as date) then 0 else 1 end)

Of course, you might need to remove the column first.
Note:  this uses 1 for true and 0 for false.  These constants are not defined in SQL Server.  You can use whatever values you like.


text:
Q: Is it possible to have multiple ingress paths under the same host that point to the same backend service I'm trying to restrict access to certain paths on my service how can I accomplish this on kubernetes?
I have a service that runs a basic API but it also runs an admin service. Is it possible to use multiple paths under the same host as an ingress rule?
Example.com/API can be open but
Example.com/admin needs to be restricted. Both services run on the same backend service.


text:
Q: Cómo puedo hacer un backup a MongoDB si no puedo iniciar el servidor mongod en windows Al intentar abrir mi servidor mongod en mi pc no me inicia y me sale excepción no encontrada, en muchas partes dicen que hay que desinstalar y volver a instalar el programa pero no puedo perder las bases de datos y las colecciones, la cuestión es que está la carpeta data y dentro de esta está la de DB y LOG,  me gustaría saber si copiando esa carpeta puedo recuperar esa información después al instalar el programa.
Muchas gracias

A: Sigue los siguientes pasos

*

*Reinstala la misma versión de MongoDB qe tenías anteriormente.

*Asegúrate que tu mongod.cfg apunta a las carpetas de datos y log que tenías anteriormente

*Inicia el proceso o servicio.

Deberías poder levantar mongod sin problemas. Si obtienes algún error actualiza tu pregunta con el error para poder ayudarte.


text:
Q: Buttons in vector not responding to custom drawing I have a Win32 program in which I have a vector which contains the HWND of some buttons which I want to custom draw. I can owner-draw them, but all I want to do is change the background color, so it seems unnecessary to do so. However, they don't seem to change as a result of being custom drawn. They look the same.
I create the buttons like this:
#define ID_BUTTON1 40000

std::vector<HWND> ButtonsVector;

for (int i = 0, i > NumButtons, i++) {
    ButtonsVector.push_back(CreateWindowEx(
                NULL,
                L"BUTTON",  // Predefined class; Unicode assumed
                L"X",      // Button text
                WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,  // Styles
                x,         // x position
                y,         // y position (substitute some x and y values for these)
                20,        // Button width
                20,        // Button height
                hWnd,     // Parent window
                (HMENU)ID_BUTTON1 + i,       // Unique button ID
                (HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE),
                NULL));
}

I use this WM_NOTIFY to draw them:
HBRUSH hHotBrush;
HBRUSH hDefaultBrush;

case WM_NOTIFY:
    {
            LPNMHDR some_item = (LPNMHDR)lParam;

            if (some_item->idFrom >= ID_BUTTON1 && some_item->code == NM_CUSTOMDRAW)
            {
                LPNMCUSTOMDRAW item = (LPNMCUSTOMDRAW)some_item;

                if (item->uItemState & CDIS_HOT) //Our mouse is over the button
                {
                    //Select our color when the mouse hovers our button
                    if (hHotBrush == NULL)
                        hHotBrush = CreateSolidBrush(RGB(230, 0, 0));

                    HPEN pen = CreatePen(PS_INSIDEFRAME, 0, RGB(0, 0, 0));

                    HGDIOBJ old_pen = SelectObject(item->hdc, pen);
                    HGDIOBJ old_brush = SelectObject(item->hdc, hHotBrush);

                    RoundRect(item->hdc, item->rc.left, item->rc.top, item->rc.right, item->rc.bottom, 5, 5);

                    SelectObject(item->hdc, old_pen);
                    SelectObject(item->hdc, old_brush);
                    DeleteObject(pen);

                    return CDRF_DODEFAULT;
                }

                //Select our color when our button is doing nothing
                if (hDefaultBrush == NULL)
                    hDefaultBrush = CreateSolidBrush(RGB(255, 0, 0));

                HPEN pen = CreatePen(PS_INSIDEFRAME, 0, RGB(0, 0, 0));

                HGDIOBJ old_pen = SelectObject(item->hdc, pen);
                HGDIOBJ old_brush = SelectObject(item->hdc, hDefaultBrush);

                RoundRect(item->hdc, item->rc.left, item->rc.top, item->rc.right, item->rc.bottom, 5, 5);

                SelectObject(item->hdc, old_pen);
                SelectObject(item->hdc, old_brush);
                DeleteObject(pen);

                return CDRF_DODEFAULT;
            }
    }
    break;

A: I needed to add the following line:
#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version = '6.0.0.0' processorArchitecture = '*' publicKeyToken = '6595b64144ccf1df' language = '*'\"")

This makes sure that ComCtrl32.dll version 6 is being used, allowing the custom-drawing of button controls. One thing you have to be careful of, however, is which version of Windows you are targeting for your application, as versions older than XP do not include this version of the dll.


text:
Q: Looping through array forwards and backwards? I'm currently testing out looping through an array of objects.
The current object is presented in a ViewController with next and previous buttons. When next is pressed, the next object in the array should be presented in the view controller. If it is the last object, it should go to the first object in the array. When previous is pressed, it should display the previous object to the current object in the array. If it reaches the first object, it should go to the last object in the array. However, only the next button works, the previous button gets stuck on the first object and I don't know why. The next button works perfectly. Any ideas?
- (void)changeObject:(id)sender{

    NSUInteger index = [self.objectArray indexOfObject:self.currentObject];

    UIBarButtonItem *button = (UIBarButtonItem *)sender;
    NSUInteger nextIndex;

    if([button.title isEqualToString:@"Next Object"]){
        nextIndex = (index + 1) % self.objectArray.count;
    }
    else{
        // Previous Object
        NSLog(@"Previous Object");
        nextIndex = (index - 1) % self.objectArray.count;

        if (nextIndex == -1) {
            nextIndex = self.objectArray.count - 1;
        }
    }

    index = nextIndex;
    self.currentObject = [self.objectArray objectAtIndex:index];

    self.navigationItem.title = [NSString stringWithFormat:@"%@'s Values", self.currentObject.name];

}

EDIT: what I ended up doing was the following:
- (void)changeObject:(id)sender{

    NSInteger index = [self.objectArray indexOfObject:self.currentObject];

    UIBarButtonItem *button = (UIBarButtonItem *)sender;

    if([button.title isEqualToString:@"Next Object"]){
        index++;
        if (index >= self.objectsArray.count){
             index = 0;
        }
    }
    else{
        index--;
        if (index < 0){
             index = self.objectsArray.count - 1;
        }
    }

    self.currentObject = [self.objectArray objectAtIndex:index];

    self.navigationItem.title = [NSString stringWithFormat:@"%@'s Values", self.currentObject.name];

}

A: Try something like this:
- (void)changeObject:(id)sender{

    NSInteger index = [self.objectArray indexOfObject:self.currentObject];

    UIBarButtonItem *button = (UIBarButtonItem *)sender;

    if([button.title isEqualToString:@"Next Object"]){
        index++;
        if (index >= self.objectsArray.count) index = 0;
    }
    else{
        index--;
        if (index < 0) index = self.objectsArray.count - 1;
    }

    self.currentObject = [self.objectArray objectAtIndex:index];

    self.navigationItem.title = [NSString stringWithFormat:@"%@'s Values", self.currentObject.name];

}


text:
Q: Paypal Sandbox doing crazy things First of all , the test accounts I created were not working. So, I removed all Paypal cookies.So, now good thing I can login into test accounts but can't access My Settings and My Selling tools under My Profile. I'm trying to create Buy Now button in My Selling tools.
Also, My Paypal live account is for Paypal Payments Standard(My Business Setup->My payment solution) and in test account the payment solution is Paypal Payments Pro and doesn't let me change this option.The links in my business solution (View all products to learn more or select an additional payment solution or we can recommend one that fits your needs.) goes to PayPal live site.
Any one facing this crazy PayPal sandbox behavior !!!

A: When you say you can't access My Settings and My Selling tools under My Profile, are you getting an error or what is it doing specifically.  The Pro account that you have in sandbox, will work for testing Website Payments Standard.  Also, another option if you can't create test buttons from your sandbox account would be to log into your live account and create a non hosted / clear text button.  Then you would just modify the button code, and change the URL in the form tag from the live site to the sandbox site.  Also, you will need to change the value of the business variable and set it to either the email address of your test sandbox seller account or the merchant id.  Another work around that has worked in the past as well, is going into your live account and going to the page you are wanting and copy the URL from the address bar and just modifing it to include the sandbox URL.
So if my live site URL was something like:
https://www.paypal.com/us/cgi-bin/webscr?cmd=_flow&SESSION=

I would just change it to
https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_flow&SESSION=

Also, if you can give me more details about what is happening when you try to access your profile in your sandbox account I can look into it further.


text:
Q: Parsing JsonObject to List> using Gson? I'm trying to parse a string representation of a JSON object into a List of maps.
The json object will be structured something like the following:
[
 {
  "first_name": "fname1",
  "last_name": "lname1"
 },
 {
  "first_name": "fname2",
   "last_name": "lname2"
 }
 .
 .
 .
]

The only thing that is known is the strings values (e.g "first_name", "last_name") on runtime only, therefore I cannot create any predefined classes (like usually used in fromJson() method).
I have tried to create the following function (after I saw some examples online) and it didn't work:
public List<Map<String, Object>> fromJson(String jsonAsString) {
    final JsonElement jsonElement = this.jsonParser.parse(jsonAsString);

    List<Map<String, Object>> myList= new ArrayList<Map<String, Object>>();
    Type listType = TypeToken.get(myList.getClass()).getType();
    myList= (new Gson()).fromJson(jsonElement, listType);

    return myList;
}

The result of this function is a list (length == 2 in the above case) but instead of 2 maps i'm getting 2 Objects.
Any help?
Thanks!

A: I don't quite understand your use of TypeToken.
The point of TypeToken is to capture parameterized type (such as List<...>) by creating anonymous class that extends generic supertype parameterized by the type you want to capture, using the following syntax:
new TypeToken<... type you want to capture ...>() {}.getType()

In your case it should be used as follows:
myList = new Gson().fromJson(jsonAsString,
    new TypeToken<List<Map<String, Object>>>() {}.getType());

A: You cannot use generics like that, at runtime List<Map<String, Object>> myList is the same as List<Object> myList.
You can try with an array of maps
    Gson gson = new Gson();
    Map[] x = new Map[0];
    Map[] fromJson = gson.fromJson("[\r\n" +
            " {       \r\n" +
            "  \"first_name\": \"fname1\",\r\n" +
            "  \"last_name\": \"lname1\"\r\n" +
            " },\r\n" +
            " {\r\n" +
            "  \"first_name\": \"fname2\",\r\n" +
            "   \"last_name\": \"lname2\"\r\n" +
            " }]",x.getClass());


text:
Q: What's the easiest way for the multiple if-else conditions? I have a data set something like this:
df_1 <- tribble(
  ~A,   ~B,  ~C,
  10,   10,  NA,
  NA,   34,  15,
  40,   23,  NA,
   4,   12,  18,
)

Now, I just want to compare A, B, C for each row, and add a new column that shows us the minimum number. Let's see how desired data looks like:
df_2 <- tribble(
  ~A,  ~B,  ~C,  ~Winner,
  10,  10,  NA,  "Same",
  NA,  34,  15,  "C",
  40,  23,  NA,  "B",
   4,  12,  18,  "A",
)

There are four outputs: Same, A-Win, B-Win, C-Win.
How would you code to get this result?
Thanks in advance.

A: Here is something:
foo <- function(x) {
  rmin <- which(x == min(x, na.rm = TRUE))
  if (length(rmin) > 1) "same" else names(rmin)
}
apply(df_1, 1,  foo)

[1] "same" "C"    "B"    "A"

You can add this as a column to your data.frame with:
df_1$winner <- apply(df_1, 1,  foo)

# A tibble: 4 x 4
      A     B     C winner
  <dbl> <dbl> <dbl> <chr>
1    10    10    NA same
2    NA    34    15 C
3    40    23    NA B
4     4    12    18 A

If you have more variables and only want to use some you can use a character vector:
vars <- c("A", "B", "C")
apply(df_1[vars], 1,  foo)

A: df_1 <- tribble(
  ~A,   ~B,  ~C,
  10,   10,  NA,
  NA,   34,  15,
  40,   23,  NA,
  4,    12,  18,
)

df_1 %>%
  mutate(
    winner = colnames(df_1)[apply(df_1,1,which.min)],
    winner = if_else(A == B | B == C | A == C, 'same', winner, missing = winner))

# A tibble: 4 x 4
      A     B     C winner
  <dbl> <dbl> <dbl> <chr>
1    10    10    NA same
2    NA    34    15 C
3    40    23    NA B
4     4    12    18 A


text:
Q: Tangential velocity - Spherical coordinates In a spherical coordinates system ($r$, $\theta$, $\phi$ ), assuming an angular rotation $\omega_z$ around the z-axis, the tangential velocity of a point can be expressed as:
$$V_x = -\omega_z R \sin\theta \sin\phi $$
$$ V_y = \omega_z R \sin\theta \cos\phi$$
What happens if I have a rotation $\omega_x$ around the $x$-axis? What are the equation for the $V_y$ and $V_z$ velocity components of the point?

A: The equation is always
$$ \boxed{\; \boldsymbol{v} = \boldsymbol{\omega} \times \boldsymbol{r} \; } $$
where $\boldsymbol{\omega}  = \pmatrix{\omega_x \\ \omega_y \\ \omega_z } $ and $\boldsymbol{r} = \pmatrix{ r \cos \phi \sin \theta \\ r \sin \phi \sin \theta \\ r \cos \theta} $
In your first case $\omega_z \neq 0$ while others are 0, and in the second case $\omega_x \neq 0$.
$$\boldsymbol{v} = \begin{bmatrix} 0 & r\cos \theta & -r \sin \phi \sin \theta \\ -r \cos \theta & 0 & r \cos \phi \sin \theta \\ r \sin \phi \sin \theta & -r \cos \phi \sin \theta & 0 \end{bmatrix} \pmatrix {\omega_x \\ \omega_y \\ \omega_z } $$
If rotation is about the x-axis, then use the first column of the matrix above and multiply it with $\omega_x$.


text:
Q: Unable to launch chrome browser using selenium web-driver I have installed
java version : 18.0.1
selenium jar version : 4.1.4,
chrome browser version : 101.0.4951.41
I want to launch the google in chrome browser using selenium web-driver test case. But I am not able to launch due the above attached issue.
Screenshot of eclipse error


text:
Q: Image always loading placeholder in e-mail template I'm trying to create some fancy e-mail template for the productalert (when a product returns back in stock) in our website, but I'm not able to load the product image, in any method. In the /template/email/productalert/stock.phtml file I've tried:
(string)Mage::helper('catalog/image')->init($product, 'thumbnail')->resize(130, 130)

using thumbnail/image/small_image
or
$product->getImageUrl()

both with or without a $product = Mage::getModel('catalog/product')->load($product->getId()); before.
All I get is always the placeholder. Images are loaded correctly in the website.
Any hints?


text:
Q: Establish secure channel to domain workstations to transmit password in clear text I want to use some command line tools for remote administration of Microsoft domain workstations, however some of them transmit the credentials in clear text.
Is there a command line utility I can use to establish an secure connection prior to using those tools?

A: If you application layer sends sensitive data in plain text I see 2 possible workarounds:

*

*Remote to the target system using a secure connection and issue commands there. Not always feasible, because you'd need to have needed tools installed on the target systems.

*Employ encryption on a lower level of a stack. This could take a form of VPN between the systems involved. Probably a lot of hassle to configure it for all systems you'd want to connect to.
There's also a 3rd possibility. Replace your utility with a tool that pays attention to security and privacy.


text:
Q: Explicit Casting a return I'm maintaining a codebase (old, Java 3) written by a vendor that no longer maintains this product.
I am regularly running into things like this:
private boolean doSomething() {
    boolean success = false;
    // do stuff
    if (/*some stuff*/) {
        success = true;
    }
    return success;
}

public void doStuff() {
    boolean ok = (boolean) doSomething();
    if (ok) {
        // do stuff
    }
}

So, Obviously they are trying to determine method success/fail by passing back a boolean indicating status (validation)... I personally think that is bad practice, I'd much rather an exception bubble up to the caller, but that's just me.
The part I'm confused on, why does/did this vendor constantly explicitly cast boolean return values into a boolean? This is redundant and surely causes some overhead during runtime, no? Have I been doing it wrong all this time!? - or is this just some stylistic thing that I should pay no attention to?

A: It doesn't incur overhead at runtime because casts are there for the compiler.
But it is unnecessary. All you need is
if (doSomething()) {
    // do stuff
}

It's an idiosyncratic weirdness of somebody who didn't know the language very well and who hasn't read others' code to get an idea of what's good style.

A: You are correct in saying that it could be considered "bad practice" and the return type obviously is boolean.
They most likely had done this to maintain type safety, and it was their own prerogative.  Maybe the vendor had a convention that casts every method that had a return type to make sure that they were indeed getting that type.

A: Casts happen at compile time rather than runtime so there'll be non performance impact that I can think of. It's just cruft in the codebase.


text:
Q: FullCalendar: Rendering background events as regular ones I'm writing an app that employs Fullcalendar. I need to have two view/edit modes:

*

*one typical - Regular edit - with regular and background events, where regular events are editable through clicking and background ones are only drawn as informative areas

*and another - Background edit - where regular events are hidden (return false), and the background events are rendered as regular ones, with editing capability through clicking.

Something along these lines:
    eventRender: function(event, element) {
        if($('#background-edit-chk').is(':checked')) {
            if (event.rendering == EVENT_RENDERING.NORMAL) return false;
            else event.editable = true; // here: render background as editable
        }
    }

What would be the code in the else line - obviously the above code does not render event as regular.
I mean, I could re-fetch the events and use separat transformation function for each mode, but I'm hoping that there's a way to just act on the rendering layer.

A: i have exactly 30minutes experience with fullcalendar,
but perhaps

event.rendering = ""

(making the rendering property empty should render the event as a normal event)


text:
Q: How to setup communication between virtual machines Probably my issue is not hard to resolve but I got a stuck.
I have several LXC containers. One of them has MySQL, RabbitMQ, MongoDB (and several other services) installed and configured. Every other container has running on the board a service which requires MySQL, RabbitMQ, MongoDB and others. Beside that every container communicates (HTTP, sockets) between each other.
The problem is that IPs of these containers changes. And when this happens I need to change config files on each container. IPs changes because they gets IPs from DHCP server which changes when I move my laptop from one place to another. And this is not the only reason why IPs could be changed. Also I need some IPs to be public, so I will be able to connect from other PC to some container within the same LAN.
One solution which comes to mind is to bring up and configure dnsmasq (or other local DHCP server) on the host machine, but I'm not sure that that will resolve the issue. And also quite important note: I would like to avoid additional configuration of the host machine.
Is there any other way to setup communication between virtual machines? How would you resolve such a task?
Edited: Static IPs for sorry are not suitable for my needs because sometimes I want to bring up the set of containers on the different PCs but within the same LAN.


text:
Q: Speak UI - SearchPanel config setting I am currently working in Speak Ui .I need to display all child of Root which belongs from some specific template . For that I am using "SearchPanel Config" to do template and root setting . After doing this setting I noticed its not talking template setting from "SearchPanel Config" and displaying all Items . I am new to speak UI . Please help me .

A: When you say "not taking the template" are the results not filtered as you expect?
When configuring your Search Panel Config template you should add the required item ids in the Root and Template fields.

You then need to edit the properties of the SearchDataSource rendering

To set the SearchConfigItemId to the SearchPanelConfig item you previously edited using the TreeList to select the required config item.

You can verify the appropriate configuration is being passed by checking the Network Tab in your browser to see the calls being made by your SPEAK component.
You should see - [hostname]-/item/v1/sitecore/shell?search=&searchConfig=%7BC01B6B84-4D24-4214-B663-52902F43F113%7D&sc_content=master&language=en where the searchConfig parameter is the value of the SearchConfigItemId you previously set
Additionally look in your Sitecore log files and verify what the query being passed to the search index is, see below for an example of mine.

21376 08:35:37 INFO  Query -
  (((_path:(7cc230f160a84d979c06c738a1334c6e) AND _language:(en)) AND
  _templatename:("Your Template Name")) AND -__hidden:(1)) 21376 08:35:37 INFO  Serialized Query - ?q=(((_path:(7cc230f160a84d979c06c738a1334c6e) AND
  _language:(en)) AND _templatename:("Your Template Name")) AND -__hidden:(1))&rows=500&fl=*,score&fq=_indexname:(sitecore_master_index)&sort=_name
  asc


text:
Q: what is the class of jsp pages? What is the class of jsp pages? I want to pass an object of page to a class whith "this" pointer on the page. How can I do this?
Thanks.

A: Once they've been compiled to servlets, JSPs implement the interface javax.servlet.jsp.JspPage.
The actual base class depends on the servlet container, though. For example, Tomcat 6 genrated compiled JSPs extending the base class org.apache.jasper.runtime.HttpJspBase.


text:
Q: how to insert dynamically added form fields in database using php I want to add dynamic form fields in the database using PHP. I have used angular to add dynamic form fields. The thing is when I am trying to insert this data into the database only last form field is inserting in the database. SO, I used array and loop to increment and update this form field into the database. but somehow query is not working properly and data is also not inserting into the database. can anybody tell me what is wrong here? I am stuck. Please help. Thanx in advance
Php Code:
<?php
if(isset($_POST['submit_row']))
{
$link = mysqli_connect("localhost", "root", "", "midata");

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

 $camp_name = mysqli_real_escape_string($link, $_REQUEST['camp_name']);
 $start_date = mysqli_real_escape_string($link, $_REQUEST['start_date']);
 $end_date = mysqli_real_escape_string($link, $_REQUEST['end_date']);

$store = mysqli_real_escape_string($link, $_REQUEST['$store']);
$elements= $mysqli->real_escape_string($_POST['elements']);
$quantity = $mysqli->real_escape_string($_POST['quantity']);

$description = mysqli_real_escape_string($link, $_REQUEST['description']);

for($i=0;$i<count($elements);$i++)
 {
  if( $elements[$i]!="" && $quantity[$i]!="")
  {

$sql = "INSERT INTO create_campaign(camp_name, start_date, end_date,store,elements,quantity, description )
VALUES('$camp_name',' $start_date', '$end_date','$store','$elements[$i]', '$quantity[$i]', '$description')";

if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_query($sql, $link);
}
}
}

?>

HTML Code:

                                                    <fieldset  data-ng-repeat="choice in choices" name="records">
                                                        Elements

                                                            <input type="text" placeholder="Campaign Name" ng-model="choice.name" class="form-control c-square c-theme input-lg" name="elements[]">

                                                        Quantity

                                                           <select class="form-control  c-square c-border-2px c-theme"  name="quantity[]>
                                                             <option value="1">100</option>
                                                             <option value="2">200</option>
                                                             <option value="3">300</option>
                                                             <option value="4">400</option>

                                                            </select>

                                                     <button type="button" class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square" ng-click="addNewChoice()" >add</button>
                                                     <button   ng-show="$last" ng-click="removeChoice()" class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square" >Remove</button>
                                                     </fieldset>

                                            <input type="text" placeholder="Description" class="form-control c-square c-theme input-lg" name="description">

                                        <input class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square" value="Submit" type="submit" name="submit_row">

                                    </form>

A: You should declare a variable like x=1 and use it inside your array of input like name="input_name[+ x +]"
and increment the variable after each input field i.e x++
You can access those inputs using inputName[1], input_name[2] in your php controller


text:
Q: Error occurred trying to load the template for preview: Attempt to de-reference a null object. Please try editing your markup to correct the problem I am trying to add a Visual Force component into a VisualForce email template but keep getting the error message below:
[Error]
Error occurred trying to load the template for preview: Attempt to de-reference a null object. Please try editing your markup to correct the problem.
I do not get any errors when saving class or component.
Apex Class:
public class InteractionsForCustomer {

private List<Interactions__c> allInteractions;
    private Interactions__c currentInteractions;

public InteractionsForCustomer() {

 }

public List<Interactions__c> getAllInteractions() {
            allInteractions = [Select Id, Name from Interactions__c where Stage__c = 'Open' AND Cutomer__c = :currentInteractions.Customer__c];
    return allInteractions;
}

 public Interactions__c getcurrentInteractions() {
         return currentInteractions;
 }
 public void setcurrentInteractions(Interactions__c val) {
        this.currentInteractions = val;
  }

}
VisualForce Component:
<apex:component controller="InteractionsForCustomer" access="global">
    <apex:dataTable value="{!allInteractions}" var="inv">
      <apex:column >
        <apex:facet name="header">Invoice Name</apex:facet>
           {!inv.Customer__c}
       </apex:column>
     </apex:dataTable>
 </apex:component>

Can anybody help??
Thanks
Josh

A: The general reason for this error is that the VF email template previewer doesn't have enough information to pass to the component's controller all such information as is typically provided at runtime when you either test the template (by providing a valid ID of the record used in relatedTo attribute) or use in APEX or a workflow/process builder.
To solve this and avoid the error message, you need to code the component controller to handle null values for all inputs in a graceful way (that is, assume all inputs can be null - check for null, and handle accordingly without throwing exceptions)
For example - the most likely cause of the NPE is that currentInteractions is null because the setter for it was never invoked. Thus rewrite this method to:
public List<Interactions__c> getAllInteractions() {
        allInteractions = currentInteractions != null
         ? [Select Id, Name from Interactions__c where Stage__c = 'Open' AND Cutomer__c = :currentInteractions.Customer__c]
         : new List<Interactions__c>();
  return allInteractions;
}

That said, @Himanshu asks a good question - how does currentInteractions get set in the component controller; normally you would pass in an attribute from the containing VF page that would in turn be sent to the component controller via an apex:attribute assignto={!currentInteractions} attribute.
N.B. It is unusual for an SOBject to be named implying a plural , e.g. "Interactions__c" as opposed to "Interaction__c". Plurals are used for variables that represent lists or sets. Think of Account, Opportunity, Quote, etc.


text:
Q: Excel removes '+' as a first character of a string I am exporting mobile nos from JSON to CSV using Papa Parse. Each mobile no has a country code which starts with + as the first character. The list is exported but when I open the CSV file in microsoft excel the + gets removed from the mobile no string.
const profileListDownload = [];
let dataid = 1;

list.forEach(e => {
  const newRow = {};
  newRow["dataid"] = e.dataid;
  newRow["mobileno"] = e.mobileno;
  profileListDownload.push(newRow);
  dataid++;
});

const csv = Papa.unparse(JSON.stringify(profileListDownload));
const url = window.URL.createObjectURL(new Blob([csv]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "ProfileEdit.csv"); //or any other extension
document.body.appendChild(link);
link.click();

But when I open the csv file using google sheets or notepad. The + character is present.

A: You need to add an apostrophe before the plus sign like this: '+ this way Excel passes over it and doesn't treat it like a value.
If all of the numbers have the + before them then you should be able to just prepend the apostrophe onto the number in your loop.
list.forEach(e => {
  const newRow = {};
  newRow["dataid"] = e.dataid;
  newRow["mobileno"] = "'" + e.mobileno;
  profileListDownload.push(newRow);
  dataid++;
});


text:
Q: magento2 and gmail image proxy issue i've faced with magento2 and gmail image proxy issue:
i'm sending transactional emails with images and gmail shows broken image because it has wrong URL inside (double dot in URL address):

it takes URL from Base URL and of course it correct and always was.
moreover, any other shipment and/or payment method works ok.
Kindly asking about any hints or suggestions.
p.s. same with some products:

A: If you are currently working in your localhost or under a private network this issue will happen because Gmail uses Google's secure proxy servers to serve images. If your website is publicly accessible you will not face this issue.
You can bypass the image url proxy but it is not recommended for security reasons.
Refer the below link
https://support.google.com/a/answer/3299041?hl=en


text:
Q: Only variables should be passed by reference in... on line 13 Fail I'm practicing building a PHP registration form script for a website. I have done this code, but when I click the submit button I get the notice: Only variables should be passed by reference in line 13, and I'm stuck on what to do here. Any help is greatly appreciated, again I'm not a PHP expert.
<?php

require 'database.php';

if(!empty($_POST['email']) && !empty($_POST['username']) && !empty($_POST['password'])):

    //Enter the new user into the database
    $sql = "INSERT INTO users (email, username, password) VALUES (:email, :username, :password)";
    $stmt = $conn->prepare($sql);

    $stmt->bindParam(':email', $_POST['email']);
    $stmt->bindParam(':username', $_POST['username']);
    $stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));

    if($stmt->execute() ):
        die('Success');
    else:
        die('Fail');
    endif;
endif;

?>

here

A: change this
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));

to this
$email =  $_POST['email'];
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);

$stmt->bindParam(':email', $email);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password',$password);

the error message is clear though you need to assign those values into variables then pass them

A: $result->bindParam(':id', $id, PDO::PARAM_INT);
if string, you need write:
$stmt->bindParam(':username', $_POST['username'], PDO::PARAM_STR);


text:
Q: Looping on Text boxes included in ajax Tab I have 20 Text boxes and i want to take their value by loop on each one ,
the problem is all of text boxes are included in Ajax Tab Container , so when i use below code it gives me error :

object reference not set to an instance of an object

It can`t find the control because it's on tab,
if I try to use below code away from tab container it works fine
string TicketIDLoop = "";
for (int MutiVar = 1; MutiVar <= 20; MutiVar++)
{

 ContentPlaceHolder mpContentPlaceHolder;
 TextBox mpTextBox;
 mpContentPlaceHolder =
   (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
 if (mpContentPlaceHolder != null)
 {
     mpTextBox =
         (TextBox)mpContentPlaceHolder.FindControl("TTIDTextBox" + MutiVar.ToString());
     if (string.IsNullOrEmpty(mpTextBox.Text) == false)
     {

         TicketIDLoop = mpTextBox.Text;
         //MessageBox.Show(mpTextBox.Text.ToString());

         SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ZainJTAConnectionString_96"].ConnectionString);
         SqlCommand cmd = new SqlCommand();
         cmd.CommandType = CommandType.StoredProcedure;
         cmd.CommandText = "[JTA_Schema].[SP_WFM_Update]";

         cmd.Parameters.Add("@UpdateID", SqlDbType.Int).Value = TicketIDLoop;
         cmd.Parameters.Add("@Specialist", SqlDbType.VarChar).Value = Session["Session_UserName"];
         cmd.Parameters.Add("@resoultion", SqlDbType.VarChar).Value = ClosingResolutionDropDownList.SelectedValue.Trim();
         cmd.Parameters.Add("@WFMComment", SqlDbType.VarChar).Value = CommentVar;

         cmd.Connection = con;

         try
         {
             con.Open();

             cmd.ExecuteNonQuery();
         }

         catch (Exception ex)
         {
             throw ex;
         }

         finally
         {
             con.Close();
             con.Dispose();
         }
}
}
}


text:
Q: plsql insert multiple rows using one execute immediate command Is there a way to insert multiple rows in one EXECUTE IMMEDIATE?   Rather than writing EXECUTE IMMEDIATE for each insert...

A: Hard to tell what you are inserting. You can use EXECUTE IMMEDIATE to do an INSERT...SELECT easily enough, but I suspect that isn't what you are after, and probably you're not simply wanting a loop around the EXECUTE IMMEDIATE.
If the multi-table insert isn't what you are looking for, you can use EXECUTE IMMEDIATE on a PL/SQL block and/or within a FORALL
create table test_forall_dyn (val varchar2(1));

declare
  type tab_char is table of varchar2(1) index by binary_integer;
  t_char tab_char;
begin
  for i in 1..26 loop
    t_char(i) := chr(64 + i);
  end loop;
  forall i in 1..26
    execute immediate
      'begin
         insert into test_forall_dyn (val) values(:1);
         insert into test_forall_dyn (val) values(:1);
       end;'
       using t_char(i);
end;
/

select count(*) from test_forall_dyn;

A: EXECUTE IMMEDIATE
INSERT INTO table (col1, col2, col3) (
            SELECT 1 AS col1, 2 AS col2, 3 AS col3 FROM dual
  UNION ALL SELECT 4,         5,         6         FROM dual
  UNION ALL SELECT 7,         8,         9         FROM dual ) ;

A: Mariya,
why use dynamic sql in the first place?
Most of the times scalability is not exactly improved using dynamic sql.
The same is for readability.
Debugging is harder ....
In many cases there are also weird security issues....
I don't know why you use dynamic sql but if this is part of a production application I would reconsider using it.
Ronald.

A: @maria
First frame  select quesry which gives u multiple row wich u are going to insert...
You select stament shoud give data in order of data u want to insert in table
Then use..
Insert into Tabl1 (col1,col2,col3)(select name,address,phone from tabl2)
commit;

A: Sure, you can go for batch insert...


text:
Q: Styling a TableView scroll-bar in CSS (JavaFX) How can I style the "THIS" point in my TableView?

A: This area is a StackPane which belongs to your ScrollPane.
(I assume that your ScrollPane has the id "Sp")
Then style it like:
#Sp>StackPane {
    -fx-background-color: #ff0000;
}

A: The styleClass you are looking for is .corner
In your applications .css file you can apply the style you like e.g.
.corner {-fx-background-color: green;}

When you need to know a styleClass of a component, you can use the CSS Analyzer in Scenebuilder (View -> Show CSS Analyzer), or Scenicview which is even more convenient


text:
Q: AWS Lambda bootstrap.py file is throwing error while trying to upload data to elastic search I'm trying to index pdf documents that are uploaded to s3 bucket. My lambda function is working fine til PDF extraction part. it's establishing connection with elastic search endpoint and while uploading data elastic search for indexing, it's throwing error. Please find lambda function code below. Please help me with this. Thanks in advance.
from __future__ import print_function

import json
import urllib
import boto3
import slate
import elasticsearch
import datetime

es_endpoint = 'search-sdjsf-zrtisx]sdaswasfsjmtsyuih3awvu.us-east-
1.es.amazonaws.com'
es_index = 'pdf_text_extracts'
es_type = 'document'

print('Loading function')

s3 = boto3.client('s3')

# prepare a dict to hold our document data
doc_data = {}
doc_data['insert_time'] =
str(datetime.datetime.isoformat(datetime.datetime.now()))

def lambda_handler(event, context):
    #print("Received event: " + json.dumps(event, indent=2))

    # Get the object from the event and show its content type
    bucket = event['Records'][0]['s3']['bucket']['name']
    object_key = urllib.unquote_plus(event['Records'][0]['s3']['object']
    ['key']).decode('utf8')
    try:
        # get the file data from s3
        temp_pdf_file = open('/tmp/tempfile.pdf', 'w')
        response = s3.get_object(Bucket=bucket, Key=object_key)
        print("CONTENT TYPE: " + response['ContentType'])
        # return response['ContentType']
        temp_pdf_file.write(response['Body'].read()) # write the object data
        to a local file; will be passed to slate
        temp_pdf_file.close() # close the temporary file for now

        # pull the text from the temporary PDF file using slate
        print("Extracting data from: " + object_key)
        with open('/tmp/tempfile.pdf') as temp_pdf_file:

        doc = slate.PDF(temp_pdf_file)

        # store document data to dict
        doc_data['source_pdf_name'] = object_key
        doc_data['document_text'] = doc[0] # we're only worried about page 1
        at this point

        #datj=json.dumps(doc_data)
        #z=json.loads(datj)
        #print(z)
    except Exception as e:
        print(e)
        print('Error getting object {} from bucket {}. Make sure they exist
        and your bucket is in the same region as this
        function.'.format(object_key, bucket))
        raise e

    # put the data in ES
    #try:
    es = elasticsearch.Elasticsearch([{'host': es_endpoint, 'port': 443,
   'use_ssl': True}]) # hold off on validating certs
    es_response = es.index(index=es_index, doc_type=es_type, body=doc_data)
    print('Data posted to ES: ' + str(es_response))

    #except Exception as e:
        #print('Data post to ES failed: ' + str(e))
        #raise e

return "Done"

I have removed try and except in last block to find the actual error and its throwing the below error while trying to upload data to elastic search.
Traceback (most recent call last):
File "/var/runtime/awslambda/bootstrap.py", line 576, in <module>
main()
File "/var/runtime/awslambda/bootstrap.py", line 571, in main
handle_event_request(request_handler, invokeid, event_body, context_objs,
invoked_function_arn)
File "/var/runtime/awslambda/bootstrap.py", line 264, in
handle_event_request
result = report_fault_helper(invokeid, sys.exc_info(), None)
File "/var/runtime/awslambda/bootstrap.py", line 315, in report_fault_helper
msgs = [str(value), etype.__name__]

A: Remove the return "Done" at the end, that's not allowed in a Lambda environment.


text:
Q: Check if site is up or down I have problem with this script if i check http://google.com/ or other website is not work and with http://stackoverflow.com or cnn.com is work...
$url = 'http://google.com/';

function urlExists($url=NULL)
{
    if($url == NULL) return false;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if($httpcode>=200 && $httpcode<300){
        return true;
    } else {
        return false;
    }
}

if(urlExists($url))
{
    echo "ok";
}
else
{
    echo "no";
}

I have test @fopen and not work too
Website like google have blocker ? Thanks

A: You should change:
if($httpcode>=200 && $httpcode<300){

to:
if($httpcode>=200 && $httpcode<303){

The reason is that many sites use a 301 Moved Permanently by default as well as 302 Found.

A: You are curling http://google.com which responds with the response code 301 to redirect visitors the http://www.google.com. In your logic, the 301 response code is considered offline.
You will need to adjust the URL you are checking, adjust the logic to accept this response code, or add the code below to make cURL follow redirects.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

A: it should probably read
if($httpcode>=200 && $httpcode<400){

Instead Of
if($httpcode>=200 && $httpcode<300){

Otherwise, a redirect would be regarded as "server down".
With the above change, the result for http://google.com is ok


text:
Q: Can't access variable for unknown reason I'm trying to execute two INSERT statements and I need the last inserted id to do so. I've tried $question_id = $dbh->lastInsertId();, but it doesn't work. Now I'm executing an additional SELECT LAST_INSERT_ID() statement, but that doesn't work either. I keep getting this error: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined, which occurs because $question_id is empty because selecting the last insert id doesn't seem to work.
Here's my code:
public function add_question($user_id, $group_id, $title, $caption, $datetime, $status) {
    // Add user to database
    try {
        $dbh = new DBHandler();

        $sql =
        "INSERT INTO question(
                user_id,
                group_id,
                title,
                caption,
                created_date_time,
                question_status
            )
            VALUES(
                :user_id,
                :group_id,
                :title,
                :caption,
                :created_date_time,
                :question_status
            )";

        $stmt = $dbh->get_instance()->prepare($sql);

        $stmt->execute(
            array(
                ':user_id' => $user_id,
                ':group_id' => $group_id,
                ':title' => $title,
                ':caption' => $caption,
                ':created_date_time' => $datetime,
                ':status' => $status
             )
        );

        //$question_id = $dbh->lastInsertId();

        $sql= "SELECT LAST_INSERT_ID() AS question_id";
        $stmt = $dbh->get_instance()->prepare($sql);
        $stmt->execute();

        // Resultset
        $result = $stmt->fetchAll();

        foreach($result AS $question_id_row) {
            $question_id = $question_id_row['question_id'];
        }

        $sql =
        "INSERT INTO notification(
            n_question_id,
            n_question_user_id,
            n_question_group_id,
            n_question_title
        )
        VALUES(
            :n_question_id,
            :n_question_user_id,
            :n_question_group_id,
            :n_question_title
        )";

        $stmt = $dbh->get_instance()->prepare($sql);

        $stmt->execute(
            array(
                ':n_question_id' => $question_id,
                ':n_question_user_id' => $user_id,
                ':n_question_group_id' => $group_id,
                ':n_question_title' => $title
             )
        );

        echo 'Question added!';
    }
    catch(PDOException $e) {
        echo $e->getMessage();
    }
}

A: Your query fails with invalid number of parameter and parameter was not defined because you define this parameter
:question_status
but you bind
':status' => $status
change
$stmt->execute(
array(
    ':user_id' => $user_id,
     ':group_id' => $group_id,
     ':title' => $title,
     ':caption' => $caption,
     ':created_date_time' => $datetime,
     ':question_status' => $status //here
)
);

and it will work


text:
Q: Is there a pre-read event for mongoose? I want to run a method every time I read from a Schema. Something like this:
var Schema = mongoose.Schema;
var exampleSchema = new Schema({
    views: {
        type: Number
    }
});

exampleSchema.pre('read', function(next) {
    this.views++;
    next();
});

Alternatively if there is a better way to do this, please let me know. Thanks.


text:
Q: In the Holometer experiment, why would one of the split laser beams arriving back at a slightly different time indicate the universe was quantized? All the pop-sci articles I've read have a description of the set-up similar to this:

It uses a pair of laser interferometers placed close to one another, each sending a one-kilowatt beam of light through a beam splitter and down two perpendicular arms, 40 meters each. The light is then reflected back into the beam splitter where the two beams recombine. If no motion has occurred, then the recombined beam will be the same as the original beam. But if fluctuations in brightness are observed, researchers will then analyze these fluctuations to see if the
  splitter is moving in a certain way, being carried along on a jitter of space itself.

I have emboldened the sections I'm having trouble with. If the universe was discretised, why would that result in the splitter moving? Bounce two balls off a wall made of discrete lego blocks and they'll return to your hands at the same time. The lego blocks in the wall, or the pixels in a digital image, are discrete, but don't move.
As a side note: I could understand if they varied the distance for one of the split laser beams and found that the intensity of the recombined laser always varied at some integer multiple of a constant*Planck_length, but this is not their procedure. (I assume there's a reason that this wouldn't work?)
I apologise for my lack of knowledge or if this question is tiringly uninformed.

A: Chris Hogan, University of Chicago. March 1,2009 article in Back Reaction.
The idea underlying Hogan's prediction is that our world might have holographic properties, in which case not all three dimensions of our spacetime would encode really independent degrees of freedom. This conjectured property would become noticeable only at very large distances. A device that was able to measure distances in orthogonal directions at long distances and to high precision could be sensitive to this fundamental limit of encoding details, and be subject to a new kind of uncertainty. Gravitational wave interferometers provide exactly such a device. The holography would show up as noise in the detector.
Gravitational waves create distortions in our space-time that make themselves felt as tiny changes in lengths which are not the same for all three spatial dimensions. Interferometers lead a laser through a beam-splitter that splits the beam into two orthogonal directions into the "arms" of the interferometer, bounce the beam back on mirrors at the end of these arms, and compare the phases of the light when it comes back. This procedure can detect tiny deviations in the arm lengths which will change the phase shift. A common way to enhance the sensitivity of interferometers are "recycling techniques" that basically artificially increase arm lengths by reflecting the beam several times back and forth. GEO600 would be particularly sensitive to the holographic modification of quantum mechanics Hogan is proposing because the laser is reflected through both arms several times, whereas LIGO, VIRGO and TAMA use so called Fabry-Perot arms that reflect the beam in each arm separately. You find a very useful illustration of this difference between LIGO and GEO600 in Peter Shawhan's presentation, slide 19 and 20.
*You may be asking yourself "Gravity is not equal in 3 dimensions"? That is the an aspect of Holographic Universe, a false dimension comes out of it.


text:
Q: Run another application from within my app, but continue executing when that app has closed? Okay so, I have a program (prog1) that opens another program through an intent (prog2).  My goal is to have prog1 not do anything while prog2 is in the foreground.  When prog2 exits the foreground, have prog1 continue executing.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
        Intent LaunchIntent = new Intent(Intent.ACTION_MAIN);
        LaunchIntent = getPackageManager().getLaunchIntentForPackage("prog2");
        startActivity(LaunchIntent);
    }}, 3000);  // 3 seconds

But I don't know where to go from here.
Is this at all possible?  Can anyone provide guidance as to where to go from here?


text:
Q: Is there a way in Python to Multiply names with value? CSV i have a csv file which has names and a number. I want that name gets multiplied by the value and stored in a dictionary. If there is no value than the name should be skipped.
Nicole  15,
Heike   20,
Markus  32,
Carmen  23,
Holger   ,
Carolin  ,
Marcin  16,
Vero    12,
Sabine  16,
Peter   32,
Nicole   ,
Markus S    15,

for example to look like this
´´´people = {"sachbearbeiter" : ["Nicole", "Nicole", "Nicole", "Nicole", "Nicole", "Nicole", "Nicole", "Nicole", "Nicole", "Nicole", "Nicole", "Nicole", "Nicole", "Nicole", "Nicole", "Heike", "Heike", "Heike", "Heike", "Heike", "Heike", and so on]}´´´

So that i can load this series and append it to my dataframe. Because i have a list of cases which i need to give to my employees.
Thanks

A: why not using a loop ?
l=[("Nicole",3),("Bob",2)]

r=[]

for i in l:
   for j in range(0,i[1]):
      r.append(i[0])

print(r)

or indeed multiplication
l=[("Nicole",3),("Bob",2),("Chloe",0)]

r=[]

for i in l:
    if (i[1]!=0):
        r=r+i[1]*[i[0]]

print(r)

A: This should work for your examples. If you have a number but no value, or no value and no number, you'll have to write some code to handle that. (Assuming the csv is called sachbearbeiter.csv).
import csv

def csv2list(source_name):
    with open(source_name, encoding='utf-8') as csvfile:
        read_csv = csv.reader(csvfile, delimiter=',')
        return list(read_csv)

people = {"sachbearbeiter": []}

for line in csv2list("sachbearbeiter.csv"):
    t = line[0].rsplit(None, 1)
    if t[-1].isdigit():
        people["sachbearbeiter"].extend(int(t[1])*[t[0]])


text:
Q: Centre of Mass of a Constant Density Lamina I am having trouble calculating the centre of mass of a constant density lamina. The problem is as follows:  Consider a constant density lamina (two–dimensional plate) with edges given by the curves y = x^(1/2) and y = −x + 2x^2. Calculate the centre of mass of the lamina.
I understand that I need to set up integrals to first find the mass - however I am confused if the mass should include the region below the x axis bound by y = -x + 2x^2 or not.
I have calculated the mass to equal 1/2*c (where c is the constant density) by integrating a double integral of constant c with bounds x=0 and x=1 and y = 2x^2 - x and y = x^(1/2) dy dx (apologies - I don't know how to write an integral on here).
Am I going about this the right way? If not, what is the correct method for calculating the centre of mass. I have searched the internet for hours for a similar problem which involves a region below the x-axis.
Thanks a lot.

A: You are essentially correct. The center of mass is defined as follows
$$\mathbf{C}=\frac{\int \mathbf{r}dA}{\int dA}=\hat{\mathbf{i}} \frac{\int xdA}{\int dA} + \hat{\mathbf{j}} \frac{\int ydA}{\int dA}$$
You already have $A=1/2$ (assuming unit density), so just be careful with the double integrals. And yes, the area below the $x$-axis is part of the area being considered. You have the correct integration limits, as well.
Just for the record, I determined that $\mathbf{C}=(7/15,11/30)$ This was verified by numerical simulation.


text:
Q: Cocos2d Font Extensions Issues Good afternoon, sports!
I have a fast doubt.
I'm using COCOS2D and i need to know if i can use other extension type of font other than ".fnt".
Because i used a few and didn't have any luck.
I'm using this piece of code to make a "credits" scene:
CCBitmapFontAtlas* l_026  = [CCBitmapFontAtlas bitmapFontAtlasWithString:@"Look for our apps in the AppStore"   fntFile:@"fission.fnt"];

If it isn't which can i use?
And it is do you know any font converter to change "normal fonts" to ".fnt"
Thanks!

A: The best font program in my opinion is:  Glyph Designer.  It is inexpensive and very easy to make great looking fonts.
I use CCLabelBMFont but I'm pretty sure it is basically the same thing.

A: If you have some cash to spend you can use Glyph Designer as suggested by Aaron. But you can also use a free Java tool named Hiero. You might have to do some tweaking to get the result you want though.
The tool will output 2 files: one .png and another .fnt. Add these files into your Xcode project and use it using simple lines like below:
CCLabelBMFont *some_label = [CCLabelBMFont labelWithString:@"Your Text" fntFile:@"fontfile.fnt"];

Do note though that the size of the font from each pair of fnt/png files is fixed, so you have to create multiple pairs if you want to have different font sizes. Also, you need separate pair for Retina and non-Retina display modes.