text:
Q: What method of password hashing should I use for CoreOS ignition file? I am attempting to install CoreOS for the first time and am currently working my way through the initial FCC file which will be transpiled into the ignition file.
The Fedora CoreOS FCCT Specification and documentation is very helpful in breaking down the syntax of the FCC yaml file, however, there is one detail I am unclear on. When building the passwd node, the documentation states that I can add a hashed password for a user.
My question is, is there a specific hashing method I need to use to generate this hash? I have been unable to find any information regarding being able to specify which hash function was used, and since I'm fairly new to the concept, I'm not sure if it is even necessary to do so. Can I just generate a sha-256 hash using mkpasswd and paste it into the yaml file?

A:
To generate a secure password hash, use the mkpasswd command:
mkpasswd --method=yescrypt

Docs


text:
Q: Python3 Boto describe_instances probelm I'm using Python 3 to get a list of ec2 instance IDs from user input, and then print some info about the instances using the describe_instances() function from boto3.
When I run my script I get this error:
 File ".\aws_ec2_list_instances.py", line 9
    InstanceIds=[
               ^
SyntaxError: invalid syntax

This is my code so far:
import sys
import boto3
ec2 = boto3.client('ec2')
instance_id_list = input("Enter an instance ID separated by commas: ")
instance_ids = instance_id_list.split(",")
print("Deleting Instance IDs:")
for instance_id in instance_ids:
    instance = client.describe_instances(
        Filters=[
            InstanceIds=[
                'instance_id',
            ]
        ]
    )

How can I get past this error?

A: I believe instance ids should be set on the same level as Filters. Here's an example from the docs:
response = client.describe_instances(
    Filters=[
        {
            'Name': 'string',
            'Values': [
                'string',
            ]
        },
    ],
    InstanceIds=[
        'string',
    ],
    DryRun=True|False,
    MaxResults=123,
    NextToken='string'
)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Animated Can't Scroll Up the content I'm getting stuck at scroll the content with Animated. When I click on the arrow button, only the Animated tag scrolls up but the content inside it.
Here is my detail image:

And when I click the button:

And here is my code:
 This is my function:

This is render:

And this is my style:

A: You're animating the view's height rather than scroll position.
Instead, try animating the y offset of scrollTo({x: 0, y: 0, animated: true})
more info here...
https://facebook.github.io/react-native/docs/scrollview.html#scrollto
 `


text:
Q: TreeStore: different behaviour beetween autoLoad configuration and load() function The test case in fiddle is working with autoLoad: true but with autoLoad: false (line 86) the load() function called at line 161 in the TreePanel beforerender event does not load the data...
For (non tree) panels I allways have set autoLoad to false and load the store on render of the GridPanel and it works perfectly. I do it like this to prevent loading all the stores at the beginning (and to set filters sometimes).
The beforeload event of the store is preventing double-load.
Where is my fault for this TreeStore ? I am looking for a solution for a long time without any result...

A: There has been similar issue in Ext JS 4 explained here ExtJS 4. Hidden treepanel with autoload false .
What I did in your fiddle is that I just added the following
  autoLoad: false,
  root:{
    //expanded: true, // optional
    children: []
  }

to line 91 in your store configuration. Everything worked magically.

A: I think I've solved your problem.
Use the root property for your TreeStore.
/*
 * Store
 */
Ext.define('Chronos.store.Clockings', {
    extend  : 'Ext.data.TreeStore',
    requires: [
        //'Chronos.store.Session'
    ],
    model       : 'Chronos.model.Presence',
    autoLoad    : false, //true, // false,
    //autoSync    : true, // DEBUG
    sortOnLoad  : false,
    pageSize    : 0,
    remoteFilter: true,

    root: {
       id: 'id',
       expanded: true
    },

    listeners: {
        load: function(treestore, records, success) {
            console.log(Date(), 'clockings loaded: ', success, treestore);
        },
        beforeload: function (treestore) {
            if(treestore.isLoading()) return false;
        }
    }
});

Hope this is what you are looking for!


text:
Q: c Receive / Send same socket I am very noob and i have a question to know if its possible to send/recv on the same socket since recv/recvfrom are blocking my code ?
int main(void) {
    struct sockaddr_in si_me, si_other;
    int s, i, slen=sizeof(si_other);
    char buf[BUFLEN];

    if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
        die("socket");

    memset((char *) &si_me, 0, sizeof(si_me));
    si_me.sin_family = AF_INET;
    si_me.sin_port = htons(1234);
    si_me.sin_addr.s_addr = htonl(192.168.1.1);

    if (bind(s, &si_me, sizeof(si_me))==-1)
        die("bind");

    recvfrom(s, buf, BUFLEN, 0, &si_other, &slen;

    close(s);
    return 0;
}

Thanks!

A: Yes you can !
However Just be cautioned that the next read or recv might read a different datagram. UDP datagrams are always discardable
you can still flag your recv() with MsgPEEK or something like that
see this topic here , i think you take the code from that guy isn't ? :)
if your lazy here is the code from the topic
    struct sockaddr_in si_me, si_other;
    int s, i, blen, slen = sizeof(si_other);
    char buf[BUFLEN];

    s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (s == -1)
        die("socket");

    memset((char *) &si_me, 0, sizeof(si_me));
    si_me.sin_family = AF_INET;
    si_me.sin_port = htons(1234);
    si_me.sin_addr.s_addr = htonl(192.168.1.1);

    if (bind(s, (struct sockaddr*) &si_me, sizeof(si_me))==-1)
        die("bind");

    int blen = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr*) &si_other, &slen);
    if (blen == -1)
       diep("recvfrom()");

    printf("Data: %.*s \nReceived from %s:%d\n\n", blen, buf, inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));

    //send answer back to the client
    if (sendto(s, buf, blen, 0, (struct sockaddr*) &si_other, slen) == -1)
        diep("sendto()");

    close(s);
    return 0;
}```


text:
Q: Intuition for cofibration The notion of a fibration has a nice geometric intuition of one topological space (a fiber) being parametrized by another topological space (the base) -- this is taken from the Wikipedia entry on Fibration.
Now, I would like to know if there is an analogous geometric picture for the situation of cofibrations. Like that of a parametrized inclusion of a space into another space (apologies if this is nonsense).

A: Yes, there are precisely the dual diagrams defining a cofibration.  The way to think about them -- the way I think about them, at least -- is just that they're sufficiently nice inclusions, such that the subspace has a bit of "wiggle room".  This is made precise in the definition of a "neighborhood deformation retract (NDR) pair", which you can read about in May's Concise Course in Algebraic Topology.  Maybe the best example to keep in mind is when you turn an arbitrary map into a cofibration with the "mapping cylinder" construction; then it's obvious that the subspace has plenty of wiggle room.


text:
Q: Make a WFS-T Insert request to geoserver and add non spatial values to the layer My question is somehow related with my previous one Failed to insert data to geoserver layer with WFS-T.
I use python and requests in order to create a new feature in a geoserver layer. I have managed to make a successful request and add the geometry of the feature to the layer.
Now I am trying to make the same post request but also to include other values of attributes that they exist in the layer.
What is the format in order to achieve something like this? As far as I see, the Demo page of geoserver doesn't provide an example like this.
@iant helped me figure this out. This is how my xml looks like:
<wfs:Transaction service="WFS" version="1.1.0"
  xmlns:wfs="http://www.opengis.net/wfs"
  xmlns:gml="http://www.opengis.net/gml">
  <wfs:Insert>
   <bgd_uti_transmissionline_nrel>
     <the_geom>
      <gml:MultiLineString srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">
      <gml:lineStringMember>
       <gml:LineString>
        <gml:coordinates decimal="." cs="," ts=" ">
        39.247354197,21.438097723 89.247354197,18.438097723
        </gml:coordinates>
      </gml:LineString>
     </gml:lineStringMember>
    </gml:MultiLineString>
   </the_geom>
   5
   <POWERLIN_I>1</POWERLIN_I>
   <OBJECTID>2</OBJECTID>
   <GLOBALID>fd</GLOBALID>
  </bgd_uti_transmissionline_nrel>
 </wfs:Insert>
</wfs:Transaction>

A: The best place to look for details like this is in the standard.
Inserting non spatial attributes is done in exactly the same way as adding spatial attributes. First check the schema of the feature type by using a describeFeature request, then construct a Transaction request with the attribute values in the same order as the schema requires.


text:
Q: Creating a Student object for unit test I'm new to Java and needed some help. I have a utility class that has two methods where one method converts Json string to object and the other converts an object to Json string
I wanted to test these methods with junit. For this test purpose I would need an object ofcourse. Lets say a student object with a name and StudentId.
My question is that is there any way I can get this object in my Test without actually creating a separate class for the student? Since I only need this object for testing purposes.

A: Why create another Student class?
Just create a Student object in your junit test class (tests have to be separate from code of course)
It will be something like this:
import org.junit.Before;
import org.junit.Test;
import org.junit.After;

public class StudentTest
{

    private Student tester;

    @Before
    public void setUp() throws Exception
    {
        //init student objects
    }

    @Test
    public void test()
    {
        //test logic
    }

    @After
    public void cleanUp()
    {
        //destruct
    }
}

see the junit documentation for an explanation of test logic, e.g. AssertNotNull
If your class isn't called student, take the class you ment on your question (your utility class?)

A: If you don't want to create a separate class, you could just create a static member class in your JUnit test class as shown in the example below:
public class StaticMemberClassDemo {

    public static void main(String[] args) {
        Student student = new Student("John Doe", 1);
    }

    private static class Student {
        private final String name;
        private final int id;

        public Student(String name, int id) {
            this.name = name;
            this.id = id;
        }
    }
}

A: I am not sure what you mean by a separate class here. Just note that in java you can define different types of nested classes. Here it would not hurt to define a static nested class as rohitvats suggested.


text:
Q: Indexing and searching lists of data in elasticsearch I'm trying to figure out how to use elasticsearch to index and search a bunch of lists.
My current set-up is as follows:
var item1 = { "title" : "The Great Gatsby" };
var item2 = { "title" : "Ender's game" }
var item3 = { "title" : "The name of the wind" }

var itemList1 = [item1, item2];
var itemList2 = [item2, item3];
var itemList3 = [item3, item1];

Is there a way to index my lists? Cause an item can belong to multiple lists and has no reference to what lists it belongs.
The ultimate goal is to find items with the word "great" in its title in itemList3.

A: Here is an example that does what you want to do. At least from my understanding of your question.
Index and query:
curl -XPUT localhost:9200/test/
curl -XPOST localhost:9200/test/testtype/1 -d '{"array" : [{ "title" : "The Great Gatsby" }, { "title" : "Enders game" }] }'
curl -XPOST localhost:9200/test/testtype/2 -d '{"array" : [{ "title" : "Enders game" }, { "title" : "The name of the wind" }] }'
curl -XPOST localhost:9200/test/testtype/3 -d '{"array" : [{ "title" : "The name of the wind" }, { "title" : "The Great Gatsby" }]}'

curl -XPOST localhost:9200/test/testtype/_search -d '{
"query" : {
    "term" : { "title" : "great" }
}}'

