text:
Q: validate a date format in (mm/yyyy) type in java how to validate date format MM/YYYY as String
example-
09/20  false
13/5651 false
3/2104 true
03/2010 true

A: Use YearMonth class.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/uuuu" ) ;
YearMonth ym = YearMonth.parse( "3/2018" , f ) ;

Trap for DateTimeParseException to detect invalid input.

Tip: Use standard ISO 8601 formats for exchanging date-time values as text. For year-month: YYYY-MM
The java.time classes use these standard formats by default.
YearMonth.parse( "2018-03" )

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later  - Part of the standard Java API with a bundled implementation.

*

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*Later versions of Android bundle implementations of the java.time classes.

*For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

A: What you want is a customized method because you place special constraints to the validity of the date.
The following passed all your 4 examples:
public static boolean validDate(String date) {
    date = date.trim();
    if (date.length() < 6)
        return false;

    String[] parts = date.split("/");
    if (parts.length != 2)
        return false;

    int month = 0;
    try {
        month = Integer.parseInt(parts[0]);
    } catch (NumberFormatException e) {
        e.printStackTrace();
        return false;
    }
    if (month < 1 || month > 12)
        return false;

    int year = 0;
    try {
        year = Integer.parseInt(parts[1]);
    } catch (NumberFormatException e) {
        e.printStackTrace();
        return false;
    }
    if (year < 1000)
        return false;

    return true;
}

public static void main(String[] args) {
    String s1 = "09/20";
    String s2 = "13/5651";
    String s3 = "3/2104";
    String s4 = "03/2010";

    System.out.println(s1 + " " + validDate(s1));
    System.out.println(s2 + " " + validDate(s2));
    System.out.println(s3 + " " + validDate(s3));
    System.out.println(s4 + " " + validDate(s4));
}

will print:
09/20 false
13/5651 false
3/2104 true
03/2010 true

I'm not sure about this part:
if (year < 1000)
    return false;

you can change it if you like.

A: public boolean isThisDateValid(String dateToValidate, String dateFromat){

    if(dateToValidate == null){
        return false;
    }

    SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
    sdf.setLenient(false);

    try {

        //if not valid, it will throw ParseException
        Date date = sdf.parse(dateToValidate);
        System.out.println(date);

    } catch (ParseException e) {

        e.printStackTrace();
        return false;
    }

    return true;
}

Referensi https://www.mkyong.com/java/how-to-check-if-date-is-valid-in-java/


text:
Q: call c# function from javascript onclick event button how to use something like this :

and c# code is like this
    protected void btn_newpl_Click(object sender, EventArgs e)
{...}

how can call this c# function from javascript event click

A: To trigger button event, you have to add this line of code in javascript.
document.getElementById("btn_newpl").click();

Your button must have runat="server" and OnServerClick="btn_newpl_Click" attributes.
If your problem is that the input element is in javascript string, than you can extract the string value of input and concatenate to your string on client side.
<input type="button" id="btn_newpl" value="submit"
       OnServerClick="btn_newpl_Click"
       runat="server" />

Please note that you don't actually call a C# function, you just trigger the click event on webforms and a postback to sever will be done. The server will figure out which event has been triggered and will execute the C# function.
Source: How to call a code behinds button click event using javascript

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I share a folder for a Client Machine I am using windows 7 on server and linux
RedHat on client, I am in LAN
 i want to share specific folder with specific client,
 what should i do?? please help me.
it gives an error and it shared for all machines .

A: right click the folder is to be shared and click sharing in that use advanced sharing option and type evryone there and apply the changes it will be gets shared


text:
Q: how to disable one checkboxout of two check box at a time using javascript?

      Gold Foil Stamping :

<input type="checkbox" name="gold_foil_option" value="Gold_Silver_Printing"> Gold / Silver Printing

      <input type="checkbox" name="gold_foil_option1" value="Gold_Foil_Stamping"> Gold Foil Stamping

I want to select one check box out of two check box using javascript? What is the possible way to select one checkbox using javascript? Can i name both the name as same so as to select one checkbox at a time? I want to use only javascript only at a time?


text:
Q: ElasticSearch : Aggregate on the Filtered Unique records I am struck with an issue in ElasticSearch.
I are trying to get unique documents from the filtered data set and do an aggregation on top of it.
Our data set looks something like this..
ID    object  Property1   Property2
12  123 Test1   Fest2
23  234 Test3   Fest4
5   123 Test1   Fest2
55  123 Test2   Fest4
3   234 Test2   Fest2
I  could like to filter the devices based on property2  and aggregate (group by) on property1 of the unique filtered records.
Could someone help me on this?
Filtering and getting unique records.
{
 "size": 0,
 "query": { "match": { "Property2": "Fest2" }},
"aggs": {
    "Unique-Object": {
      "terms": {
        "field": "object.keyword",
        "size": 20
},
"aggs": {
    "top_uids_hits": {
          "top_hits": {
            "sort": [
              {
                "_score": {
                  "order": "desc"
                }
              }
            ],
            "size": 1
          }
        }
      }
    }
    }
}'