Result:
{
  "took" : 2,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "failed" : 0
  },
  "hits" : {
    "total" : 2,
    "max_score" : 0.5,
    "hits" : [ {
      "_index" : "test",
      "_type" : "testtype",
      "_id" : "1",
      "_score" : 0.5, "_source" : {"array" : [{ "title" : "The Great Gatsby" }, { "title" : "Enders game" }] }
    }, {
      "_index" : "test",
      "_type" : "testtype",
      "_id" : "3",
      "_score" : 0.5, "_source" : {"array" : [{ "title" : "The name of the wind" }, { "title" : "The Great Gatsby" }]}
    } ]
  }
}


text:
Q: Junit is successful when use session.save but not inserting data in MySQL database tables eventhough i tried with flush the session as well Simple DAO Layer wiht applicationContext.xml please find below my applicationContect.xml
    please help me to understand why my Junit says successful but data are not inserting into the db.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:component-scan base-package="com.VideoRental.*" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>com.VideoRental.domain.Category</value>
<value>com.VideoRental.domain.Customer</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect"> org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.hbm2ddl.import_files">import.sql</prop>
<prop key="connection.autocommit">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.connection.autocommit">true</prop>

</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  <property name="sessionFactory" ref="mySessionFactory"/>
</bean>

</beans>

A: By default, @Transactional tests will roll-back all changes when the test method completes. So even if the test passes, the changes are only valid for the current running Transaction. To persist your changes, you need to commit the transaction.
Check out the example on this SO question.
You can replace @Transactional with transactionTemplate to commit the transaction prior to finishing a test.

A: If you are using @Transactional annotation driven in your project, you can simply set
@TransactionConfiguration(defaultRollback = false, transactionManager = "YourTransactionManager")

in your test case will work perfectly. I've researched for days and worked good finally in my local test cases, hopefully this will helps you too.


text:
Q: Where are these scss functions defined in the Bigcommerce Stencil stack? I'm looking through the source for a store using Bigcommerce's default Stencil theme. In an SCSS file I see functions being used, but I'm not sure where these functions are defined. For example:
# assets/scss/layouts/footer/_footer.scss

.footer {
    background-color: $footer-background;
    border-top: container("border");
    padding: spacing("double") 0;
}

I can't find where this container or spacing methods are coming from? Are these part of scss? Part of Foundation? Or maybe something Bigcommerce has defined in their Citadel library?

A: You can find the "container" function in
<your_theme>/assets/jspm_packages/github/bigcommerce-stencil/citadel@2.4.3/dist/settings/global/container/_container.scss

And the spacing function in:
<your_theme>/assets/jspm_packages/github/bigcommerce-stencil/citadel@2.4.3/dist/settings/global/layout/_layout.scss


text:
Q: Understanding consequences of breaking strict-aliasing int main()
{
    struct { int x; } foo;

    dostuff(&foo);
    return 0;
}

void dostuff(void *ptr)
{
    struct { int x; } *p = ptr;

    p->x = 5;
}

Dereferencing p is a strict-aliasing violation because the two unnamed structs cannot alias each other for they are not compatible.
Now what problems could/would arise in such code?
Edit:
I'm still not sure whether this defined behaviour since they don't have the same tag.
Assuming they are not compatible, would the following make any difference?
union u {
    void *v;
    struct {
        int x;
    } *p;
};

void dostuff(void *ptr)
{
    union u tmp = {.v = ptr};

    tmp.p->x = 5;
}

A: As strange|crazy|surprising|paradoxical it may seem, struct { int x; } and struct { int x; } within one translation unit indeed declare not the same type, as stated in e. g. this comment.

would the following make any difference?
union u {
    void *v;
    struct {
        int x;
    } *p;
};

void dostuff(void *ptr)
{
    union u tmp = {.v = ptr};

    tmp.p->x = 5;
}

You didn't specify how dostuff() is invoked here, so you must have the same main() as in the first example in mind; given this, the types are still not compatible if the argument is declared in the same translation unit - the two declarations of the structure types again declare distinct types, regardless of one of them being contained within a union.
Moreover, this second version of dostuff() reinterprets void *v as struct … *p; since the C standard does not guarantee that a pointer to void has the same representation as a pointer to a structure type, this usage is not strictly conforming.

A: The scenario you describe could realistically arise in cases where different modules each declare their own structures with a particular layout and use them to exchange data, and there is a desire to change some functions in a header file from "extern" scope to "inline" scope.  Unfortunately, your scenario falls into the category of useful behaviors which compilers used to support, and which sometimes have no practical alternative, but for which support is no longer mandated by the Standard, and which some compilers can no longer support without disabling a broad range of useful optimizations in addition to the useless breaking "optimizations" allowed by the Standard.


text:
Q: In Yii controller I'm newbie and learning Yii framework where Im designing first small application and got stuck on this position where I need your attention as your guys are guru.
I have a 'City name' list on main layout in header section where a user select a 'City' then I would like to pass that City_id to 'PostController' and search for that city post and display the last Postonly.
Any idea how to handle this.
I look forward to hear from you guys soon and will appreciated an early reply.
Khan

A: You can use a standard  to pass the selected city value to your PostCtonroller, you can then have your PostController call a function within one of your models to run whatever search you need on your database layer. You then take those results, pass them back to the controller and render a new page with your result. You can also do everything with Ajax so its nice and dynamic, but if you're new it would be best to use the basics first.
Also check out the yii framework website as they have a screencast (Video) about using their built in CRUD features.


text:
Q: org.json.JSONArray 's remove method is giving NoSuchMethodError exception i am using following import org.json.JSONArray
String name = "manjeet";
if (jsonArray.getJSONObject(i).get("name").equals(name))
{
jsonArray.remove(i);
}

if I am calling this code from main in a class it is working fine but when I am calling it from UI it is behaving differently.
it is able to get inside if but while executing .remove(i) it is giving
com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SEVERE: The exception contained within MappableContainerException could not
be mapped to a response, re-throwing to the HTTP container
java.lang.NoSuchMethodError: org.json.JSONArray.remove(I)Ljava/lang/Object;

A: To remove particular element from your jsonArray you will have to create an Arraylist and store the values you want from the jsonArray instead.
You can implement it like:
String name = "manjeet";
ArrayList<String> final_list = new ArrayList<>();
if (! jsonArray.getJSONObject(i).get("name").equals(name))
{
    final_list.add(i);
}
// now you can use the final_list instead of using jsonArray.

Notice the ! in if condition.

A: Problem: jar conflict
It may happen sometime that same class is provided by multiple jar's.
In my case org.json.JSONArray is also present in 'jackson-datatype-json-org' but that is having an older version of the class, in which remove method is not available.
Due to this the 'remove' method was avilable at compile time or while running the same code from main, but when I was running it from UI it was picking the class from 'jackson-datatype-json-org'.
So that is the reason I was getting java.lang.NoSuchMethodError exception.
Solution: we can use exclusions tag in dependency('jackson-datatype-json-org') to remove the class that we don't want to use.
Example:
<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-json-org</artifactId>
  <version>2.8.8</version>
  <exclusions>
    <exclusion>
      <groupId>org.apache.geronimo.bundles</groupId>
      <artifactId>json</artifactId>
    </exclusion>
  </exclusions>
</dependency>


text:
Q: Android inflated view is empty I am trying to add a divider between entries in a vertical LinearLayout, to emulate the appearance of a ListView. (I can't just use a ListView in this particular situation.)
This is what I have in list_divider.xml:
<?xml version="1.0" encoding="utf-8"?>
<View
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:background="@color/panel_border"
  android:layout_width="fill_parent"
  android:layout_height="@dimen/border_width"
 />

And here's the code which attempts to inflate this divider before every element except the first in the list:
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < categories.size(); i++ ) {

    if (i > 0)
        items.addView(vi.inflate(R.layout.list_divider, null));
        // these dividers never appear

    // but these main entries always appear just fine
    items.addView(ad.getView(i, null, null));
}

The main list items appear correctly, but the dividers are invisible.
The dividers do appear if I change them to be a TextView rather than a plain View:
<?xml version="1.0" encoding="utf-8"?>
<TextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:background="@color/panel_border"
  android:layout_width="fill_parent"
  android:layout_height="@dimen/border_width"
  android:text="---"
 />

I have tried setting explicit pixel values for the width and height, as well as using the border_width definition and fill_parent options. It makes no difference.
Is there something special about a plain old View which makes it not appear?

A: I eventually worked around it by wrapping my divider View inside a FrameLayout. It seems that having a single empty View with no content just doesn't work.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">

  <View
    android:background="@color/panel_border"
    android:layout_width="fill_parent"
    android:layout_height="@dimen/border_width" />

</FrameLayout>


text:
Q: when to set the NSLocale for the NSDateFormatter ? In my app , Im using following code to convert string to date before inserting the date into the database.
However this code fails for the users in UK, they have the Region set to UK, and Timezone set to London.
This works for the users in the US as their locale is en_US. So that says, this code works fine for en_US locale but not en_GB locale.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T1'HH-mm-ss-SSS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; //doing this as timestamp stored in server is based on UTC, hence I'm using UTC instead of systemTimeZone
 date = [dateFormatter dateFromString:theDate];

The passed string is : 2014-6-26T121-21-6-000
If I set the locale as follows, instead of currentLocale for all the users across the world:
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

then the code works, but I would like to know if this cause any issues in future?
Why we need set the locale property for converting the dates ?
Why the currentLocale fails in my case but not the en_US locale even though the date format is matched properly ?

A: Whenever you're dealing with ISO 8601 or RFC 3339 dates (i.e. dates exchanged with web services and/or stored as a string in some data store) use en_US_POSIX. See Technical Note 1480.
Or one can use NSISO8601DateFormatter and you don't have to deal with this locale silliness. E.g.
NSString *string = @"2014-06-26T12:21:06.000Z";

NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
formatter.formatOptions = NSISO8601DateFormatWithInternetDateTime | NSISO8601DateFormatWithFractionalSeconds;

NSDate *date = [formatter dateFromString:string];

Also, standard representations of ISO 8601 and RFC 3339 datetime strings, you'd generally use a format like 2014-06-26T12:21:06.000Z where:

*

*the hour is less than 24;

*numbers are zero-padded;

*separators between hours and minutes and seconds are :;

*the separator between seconds and milliseconds is .; and

*you'd often add Z at the end of the string to unambiguously designate that the time string is in GMT/UTC/Zulu.


text:
Q: How to externalize application.properties to an external filesystem location in Spring Boot? @ComponentScan
@EnableAutoConfiguration
@PropertySource(value = { "file:/Users/Documents/workspace/application.properties" })

public class Application  extends SpringBootServletInitializer{
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
    }

In this case it gives while deploying:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] found for dependency:

Not able to find the correct way to externalize the application properties file
I tried autowiring environment variable which is correctly loaded but then I need to manually define all the beans
@Bean
public JdbcTemplate dataSource() {
    String driverClassName = env
            .getProperty("spring.datasource.driverClassName");
    String dsUrl = env.getProperty("spring.datasource.url");
    String username = env.getProperty("spring.datasource.username");
    String password = env.getProperty("spring.datasource.password");
    //DataSource dataSource = new SimpleDriverDataSource(new driverClassName, dsUrl, username, password);
    JdbcTemplate jdbc = new JdbcTemplate(dataSource);
    return jdbc;

}

This deploys without throwing error but not responding.

A: If you're deploying a WAR to Tomcat, then you need to define a context XML as described here: https://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Defining_a_context
For example, you would typically define $CATALINA_BASE/conf/Catalina/localhost/my-app.xml if you have http://localhost:8080/my-app/.
The file would then look like this:
<Context docBase='path/to/my-app/my-app.war'>
   <Environment name='app_config_dir' value='path/to/my-app/' type='java.lang.String'/>
</Context>

In your code, implement ApplicationContextAware and override setApplicationContext. Here is an example:
public class Setup implements ApplicationContextAware {

  @Override
  public void setApplicationContext(ApplicationContext applicationContext)  throws BeansException {
    log.info("Set application context. App Config Property: {}",applicationContext.getEnvironment().getProperty("app_config_dir"));
  }
}

You can now load the properties file from app_config_dir.

A: There is no need to define it by using @PropertySource annotation. You should just use spring.config.location property to set your application.properties location. That property can be set up for example in command line:
java -jar myapp.jar --spring.config.location=/Users/Documents/workspace/

A: You can define an environment variable called SPRING_CONFIG_LOCATION and give it a value that can be a folder (which should end in /) or a file. In any case the location should pe prefixed with file::
SPRING_CONFIG_LOCATION = file:C:/workspace/application.properties

or
SPRING_CONFIG_LOCATION = file:C:/workspace/

More about this here.

A: You can use @PropertySource too because it is useful when you are deploying application as war file to tomcat.
@PropertySource is not working because you are missing @Configuration annotation. As per the Spring-Boot documentation, @PropertySource annotations should be present on your @Configuration classes.
Following works
@Configuration
@ComponentScan
@EnableAutoConfiguration
@PropertySource(value = { "file:/Users/Documents/workspace/application.properties" })

public class Application  extends SpringBootServletInitializer{
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
}

You can also load multiple properties file. For ex:
@PropertySource(value = {"classpath:application.properties", "file:/Users/overriding.propertis"}, ignoreResourceNotFound = true)

Note that the order of the declared files is important. If the same key is defined in two or more files, the value associated with the key in the last declared file will override any previous value(s).


text:
Q: iPhone 5s, send "volume up" signal As many are aware, one can snap a photo using the "volume up" button and even the same button on the earbud volume controls.  I am trying to control the camera remotely and need more distance than the earbuds provide.  How can I generate the signal?  Are the specs available?  Is it a proprietary control or a simple on/off pulse on one of the three conductors through the stereo jack?  I tried a simple 1/8" stereo cable extension, but it doesn't work.