I could like to group by Property1 as below on the output of the above DSL…Could some one throw light on this?
Group by Property1
"aggs": {
"Property1_count": {
"terms": {
"field": " Property1.keyword"
}

Thanks
Arun S

A: I think this should be your query . check using this , agg inside agg :-
Use of cardinality link .
  {
    "_source":false,
    "query": {
        "match": {
            "Property2": "xxxx"
        }
    },
    "aggregations": {
        "byProperty1": {
            "terms": {
                "field": "property1"
            },
            "aggs": {
                "byId": {
                    "cardinality": {
                        "field": "id"
                    }
                }
            }
        }
    }
}

For java implementation , check my answer .
Check this question group by on multiple fields link .


text:
Q: What is a more modern way of getting numerical solution/roots of polynomial in base 10 than this? I know Graeffe's method to approximate roots is great, but people always find troubles when they convert the root in n-th-root form into base 10 form by hand, for example, a large number in 64-th-root.
What is a more modern way of getting numerical solution/roots of polynomial in base 10 than this by hand? I prefer a method that you could control the accuracy in terms of significant digit
Graeffe's method - http://mat.iitm.ac.in/home/sryedida/public_html/caimna/transcendental/polynomial%20methods/direct.html
Now a bounty is offered to address all the concerns.


text:
Q: How can I convert a double value into a datetime? I have a class that converts the current time to some specific time that's specified in web.config, like adding  2.30 or 2.45 to the current time.
Here is my class:
Public Shared Function GetGoTime() As DateTime
    Dim hrs = Double.Parse(ConfigurationManager.AppSettings("Gotime"))
    Dim GoTime As DateTime = DateTime.Now.AddHours(hrs)
    Return GoTime
End Function

This works fine when we are adding an integer, but when we add something like 2.45 or 7.37 hours, then it doesn't work. What should I do?

A: You should parse the hours and minutes separately by splitting the given time by . and then use  AddMinutes function by calculating the value in minutes for hours by multiplying it by 60, something like,
Dim hrs = ...your code only to extract the hours;
Dim minutes = ...your code only to extract only the minutes;
Dim GoTime As DateTime = DateTime.Now.AddMinutes(hrs*60 + minutes);

A: What about to use TimeSpan.FromHours and DateTime.Add ?
Public Shared Function GetGoTime() As DateTime
    Dim hrs = Double.Parse(ConfigurationManager.AppSettings("Gotime"))
    Dim GoTime As DateTime = DateTime.Now.Add(TimeSpan.FromHours(hrs))
    Return GoTime
End Function


text:
Q: Is it possible to use a repository in the AuditorAwareImpl class? I want to implement a reference in the database who and when an entity was created/updated.
The createdAt and updatedAt date are already working.
But I can see when I set a breakpoint that the return of the getCurrentAuditor method gets called about ten times till a response comes to the client. And the response is an error with the CONFLICT HttpStatus-Code.
I have a class named BaseEntity where the attributes are defined.
See my classes below:
class AuditorAwareImpl implements AuditorAware<Person> {

    @Autowired
    private PersonRepository personRepo;

    @Override
    public Optional<Person> getCurrentAuditor() {
        return Optional.of(personRepo.findByUserPrincipalName(SecurityContextHolder.getContext().getAuthentication().getName() + "@email.com"));
    }
}

@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
class JpaConfig {
    @Bean
    public AuditorAware<Person> auditorProvider() {
        return new AuditorAwareImpl();
    }
}

@Data
@Getter
@Setter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class BaseEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    protected Long id;

    @CreatedDate
    private Date createdAt;

    @CreatedBy
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(referencedColumnName="id")
    private Person createdBy;

    @LastModifiedDate
    private Date updatedAt;

    @LastModifiedBy
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(referencedColumnName="id")
    private Person updatedBy;

    @PrePersist
    protected void prePersist() {
        if (this.createdAt == null) createdAt = new Date();
        if (this.updatedAt == null) updatedAt = new Date();
    }

    @PreUpdate
    protected void preUpdate() {
        this.updatedAt = new Date();
    }

    @PreRemove
    protected void preRemove() {
        this.updatedAt = new Date();
    }

}

Edit v1 from Zorglube(does not work for me)
class AuditorAwareImpl implements AuditorAware<Person> {

    @Autowired
    private ApplicationContext context;

    @Override
    public Optional<Person> getCurrentAuditor() {
        PersonRepository personRepo = context.getBean(PersonRepository.class);
        return Optional.of(personRepo.findByUserPrincipalName(SecurityContextHolder.getContext().getAuthentication().getName() + "@email.com"));
    }
}

A: Try this :
class AuditorAwareImpl implements AuditorAware<Person> {

    @Override
    public Optional<Person> getCurrentAuditor() {
        PersonRepository personRepo = ApplicationContextProvider.getApplicationContext().getBean(PersonRepository.class)
        return Optional.of(personRepo.findByUserPrincipalName(SecurityContextHolder.getContext().getAuthentication().getName() + "@email.com"));
    }
}

@Component(value = "applicationContextProvider")
public class ApplicationContextProvider implements ApplicationContextAware {

    private static class AplicationContextHolder {
        private static final InnerContextResource CONTEXT_PROV = new InnerContextResource();
    }

    private static final class InnerContextResource {

        private ApplicationContext context;

        private void setContext(ApplicationContext context) {
            this.context = context;
        }
    }

    public static ApplicationContext getApplicationContext() {
        return AplicationContextHolder.CONTEXT_PROV.context;
    }

    @Override
    public void setApplicationContext(ApplicationContext ac) {
        AplicationContextHolder.CONTEXT_PROV.setContext(ac);
    }

}


text:
Q: Error establishing a database connection while accessing azure web app **The problem is, we have hosted two web apps in standard pricing mode of  two azure accounts. Both apps are getting down continuously for sometimes and automatically recovers back. NOW BOTH APPS ARE DOWN AND NOT RECOVERING BACK.
The error usually getting is
Error establishing a database connection**
The problem was occuring several times a day and becomes down for 10 to 15 minutes. NOW IT IS PERMANENTLY DOWN.
It is affecting our business critically. So please help us immediately.
YOUR HELP ON THIS PROBLEM IS HIGHLY APPRECIATED.

A: We've been having the same problem today. Our databases are hosted with ClearDB at this endpoint azure-east-a and they've been failing all day. Quick fix was to move all our databases to a new instance hosted in Aus-SouthEast. Our sites are back up now but the Aus-East instance is still having troubles.

A: Having Issue too:
Getting Error Message:
Error establishing a database connection
Even through there is no database.
Just the standard your app had been created web page that Azure put in there.
This been happening the last few days.
Then I notice some times that the original App Service plan was changed to a newly created one that I did not made.
When looking for the app service plan in Azure it does not show up.
There is also no option in Web site settings to change service plan.
That link was gone.


text:
Q: Making Qt Widgets Stretch and Scale w/ Main Window I'm wondering if there is a way to make Qt widgets within a QMainWindow widget stretch and scale as the size of the main window is stretched and shrunk. Basically, I'd like the entire window and it's contents to have the same appearance except for size:

At the only way I can think to accomplish this is to get the size of the main window, do the math for every single widget, and reset their sizes any time the main window size is changed, but I'm thinking there's an easier way.

A: I like this video tutorial on youtube.  I'll help you create a layout using QLayout classes.  If you use QtCreator/Designer, you can also take a look at the auto-generated ui_MainWindow.XXX file that will clue you in on how it uses some of the UI classes.
As always, QtCreator/Designer has a bunch of hints and tips so you should be able to dig up from the documentation that's embedded in the application.


text:
Q: Do not parser XML using SimpleXML library I have an issue when I try paser xml string to object using SimpleXML(version 2.7.1) library.
This is my string :

        Weather

         Ney
         14
         15
         16

         Pana
         30
         31
         30

         Sin
         32
         33
         36

And this is my model :
@Root
public class TBody {
    @ElementList
    List
 tr;
}
public class TR {
    @ElementList(entry = "th")
    List th;
    @ElementList(entry = "td")
    List td;
    public TR() {
    }
    public static class TH {
        @Element
        String th;
        @Element
        IMG img;
        public TH() {
            // TODO Auto-generated constructor stub
        }

    }
    public static class IMG{
        @Element
        String img;
        @Attribute
        String src;
        public IMG() {
        }
    }

    public static class TD {
        @Element
        IMG img;
        @Element
        String td;
        @Element
        A a;
    }
    public static class A{
        @Element
        String a;
        @Attribute
        String href;
        @Attribute
        String title;
        @Attribute
        String target;
        @Attribute
        String style;
        public A() {
        }
    }
}

This is logcat trace :
05-12 23:14:46.711  W/System.err﹕ org.simpleframework.xml.core.ValueRequiredException:
Unable to satisfy @org.simpleframework.xml.ElementList(data=false, empty=true, entry=td, inline=false, name=, required=true, type=void) on field 'td' java.util.List
com.example.model.TR.td for class com.example..model.TR at line 3
05-12 23:14:46.711  W/System.err﹕ at org.simpleframework.xml.core.Composite.validate(Composite.java:644)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Composite.readElements(Composite.java:449)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Composite.access$400(Composite.java:59)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Composite$Builder.read(Composite.java:1383)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Composite.read(Composite.java:201)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Composite.read(Composite.java:148)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Traverser.read(Traverser.java:92)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.CompositeList.populate(CompositeList.java:175)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.CompositeList.read(CompositeList.java:120)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Composite.readVariable(Composite.java:623)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Composite.readInstance(Composite.java:573)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Composite.readUnion(Composite.java:549)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Composite.readElement(Composite.java:532)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Composite.readElements(Composite.java:445)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Composite.access$400(Composite.java:59)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Composite$Builder.read(Composite.java:1383)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Composite.read(Composite.java:201)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Composite.read(Composite.java:148)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Traverser.read(Traverser.java:92)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Persister.read(Persister.java:625)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Persister.read(Persister.java:606)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Persister.read(Persister.java:584)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Persister.read(Persister.java:562)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Persister.read(Persister.java:499)
05-12 23:14:46.715  W/System.err﹕ at org.simpleframework.xml.core.Persister.read(Persister.java:408)

Can anyone help me understand the reason at here ?
Thanks!

A: [removed because it had bugs]

*

*Added @Root annotation to all classes

*added inline=true to all element lists

*added type = _.class to each element lists

*added required=false for th and td

*added explicit empty constructors

EDIT: had to add some required=false but more importantly, SimpleXML cannot handle both @Text and @Element tags on the same data object, so I used the solution in this question to alter the XML in order to provide an actual @Element rather than a @Text.
My final solution that parses properly is the following:
@Root
public class A{
    @Element(required=false)
    String a;
    @Attribute
    String href;
    @Attribute
    String title;
    @Attribute
    String target;
    @Attribute(required=false)
    String style;
    public A() {
    }
}

@Root
public class IMG {
    @Element(required=false)
    String img;
    @Attribute
    String src;
    public IMG() {
    }
}

@Root(name="tbody")
public class TBody {
    @ElementList(entry = "tr", inline=true, type=TR.class)
    List
 tr;

    public TBody() {}
}

@Root
public class TD {
    @Element(required=false)
    IMG img;
    @Element(required=false)
    Content content;
    @Element(required=false)
    A a;

    public TD() {}
}

@Root
public class TH {
    @Element(data=true, required=false)
    Content content;

    @Element(name="img", required=false)
    IMG img;

    public TH() {
        // TODO Auto-generated constructor stub
    }

}

@Root
public class TR {
    @ElementList(entry = "th", inline = true, type = TH.class, required = false)
    List th;
    @ElementList(entry = "td", inline = true, type = TD.class, required = false)
    List td;

    public TR() {
    }
}

Also added a class:
@Root
public class Content {
    @Text(required=false)
    String content;
}

And I had to use the following Persister, similarly to what was in the linked question:
public class SerializerWithPreprocessor extends Persister {

    public SerializerWithPreprocessor() {
    }

    @Override
    public <T> T read(Class<? extends T> type, String source) throws Exception {
        //System.out.println("Source: " + source);
        source = source.replaceAll("([[\\s||\\w||[+=]]&&[^<>]]+)	", "<content>$1</content>	");
        source = source.replaceAll("([[\\s||\\d||\\w||[+=]]&&[^<>]]+)	", "<content>$1</content>	");
        //System.out.println("Source2: " + source);
        return super.read(type, source);
    }
}

This way, the following works:
public class Main {
    private final static String data = "
\n" +
            "
\n" +
            "        	\n" +
            "        Weather	\n" +
            "        	\n" +
            "        	\n" +
            "        	\n" +
            "
\n" +
            "
\n" +
            "        	\n" +
            "         Ney 	\n" +
            "         14 	\n" +
            "         15 	\n" +
            "         16 	\n" +
            "
\n" +
            "
\n" +
            "        	\n" +
            "         Pana 	\n" +
            "         30 	\n" +
            "         31 	\n" +
            "         30 	\n" +
            "
\n" +
            "
\n" +
            "        	\n" +
            "         Sin 	\n" +
            "         32 	\n" +
            "         33 	\n" +
            "         36 	\n" +
            "
\n" +
            "
";

    public static void main(String[] args) {
        Serializer serializer = new SerializerWithPreprocessor();
        try {
            TBody tBody = serializer.read(TBody.class, data);
            serializer.write(tBody, System.out);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

With the following output:

         <content>Weather</content>

         <content> 14 </content>

         <content> 15 </content>

         <content> 16 </content>

         <content> 30 </content>

         <content> 31 </content>

         <content> 30 </content>

         <content> 32 </content>

         <content> 33 </content>

         <content> 36 </content>

You might need to tinker with the REGEXes in the replaceAll to make it more whitespace-friendly.


text:
Q: Can I Promote Notes About Uninitialized Variables to Errors When SAS encounters an uninitialized variable, it will output a note to the log that looks like this:
NOTE: Variable not_in_data is uninitialized.

Is it possible to have SAS output that message as a warning or an error instead?

A: Yes (in 9.4 or later):
option varinitchk = error;
Default value is note, other possible values are nonote and warning.
There is also undocumented feature that changes certain notes to errors. You can either set the option using option dsoptions = note2err; or by adding / note2err to a data statement. I found a list on SAS-L of the notes this option changes to errors:
19   Variable %*v is uninitialized.
97   Missing values were generated as a result of
98   Division by zero detected at %2q.
99   Mathematical operations could not be performed
108  Invalid numeric data, '%*s' , at %2q.
109  Invalid character data, %f , at %2q.
110  Invalid %sargument to function %b at %2q.
139  Argument to function %*s is not a known variable name:  %*v.
140  Argument to function %*s is not a valid variable name:  %*s.
205  Invalid argument(s) to the exponential operator "**" at %2q.
208  Invalid numeric data, %*s='%*s' , at %2q.
209  Invalid character data, %*s=%f , at %2q.
223  A number has become too large at %2q. %w%*s
224  A number has become too large during the compilation phase.
225  Division by zero detected during the compilation phase.
242  Invalid argument(s) to the exponential operator "**".
258  Invalid argument to function %*b at %2q.
259  Invalid first argument to function %*b at %2q.
260  Invalid second argument to function %*b at %2q.
261  Invalid third argument to function %*b at %2q.
262  Invalid fourth argument to function %*b at %2q.
267  Argument %d to function %*b at %2q is invalid.
356  The SUBSTR pseudo-variable function does not allow character
424  Character values have been converted to numeric
425  Numeric values have been converted to character
429  A number has become too large during the compilation phase,
430  Division by zero detected during the compilation phase,
484  Format %*b was not found or could not be loaded.
485  Informat %*b was not found or could not be loaded.

Source


text:
Q: Serial Port Communication problem while using UART I'm trying to send and receive data between a board (Dialog DA14531) and a simulation application of a temperature sensor.

*

*I can easily send and receive data between the board and my computer, using Termite for instance.

*By using Com0Com, I can receive the data sent from the sensor simulator in Termite as well.
However; I can't directly send data between this simulator and my board. I'm using Advanced Serial Port Monitor application and while the simulator states that the connection has been established, there seem to be nothing going on with this port.
Does someone have any idea about what might have caused the problem and how should I proceed for debugging?

A: So, I've figured out a new way to fix the issue:

*

*Created a pair of virtual ports by using Com0COM.

*Connected the simulator to one of these ports and Termite to the other one.

*Connected the board to the system.

*Used port forwarding in Termite to send the received data to the board.
This way, I can also monitor the data traffic between the board and the simulator.


text:
Q: Using getDoc().then() inside of a loop Firebase I am trying to loop through an array and for each element in an array i want to use getDoc() and then add the data of the document to a new array. Basically to do this:
useEffect(() => {
    let items = [];
    for(const cart_item of cartItems){
        getDoc(doc(getFirestore(), 'tickets', cart_item.ticket_id)).then((ticket_item) => {
            items.push({...ticket_item.data()});
        });
    }
    console.log(items);
}, [cartItems])

However, the items array is still empty after a loop where i log it. I think that the issue is that the loop is not waiting for the getDoc() to return something and goes on. How to make it wait for the getDoc() to finish? I have been reading about async, await but i still don't understand how to handle it.

A: Try refactoring your code with an async function as shown below:
useEffect(() => {
  const getItems = async () => {
    // fetching all documents by mapping an array of promises and using Promise.all()
    const itemsDocs = await Promise.all(cartItems.map(c => getDoc(doc(getFirestore(), 'tickets', c.ticket_id)))
    // mapping array of document data
    const items = itemsDocs.map(i => i.data())
    console.log(items);
  }
  getItems();
}, [cartItems])

A: When you call getDoc it needs to make a call to the Firestore server to get your data, which may take some time. That's why it doesn't immediately return the document snapshot, but instead you use a then() callback that the Firestore SDK calls when it gets the data back from the server.

This sort of asynchronous call changes the order in which you code executes, which is easiest to see if we add some logging to the code:
console.log("Before loading data");
for(const cart_item of cartItems){
    getDoc(doc(getFirestore(), 'tickets', cart_item.ticket_id)).then((ticket_item) => {
        console.log("Got data");
    });
}
console.log("After starting data load");

Then you run this code, the logging output i:

Before loading data
After starting data load
Got data
Got data
...

This is probably not what you initially expected, but it perfectly explains why your console.log(items) shows an empty array: by that time none of the calls to items.push({...ticket_item.data()}) have run yet, because the data is still being loaded from the server.

I noticed that Dharmaraj just posted an answer with the code for a working solution using Promise.all, so I recommend checking that out too.


text:
Q: Runtime Error while using AppCompatActivity instead of Actionbar I  am using the AppCompatActivity library to make support all the devices. After upadting the android-support-v7-appcompat library i am facing issue.  But i am facing an error during run-time. I am using eclipse studio to code for android project. Any help will be appreciated.
Below is my error ,and i am getting no idea where i am going wrong.
** ERROR **
     E/AndroidRuntime(6899): FATAL EXCEPTION: main
     E/AndroidRuntime(6899): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.drawer.sample/com.drawer.sample.MainActivity}: android.view.InflateException: Binary XML file line #19: Error inflating class android.support.v7.internal.widget.NativeActionModeAwareLayout
     E/AndroidRuntime(6899):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
     E/AndroidRuntime(6899):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
     E/AndroidRuntime(6899):    at android.app.ActivityThread.access$800(ActivityThread.java:144)
     E/AndroidRuntime(6899):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
     E/AndroidRuntime(6899):    at android.os.Handler.dispatchMessage(Handler.java:102)
     E/AndroidRuntime(6899):    at android.os.Looper.loop(Looper.java:135)
     E/AndroidRuntime(6899):    at android.app.ActivityThread.main(ActivityThread.java:5221)
     E/AndroidRuntime(6899):    at java.lang.reflect.Method.invoke(Native Method)
     E/AndroidRuntime(6899):    at java.lang.reflect.Method.invoke(Method.java:372)
     E/AndroidRuntime(6899):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
     E/AndroidRuntime(6899):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     E/AndroidRuntime(6899): Caused by: android.view.InflateException: Binary XML file line #19: Error inflating class android.support.v7.internal.widget.NativeActionModeAwareLayout
     E/AndroidRuntime(6899):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:757)
     E/AndroidRuntime(6899):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
     E/AndroidRuntime(6899):    at android.view.LayoutInflater.parseInclude(LayoutInflater.java:890)
     E/AndroidRuntime(6899):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
     E/AndroidRuntime(6899):    at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
     E/AndroidRuntime(6899):    at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
     E/AndroidRuntime(6899):    at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
     E/AndroidRuntime(6899):    at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:299)
     E/AndroidRuntime(6899):    at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:246)
     E/AndroidRuntime(6899):    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:106)
     E/AndroidRuntime(6899):    at com.drawer.sample.MainActivity.onCreate(MainActivity.java:12)
     E/AndroidRuntime(6899):    at android.app.Activity.performCreate(Activity.java:5933)
     E/AndroidRuntime(6899):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
     E/AndroidRuntime(6899):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
     E/AndroidRuntime(6899):    ... 10 more
     E/AndroidRuntime(6899): Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v7.internal.widget.NativeActionModeAwareLayout" on path: DexPathList[[zip file "/data/app/com.drawer.sample-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
     E/AndroidRuntime(6899):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
     E/AndroidRuntime(6899):    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
     E/AndroidRuntime(6899):    at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
     E/AndroidRuntime(6899):    at android.view.LayoutInflater.createView(LayoutInflater.java:571)
     E/AndroidRuntime(6899):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743)
     E/AndroidRuntime(6899):    ... 23 more
     E/AndroidRuntime(6899):    Suppressed: java.lang.ClassNotFoundException: android.support.v7.internal.widget.NativeActionModeAwareLayout
     E/AndroidRuntime(6899):        at java.lang.Class.classForName(Native Method)
     E/AndroidRuntime(6899):        at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
     E/AndroidRuntime(6899):        at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
     E/AndroidRuntime(6899):        at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
     E/AndroidRuntime(6899):        ... 26 more
     E/AndroidRuntime(6899):    Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