A: There is a proprietary micro-controller in the Applebuds, so you won't be able to simulate it.
Maybe you could try a jack extension cord. (beware, you'll need a jack with 4 connectors).


text:
Q: Android columns layout I'm working on an app that retrieves news articles from the web and displays them.
The article contains different parts, text parts, images etc. so what I'm doing is parsing the article, creating Views (TextView, ImageView etc) accordingingly and adding them to a LinearLayout.
Especially  on a tablet in landscape mode, this doesnt look good, so first thing which comes to mind is makes it 2 columns.
My question is: is there a library or a good piece of code out there that can do some if the work that is entailed with that, like measuring the height if the views I have added, choosing a good place within the content from where to switch to the second column, take care that the right column doesn't get deeper than the left one etc?
Pic for explanation.

A: Sorry, I misread your question, you're building the layout programatically.
As seen in this answer you can get the window dimensions like this:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

You can then figure out a threshold that looks good to start using multiple columns and make your views percentages of those sizes you measure.

A: There is not such a library since it is just supported by android system, but not in the your way.
We use fragments and flexible layouts for different screen sizes, it simple and powerful.
Try to read the following page for details.
http://developer.android.com/guide/practices/tablets-and-handsets.html


text:
Q: Python yaml parse error import pandas as pd
import yaml as y

Movies = pd.read_csv('tmdb_5000_movies.csv',encoding="ISO-8859-1")
company = pd.DataFrame(Movies[['original_title','production_companies']])
for idn in range(10000):
    for index in range(len(company['original_title'])):
        akm = y.load(company.loc[index,'production_companies'])
        for i in range(len(akm)):
            if akm[i]['id'] == idn:
                if str(idn) not in keyword.columns:
                    keyword[str(idn)] = " "
                    keyword.loc[index,str(idn)] = 1
                elif str(idn) in keyword.columns:
                    keyword.loc[index,str(idn)] = 1
            # check if akm == idn
        # akm length
        keyword = keyword.fillna(0)

My data:
[{"id": 416, "name": "miami"},
 {"id": 529, "name": "ku klux klan"},
 {"id": 701, "name": "cuba"},
 {"id": 1568, "name": "undercover"},
 {"id": 1666, "name": "mexican standoff"},
 {"id": 1941, "name": "ecstasy"},
 {"id": 7963, "name": "guant\u00e1namo"},
 {"id": 10089, "name": "slaughter"},
 {"id": 10950, "name": "shootout"},
 {"id": 12371, "name": "gunfight"},
 {"id": 12648, "name": "bromance"},
 {"id": 13142, "name": "gangster"},
 {"id": 14819, "name": "violence"},
 {"id": 14967, "name": "foot chase"},
 {"id": 15271, "name": "interrogation"},
 {"id": 15483, "name": "car chase"},
 {"id": 18026, "name": "drug lord"},
 {"id": 18067, "name": "exploding house"},
 {"id": 155799, "name": "narcotics cop"},
 {"id": 156117, "name": "illegal drugs"},
 {"id": 156805, "name": "dea agent"},
 {"id": 167316, "name": "buddy cop"},
 {"id": 179093, "name": "criminal underworld"},
 {"id": 219404, "name": "action hero"},
 {"id": 226380, "name": "haitian gang"},
 {"id": 226381, "name": "minefield"}]

Error message (copied from the comments below):
ParserError: while parsing a flow mapping in "<unicode string>", line 1, column 2: {""name"": ""Dune Entertainment"" ^ expected ',' or '}', but got '<scalar>' in "<unicode string>", line 1, column 5: {""name"": ""Dune Entertainment"" ^


text:
Q: I got an error 530 5.7.0 from gmail server while trying to send an email from Arduino and Ethernet shield I got an error 530 5.7.0 from gmail server while trying to send an email from Arduino and Ethernet shield.
I want to send an e-mail from my arduino uno board.
I bought an Ethernet shield for it.
I found a code to send an e-mail using Ethernet shield below but I failed.
Gmail server said "530 5.7.0" error code but I don't know what it means.
What did I wrong?
/*
   Email client sketch for IDE v1.0.1 and w5100/w5200
   Posted December 2012 by SurferTim
*/

#include <SPI.h>
#include <Ethernet.h>

// this must be unique
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x59, 0x67 };
// change network settings to yours
IPAddress ip( 10, 6, 0, 248 );
IPAddress gateway( 10, 6, 0, 1 );
IPAddress subnet( 255, 255, 255, 0 );

// change server to your email server ip or domain
// IPAddress server( 1, 2, 3, 4 );
char server[] = "smtp.gmail.com";

EthernetClient client;

void setup()
{
  Serial.begin(9600);
  pinMode(4,OUTPUT);
  digitalWrite(4,HIGH);
  Ethernet.begin(mac, ip, gateway, gateway, subnet);
  delay(2000);
  Serial.println(F("Ready. Press 'e' to send."));
}

void loop()
{
  byte inChar;

  inChar = Serial.read();

  if(inChar == 'e')
  {
      if(sendEmail()) Serial.println(F("Email sent"));
      else Serial.println(F("Email failed"));
  }
}

byte sendEmail()
{
  byte thisByte = 0;
  byte respCode;

  if(client.connect(server,25) == 1) {
    Serial.println(F("connected"));
  } else {
    Serial.println(F("connection failed"));
    return 0;
  }

  if(!eRcv()) return 0;
  Serial.println(F("Sending helo"));

// change to your public ip
  client.println(F("helo 1.2.3.4"));

  if(!eRcv()) return 0;
  Serial.println(F("Sending From"));

// change to your email address (sender)
  client.println(F("MAIL From: <me@mydomain.com>"));

  if(!eRcv()) return 0;

// change to recipient address
  Serial.println(F("Sending To"));
  client.println(F("RCPT To: <receiver@gmail.com>"));

  if(!eRcv()) return 0;

  Serial.println(F("Sending DATA"));
  client.println(F("DATA"));

  if(!eRcv()) return 0;

  Serial.println(F("Sending email"));

// change to recipient address
  client.println(F("To: You <receiver@gmail.com>"));

// change to your address
  client.println(F("From: Me <me@mydomain.com>"));

  client.println(F("Subject: Arduino email test\r\n"));

  client.println(F("This is from my Arduino!"));

  client.println(F("."));

  if(!eRcv()) return 0;

  Serial.println(F("Sending QUIT"));
  client.println(F("QUIT"));

  if(!eRcv()) return 0;

  client.stop();

  Serial.println(F("disconnected"));

  return 1;
}

byte eRcv()
{
  byte respCode;
  byte thisByte;
  int loopCount = 0;

  while(!client.available()) {
    delay(1);
    loopCount++;

    // if nothing received for 10 seconds, timeout
    if(loopCount > 10000) {
      client.stop();
      Serial.println(F("\r\nTimeout"));
      return 0;
    }
  }

  respCode = client.peek();

  while(client.available())
  {
    thisByte = client.read();
    Serial.write(thisByte);
  }

  if(respCode >= '4')
  {
    efail();
    return 0;
  }

  return 1;
}

void efail()
{
  byte thisByte = 0;
  int loopCount = 0;

  client.println(F("QUIT"));

  while(!client.available()) {
    delay(1);
    loopCount++;

    // if nothing received for 10 seconds, timeout
    if(loopCount > 10000) {
      client.stop();
      Serial.println(F("\r\nTimeout"));
      return;
    }
  }

  while(client.available())
  {
    thisByte = client.read();
    Serial.write(thisByte);
  }

  client.stop();

  Serial.println(F("disconnected"));
}

A: There are some ways to send email with embedded system such as arduino. And your sketch shows how to send email directly to mail server which has an account for the destination address.
As you already know that error code says "Must issue a STARTTLS command first".
It means SSL connection is required. Of course, it's a one of restrictions from Google. Unfortunately, "Arduino Ethernet Shield" does NOT support SSL. So you may want to check another shield which supports SSL.
"PHPoC Shield for Arduino" can be an alternative. To use this shield, "Arduino Library for PHPoC" is required. This library provides some examples. And "EmailClient" example can be a what are you looking for.

/* arduino email client - send email to server directly */

#include "SPI.h"
#include "Phpoc.h"

PhpocEmail email;

void setup() {
  Serial.begin(9600);
  while(!Serial)
    ;

Phpoc.begin(PF_LOG_SPI | PF_LOG_NET | PF_LOG_APP);
//Phpoc.begin();

Serial.println("Sending email to server directly");

// setup From/To/Subject
email.setFrom("from_email_address", "from_user_name");
email.setTo("to_email_address", "to_user_name");
email.setSubject("Mail from PHPoC Shield for Arduino");

// write email message
email.beginMessage();
email.println("Hello, world!");
email.println("I am PHPoC Shield for Arduino");
email.println("Good bye");
email.endMessage();

// send email
if(email.send() > 0)
  Serial.println("Email send ok");
else
  Serial.println("Email send failed");
}

void loop() {
}

I run this sketch for your reference. Of course, I changed some parameters such as from_email_address, from_user_name, to_email_address and to_user_name.

But it's failed to send the email with 421-4.7.0 error code.

According to the error message, this email may be rejected because of the spam policy on google mail server. Anyway, your problem - got an error 530 5.7.0 from gmail server - can be resolved with this PHPoC Shield for Arduino.
If you still want to send email to google, the below reference will be helpful to you.

*

*Gmail & Arduino UNO & IPv6 - Arduino Project Hub

*Arduino, Monitoring Door-Opening via Gmail - Hackster.io


text:
Q: Is MessageReceiver supported in Service Bus Topic Triggered Java Azure Function? Basically the title.
Here's my code
   @FunctionName("Process")
public void run(@ServiceBusTopicTrigger(
        name = "req",
        topicName = TemplatedConstants.topicName,
        subscriptionName = TemplatedConstants.subscriptionName,
        connection = "ServiceBusConnectionString")
                    @BindingName("MessageReceiver") MessageReceiver messageReceiver,  String message, final ExecutionContext context) {

I am trying to inject MessageReceiver into the Java Azure Function but I get the following error.
'com.microsoft.azure.servicebus.MessageReceiver' is not public in 'com.microsoft.azure.servicebus'. Cannot be accessed from outside package
My goal is to read the message in a 'destructive read' mode instead of the default 'peek lock' mode. I was hoping to call the .complete() method on the MessageReceiver object upon receiving the message right away so the message does not get dead lettered after the lock duration is over.

A: Unfortunately, non-C# languages in Azure Functions do not support binding to complex language-specific types. You would have to directly use SDK when required.
But you can still achieve "destructive read" (aka ReceiveAndDelete) by setting the extensions.serviceBus.messageHandlerOptions.autoComplete property value to true in host.json.
The only other option is using the function execution to pass the message to another function via REST or the likes, and have the triggered function end immediately.
If the sequence number and lock token were available in the message metadata, technically you should be able to complete the message via the Service Bus API. But this would be a feature request to expose them as such, not to mention the Service Bus SDKs do not expose a method that uses these parameters to allow completing a message.


text:
Q: Problems while trying to move files from HDD to SSD Recently I bought a new SSD to replace a 1 TB HDD with Windows 10 installed. After getting the SSD, my next step was to install windows 10 on it. After installing Windows on the SSD I basically had 2 bootable drives, on the HDD and SSD.
After booting from the HDD I moved all the files I wanted from the HDD to the SSD because I didn't back up to the cloud. Everything was working properly, but when I finally booted from the SSD and was trying to see the files I moved, I got an error of "The file or directory is corrupted and unreadable". Additionally, some files/folders had disappeared and my SSD was still showing used space because of them. Is there a way to recover my files?


text:
Q: Merging two folders with the same or different names How can I merge two folders with the same or different names with subdirectories, using shell script or terminal. Also, if there is a file with the same name, then it should skip.

A: To merge "dir2" into "dir1," I would expect the following to do what you want:
cp -nr dir2/* dir1/

The -r switch means copy recursively, and the -n switch means don't overwrite existing files (i.e., skip files with the same name).


text: Q: Applications of Rolle's Theorem and function analysis I was playing around with the Rolle's theorem when I ended up fixing a tricky constraint for a function. Suppose, $f$ is a differentiable function in $[0,1]\to\mathbb R$ such that $f(0)=f(1)$. Now if I set a constraint like $f(x)\neq f(x+1/3)$ for all $x\in(0,2/3)$, then can I find such a function? Since $f(0)=f(1)$, there had to be a point where $f'(x)=0$ in $(0,1)$. Intuitively, I feel that there must be some $x\in(0,2/3)$ such that $f(x)=f(x+1/3)$, as it's many-one. But can someone help me prove this using Rolle's or Lagrange's?


text:
Q: DetailsView Update command doesn't update unless all of the fields are present! I have a page that binds data from DB to a DetailsView.
I want to use the auto-generated Update command.
Everything went OK, and also updating was successful, but if I remove any field that I don't want to have chance to update, then the Update command doesn't update! the old values retain!
I mean: if all of the fields are present in the detailsView, the update will be OK, otherwise, the update will NOT update any thing.
I've tried to mark the fields that I don't want to view as "Visible = 'false'" but with no good results!
How could I hide some fields?
Thanks :)

A: Did you try to put the field you don't want to update at 'ReadOnly = True' too? This should mark them as to not be updated.

A: Here is a way of doing it..
protected void DetailsView1_ModeChanged(object sender, EventArgs e)
{
    if (DetailsView1.CurrentMode == DetailsViewMode.Edit)
    {
        foreach (DataControlField fd in DetailsView1.Fields)
        {
            BoundField tmp = fd as BoundField;
            if (tmp != null)
                if (tmp.DataField == "YourReadOnlyColumnName")
                    tmp.ReadOnly = true;
        }

    }
}


text:
Q: Writing to a csv file in python (if can be opened by others) I'm writing data to a csv file with python. The file will log data and can be opened by other people. If someone has the file open, python is unable to write to the file (access denied).
What is the best way to account for this?


text:
Q: Repopulating form on failed validation I have a form for a user to create a question (in additon to user model, there's a question model, with nested answers) on their profile page. It submits from the users profile page /views/users/show.html.erb to the create action of the questions_controller.rb. If it doesn't validate, I think the default for Rails is to render the form(with the invalid information in the form for the user to edit). However, since I'm submitting the form for the question model from the users profile page the prepopulation isn't happening upon failed validation;  the user is forced to enter all the information in the form again. Is there a way in this context to get the form on the users show page to fill out with the information that was entered prior to submission?
questions_controller
def create
    @question = current_user.questions.build(params[:kestion])

    if @question.save
      redirect_to current_user, :notice => "Successfully created question."
    else
      ###render  :action => 'show'
      redirect_to current_user

    end
  end

Update
I've changed the end of the create method too
Redirect ( : back ), :notice => "something went wrong.try again"

But I still can't get the form to populate, and the validation error messages aren't showing either, only the flash notice.
Update
The show method of the users controller creates the new Question (along with the user)
   def show
        @user = User.find(params[:id])
        @question = Question.new
        3.times {@question.answers.build}

   end

The /views/users/show.html.erb
<%= form_for @question do |f| %>
   <% if @question.errors.any? %>

<%= pluralize(@question.errors.count, "error") %> prohibited this question
    from being saved:

      <% @question.errors.full_messages.each do |msg| %>

 <%= msg %>

    <% end %>

  <% end %>

     <%= f.label :content, "Question"%>
    <%= f.text_area :content, :class => 'span4', :rows => 1 %>

    <%= f.label :link, "QuoraLink" %>
    <%= f.text_field :link, :class => 'span4', :rows => 1  %>

  <%= f.fields_for :answers do |builder| %>

      <%= render 'answer_fields', :f => builder %>

   <% end %>

<%= link_to_add_fields "Add Answer", f, :answers %>

<%= f.submit %>

<% end %>

the answer_fields partial rendered from the questions partial

<%= f.label :content, "Answer..." %>

  <%= f.text_field :content, :class => 'span3', :rows => 1%>

   <%= f.label :correctanswer, "Correct" %>
  <%= f.check_box :correctanswer, :class => 'span1' %>

   <%= link_to_remove_fields "remove answer", f %>

A: Firstly, the reason that using redirect_to instead of render doesn't repopulate the form is that when you redirect_to, the controller logic for the action is run, whereas using render ignored the controller logic.
So when you render :action => 'show' (the "default" behaviour), it renders show.html.erb, with @question set like this:
@question = current_user.questions.build(params[:kestion])

When you redirect_to current_user, it renders show.html.erb with @question set using the code in your show action:
@question = Question.new
3.times {@question.answers.build}

This is why you get a new (blank) form, instead of a pre-populated one.
Is it really that important that you use redirect_to? If it is, you'll need to get your show method to do the validation. For example, you could rewrite your show method to something like:
def show
  @user = User.find(params[:id])
  if params.has_key?(:kestion)
    @question = @user.questions.build(params[:kestion])
  else
    @question = Question.new
    3.times {@question.answers.build}
  end
end

and then make your form point at that page, with something like:
<%= form_for(@question, url: users_path(@question.user) do |f| %>
  ...
<% end %>

(depending on how your routes are set up and named). Of course, by that point the whole thing become horribly un-RESTful, a bit of a mess, and definitely not the Rails way of doing things. (The other, worse option would be to redirect back and pass the params through a get query.) In my opinion, you lose a lot for a minor gain, and I'm not sure that I'd really recommend it.

A: Currently, in views/users/show.rb you do
@question = Question.new

that creates an empty new question. Then you populate the forms with this empty model.
What you could do instead is:
if session[:question]
  @question = @user.questions.new(session[:question])
  session[:question] = nil
  @question.valid? # run validations to to populate the errors[]
else
  @question = Question.new
end

Now all what's left to do is populating session[:question] in your questions_controller before redirecting to :controller=>"users", :action=>"show". Something like:
if @question.save
  redirect_to current_user, :notice => "Successfully created question."
else
  session[:question] = params[:question]
  redirect_to current_user
end

You may need to work on serialization/deserialization additionally for populating/using session[:question]. I didn't try to compile, so am not sure.
All this is needed because when you do redirect_to your processing of the user request ends, the user browser gets a redirect status code from your server and goes for another page, sending you a new request (which lands on the path, and eventually controller/action, to which you redirected to). So, as soon as you return from the request processing, all your variables are lost. For the next request you start from scratch.
The render :action => "show" approach (that was in the original scaffold and that you commented out) worked because you didn't return back to user but simply rendered the template with a specific name using the variables you already had in place (including @question, on which 'save' was called and failed, and thus internally validations were called and populated the errors object).
Actually, that reminded me that you may want to use another approach. Instead of passing parameters through session[] and redirecting to UsersController, you may want to populate all required variables and just render the view from that controller. Like below:
if @question.save
  redirect_to current_user, :notice => "Successfully created question."
else
  @user = current_user
  render "users/show"
end


text:
Q: How do I retrieve the information about the maximum and minimum price of a stock just during the after hours, or the pre-market? How do I retrieve the information about the maximum  and minimum price of a stock just during the after hours, or the pre-market? For example, I can use the formula =GOOGLEFINANCE("TSLA";"high";"02/02/2022") which will retrieve the maximum price of the stock during regular hours. However, I can't find a way to get the maximum price just during after hours and premarket hours, excluding regular hours. Thank you

A: not supported via GOOGLEFINANCE formula. for max, you can do high for min its low and then you can do only close

for after hours and pre-market you will need to resort to scrapping some non-javascript website that holds this data


text:
Q: .NET Core 3.1 after updating Interaction Trigger and Prism no SelectionChanged event was firing Today I have changed all my interaction triggers from http://schemas.microsoft.com/expression/2010/interactivity to http //schemas.microsoft.com/xaml/behaviors. Now my problem is, that no selectionChanged event was firing in the view model. My datasource is the view model.
My code:
<ComboBox Name="CBGL" ItemsSource="{Binding Path=Troughs}"
          DisplayMemberPath="TroughNumber"  SelectedValuePath="Id"
          SelectedValue="{Binding Model.Trough}" Width="173">
     <i:Interaction.Triggers>
          <i:EventTrigger EventName="SelectionChanged">
               <i:InvokeCommandAction  Command="{Binding CBGLRegionChangedCmd}" />
          </i:EventTrigger>
     </i:Interaction.Triggers>

If someone changes the selection, CBGLRegionChangedCmd is not firing.
The code from the view model:
CBGLRegionChangedCmd = new MyICommand(InvokeCommandAction_Changed);

If I undo the update all is working fine...

A: You must added ViewModel to this question for best answer.
but i think your binding in SelectedValue="{Binding Model.Trough}" is wrong
please define a property full inside viewmodel with type Trough and xxx name then call inside it a notifyPropertyChange() method then set SelectedItem="{Binding xxx,UpdateSourceTrigger=PropertyChanged}"
alse you can set a property full inside viewmodel of type int with name yyy and bind it to SelectedValue property for example:
SelectedValue="{Binding yyy,UpdateSourceTrigger=PropertyChanged}"


text:
Q: NodeJS break a Promise Using ES6 Promises, how can I break it in the following scenario?
addClient: function(request, response, next) {
    var id = mongo.validateString(request.body.id);

    mongo.Test.findOne({
        id: id
    })
    .then(client => {
        if (client) {
            // want to break here
            response.status(400).send({
                error: 'client already exists'
            });
        } else {
            return auth.hashPassword(mongo.validateString(request.body.secret));
        }
    })
    .then(hashedSecret => {
        // gets executed even if I don't return anything
        return new mongo.Test({
            name: mongo.validateString(request.body.name),
            id: id,
            secret: hashedSecret
        }).save();
    })
    .then(doc => {
        return response.status(201).send({
            client: {
                id: doc._id
            }
        });
    })
    .catch(err => {
        return next(err);
    });
}

I haven't found any clear docs stating how to break this.
Instead of having chained thens I could have it inside the first then but on more complex requests it would be nice to be able to have them chained.

A: // gets executed even if I don't return anything
return new mongo.Test({
      name: mongo.validateString(request.body.name),
      id: id,
      secret: hashedSecret
    }).save();

This gets executed even if you don't return anything because the default return value of such thing is undefined. It is assumed that code resolved with undefined

If this value is not a promise, including undefined, it becomes the fulfillment value of the associated promise

Mozilla docs on this
You can break a Promise chain by rejecting it early.
addClient: function (request, response, next) {
  var id = mongo.validateString(request.body.id);
  mongo.Test.findOne({
    id: id
  }).then(client => {
    if (client) {
      // reject with a type
      return Promise.reject({
        type: 'CLIENT_EXISTS'
      });
    }
    return auth.hashPassword(mongo.validateString(request.body.secret));
  }).then(hashedSecret => {
    // gets executed even if I don't return anything
    return new mongo.Test({
      name: mongo.validateString(request.body.name),
      id: id,
      secret: hashedSecret
    }).save();
  }).then(doc => {
    return response.status(201).send({
      client: {
        id: doc._id
      }
    });
  }).catch((err) => {
    // check type
    if (err.type === 'CLIENT_EXISTS') {
      return response.status(400).send({
        error: 'client already exists'
      });
    }
    return next(err);
  });
}

A: If you want to break a promise chain aka not execute the following chained promise links you can inject a unresolved promise into the chain by returning a promise that will never resolve.
new Promise((resolve, reject) => {
    console.log('first chain link executed')
    resolve('daniel');
}).then(name => {
    console.log('second chain link executed')
    if (name === 'daniel') {
        return new Promise(() => {
            console.log('unresolved promise executed')
        });
    }
}).then(() => console.log('last chain link executed'))

// VM492:2 first chain link executed
// VM492:5 second chain link executed
// VM492:8 unresolved promise executed

A: I break the chain by returning a new Promise which is rejected directly inn the same line with a certain error message or object.
Due to that I get the error in the last catch block and return my response in a single place.
betHelper.getPrediction(db, match_id, _userID)
    .then(function (prediction) {
        if (prediction != null) {
            return Promise.reject({error: "You already have a bet for this match", prediction: prediction});
        } else {
            //Prediction does not exist find user and match data
            return Promise.all([userHelper.findUserWithID(_userID, db), betHelper.getMatchData(match_id)]);
        }
    })
    .then(function (results) {
        let user = results[0];
        let game = betHelper.simplifiedMathData(results[1]);
        //Append user prediction
        return new Promise(betHelper.appendPrediction(db, user, game, localteam_score, visitorteam_score));
    })
    .then(function (prediction) {
        response.send(prediction);
    })
    .catch(function (err) {
        response.send(err);
    });


text:
Q: How to prevent my screens from turning off, when the screen is locked? I would like to have my screen fully powered at all times, but it goes to standby once I lock my PC.

A: I had to install additional screensaver program XScreenSaver and use it instead of default one because accepted answer had no effect for me on Ubuntu 16.04 and 17.10.

*

*Install XScreenSaver:
 sudo apt install xscreensaver

*Add this command to Startup Applications:
 xscreensaver -nosplash

*Disable default Super+L shortcut

*

*Install CompizConfig Settings Manager
sudo apt install compizconfig-settings-manager

*Launch it and click "Ubuntu Unity Plugin"

*Click the button next to "Key to lock the screen."

*Disable

*Add this command to enable Super+L shortcut for XScreenSaver in System Settings → Keyboard → Shortcuts → Custom Shortcuts:
 xscreensaver-command -lock

A: Open your System Settings. We need to make changes to Power and Brightness & Lock settings.

Power Settings
Change the value of Suspend when inactive for to Don't suspend.

Brightness & Lock Settings
Change the value of Turn screen off when inactive for to Never.

This should help to achieve your desired result.


text:
Q: CSS3 effects with jQuery only works on chrome debug I am trying to animate a div object using jQuery and CSS3. But i am obtaining a weird behavior. Effect works on only chrome debug mode. Here is the code
var $s = $('#animateMePlease');
$s.css('transition-duration', 0+'ms');
$s.css({
opacity:0,
display:'block'
});
// debugger; // only works when i stop once code execution here, and release again
$s.css('transition-duration', d.duration+'ms');
$s.css({
opacity:1
});

Thanks for any help.

A: Since you're already using jQuery why not just use:
$('#animateMePlease').hide().fadeIn(d.duration);

and let jQuery handle the details in a browser-comaptible way - compare the jQuery browser support with the support for CSS3 transitions.
(Make sure that you actually have some number in d.duration)
Update
After reading your comment I see why you don't want to use the standard jQuery way. Also if you are already using those transforms then you already depend on CSS3 support so using transition-duration is not an issue.
In that case you can change this:
$s.css({
  opacity: 1
});

to this:
setTimeout(function () {
  $s.css({
    opacity: 1
  });
}, 10);

so your code becomes:
var $s = $('#animateMePlease');
$s.css('transition-duration', 0 + 'ms');
$s.css({
  opacity: 0,
  display: 'block'
});
$s.css('transition-duration', d.duration + 'ms');
setTimeout(function () {
  $s.css({
    opacity: 1
  });
}, 10);

Adding a small timeout will make sure that the state that the DOM is in so far gets rendered before the opacity gets changed to 1.
See DEMO.


text:
Q: Disallow user to resize form under certain dimensions My form size is 620 by 320 and I'd like the user to resize the form over those dimensions but not under, how would I go about doing that?

A: Windows Forms have a MinimumSize property. MSDN
myform.MinimumSize = new Size(620, 320);


text:
Q: Plain integer equation numbers (without chapter prefix) that resets on every new chapter with correct eqref/hyperref behavior for them My code:
\documentclass{book}
\usepackage{amsmath}
\usepackage{hyperref}
\begin{document}

\chapter{Introduction}
\begin{equation}
  \label{a}
  1 + 1 = 2.
\end{equation}

\begin{equation}
  \label{b}
  2 + 2 = 4.
\end{equation}

\chapter{Elementary Results}
\begin{equation}
  \label{c}
  10 + 10 = 20.
\end{equation}

\begin{equation}
  \label{d}
  20 + 20 = 40.
\end{equation}

From \eqref{c} and \eqref{d} we get

\begin{equation}
  30 + 30 = 60.
\end{equation}

\end{document}

Here is how the document layout looks:

*

*Chapter 1

*

*Equation 1.1

*Equation 1.2

*Chapter 2

*

*Equation 2.1

*Equation 2.2

*Two links to equations 2.1 and 2.2

*Equation 2.3

What I want instead:

*

*Chapter 1

*

*Equation 1

*Equation 2

*Chapter 2

*

*Equation 1

*Equation 2

*Two links to equations 1 and 2 of the current chapter (chapter 2)

*Equation 3

Can this be achieved in LaTeX?

A: Given that you're using the book document class, running
\renewcommand\theequation{\arabic{equation}

in the preamble is really all you need to apply to your test code in order to achieve your formatting objectives.
The following screenshot shows the output of the chapter-2 test material. You may verify easily that the cross-references "(1)" and "(2)" point to the equations on that page rather than at, say, the sample equations associated with chapter 1.

\documentclass{book}
\renewcommand\theequation{\arabic{equation}} % <-- new
\usepackage{amsmath}
\usepackage[colorlinks=true]{hyperref}
\usepackage[nameinlink,noabbrev]{cleveref}
\begin{document}

\chapter{Introduction}
\begin{gather}
  1 + 1 = 2. \label{a} \\
  2 + 2 = 4. \label{b}
\end{gather}

\chapter{Elementary Results}
\begin{gather}
  10 + 10 = 20.  \label{c} \\
  20 + 20 = 40.  \label{d}
\end{gather}
From \labelcref{c,d} we get
\begin{equation}
  30 + 30 = 60.
\end{equation}

\end{document}


text:
Q: Storing JWT on local storage shows undefined in React Project I have found difficulties while storing JWT on my local browser. Here is my code:
const SignIn = () => {

    const navigate = useNavigate();
    let location = useLocation();
    const from = location.state?.from?.pathname || '/';
    const [
        signInWithEmailAndPassword,
        user,
        loading,
        error,
    ] = useSignInWithEmailAndPassword(auth, {sendEmailVerification:true});
    const handleUserSignIn = async event =>{
        event.preventDefault();
        const email = event.target.email.value;
        const password =event.target.password.value;
        await signInWithEmailAndPassword(email, password);
        const {data} =await axios.post("http://localhost:5000/signin", {email});
        localStorage.setItem('accessToken', data.accessToken)
        navigate  (from, {replace: true});
    }
}

I get the key property key name okay but the value shows "undefined"
accessToken undefined


text:
Q: A proof of $=e^{A+B}=e^{A}e^{B}$ using ODEs I want to prove that $=e^{A+B}=e^{A}e^{B}$ for commuting matrices $A,B$ using differential equations. I found a proof here: LINK
Here is how the proof goes:

Given a square matrix $M$, the function $X(t):=e^{tM}$ is the unique
  solution of the linear differential equation: $X'=MX$ and $X(0)=I$.
Now set $X(t):=e^{tA}e^{tB}$ and observe that the factors commute with
  each other, as well as they commute with $A$ and $B$. It follows that
  $$ X'(t)=Ae^{tA}e^{tB}+e^{tA}Be^{tB}=(A+B)e^{tA}e^{tB}=(A+B)X(t). $$
  And since $X(0)=e^0e^0=I$, it follows from the uniqueness above that
  $$ X(t)=e^{tA}e^{tB}=e^{t(A+B)}\qquad\forall t\in\mathbb{R}. $$ Set
  $t:=1$ to get the desired formula.

Can someone explain to me how the author of this proof gets from $(A+B)X(t)$ to $X(t)=e^{tA}e^{tB}=e^{t(A+B)}$
What is meant by "it follows from uniqueness"?

A: The commutativity of $A,B$ with the respective exponentials gives the second to last equality. Then set $M=A+B$ and by the original claim, this $X$ is the unique solution to $X'=MX=(A+B)X, X(0)=I$ so that $X=e^{t(A+B)}$, but by assumption we had already set $X=e^{tA}e^{tB}$.

A: The Picard-Lindelöf's theorem gives you that, for $M\in\mathcal{M}_n(\mathbb{R}),$ the Cauchy's problem $X'=MX, X(0)=\mathrm{Id}_n$ has a unique solution $X:\mathbb{R}\to\mathcal{M}_n(\mathbb{R})$. You show in your proof that both of $t\mapsto e^{t(A+B)}$ and $t\mapsto e^{tA}\cdot e^{tB}$ are solutions, and by uniqueness you give $$\forall t\in\mathbb{R},e^{t(A+B)}=e^{tA}\cdot e^{tB}.$$ Then for $t=1$ you get indeed your relation.

A: The author checks $X(t)$ satisfies the differential equation
$$
X'(t)
=(A+B)X(t)
$$
with initial condition $X(0)=I$.
Now the quoted theorem asserts that, setting $M = A+B$, this differential equation has a unique solution, which is
$$X(t)=X(0)\mathrm e^{tM}=I\mathrm e^{tM}=\mathrm e^{t(A+B)}.$$


text:
Q: How do I install Git for Windows software to a specific directory? I have just downloaded the latest Git for Windows installer, v2.4.  It appears to want to install to the standard Windows "Program files" (with-spaces-in-name) directory.
Since I have all my development code in a folder called (simply) "/bin" -- I want to see if there's a command line option or parameter to change the install directory.
In my case, these days I use a environment variable such as GIT_HOME for important software like git; so it would be useful if there was a way to apply that to things like git commands, etc once I have the program installed.
possibly related:

*

*How do I change the directory in Git Bash with Git for Windows?
I also came across a few questions asking: "whereis git".  That's answered above, however I take that as an indicator that others may want git somewhere else too.

A: To start the installer with a different installation path you can open a CMD terminal in the same directory as the installer executable and pass in an option parameter of /DIR="x:\dirname"
For instance, if you have version 2.17.0 for Windows 64bit and you want to install git to D:\git, you would run:
Git-2.17.0-64-bit.exe /DIR="D:\git"

The installer will launch as usual and you need to walk through the other options, but the install location will be the path specified.

A: Since I just ran into this problem because my SSD is filling up, I figured I'd share the solution I came to on Windows 11 with Git v. 2.37.2.
The best way I could figure was to uninstall Git, then in CMD Prompt use the suggested command from the Git website with an appended --location/ -l flag:
winget install --id Git.Git -e --source winget --location [drive:/directory]

where [drive:/directory] is your target for the install. Had no issues and verified it worked with a project.


text:
Q: Best approach for adding relatively huge amount of data into List in .net core I am developing .net core 2.1 web app which has no database.
I have a task which I need to perform:
Task:
Implement all postal codes as dropdown option with tag helpers and rendering a list within.
Example of html what should I get:

    Postal code:

        Postal code
        <select data-required="">
            @if (!string.IsNullOrWhiteSpace(Model.PostalCode))
            {
                <option value="@Model.PostalCode" selected>@Model.PostalCode</option>
            }
            <option>00001</option>
            <option>00002</option>
            <option>00003</option>
            <option>258745</option>
            ...so on..
        </select>

I was reading this post and I started to develop, but question is:

*

*If I have 10000 postal codes like KeyValue pair, should I store it in some file, or in appsettings.json?
Or just to do AddRange() method base on my List?

Here is the sample model of PostalCode
public class PostalCode
{
   public int Value { get; set; }
   public string Name { get; set; }
}

and ofc, I have a list in my main model:
public class MainModel
{
    // Property needed to catch selected value
    public string SelectedPostalCode {get; set; }
    public List<PostalCode> PostalCodes { get; set; }

   //...all other properties removed for clarity...
}


text:
Q: implicty error about cs0029 in C# Machine Learning When i do the ML.DOTNET practice through Microsoft Docs presented exercise, I found error that about CS0029
The total code is like that
using System;
using System.IO;
using Microsoft.ML;
using System.Collections.Generic;
using Microsoft.ML.TimeSeries;
namespace ProductSalesAnomalyDetection
{
    class Program
    {
        static readonly string _dataPath = Path.Combine(Environment.CurrentDirectory, "Data", "phone-calls.csv");

        static void Main(string[] args)
        {
            MLContext mlContext = new MLContext();

            IDataView dataView = mlContext.Data.LoadFromTextFile<PhoneCallsData>(path: _dataPath, hasHeader: true, separatorChar: ',');

            int period = DetectPeriod(mlContext, dataView);

            DetectAnomaly(mlContext, dataView, period);
        }

        static void DetectPeriod(MLContext mlContext, IDataView phoneCalls)
        {
            int period = mlContext.AnomalyDetection.DetectSeasonality(phoneCalls, nameof(PhoneCallsData.value));

            Console.WriteLine("Period of the series is: {0}.", period);
        }

        static void DetectAnomaly(MLContext mlContext, IDataView phoneCalls, int period)
        {
            var options = new SrCnnEntireAnomalyDetectorOptions()
            {
                Threshold = 0.3,
                Sensitivity = 64.0,
                DetectMode = SrCnnDetectMode.AnomalyAndMargin,
                Period = period,
            };

            var outputDataView = mlContext.AnomalyDetection.DetectEntireAnomalyBySrCnn(phoneCalls, nameof(PhoneCallsPrediction.Prediction), nameof(PhoneCallsData.value), options);

            var predictions = mlContext.Data.CreateEnumerable<PhoneCallsPrediction>(
                outputDataView, reuseRowObject: false);

            Console.WriteLine("Index\tData\tAnomaly\tAnomalyScore\tMag\tExpectedValue\tBoundaryUnit\tUpperBoundary\tLowerBoundary");

            var index = 0;

            foreach (var p in predictions)
            {
                if (p.Prediction[0] == 1)
                {
                    Console.WriteLine("{0},{1},{2},{3},{4}  <-- alert is on, detecte anomaly", index,
                        p.Prediction[0], p.Prediction[3], p.Prediction[5], p.Prediction[6]);
                }
                else
                {
                    Console.WriteLine("{0},{1},{2},{3},{4}", index,
                        p.Prediction[0], p.Prediction[3], p.Prediction[5], p.Prediction[6]);
                }
                ++index;

            }

            Console.WriteLine("");

        }

    }
}

the error section is in Main method
int period = DetectPeriod(mlContext, dataView);

and the error is cannot implicitly convert type 'void' to 'int'.
I just follow the presented code but it looks like some error on it.
Maybe I put the wrong code in wrong place but I try to follow their instruction strictly.
Also It will be very thankful if you tell me about difference between JAVA and C# implicitly convert type 'void' to 'int'.
Thank you

A: static void DetectPeriod(MLContext mlContext, IDataView phoneCalls) says that DetectPeriod() doesn't return anything. You're then trying to assign that non-existent return value to int period.
You need to change the definition to returning int, and then actually return an int value.
static int DetectPeriod(MLContext mlContext, IDataView phoneCalls)
  {
      int period = mlContext.AnomalyDetection.DetectSeasonality(phoneCalls, nameof(PhoneCallsData.value));

      Console.WriteLine("Period of the series is: {0}.", period);
      return period;
  }


text:
Q: Encrypt a file and share between computers I started using LastPass and after a few months a bug started and has me re-thinking my move from storing my files in an encrypted folder on my computers. You can see from the link the bug isn't dangerous on the surface, just inconvenient and unresolved since the beginning of August.
I'd consider switching to one of the other many password managers like 1password, keepersecurity, kaspersky password manager or others but I'd rather not be tied to a online 3rd party password manager and hoping there's never a breach.
The biggest problem with using the encrypted folder method is at least 1 or more computers needs to be updated manually each time I add a site, note or update a password.
For something more robust than a text file I'd consider using keepassx but it looks like it's not under active development and has severe unresolved bugs. So I considered moving to the fork keypassxc which is active but has many unresolved issues. Sync to external file is still a waiting to be implemented with keypassxc.
Ideally it would be great if i could create a encrypted file in my private directory, have all changes, synced (maybe by a symbolic link) to a shared folder, but only readable by a program (maybe with nodejs crypto) on the host that has the ciphers and user supplied password.
Does any script or program already do this on Ubuntu?


text:
Q: How exactly mvn -U works? I want to know what exactly Maven do in the -U phase.
The argument ordering forced check for updates on remote repositories and if needed, updating the local maven repository with the updated dependencies used in our project.
As described:
-U --update-snapshots Forces a check for updated releases and snapshots on remote repositories

But, how exactly is this done? Is maven first of all downloading all the remote repositories and locally decides that they need to get updated, or, deciding without downloading them first? Is there some corner cases that should be known?
My Maven version is:
Apache Maven 3.2.2 (45f7c06d68e745d05611f7fd14efb6594181933e; 2014-06-17T16:51:42+03:00)
Maven home: /usr/local/Cellar/maven/3.2.2/libexec
Java version: 1.7.0_60, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.7.0_60.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.9.4", arch: "x86_64", family: "mac"

A: It is done only for the artifacts or dependencies referenced by your project.
The last check timestamp is stored within local artifact metadata (in your local Maven repository), so Maven can apply different strategies how often to check for updates based on that. The default update interval for snapshots is "daily".
Also see updatePolicy for remote repositories in Maven's settings.xml.


text:
Q: How can do something similiar to this with css grid? I'm trying to get a grid layout with 6 elements centered on the page like the following:

But I cannot get the grid is center with images, any idea?

    .grid-container {
      display: grid;
      grid-template-columns: auto auto auto;
      background-color: #999999;
      padding: 10px;
    }

    .grid-item {
      background-color: rgba(255, 255, 255, 0.8);
      border: 1px solid rgba(0, 0, 0, 0.8);
      padding: 20px;
      font-size: 30px;
      text-align: center;
      &.one{
       background-image: url("img/mainmeu/e.png");
     }
      &.two{
       background-image: url("img/mainmeu/b.png");
      }
    }

1

2

3

4

5

6

A: Just use justify-content: center to center the grid items. Also use a grid-gap values to get the required layout. See demo below:

.grid-container {
  display: grid;
  grid-template-columns: auto auto auto;
  background-color: #999999;
  padding: 10px;
  grid-row-gap: 20px; /* added */
  grid-column-gap: 10px; /* added */
  justify-content: center; /* added */
}

.grid-item {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  padding: 20px;
  font-size: 30px;
  text-align: center;
  background-image: url("https://via.placeholder.com/200");
  background-size: cover; /* image as cover */
}

1

2

3

4

5

6

If you want to vary the grid item sizes, you can the relative dimensions using padding (because its always based on width). In the below demo I've used padding-top: 60% (if you use 100% you will get a square grid item):

.grid-container {
  display: grid;
  grid-template-columns: auto auto auto;
  background-color: #999999;
  padding: 10px;
  grid-row-gap: 20px; /* added */
  grid-column-gap: 10px; /* added */
  justify-content: center; /* added */
}

.grid-item {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  padding: 20px;
  font-size: 30px;
  text-align: center;
  background-image: url("https://via.placeholder.com/200");
  background-size: cover; /* image as cover */
  box-sizing: border-box;

  /* added width */
  width: 20vw;
  /* center inner content using flexbox */
  display: flex;
  justify-content: center;
  align-items: center;
}

.grid-item:after {
  padding-top: 60%; /* according to your aspect ratio */
  content: '';
  display: block;
}

1

2

3

4

5

6

A: *

*Use column-gap and row-gap for grid spacing.

*Use background-image properties to center the image inside grid box

.grid-container {
    display: grid;
    grid-template-columns: auto auto auto;
    background-color: #999;
    column-gap: 10px;
    padding: 10px;
    row-gap: 30px;
    justify-items: left;
    align-items: center;
}

.grid-item {
    background-color: rgba(255, 255, 255, 0.8);
    border: 1px solid rgba(0, 0, 0, 0.8);
    padding: 20px;
    font-size: 30px;
    text-align: center;
    width: 120px;
    height: 120px;
    align-content: center;
    display: inline-grid;
}

.grid-item.one {
    background-image: url("https://via.placeholder.com/200x200");
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}

.grid-item.two {
    background-image: url("https://via.placeholder.com/200x200");
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}

1

2

3

4

5

6

A: Since you aren't setting sizes, use inline-grid and center that using text-align:center on the parent.

body {
  text-align: center;
}

.grid-container {
  display: inline-grid;
  grid-template-columns: auto auto auto;
  background-color: #999999;
  padding: 10px;
  grid-gap: 10px;
}

.grid-item {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  padding: 20px;
  font-size: 30px;
  text-align: center;
}

1

2

3

4

5

6


text:
Q: Firestore NodeJS throws catch when retrieving document I am attempting to retrieve a firestore document in NodeJS. Any call I make to the database throws a catch error with the results {}. I am able to generate custom tokens to authenticate on my NodeJS server so the setup is correct. Why is my server throwing a catch when attempting to retrieve a document?
var firebaseService = require('./service.json');
var admin = require('firebase-admin');

admin.initializeApp({
    credential: admin.credential.cert(firebaseService),
    databaseURL: "https://mydatabase.firebaseio.com"
});
var db = admin.firestore();

exports.test = function(req, callback) {
    // token
    var ref = db.collection('users').doc('72bf07f8-0ae2-474a-b9b3-4386528b17b1');
    ref.get()
    .then(doc => {
        callback(false,doc);
        return
    })
    .catch(err => {
        callback(true,err);
        return ;
    });
}


text:
Q: jsDatePick - Using a Selected Date Using the jsDatePick Full JQuery example i am unable to get the calender to load with a specified date selected, i recieve either undifined message or syntax errors
The full code can be downloaded from JsDatePick
The Code they supply
g_globalObject2 = new JsDatePick({
useMode:1,
isStripped:false,
target:"div4_example",
cellColorScheme:"beige"
/*
selectedDate:{
day:16,
month:3,
year:2013
},
yearsRange:[1978,2020],
limitToToday:false,
dateFormat:"%m-%d-%Y",
imgPath:"img/",
weekStartDay:1*/
});

If i then un comment the slected date part i get either undifined on the calendar once it loads or it fails to load with a syntax issue
Can anyone help?
Thanks

A: I had the same problem and found the following solution from a post by this German fellow (http://www.viathinksoft.de/?page=news&id=184). The post is in German and if you translate it in English, it messes up the code he provided so copy the code first or you can copy below.
Here's his fix, you need to modify "jsDatePick.full.1.3.js" script, function "setConfiguration" with the following:
 this.selectedDayObject = {};
 this.flag_DayMarkedBeforeRepopulation = false;
 this.flag_aDayWasSelected = false;
 this.lastMarkedDayObject = null;

 if (!this.oConfiguration.selectedDate){
      this.currentYear      = this.oCurrentDay.year;
      this.currentMonth     = this.oCurrentDay.month;
      this.currentDay          = this.oCurrentDay.day;
 } else {
      this.currentYear      = this.oConfiguration.selectedDate.year;
      this.currentMonth     = this.oConfiguration.selectedDate.month;
      this.currentDay          = this.oConfiguration.selectedDate.day;
      this.selectedDayObject = this.oConfiguration.selectedDate;
      this.flag_aDayWasSelected = true;
 }

Basically, he added the "else" condition and actions to the code.
In your HTML, you need to use "jsDatePick.full.1.3.js".
Hope this helps.

A: When uncommenting the selected date part, did you add a , at the end of cellColorScheme:"beige" ?
If no, you'll get a syntax error.

A: I had the same problem, and mine was on an edit page so I need to set for the record being edited in the jsDatePick date and have that appear in the target textbox (I couldn't just set the date in the textbox, this caused the NaN issue in the first place).  So my resolution is an extension of Cesar's one:
this.selectedDayObject = {};
this.flag_DayMarkedBeforeRepopulation = false;
this.flag_aDayWasSelected = false;
this.lastMarkedDayObject = null;

 if (!this.oConfiguration.selectedDate){
      this.currentYear      = this.oCurrentDay.year;
      this.currentMonth     = this.oCurrentDay.month;
      this.currentDay          = this.oCurrentDay.day;  } else {
      this.currentYear      = this.oConfiguration.selectedDate.year;
      this.currentMonth     = this.oConfiguration.selectedDate.month;
      this.currentDay          = this.oConfiguration.selectedDate.day;
      this.selectedDayObject = this.oConfiguration.selectedDate;
      this.flag_aDayWasSelected = true;
      this.populateFieldWithSelectedDate();
}

This causes an issue in the closeCalendar function, which needs to be changed to:
JsDatePick.prototype.closeCalendar = function () {
    if (this.JsDatePickBox) {
        this.JsDatePickBox.style.display = "none";
        document.onclick = function() {};
    }
};


text:
Q: Problem with Sending and Receiving Files with SPP over Bluetooth I am attempting to transfer files (MP3s about six megabytes in size) between two PCs using SPP over Bluetooth (in Java, with the BlueCove API).  I can get the file transfer working fine in one direction (for instance, one file from the client to the server), but when I attempt to send any data in the opposite direction during the same session (i.e., send a file from the server to the client), the program freezes and will not advance.
For example, if I simply:
StreamConnection conn;
OutputStream outputStream;

outputStream = conn.openOutputStream();

....

outputStream.write(data);  //Data here is an MP3 file converted to byte array

outputStream.flush();

The transfer works fine.  But if I try:
StreamConnection conn;
OutputStream outputStream;
InputStream inputStream;
ByteArrayOutputStream out = new ByteArrayOutputStream();

outputStream = conn.openOutputStream();
inputStream = conn.openInputStream();

....

outputStream.write(data);
outputStream.flush();

int receiveData;
while ((receiveData = inputStream.read()) != -1) {
   out.write(receiveData);
}

Both the client and the server freeze, and will not advance.  I can see that the file transfer is actually happening at some point, because if I kill the client, the server will still write the file to the hard drive, with no issues.  I can try to respond with another file, or with just an integer, and it still will not work.
Anyone have any ideas what the problem is?  I know OBEX is commonly used for file transfers over Bluetooth, but it seemed overkill for what I needed to do.  Am I going to have to use OBEX for this functionality?

A: It could be as simple as both programs stuck in blocking receive calls, waiting for the other end to say something...  try adding a ton of log statements so you can see what "state" each program is in (ie, so it gives you a running commentary such as "trying to recieve", "got xxx data", "trying to reply", etc), or set up debugging, wait until it gets stuck and then stop one of them and single step it.

A: you can certainly use SPP to transfer file between your applications (assuming you are sending and receiving at both ends using your application). From the code snippet it is difficult to tell what is wrong with your program.
I am guessing that you will have to close the stream as an indication to the other side that you are done with sending the data .. Note even though you write the whole file in one chunk, SPP / Bluetooth protocol layers might fragment it and the other end could receive in fragments, so you need to have some protocol to indicate transfer completion.

A: It is hard to say without looking at the client side code, but my guess, if the two are running the same code (i.e. both writing first, and then reading), is that the outputStream needs to be closed before the reading occurs (otherwise, both will be waiting for the other to close their side in order to get out of the read loop, since read() only returns -1 when the other side closes).
If the stream should not be closed, then the condition to stop reading cannot be to wait for -1. (so, either change it to transmit the file size first, or some other mechanism).

A: Why did you decide to use ByteArrayOutputStream? Try following code:
    try {
        try {

            byte[] buf = new byte[1024];

            outputstream = conn.openOutputStream();
            inputStream = conn.openInputStream();

            while ((n = inputstream.read(buf, 0, 1024)) > -1)
                outputstream.write(buf, 0, n);

        } finally {
            outputstream.close();
            inputstream.close();
            log.debug("Closed input streams!");
        }
    } catch (Exception e) {
    log.error(e);
        e.printStackTrace();
    }

And to convert the outputStream you could do something like this:
byte currentMP3Bytes[] = outputStream.toString().getBytes();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(currentMP3Bytes);


text:
Q: Redirect issue in select element I have used dependency drop downs.
 <html>
 <body>
  <select id="parent-cat" name="parent-cat" onchange="getChildrenList(this.value)">
            <option value ="">- Please Select -</option>
                <option value="1">test1</option>
                <option value="2">test2</option>
                <option value="3">test2</option>
        </select>

     <select id="child-cat" name="child-cat"
        onchange="getChildUrl(this.value)">
            <option value ="">- Product category -</option>
        </select>

    <script>
function getChildrenList(parentId) {
    if(parentId !=''){
        var customurl = "result.php";
        jQuery.ajax({
             url: customurl,
             type: "POST",
             data : 'category_id='+parentId,
             dataType: 'json',
             success : function(result) {
                var optionHtml;
                optionHtml +='<option value="">-Product Category-</option>';
                for(var option of result){
                  optionHtml +='<option value="'+option.url+'">'+option.name+'</option>';
                }
                jQuery('#child-cat').html(optionHtml);
             }
        });
   }
}

function getChildUrl(childUrl) {
    var url = childUrl;
      if (url) {
          window.location = url; // redirect
      }
      return false;
 }
</script>

  </body>
 </html>

I am appending the result into next drop down once first drop down is changed.
My issue is Once the second drop down is selected it is redirecting to the url, but the option is not selected.
I am looking for code how both the drop downs are selected once the url is redirected after changing the second dropdown.
Please anyone help me on this. Thanks

A: I believe your problem lies within the getChildrenList function. You are never checking to see if your url is the same as the option you are currently adding and you are never adding the select parameter to the option hence it is not staying selected even though you have navigated to the url. Due to the way you are generating your drop-down list (i.e. you are regenerating it client side every time the page is loaded) you will also need to check if the option is selected client-side each time the page is opened. Note I have not verified if the following solution works.
function getChildrenList(parentId) {
    if(parentId !=''){
        var customurl = "result.php";
        jQuery.ajax({
             url: customurl,
             type: "POST",
             data : 'category_id='+parentId,
             dataType: 'json',
             success : function(result) {
                var optionHtml;
                optionHtml +='<option value="">-Product Category-</option>';
                for(var option of result){
                  var selected = (window.location == option.url) ? "selected=\"selected\"" : ""
                  optionHtml +='<option value="'+option.url+'" '+selected+'>'+option.name+'</option>';
                }
                jQuery('#child-cat').html(optionHtml);
             }
        });
   }
}


text:
Q: The property '#/' of type Hash did not match one or more of the required schemas I'm trying to add a user to a list through an API. However, I'm getting this error returned:
{"errors":[{"code":"parsing_error","message":"JSON parsing error: The property '#/' of type Hash did not match one or more of the required schemas"}]}

This is what I'm sending: {"subscribers":{"email":"me@gmail.com"}}
Here is the PHP code:
$subscriberInfo = [
    'subscribers' => array (
        'email' => $email
    )
];

$encoded = json_encode($subscriberInfo);

Is there something wrong with the structure of the JSON?

A: That's not the format described in the documentation. subscribers should be an array, not an object:
$subscriberInfo = [
    'subscribers' => [
        ['email' => $email]
    ]
];

$encoded = json_encode($subscriberInfo);

A: Another possible issue that I encountered when receiving the same error code is that it didn't like a null value.
$firstName = 'Paul';
$lastName = null;

$subscriberInfo = [
    'subscribers' => [
        [
            'email' => $email,
            'first_name' => $firstName,
            'last_name' => $lastName,
        ],
    ]
];

With the null coalescing operator, it can fall back to an empty string.
$firstName = 'Paul';
$lastName = null;

$subscriberInfo = [
    'subscribers' => [
        [
            'email' => $email,
            'first_name' => $firstName,
            'last_name' => $lastName ?? '',
        ],
    ]
];

The above snippet resolved my error code when attempting a batch subscriber 'create or update'.


text:
Q: Postman - Option to view compressed response size..? While testing Spring GZIP compression on REST endpoint observed, with or without compression enabled postman response size showed original response size.

Content-encoding still showed as gzip, but the response size in postman is always uncompressed/original response size. This made me wonder is response compressed or not. Only after checking in chrome realised, Postman always showed uncompressed response size.

Wanted to know why postman always shows uncompressed/original response size..? Is there a option to view compressed response size in Postman..? or Is postman not the right tool to measure response size..?

A: Instead of wasting time on Postman, I found Fiddler is the easiest way to read network size
Postman is actually using Jquery-style stuff to POST/GET/PUSH... data, then show result somehow. and the Network tab is not always working well. In my case, it never shows once how much data was transferred back, same in my teammates' environments.
[NOTE] Fiddler gives you correct Tunnel Received only when request-response are in different physical location of intranet/internet.

Here is same API with different CompressionLevel


text:
Q: Basic geometry in logic I'm trying to solve the following exercise, which just seems to express a geometric system in terms of symbols. (I edited the exercise slightly)
Let $\mathcal{L}_{\text {inc }}$ be a first order language that consists of only relation symbols $\{P, L, I\}$ where $P$ and $L$ are unary relation symbols and $I$ is a binary relation symbol. An incidence structure $\mathfrak{A}$ is an $\mathcal{L}_{\text {inc }}$ -structure where the elements of $P^{\mathfrak{A}}$ are interpreted as points, elements of $L^{\mathfrak{A}}$ are interpreted as lines and $I^{\mathfrak{A}} \subseteq P^{\mathfrak{A}} \times L^{\mathfrak{A}}$ is the incidents relation. When $(p, l) \in I^{\mathfrak{A}}$ then we say point $p$ is incident with line $l$. Consider the following set of axioms:
(A0) $P^{2}$ and $L^{\mathfrak{A}}$ partitions the domain of $\mathfrak{A}$ i.e. every element of the domain is either a point or a line but not both;
(A1) Any two distinct points are incident with exactly one line;
Express $\mathrm{A} 0, \mathrm{~A} 1$ as $L_{i n c}$ -sentences.
Here is my solution:
$\mathrm{A} 0:\forall v(((P(v) \vee L(v)) \wedge (\lnot(P(v) \land L(v)))) .$
$\mathrm{A} 1:\forall v_{1}, v_{2}\left(\left(P\left(v_{1}\right) \wedge P\left(v_{2}\right)\right) \land \left(\exists v_{3}\left(L\left(v_{3}\right) \wedge I\left(v_{1}, v_{3}\right) \wedge I\left(v_{2}, v_{3}\right) \wedge\left(\left(\forall v_{4}\left(L\left(v_{4}\right) \wedge I\left(v_{1}, v_{4}\right) \wedge I\left(v_{2}, v_{4}\right)\right) \rightarrow\right.\right.\right.\right.\right.$
$\left.\left.\left.v_{3} \doteq v_{4}\right)\right)\right)$
The official solution is:
$\mathrm{A} 0:(\forall v(P(v) \vee L(v))) \wedge \forall v((P(v) \rightarrow \neg L(v)) \wedge(L(v) \rightarrow \neg P(v))) .$
$\mathrm{A} 1:\forall v_{1}, v_{2}\left(\left(P\left(v_{1}\right) \wedge P\left(v_{2}\right)\right) \rightarrow\left(\exists v_{3}\left(L\left(v_{3}\right) \wedge I\left(v_{1}, v_{3}\right) \wedge I\left(v_{2}, v_{3}\right) \wedge\left(\left(\forall v_{4}\left(L\left(v_{4}\right) \wedge I\left(v_{1}, v_{4}\right) \wedge I\left(v_{2}, v_{4}\right)\right) \rightarrow\right.\right.\right.\right.\right.$
$\left.\left.\left.v_{3} \doteq v_{4}\right)\right)\right)$
The question is, is my solution correct? I think A0 is correct, but I'm concerned about A1, especially because I used $\land$ instead of $\rightarrow$. If my solution is wrong, can you help me understand why? Thanks.

A: A0 looks good: it translates to "any v is either a point or a line and isn't both a point and a line"
A1 will not be true if $v_1$ or $v_2$ is a line.