activity_main.xml
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:tools="http://schemas.android.com/tools"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="vertical">
       <include
         android:id="@+id/toolbar"
         layout="@layout/toolbar_layout"/>
       <TextView
         android:text="@string/app_name"
         android:layout_height="wrap_content"
         android:layout_width="wrap_content"
         android:textColor="#000000"
         android:layout_marginTop="110dp"/>
    </LinearLayout>

MainActivty.java
    package com.drawer.sample;

    import android.os.Bundle;
    import android.support.v7.widget.Toolbar;
    import android.support.v7.app.AppCompatActivity;

   public class MainActivity extends AppCompatActivity  {

     @Override
     protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);

     Toolbar mToolbar =  (Toolbar) findViewById(R.id.toolbar);
     setSupportActionBar(mToolbar);
     getSupportActionBar().setDisplayShowTitleEnabled(false);

     }
 }

Style.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <style name="AppTheme" parent="AppTheme.Base">

   </style>

   <style name="AppTheme.Base" parent = "Theme.AppCompat.Light.DarkActionBar">
     <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primaryDark</item>
    <item name="colorAccent">@color/accent</item>
</style>

A: ActionBar is used as Toolbar in material design. So add theme with no action bar and use
following to use Toolbar in xml.
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:iosched="http://schemas.android.com/apk/res-auto"
style="@style/HeaderBar"
iosched:theme="@style/ActionBarThemeOverlay"
iosched:popupTheme="@style/ActionBarPopupThemeOverlay"
android:id="@+id/toolbar_actionbar"
iosched:titleTextAppearance="@style/ActionBar.TitleText"
iosched:contentInsetStart="?actionBarInsetStart"
android:layout_width="match_parent"
android:layout_height="?actionBarSize" />

A: I found the solution of may error, i have to add the implements override methods of appCompatActivity. Below is the code by which i have fix it.
package com.drawer.sample;

import android.os.Bundle;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.Toolbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatCallback;

public class MainActivity extends AppCompatActivity implements AppCompatCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar mToolbar =  (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

    }

    @Override
    public void onSupportActionModeFinished(ActionMode mode) {
        // TODO Auto-generated method stub
        super.onSupportActionModeFinished(mode);
    }

    @Override
    public void onSupportActionModeStarted(ActionMode mode) {
        // TODO Auto-generated method stub
        super.onSupportActionModeStarted(mode);
    }
}

And i can add the statusbar as well actionbar. :)

A: Have you ever try to add this code sample in your gradle file?
   android {
         configurations {
    all*.exclude group: 'com.android.support', module: 'support-v4'
    all*.exclude group: 'com.android.support', module: 'support-annotations'
} }


text:
Q: Designing Tests for Culture/Globalisation problems I'm concerned about the predictability of my application in handling string input in different cultures. It has been a problem in older software and I don't want it to be a problem in the new.
I have generally two sources of input; Strings entered into a WPF application and Streams, loaded from files, containing text. These cultured strings are generally entered into an model before being used
public struct MyModel
{
    public String Name;
}

I want to design a meaningful test to ensure some logic can actually handle Result DoSomething(MyModel model); when it contains text inputted on a different machine.
But how can I show a case where the difference matters?
For example the following fails.
 var inNativeCulture= "[Something12345678.9:1] {YeS/nO}";
 var inChineseCulture = inNativeCulture.ToString(new CultureInfo("zh-CN"));
 Assert.That(inChineseCulture, Is.Not.EqualTo(inNativeCulture));

[Question]
How can I test DoSomething such that the test is able to fail if the strings are not converted to InvarientCulture?
Should I even bother? i.e. the string Something entered on a french keyboard will always equal Something entered on a Chinese keyboard?
What can I test for that will mitigate Globalization problems?

A: The ToString method taking a IFormatProvider on a string is essentially a no-op. The documentation states "Returns this instance of String; no actual conversion is performed."
Since you are concerned about avoiding issues here's some general advice. First it is very helpful to have a clear distinction in your mind between frontend (user facing) strings and backend (database, wire, file, etc) strings. Frontend strings should be generated/accepted according to the user's culture / application language. These strings should not be persisted (with few exceptions like when you are generating a document that will be read only by people and not by machine). Backend strings should always use standard formats that will not change over time. If you accept the fact that the data used to generate/parse globalized strings changes, then you will isolate yourself from the effects by ensuring that you do not persist user facing strings.


text:
Q: Python RegEx using re.sub with multiple patterns I'm trying to use Python RegEx re.sub to remove a colon before the antepenultimate vowel [aeiou] of a word if the antepenultimate vowel (from the end) is preceded by another vowel.
So the colon has to be between the 3rd and 4th vowel counting from the end of the word.
So the 1st example given would break down like this w4:32ny1h.
we:aanyoh > weaanyoh    # w4:32ny1h
hiru:atghigu > hiruatghigu
yo:ubeki > youbeki

Below is the RegEx statement I'm trying to use but I can't get it to work.
word = re.sub(ur"([aeiou]):([aeiou])(([^aeiou])*([aeiou])*([aeiou])([^aeiou])*([aeiou]))$", ur'\1\2\3\4', word)

A: Don't you just have too many parentheses (and other extra stuff)?:
word = re.sub(ur"([aeiou]):(([aeiou][^aeiou]*){3})$", ur'\1\2', word)

A: Not sure if you want to completely ignore consonants; this regex will. Otherwise similar to Jeff's.
import re

tests = [
    'we:aanyoh',
    'hiru:atghigu',
    'yo:ubeki',
    'yo:ubekiki',
    'yo:ubek'
]

for word in tests:
    s = re.sub(r'([^aeiou]*[aeiou][^aeiou]*):((?:[^aeiou]*[aeiou]){3}[^aeiou]*)$', r'\1\2', word)
    print '{} > {}'.format(word, s)

A: You state that you are targeting a word versus a line, so first set anchors to only deal with words:
\b[regex will go here]\b
^                      ^     assert a word boundary

Next, a colon proceeded by and followed by a [aeiou] with two more [aeiou] in the portion following the colon. I assume case independent?
(?i)(\b\w+[aeiou]):((?:[aeiou][^aeiou\s\W]*){3}\b)
                                   ^  match a character that is NOT vowel, space or not a
                                         ^   \W=[^a-zA-Z0-9_]

Demo
(Note the use of [^aeiou\W] which is consonant letters, numbers and _ but not other characters Demo.)
Python demo:
import re

tests={
    'matches':[
        'we:aanyoh',
        'hiru:atghigu',
        'yo:ubeki'
        ],
    'no match':[
        'wz:ubeki',
        'we:a anyoh',
        'yo:ubek',
        'hiru:atghiguu'
    ]
}

for k, v in tests.items():
    print k
    for e in v:
        s=re.sub(r'(?i)(\b\w+[aeiou]):((?:[aeiou][^aeiou\s\W]*){3}\b)', r'\1\2', e)
        print '\t{} > {}'.format(e, s)

Prints:
matches
    we:aanyoh > weaanyoh
    hiru:atghigu > hiruatghigu
    yo:ubeki > youbeki
no match
    wz:ubeki > wz:ubeki
    we:a anyoh > we:a anyoh
    yo:ubek > yo:ubek
    hiru:atghiguu > hire:atghiguu

This will only handle words with a single colon. If you want to match words that have multiple colons but have this same pattern, change the LH pattern to have the character class that includes a colon and an anchor that is not \b.
Example: (?i)(^[\w:]+[aeiou]):((?:[aeiou][^aeiou\s\W]*){3}\b)

A: It should work with this:
word = re.sub(ur"(?<=[aeiou]):(?=[aeiou]([^aeiou]*[aeiou]){2}[^aeiou]*$)", ur'', word)

see example here: https://regex101.com/r/kA8xH3/2
notice that I only capture the colon and replace it with an empty string rather than capturing groups and concatenate them.
Tt checks for the colon combination, then does a lookahead to check that there are 2 additional vowels (and maybe consonants). It allso allows additional consonants at the end but makes sure that there are no more vowel through the $

A: This will do it:
    word = re.sub(ur"([aeiou]):([aeiou])([^\Waeiou]*[aeiou][^\Waeiou]*[aeiou][^\Waeiou]*)$", ur'\1\2\3', word)

http://www.phpliveregex.com/p/dCa

A: Roundup(I used a capital vowel to indicate where in the word the substitution should take place).  Let me know if you want me to add other test strings.
import re

strings = [
    'wE:aanyoh',
    'hirU:atghigu',
    'yO:ubeki',

    'xE:aaa',
    'xx:aaa',
    'xa:aaaxA:aaa',
    'xa:aaaxA:aaaxx',
    'xa:aaaxA:aaxax',
    'a:aaaxA:aaxax',
    'e:aeixA:aexix',
]

pattern = r"""
    (
        .*
        [aeiou]
    )
    :
    (
        [aeiou]
        .*?
        [aeiou]
        .*?
        [aeiou]
    )
"""

template = "{:>15}: {}"
for string in strings:
    print(
        template.format('original', string)
    )

    print(template.format('Alexander:',
        re.sub(ur"(?<=[aeiou]):(?=[aeiou]([^aeiou]*[aeiou]){2}[^aeiou]*$)", ur'', string, flags=re.I)
    ))

    print(template.format('lonut:',
        re.sub(ur"([aeiou]):([aeiou])([^\Waeiou]*[aeiou][^\Waeiou]*[aeiou][^\Waeiou]*)$", ur'\1\2\3', string, flags=re.I)
    ))

    print(template.format('Tom Zych:',
        re.sub(r'([^aeiou]*[aeiou][^aeiou]*):((?:[^aeiou]*[aeiou]){3}[^aeiou]*)$', r'\1\2', string, flags=re.I)
    ))

    print(template.format('Jeff Y:',
        re.sub(ur"([aeiou]):(([aeiou][^aeiou]*){3})$", ur'\1\2', string, flags=re.I)
    ))

    print(template.format('7stud:',
        re.sub(pattern, r'\1\2', string, count=1, flags=re.X|re.I)
    ))

    print("\n")

       original: wE:aanyoh
     Alexander:: wEaanyoh
         lonut:: wEaanyoh
      Tom Zych:: wEaanyoh
        Jeff Y:: wEaanyoh
         7stud:: wEaanyoh

       original: hirU:atghigu
     Alexander:: hirUatghigu
         lonut:: hirUatghigu
      Tom Zych:: hirUatghigu
        Jeff Y:: hirUatghigu
         7stud:: hirUatghigu

       original: yO:ubeki
     Alexander:: yOubeki
         lonut:: yOubeki
      Tom Zych:: yOubeki
        Jeff Y:: yOubeki
         7stud:: yOubeki

       original: xE:aaa
     Alexander:: xEaaa
         lonut:: xEaaa
      Tom Zych:: xEaaa
        Jeff Y:: xEaaa
         7stud:: xEaaa

       original: xx:aaa
     Alexander:: xx:aaa
         lonut:: xx:aaa
      Tom Zych:: xx:aaa
        Jeff Y:: xx:aaa
         7stud:: xx:aaa

       original: xa:aaaxA:aaa
     Alexander:: xa:aaaxAaaa
         lonut:: xa:aaaxAaaa
      Tom Zych:: xa:aaaxAaaa
        Jeff Y:: xa:aaaxAaaa
         7stud:: xa:aaaxAaaa

       original: xa:aaaxA:aaaxx
     Alexander:: xa:aaaxAaaaxx
         lonut:: xa:aaaxAaaaxx
      Tom Zych:: xa:aaaxAaaaxx
        Jeff Y:: xa:aaaxAaaaxx
         7stud:: xa:aaaxAaaaxx

       original: xa:aaaxA:aaxax
     Alexander:: xa:aaaxAaaxax
         lonut:: xa:aaaxAaaxax
      Tom Zych:: xa:aaaxAaaxax
        Jeff Y:: xa:aaaxAaaxax
         7stud:: xa:aaaxAaaxax

       original: a:aaaxA:aaxax
     Alexander:: a:aaaxAaaxax
         lonut:: a:aaaxAaaxax
      Tom Zych:: a:aaaxAaaxax
        Jeff Y:: a:aaaxAaaxax
         7stud:: a:aaaxAaaxax

       original: e:aeixA:aexix
     Alexander:: e:aeixAaexix
         lonut:: e:aeixAaexix
      Tom Zych:: e:aeixAaexix
        Jeff Y:: e:aeixAaexix
         7stud:: e:aeixAaexix


text:
Q: How to use cron, PHP and MySQL code to delete records with multiple search terms I'm in a deep s**t and need help from smart fellows like you.
Here is some info about software and technologies I use: cPanel, Linux server, phpMyAdmin, MySQL.
I need to delete some records from a table on a daily basis. I do it normally by using Select statement on phpMyAdmin and then delete all the records.
*
Select `user_id` FROM `user`
WHERE EXISTS ( SELECT `user_id`
FROM `userinfo`
WHERE `essay` like '% yahoo %' AND user.user_id = userinfo.user_id)

*
The above code basically searches for specific words in userinfo table and displays their corresponding user_id in user table, which I then delete manually. In this particular case the search term is 'yahoo'. I search for all the users who have the word 'yahoo' in their profile's essay and delete them from user table.
The problem is I've got way too many search terms to do it manually.
I would love to have it written in php file and run through cron if it's possible. Would be nice to have a field or fields on php file where I would type all possible search words/phrases then the code would execute all of them one after another.
I've heard it's possible to use cron jobs for that, read some articles about them but have absolutely no idea how to handle it.
Your help would be much appreciated and please tell me if it's unclear.
Regards,
Igor

A: This should at least get you started. Keep in mind I don't know the structure of your DB so you may have to change some things. Also this is by FAR not the most efficient way to do it, but it is easy to follow, you can do this in a single MySQL query instead of looping  over each user id (which I show an untested example of see ---faster way---), but again I don't know about your DB structure so you'll have to play with it, plus this way does exactly what you do now, one at a time so hopefully it's easier to follow and you can mod it to be more efficient later. Backup your db before playing with this.
PHP script to do what you want:
<?php
//put your search terms in this array
$search_terms = array('yahoo', 'google', 'bing');

//conenct to your DB
$db_conn = mysql_connect('yourdbhost', 'yourdbuser', 'yourdbpassword');
mysql_select_db('yourdbname', $db_conn);

//query the db for each search term
foreach($search_terms as $search_term) {
    //----slow but clear way----
    $result = mysql_query("SELECT user_id
                        FROM user
                        WHERE EXISTS (
                            SELECT user_id
                            FROM userinfo
                            WHERE essay like '%{$search_term}%'
                            AND user.user_id = userinfo.user_id)", $db_conn);

    //for eachr user id returned, delete them from your users table
    //as you would have done manually. I don't know about your users
    //table so you will have to edit this query as you see fit.
    while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $user_del_result = mysql_query("DELETE FROM user
                                        WHERE user_id = {$row['user_id']}
                                        LIMIT 1", $db_conn);
        //might want to check here to see if the query executed successfully
    }

    //----faster way----
    $result = mysql_query("DELETE FROM user
                            WHERE EXISTS (
                            SELECT user_id
                            FROM userinfo
                            WHERE essay like '%{$search_term}%'
                            AND user.user_id = userinfo.user_id)", $db_conn);
}
?>

To call it periodically you need to have a look at cron jobs (read this) and then just call the PHP script periodically with something like this in your crontab (this would run once per day at midnight for instance):
0 0 * * *   /path/to/php-cli /path/to/the/above/php/file.php

A: Deep s**t is never a good place to be...
If you're set on using a PHP script, then you can do this using crontab. Perhaps, at it's most basic, your best bet is to write a PHP script that can be executed using cron:
<?php

  $DB_hostname = "localhost";
  $DB_name     = "someDB";
  $DB_username = "someUser";
  $DB_password = "guessmeifyoucan";

  $connection = mysql_connect($DB_hostname, $DB_username, $DB_password) or die(mysql_error());
  mysql_select_db($DB_name, $connection) or die(mysql_error());

  $delete_query = "DELETE from `user`
                   WHERE EXISTS ( SELECT `user_id` FROM `userinfo`
                   WHERE `essay` like '%yahoo%' AND user.user_id = userinfo.user_id)";

  $result = mysql_query($delete_query) or die(mysql_error());

?>

For the sake of sanity, I would however suggest logging any deletions to a file or using a live/dead flag in your DB. Wildcard string matches are dangerous and you may be better off using a DB flag (either live/dead or '0'/'1') - unless there is no need for comeback.
You could then set and execute this using the crontab. cPanel provides the ability to run cron scripts, but you can also achieve the same using CLI/shell:
1.crontab -e (using your editor of choice)
2. set 0 6 * * * php /path/to/script.php (for 6:00am daily)
The following format is used within the crontab (presuming you're using some flavour of linux):
Minutes [0-59]
|   Hours [0-23]
|   |   Days [1-31]
|   |   |   Months [1-12]
|   |   |   |   Days of the Week [Numeric, 0-6]
|   |   |   |   |
*   *   *   *   * php /path/to/script.php

There are other commands, options and outputs, but this is the most basic implementation. You can find further more detailed cron usage here.
You can also do this using a query.sql file if needs be and executing it using MySQL on the CLI.

A: For the purpose you are using the script I don't think you even need to use PHP. If I had to do something like this I would probably do the following:
Create a MySQL script script.sql as follows:
USE `database_name`;

DELETE A.* FROM `userinfo` A
INNER JOIN `user` B
ON A.user_id = B.user_id
AND (
    A.essay LIKE '% yahoo %'
    OR
    A.essay LIKE '% google %'
    OR
    A.essay LIKE '% microsoft %'
);

Then I would setup a cron job as follows:

*

*Open the shell and enter crontab -e to edit your cron file. This should open a vi editor instance (you should know how to use vi).

*Add a daily schedule entry to your cron file 0 2 * * *       mysql -u{user} -p{password} {db_name} < {path of script.sql}. This will run your script daily at 2:00am.

*Save the file and exit

Whenever you need to modify or add search terms just modify and use the line A.essay LIKE '% microsoft %' as per your needs.

A: Change select user_id from user to be delete from user and leave the rest of the statement exactly the same.
Be sure to back up your users table before doing this..
Once you've verified that the SQL functions how you want it to, you need to write a small PHP script that sends that SQL to MySQL, and have cron run that script once per day.

A: Your best bet is to start off by creating a PHP Script that will connect to MySQL and do what you're wanting. After that you can then look into Crons and how they work. Essentially it will kick off a script for you on a specified cadence. cPanel has a special section that let's you scheduled Crons.


text:
Q: how to get PSTricks QR codes to handle tildes properly? I am getting bitten by the same problem from one of my previous questions: tildes are not handled properly. But now it's the PSTricks QR code package that's not working, and none of the suggestions from the other question are working. Here's an example:
\documentclass{article}
\usepackage{pstricks}
\usepackage{pst-barcode}
\begin{document}
\begin{pspicture}(2cm,2cm)
\psbarcode{http://example.com/~user}{}{qrcode}
\end{pspicture}
\end{document}

When I put the result into a QR decoder, I get
http://example.com/protect unhbox voidb@x penalty @M  {}user

...which is exactly the problem I had before. But neither \textasciitilde nor \~ works; both insert weird extra bits into the file.
I can work around this instance by using a URL shortener, but really I'd like to know how to teach PSTricks the same tilde-handling magic that hyperref knows.

A: \psbarcode{http://example.com/\string~user}{}{qrcode}
\string makes the active character ~ to an inactive one.


text:
Q: Pop up window using HTML When the button is clicked, I want to ask a series of messages and give the user a secondary confirmational option. However it doesn't work.

Close the page to trigger the onunload event.

    <button onClick='function;'> </input>

A: Just add the "e" inside the function() and the variable changes.
Before: window.onbeforeunload = function() {
After: window.onbeforeunload = function(e) {

Close the page to trigger the onunload event.

    <button onClick='window.close();'> </input>


text:
Q: How to build a confusion matrix? I have the following code, that plots nested vs non-nested cross-validations of a KNN algorithm.
# Number of random trials
NUM_TRIALS = 30

# Load the dataset

X_iris = X.values
y_iris = y

# Set up possible values of parameters to optimize over
p_grid = {"n_neighbors": [1, 5, 10]}

# We will use a Support Vector Classifier with "rbf" kernel
svm = KNeighborsClassifier()

# Arrays to store scores
non_nested_scores = np.zeros(NUM_TRIALS)
nested_scores = np.zeros(NUM_TRIALS)

# Loop for each trial
for i in range(NUM_TRIALS):

    # Choose cross-validation techniques for the inner and outer loops,
    # independently of the dataset.
    # E.g "GroupKFold", "LeaveOneOut", "LeaveOneGroupOut", etc.
    inner_cv = KFold(n_splits=4, shuffle=True, random_state=i)
    outer_cv = KFold(n_splits=4, shuffle=True, random_state=i)

    # Non_nested parameter search and scoring
    clf = GridSearchCV(estimator=svm, param_grid=p_grid, cv=inner_cv)
    clf.fit(X_iris, y_iris)
    non_nested_scores[i] = clf.best_score_

    # Nested CV with parameter optimization
    nested_score = cross_val_score(clf, X=X_iris, y=y_iris, cv=outer_cv)
    nested_scores[i] = nested_score.mean()

score_difference = non_nested_scores - nested_scores

preds=clf.best_estimator_.predict(X_test)
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, preds)
one, two, three, four,five,six,seven,eight,nine = confusion_matrix(y_test, preds).ravel()

The problem that I have is with the confusion matrix plotting, I encountered this following error :
ValueError                                Traceback (most recent call last)
<ipython-input-22-13536688e18b> in <module>()
     45 from sklearn.metrics import confusion_matrix
     46 cm = confusion_matrix(y_test, preds)
---> 47 one, two, three, four,five,six,seven,eight,nine = confusion_matrix(y_test, preds).ravel()
     48 cm = [[one,two],[three,four],[five,six],[seven,eight],[nine,eight]]
     49 ax= plt.subplot()

ValueError: too many values to unpack (expected 9)

I am not sure how to fix this.
I have 9 target variables in my data set, stored in y.
[11 11 11 ... 33 33 33] #the target variables being : 11,12,13,21,22,23,31,32,33

And this is the head of my feature data set:
     Duration  Grand Mean  Max Mean Activation
0           64  136.772461           178.593750
1           67  193.445196           258.515625
2           67  112.382929           145.765625

A: The confusion matrix is built by "cm = confusion_matrix(y_test, preds)", where cm is 9x9 matrix (because you have 9 different labels in target variable). If you want to plot it you can use plot_confusion_matrix function. There is no need to ravel it. If you ravel it, the  9x9 matrix gets converted into 81 values and you are unpacking it to 9 variables on the left side of the assignment. That is the reason you are getting "too many values to unpack (expected 9)" error.


text:
Q: how to optimize the media-query styles I am repearting the styles in my media-query test but don't know how to optimize the sytles without repeating the same styles.
here is my sample styles
@media screen and  (min-width: 1261px) and  (max-width: 1340px)  {
    .wishlist-wrap {width:24.5245901639%}
    .info-wrap {width:24.262295081%}
    .meta-menu-wrap {width:28.86885245%}
    .nav-head > ul > li {padding-right:1.8823529411%;}
}

@media screen and  (min-width: 1211px) and  (max-width: 1260px)  {
    .wishlist-wrap {width:20.5245901639%}
    .info-wrap {width:25.262295081%}
    .nav-head > ul > li {padding-right:2.8823529411%;}
    .meta-menu-wrap {width:30.86885245%}
}

@media screen and  (min-width: 1181px) and  (max-width: 1210px)  {
    .wishlist-wrap {width:20.5245901639%}
    .info-wrap {width:26.262295081%}
    .nav-head > ul > li {padding-right:2.8823529411%;}
    .meta-menu-wrap {width:30.86885245%}
}

@media screen and  (min-width: 1080px) and  (max-width: 1180px)  {
    .wishlist-wrap {width:20.5245901639%}
    .info-wrap {width:28.262295081%}
    .logo-wrap {width:14.68852459%;}
    .meta-menu-wrap {width:30.86885245%}
    .nav-head > ul > li {padding-right:2.0823529411%;font-size:13px}
    .panel-primary { padding: 6px 36px 10px 20px;}
}

A: You can set it up like so
CSS
normal css

media querys (use max-width only, don't limit it to a min - max) {
    // override what you need to only
}
media querys {
    // override what you need to only
}

for example you have
.meta-menu-wrap {width:30.86885245%}

repeated a few times, if you just defined this at a max-width of xxx and not limit it to a range, then you would not need to define it again for smaller screens until you need to change it again
.meta-menu-wrap { width:28.86885245% }

@media screen and (max-width: 1260px)  {
    .meta-menu-wrap { width:30.86885245% }
}

@media screen and (max-width: 1210px)  {
    // no need to do it again here
}

@media screen and (max-width: 1180px)  {
    // no need to do it here
}

Also your percents are quite precise however the actual calculated pixels will differ from browser to browser. Nothing wrong with it but just a note.

A: As Huangism said you should provide the base style outside the @media-querys and online override the necessary styles in them.
Besides that you could take a look at http://lesscss.org/ or http://sass-lang.com/ they both allow to define variables and function-like elements and allow to use mathematic formula to calculate sizes. This helps to structure your css and is pretty easy to learn.
short less example:
.insertWidths(@size){
   .wishlist-wrap { width: **formula_dependent_on_size** }
   .info-wrap { ... }
   .nav-head > ul > li { ... }
   .meta-menu-wrap { ... }
}

@media screen and (max-width: 1260px)  {
   .insertWidths(1260);
}

@media screen and (max-width: 1210px)  {
    .inserWidths(1210);
}

@media screen and (max-width: 1180px)  {
    .inserWidths(1180)
}

Hope that helps, best regards
Ludwig


text:
Q: Automatically login and retry the original request when there is 401 error code in java I am using Apache HttpClient to consume the API calls.
We are getting sign in token using login API call and using this token as header parameter in all other API calls.
This signin token will expire after some time then subsequent API calls will return 401 unauthorized error.
I want Apache HttpCleint can detect 401 errors and automatically sign in and retry the original API call.
By googling I found the link which is exactly my requirement.
Automatically retry on 401 and send specific request with HttpClient 4.3
I can not use OkHttpClient as suggested here, but the other solution which is suggested here is that write a Proxy class over HttpClient that captured "execute" method result.
I don't have an idea on how to do this.
Can anyone please help me on this.

A: You can have a class like MyHttpClient in your code that implements the HttpClient interface. It can use the decorator pattern, which means it will have an internal instance of the real HttpClient class and delegate almost all its method calls to that class.
public class MyHttpClient implements HttpClient {
    private HttpClient httpClient;
    private String signinToken = ""

    public MyHttpClient() {
        this.httpClient = HttpClient5Factory.createHttpClient();
        this.signinToken = SigninTokenProvider.getToken();
    }

    @Override
    public HttpParams getParams() {
        return this.httpClient.getParams();
    }

    @Override
    public ClientConnectionManager getConnectionManager() {
        return this.httpClient.getConnectionManager();
    }

    ...
}

You can then implement the logic to fetch the signin header in this class, or if you have it in other classes, this class can call them to refresh the signin token when needed. I think it make much more sense to add the signin header in this class so you would have the signin handling just in one place.
In the implementation of execute methods, you should have a code like this:
@Override
public HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException {

    //  add signin header to each request
    request.addHeader(new BasicHeader("Authorization", this.signinToken));

    HttpResponse response = httpClient.execute(request);
    if(response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        //  do the authentication process again
        this.signinToken = SigninTokenProvider.getToken();
        request.removeHeader("Authorization");
        request.addHeader(new BasicHeader("Authorization", this.signinToken));

        //  resend the request
        response = httpClient.execute(request);
    }

    return response;
}

As you can see, you can make a call to the actual API and check the response status. If it's 401, then you can redo the authentication process and fetch a new signin value and retry the request using the new signin value.


text:
Q: How can I get the .so file from .whl? I want to release the Django website.
and I only find the bellow link to download the .whl file:
http://www.lfd.uci.edu/~gohlke/pythonlibs/#mod_wsgi
But how can I get the mod_wsgi.so file from the .whl file?
Because some tips says the .whl contains it, the .whl file can not unZip, alright?

A: You are better off compiling it yourself. If you have Apache installed at C:/Apache24, it is a complete Apache with header files, and you are able to compile C extensions for Python when running pip, run:
pip install mod_wsgi

Then run:
mod_wsgi-express module-config

Copy the Apache directives that prints out into your Apache configuration file. That will load the mod_wsgi module and ensure it can find the Python library and installation as well.
Restart Apache to make sure it restarts, and then configure Apache/mod_wsgi to load your WSGI application.
For more details see:

*

*https://pypi.python.org/pypi/mod_wsgi


text:
Q: Sum in a mixed list of data This is an specific questions that will help me finalize an outgoing project. It's pretty simple, I'm very new to Python and my background is mostly art. I like it, but I find it very challenging too.
I have a Text file (Data.txt) that contains a list of numbers/names, like this (short example):
String 1
34.6
45.6
45.9
String 2
34.6
45.6
45.9

This is a mixed list. After every String....12 numbers follow and so on. Notice that the numbers are 'float'.
I designed this:
numberList = []
data = []
data = open("SalesData.txt").read().split()
for i in data:
        numberList.append(i)
print numberList

This will append and print all the data in the external .txt list. How can I get all that data in the new list (numberList), but excluding all the 'Strings' found through the reading of the file. This way, I can perform a total Sum of only the numbers ---

A: First, you shouldn't do .read().split() on your file - that will split on any whitespace, not just on newlines. Fortunately, Python can iterate directly over files.
Then, you could try to convert each line into a float and only append it to the list if that works (and skip it otherwise). Also, you can convert it to floats right away - makes summing it up easier.
number_list = []
with open("SalesData.txt") as myfile:
    for line in myfile:
        try:
            number_list.append(float(line))
        except ValueError:
            pass
print(sum(number_list))

A: just iterate over the lines and only add the numbers to the list ...
with open("somefile.txt") as f:
     my_list = []
     for line in f:
         try:
            my_list.append(float(line))
         except ValueError:
             pass

print sum(my_list)

A: If your data is structured (which seems to be the case), I would simply use a counter and drop the 1st element of each sequence of len 12.
Here's an example:
numberList = []
data = []
counter = 0
with open("SalesData.txt") as myfile:
    for line in myfile:
        if counter > 0:
            number_list.append(float(line))
        counter = (counter + 1) % 12
print numberList

A: try this:
tsum = []
for j in numberList:
    try: tsum.append(float(j))
    except: pass
sum = sum(tsum)

A: You could do type checking, or if the numbers are actually digits in a string, you could do something like a "13".isdigit() check but I'd probably want to do something a little  more clever:
numberList = []

for i in range(0, len(data)/13):
    numberList.append(data[1*(i+1):13*(i+1)])

That (or something like it) should target the groups of numbers after the strings. This does depend on your input data not being junk, but it should work quicker on large datasets than doing .isdigit() or other type checks.

A: import re

ss =  '''String 1
34.6
45.6
45.9
String 2
34.6
45.6
45.9

'''

print re.findall('^(?!.*?[a-zA-Z])[0-9.+-]+',ss,re.MULTILINE)

But if there can be letters whose none is ASCII, it won't work


text:
Q: why does protobufs proto3 AssignDescriptors throw std::system_error? I'm using protoc 3.19.4
message definition
syntax = "proto3";
package wibble;
option cc_enable_arenas = true;
option optimize_for = CODE_SIZE;

message Test {
  string id = 1;
  string name = 2;
}

client code capi
#include <google/protobuf/util/json_util.h>
#include <test.pb.h>

#include <string>

int main() {
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  wibble::Test msg{};
  msg.set_id("wibble");
  msg.set_name("friznit");

  std::string asJSON{};
  google::protobuf::util::JsonPrintOptions jopts{};
  jopts.add_whitespace = true;
  jopts.preserve_proto_field_names = true;
  google::protobuf::util::MessageToJsonString(msg, &asJSON,
                                              jopts);  // crashes here
  std::cout << asJSON << std::endl;

  google::protobuf::ShutdownProtobufLibrary();
}

stack trace
Program received signal SIGABRT, Aborted.
__GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
50      ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb) where
#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
#1  0x00007ffff7bf9859 in __GI_abort () at abort.c:79
#2  0x00007ffff7e82911 in ?? () from /lib/x86_64-linux-gnu/libstdc++.so.6
#3  0x00007ffff7e8e38c in ?? () from /lib/x86_64-linux-gnu/libstdc++.so.6
#4  0x00007ffff7e8e3f7 in std::terminate() () from /lib/x86_64-linux-gnu/libstdc++.so.6
#5  0x00007ffff7e8e6a9 in __cxa_throw () from /lib/x86_64-linux-gnu/libstdc++.so.6
#6  0x00007ffff7e8573f in std::__throw_system_error(int) () from /lib/x86_64-linux-gnu/libstdc++.so.6
#7  0x00005555555c2eee in void std::call_once<google::protobuf::internal::AssignDescriptors(google::protobuf::internal::DescriptorTable const* (*)(), std::once_flag*, google::protobuf::Metadata const&)::{lambda()#1}>(std::once_flag&, google::protobuf::internal::AssignDescriptors(google::protobuf::internal::DescriptorTable const* (*)(), std::once_flag*, google::protobuf::Metadata const&)::{lambda()#1}&&) ()
#8  0x00005555555c2bb9 in google::protobuf::internal::AssignDescriptors(google::protobuf::internal::DescriptorTable const* (*)(), std::once_flag*, google::protobuf::Metadata const&) ()
#9  0x000055555556b790 in wibble::Test::GetMetadata (this=0x7fffffffe600) at src/protoc/test.pb.cc:153
#10 0x00005555555c5439 in google::protobuf::Message::GetDescriptor() const ()
#11 0x00005555555f222b in google::protobuf::util::MessageToJsonString(google::protobuf::Message const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >*, google::protobuf::util::JsonPrintOptions const&) ()
#12 0x000055555556d009 in main () at src/main.cpp:29

inspection of the parameters passed to wibble::Test::GetMetadata
::PROTOBUF_NAMESPACE_ID::Metadata Test::GetMetadata() const {
  return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(
      &descriptor_table_test_2eproto_getter, &descriptor_table_test_2eproto_once,
      file_level_metadata_test_2eproto[0]);
}

(gdb) p descriptor_table_test_2eproto_getter
$2 = {const google::protobuf::internal::DescriptorTable *(void)} 0x55555556b44a <descriptor_table_test_2eproto_getter()>

(gdb) p descriptor_table_test_2eproto_once
$4 = {_M_once = 0}

(gdb) p file_level_metadata_test_2eproto
$5 = {{descriptor = 0x0, reflection = 0x0}} // suspicious?

I suspect I'm missing a library that it expects (though I've checked all the ones listed by ldd capi are present.
Thanks for your help.

A: the answer to this question helped: std::call_once
Linking with -pthread fixed the problem.


text:
Q: CSS: How to make header background transparent on Wordpress? I want to have a background image on my site. It comes from the top of the page and is only behind the header. The problem is, my theme forces me to have a background color for the header so you can't see my background image at all. Here is a photo of what I want the site to look like:

And you can see what it actually looks like here. I'm using the Brunch Pro theme on Wordpress.
Is there a way to make the header background transparent or is there a better way to do this?

A: Add this to the end of the custom.css or style.css of your theme:
.brunch-pro .site-header{
    background: transparent;
}

A: If you can edit the CSS (which I presume you can in WP), look for where .site-header has it's CSS properties set. Remove the background and background-color properties.
You could also just add a new CSS property and apply it to the header. Something like:
header.site-header {
  background: none !important;
}

The !important will override already set properties...

A: If background-color property is required, you could use rgba color and make it transparent. background: rgba(0,0,0,0); makes background-color black, but fully transparent, without opacity and other tricks. Like so:

.black-but-transaprent {
  color: red;
  height: 100px;
  width: 100px;
  background: rgba(0,0,0,0);
  border: 1px solid black;
}

Test


text:
Q: NodeJs, how to get full STDERR message displayed? please help me how I can get full error string (to pass in res.send()) from process? For example in console now I getting printed:
Child Process STDERR: src/sketch.ino: In function 'void setup()':
src/sketch.ino:17:11: error: 'led' was not declared in this scope
src/sketch.ino: In function 'void loop()':
src/sketch.ino:23:15: error: 'led' was not declared in this scope
make: *** [.build/atmega328/src/sketch.o] Error 1

But when i pass res.send('Error:\n'+ stderr);, I get printed only "Error: src/sketch.ino: In function 'voi". Why it cuts message? And how to pass full one?
This is my code:
var exec = require('child_process').exec;

var inoVerify = exec('ino build -m atmega328', { cwd: codeFile.projectPath }, function(error, stdout, stderr) {
    console.log('Child Process STDERR: '+ stderr);
    if (stderr)
        res.send('Error:\n'+ stderr);
});

A: This is some exec limitatio.
I changed this sample to use spawn proces instead like so:
var spawn = require('child_process').spawn;

var inoVerify    = spawn('ino', ['build', '-m', 'atmega328'], { cwd: codeFile.projectPath });

inoVerify.stdout.on('data', function (data) {
  console.log('stdout: ' + data);
});

inoVerify.stderr.on('data', function (data) {
  console.log('stderr: ' + data);
  res.end('stderr: ' + data);
});

inoVerify.on('close', function (code) {
  console.log('child process exited with code ' + code);
});

By example from  http://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options


text:
Q: How to change Text color of push notification in iOS In this image i want to change the color of the push notification TEXT from white to black or any other color.

need help with coding part or any documentation.
I want this type of solution in which text color is black


text:
Q: How can I avoid an error during loading a module to handle open()? I'm trying to load the following code:
#include <linux/module.h>
#include <linux/kernel.h>
#include <sys/syscall.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <asm/uaccess.h>

extern void *sys_call_table[];
int (*orig_open)(const char *pathname, int flag, int mode);

int own_open(const char *pathname, int flag, int mode)
{
    char *kernel_path;
    char hide[]="test.txt";

    kernel_path=(char *)kmalloc(255,GFP_KERNEL);
    copy_from_user(kernel_path, pathname, 255);

    if(strstr(kernel_path,(char *)&hide) != NULL) {

    kfree(kernel_path);
    return -ENOENT;
    }

    else {

    kfree(kernel_path);
    return orig_open(pathname, flag, mode);
    }
}
int init_module()
{
    orig_open=sys_call_table[SYS_open];
    sys_call_table[SYS_open]=own_open;
    return 0;
}

void cleanup_module()
{
    sys_call_table[SYS_open]=orig_open;
}

but as a result I got the errors:
sys_open_call.c:34:30: error: '__NR_open' undeclared (first use in this function)
     orig_open=sys_call_table[SYS_open];
                              ^

sys_open_call.c: In function 'cleanup_module':
sys_open_call.c:41:20: error: '__NR_open' undeclared (first use in this function)
     sys_call_table[SYS_open]=orig_open;
                    ^

make: *** [sys_open_call.o] Error 1

How can I declare it?


text:
Q: iterate over array hold inside private property I have the 'Article' class with the private property words which holds and array of Word class objects. I also have getWord method which can return one word:
class Article {
    private $words = Array(1 => new Word(1), 2 => new Word(2), ...);

    public function getWord($wordId) {
        if (array_key_exists($wordId, $this->words)) {
            return $this->words[$wordId];
        } else {
            return NULL;
        }
    }
}

I need to iterate through all exising words. What is the best way to do that?
Currently I'm returning all words as array using another method, but I don't think that is a good option.

A: Your solution is the best an cleanest one. Making getters for private Properties is widely accepted in the OOP. See this stackoverflow entry
A getter looks like this:
public function getWords() {
  return $this->words;
}

If you would that every class can access AND edit the property you can also make it a public property. But as I understand your code other classes and methods should have read only access to this property, so a getter is the definitive best solution.
If you only want to expose some specific word objects of your property then the method would look like:
public function getFilteredWords($param) {
  $tmpWords = array();

  foreach($this->words as $w) {
    if(/*word NOT matches your filter criteria ($param)*/)
      continue;

    $tmpWords[] = $w;
  }

  return $tmpWords;
}

A: If you want to iterate over an Article object, accessing all Word objects, you should implement either the Iterator interface, or IteratorAggregate.
If this is done, iterating would be as easy as this:
foreach ($article as $word) {
    // do stuff with Word object here
}

The easiest way would be to convert your existing getWords method. You could add a new method getIterator as required by the IteratorAggregate interface and implement it like this:
public function getIterator() {
    return new ArrayIterator($this->getWords());
}

If you want to get rid of getWords(), you could also pass the internal array directly.


text:
Q: i dont why it isnt printing the linked list this is my code for inserting a node at the head of the linked list. there is no error but my printllist function is not working I don't know why. I think I have done silly somewhere. help me out I am stuck here for 3 hours.
#include <iostream>
#include <bits/stdc++.h>

using namespace std;
  class Node
   {   public:
       int data;
       Node* next;
   };

void insert(int y,Node* head){

   Node *temp=new Node();
   temp->data=y;
   temp->next=head;
   head=temp;

}

void printllist(Node *head){

   if(head=NULL)
   {
      cout<<"list is empty"<<endl;
   }
   else
   {
      while(head!=NULL)
      {
         cout<<head->data<<" ";
         head=head->next;
      }
   }

}

int main(){

   Node *head;
   head=NULL;
   int x,y,z;

   cout<<"hey can you tell me how many number you want to insert"<<endl;
   cin>>x;
   for(int i=0;i<x;i++)
   {
      cout<<"enter the data that you want to insert"<<endl;
      cin>>y;
      insert(y,head);
      printllist(head);
   }

   return 0;
}

A: You need to pass the head of the linked list by reference so that the changes which are made in the insert function actually remain preserved between the function calls. Also, keep in mind that all the new nodes are inserted at the beginning of the linked list. So, for example if you enter 1,2,3 as the three elements of the linked list, the print function will print 3 2 1.
Try this:
#include <iostream>
#include <bits/stdc++.h>

using namespace std;
  class Node
   {   public:
       int data;
        Node* next;
   };
void insert(int y,Node** head){

Node* temp = new Node();
    temp->data = y;
    temp->next = *head;
    *head = temp;
}
void printllist(Node* head)
{
    if(head==NULL)
        cout<<"List is empty";
    while(head!=NULL)
    {
       cout<<head->data<<" ";
       head=head->next;
    }
}

int main(){

Node *head;
head=NULL;
int x,y,z;
  cout<<"hey can you tell me how many number you want to insert"<<endl;
  cin>>x;
  for(int i=0;i<x;i++)
  {   cout<<"enter the data that you want to insert"<<endl;
 cin>>y;
 insert(y,&head);
}
printllist(head);

return 0;
}


text:
Q: Need to add multiple application insights results in one query is it possible to get the query to summarize from multiple Application insights? I cant get it working with Union command.
Example query:

union
app("applicationinsight02").requests,
app("applicationinsight03").requests

availabilityResults
| where timestamp > ago(30d)
// check whether location failed within 5m bin
| summarize _failure=iff(countif(success == 0)>0, 1, 0) by name, location, bin(timestamp, 5m)
// check whether all locations failed within 5m bin
| summarize _failureAll=iff(sum(_failure)>=3, 1, 0) by name, bin(timestamp, 5m)
// count all failed 5 minute bins and total number of bins
| summarize _failuresCount=sum(_failureAll), _totalCount=count() by name
| project ["Name"] = name,            ["SLA"] = todouble(_totalCount - _failuresCount) / todouble(_totalCount) * 100
| order by ["SLA"]

A: Yes, something like so
union
app("application-insights-01").requests,
app("application-insights-02").requests
| where timestamp > ago(1h)
| summarize sum(itemCount) by appName, bin(timestamp, 5m)

That will summarize the requests and show you the split by appname (the app insights resource name). Amend the where clause to fit your requirements
An example for availability results with your query would look like so, just replace application-insights-01/02 with your instance names
union
app("application-insights-01").availabilityResults,
app("application-insights-02").availabilityResults
| where timestamp > ago(1h)
| summarize _failure=iff(countif(success == 0)>0, 1, 0) by name, location, bin(timestamp, 5m)
| summarize _failureAll=iff(sum(_failure)>=3, 1, 0) by name, bin(timestamp, 5m)
| summarize _failuresCount=sum(_failureAll), _totalCount=count() by name
| project ["Name"] = name, ["SLA"] = todouble(_totalCount - _failuresCount) / todouble(_totalCount) * 100
| order by ["SLA"]


text:
Q: Bridging C++ and Swift in XCode, what are the right Build Settings? When I try to call the functions in my C++ implementation file (marked as C compatible in the header with the #ifdef __cplusplus extern "C" {} trick), I am getting the error:
"use of unresolved identifier, 'helloWorld()'"
I created the bridging header just by adding a cpp and header file to my project and clicking "OK" when it asked if I wanted to create the bridging header. I am #including "test.h" in the bridging header, which has the function declaration inside, but for some reason Swift just cannot see the function.
The weirdest part is, I created a new project and did the EXACT same procedure, and calling helloWorld() works fine, so it's something about the existing project I'm trying to add the cpp file to that isn't working.
I'm assuming then that this is a build-settings problem, and that I must have messed them up somewhere along the lines, probably when I was trying to import a static C/CPP library (Which I've since removed, but some of the build settings I changed for it probably stayed).
So are there any build settings I should know about that will fix this? Or is there a way to just completely reset my build settings to the default (Even if that means I have to recreate the bridging header to get the bridging header build settings back in place)?
Thank you for any and all help!
James
---Edit---
Here is my cpp header:

Here is my cpp implementation file:

Here is my bridging header:

Here is the relevant portion of the Swift project:

And here is the build setting that sets the bridging header:

A: Alright - This has been resolved. The problem is that the bridging header needed to be realized from both the regular target and also the Testing target, which was in my existing project because I'm doing Unit Testing.
I simply went into the build settings for my testing target and added the appropriate Objective-C Bridging Header, and then it all worked fine.
Hope it helps someone!

A: I had the same experience. Make sure you add a Unit Test Target, then ensure the Unit Test Target has visibility of the Bridging Header file.
Another mistake I made; ensure each Swift Class, Enums used in the test case has Target Membership set correctly.


text:
Q: applying gradient fill to an object on the stage ..? let's say i have this object on stage and it is called myShape and i want to manipulate it via action-script and apply a gradient color to it ..
no if it is a fill color i could have used the colortransform method but i don't think that it will work .. and please don't suggest me to draw the shape with action script .
 import flash.geom.*
 import flash.display.*
 var fillType:String = GradientType.LINEAR;
 var colors:Array = [0xFF0000, 0x0000FF];
 var alphas:Array = [1, 1];
 var ratios:Array = [0x00, 0xFF];
 var matr:Matrix = new Matrix();
 matr.createGradientBox(200, 100, 0, 0, 0);
 var spreadMethod:String = SpreadMethod.PAD;
 myShape.graphics.beginGradientFill(fillType, colors, alphas, ratios, matr, spreadMethod);

now when i test this i don't get any errors but i doesn't apply any thing ..

A: I would create a bounding rectangle Shape, fill it with the gradient and apply the object as a mask. Is it possible in your case?


text:
Q: QGIS difference operation with XYZ tiles I have a regular layer from a database containing WKT polygons. I'm also using a XYZ Tiles layer of Google Maps. I would like to perform the Vector > Geoprocessing Tools > Difference operation between the two layers, except using an XYZ Tiles layer is not a possibility in the Difference dialog box (notice no expand arrow to allow access to OpenStreetMap or gmm (Google Maps)). QGIS 3.16 being used.

A: The Difference operation is an operation that only works with vector layers (as you can see from the fact that it's located in the vector menu). You can't process any raster with that. The OpenStreetMap Layer represents raster data from raster tiles. If you want to process OpenStreetMap data with the Difference operation, you should first download OSM data in vector format. However, as you don't mention what exactely you want to achieve using the Difference operation, there are maybe other options. So I suggest to open a new question where you explain what is your final goal.
By the way: as far as I know, XYZ tiles cannot be processed at all, not even as raster. So you can't use XYZ tiles in the raster calculator. They are here just as basemaps, for orientation purpose etc.


text:
Q: I have trying to make the border of my box to point toward the side of the screen. Any suggestion? Here the demo: https://codesandbox.io/s/stupefied-hoover-i8lqd
In the demo, you can see that the borders of the control_group are pointing toward the center of the div, as in the following image:

In the test_group, I am trying to reverse the borders, as in the following image:

After reading some discussion, I have tried to use the before element in various way but I am still searching for the proper way to get the border pointing toward the side of the screen -in fact, in the reverse from the original's box-.
How can I make the border to point toward the screen?
here the ReactJS snippet:
import React from "react";
import "./styles.css";

export default function App() {
  return (

a superb reverse border

a superb reverse border

  );
}

here the CSS' snippet:
* {
  margin: 0;
  padding: 0;
}

/* control group */
.control_group {
  background: cyan;
  height: 40vh;
  width: 70%;
  margin: auto;
  margin-top: 10vh;
  margin-bottom: 20vh;
  font-family: sans-serif;
  text-align: center;

  /* flexbox just for cosmetic */
  display: flex;
  justify-content: center;
  align-items: center;
}

.control_group {
  position: relative;
  z-index: 100;
  border-left: solid 1.5vw black;
  border-right: solid 1.5vw black;
  border-radius: 1.5%;
  border-left: solid;
  border-right: solid;
  border-radius: 10px;
  border-width: 15px;
}

/* test group */
.test_group {
  position: relative;
  height: 40vh;
  width: 70%;
  margin: auto;
  margin-top: 10vh;
  margin-bottom: 20vh;
  font-family: sans-serif;
  text-align: center;
  background: yellow;

  /* flexbox just for cosmetic */
  display: flex;
  justify-content: center;
  align-items: center;
}

.test_group:before {
  content: "";
  width: 100%;
  position: absolute;
  z-index: 100;
  left: 0;
  top: 0;
  z-index: 1000;
  border-left: solid 1.5vw black;
  border-right: solid 1.5vw black;
  border-radius: 1.5%;
}

A: You can pseudo-elements :after and :before.
:before would be on the left and :after on the right. You need to add overflow: hidden to the parent element.
/* test group */
.test_group {
  position: relative;
  height: 40vh;
  width: 70%;
  margin: auto;
  margin-top: 10vh;
  margin-bottom: 20vh;
  font-family: sans-serif;
  text-align: center;
  background: yellow;
  overflow: hidden;

  /* flexbox just for cosmetic */
  display: flex;
  justify-content: center;
  align-items: center;
}
.test_group:before,
.test_group:after {
  content: "";
  width: 100%;
  position: absolute;
  top: 0;
  z-index: 1000;
  border-left: solid 12px black;
  border-right: solid 12px black;
  border-radius: 15px;
  height: 100%;
}
.test_group:before {
  left: calc(-100% - 12px);
}

.test_group:after {
  right: calc(-100% - 12px);
}

A: I would conisder a combination of radial-gradient/linear-gradient to achieve this:

.box {
  --b:20px;  /* control the border */
  --c:black; /* the color */

  width:400px;
  box-sizing:border-box;
  margin:5px;
  /*control the distance from top and bottom*/
  border-top:20px solid transparent;
  border-bottom:20px solid transparent;
  /**/
  padding:10px calc(var(--b) + 5px); /* make sure the padding is at least equal to the borders */
  background:
    radial-gradient(farthest-side at bottom right,var(--c) 98%,transparent 100%) top right   /var(--b) var(--b),
    radial-gradient(farthest-side at bottom left ,var(--c) 98%,transparent 100%) top left    /var(--b) var(--b),
    radial-gradient(farthest-side at top    right,var(--c) 98%,transparent 100%) bottom right/var(--b) var(--b),
    radial-gradient(farthest-side at top    left ,var(--c) 98%,transparent 100%) bottom left /var(--b) var(--b),
    linear-gradient(var(--c),var(--c)) left /var(--b) calc(100% - 2*var(--b)),
    linear-gradient(var(--c),var(--c)) right/var(--b) calc(100% - 2*var(--b)),
    yellow;
  background-repeat:no-repeat;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse suscipit quam eu nisi convallis aliquam. Donec non fringilla massa. Praesent malesuada leo lorem, non fermentum nulla auctor bibendum. Cras eget vestibulum ipsum. Nullam iaculis auctor odio id condimentum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse suscipit quam eu nisi convallis aliquam. Donec non fringilla massa. Praesent malesuada leo lorem, non fermentum nulla auctor bibendum. Cras eget vestibulum ipsum. Nullam iaculis auctor odio id condimentum. malesuada leo lorem, non fermentum nulla auctor bibendum. Cras eget vestibulum ipsum. Nullam iaculis auctor odio id condimentum.malesuada leo lorem, non fermentum nulla auctor bibendum. Cras eget vestibulum ipsum. Nullam iaculis auctor odio id condimentum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse suscipit quam eu nisi convallis aliquam. Donec non fringilla massa. Praesent malesuada leo lorem, non fermentum nulla auctor bibendum. Cras eget vestibulum ipsum. Nullam iaculis auctor odio id condimentum. malesuada leo lorem, non fermentum nulla auctor bibendum. Cras eget vestibulum ipsum. Nullam iaculis auctor odio id condimentum.malesuada leo lorem, non fermentum nulla auctor bibendum. Cras eget vestibulum ipsum. Nullam iaculis auctor odio id condimentum.

Use a different color for each gradient to understand the puzzle:

.box {
  --b:20px;  /* control the border */

  width:400px;
  box-sizing:border-box;
  margin:5px;
  /*control the distance from top and bottom*/
  border-top:20px solid transparent;
  border-bottom:20px solid transparent;
  /**/
  padding:10px calc(var(--b) + 5px); /* make sure the padding is at least equal to the borders */
  background:
    radial-gradient(farthest-side at bottom right,red 98%,transparent 100%) top right   /var(--b) var(--b),
    radial-gradient(farthest-side at bottom left ,blue 98%,transparent 100%) top left    /var(--b) var(--b),
    radial-gradient(farthest-side at top    right,green 98%,transparent 100%) bottom right/var(--b) var(--b),
    radial-gradient(farthest-side at top    left ,purple 98%,transparent 100%) bottom left /var(--b) var(--b),
    linear-gradient(gray,gray) left /var(--b) calc(100% - 2*var(--b)),
    linear-gradient(black,black) right/var(--b) calc(100% - 2*var(--b)),
    yellow;
  background-repeat:no-repeat;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse suscipit quam eu nisi convallis aliquam. Donec non fringilla massa. Praesent malesuada leo lorem, non fermentum nulla auctor bibendum. Cras eget vestibulum ipsum. Nullam iaculis auctor odio id condimentum.non fermentum nulla auctor bibendum. Cras eget vestibulum ipsum. Nullam iaculis auctor odio id condimentum.non fermentum nulla auctor bibendum. Cras eget vestibulum ipsum. Nullam iaculis auctor odio id condimentum.