text:
Q: Disable Dovecot pipe error message I have a server running Dovecot (VPS managed by cPanel).
I have it set to pipe all email to a certain address into a program that I wrote. The problem is that if there is an error, that is if it exits with a status other than 0, it replies to the sender with a nasty error message (including the path to the program).
I would love for those messages to go to me instead, but at the very least, disabled so that the senders never see them.


text:
Q: What is the initial number of partitions created for a dataframe? I am new to Spark. I am trying to understand the number of partitions produced by default by a hiveContext.sql("query") statement. I know that we can repartition the dataframe after it has been created using df.repartition. But, what is the number of partitions produced by default when the dataframe is initially created?
I understand that sc.parallelize and some other transformations produce the number of partitions according to spark.default.parallelism. But what about a dataframe ? I saw some answers saying that the setting spark.sql.shuffle.partitions produces the set number of partitions while doing shuffle operations like join. Does this give the initial number of partitions when a dataframe is created?
Then I also saw some answers explaining the number of partitions produced by setting
mapred.min.split.size.
mapred.max.split.size and
hadoop block size

Then when I tried to do it practically, I read 10 million records into a dataframe in a spark-shell launched with 2 executors and 4 cores per executor. When I did df.rdd.getNumPartitions, I get the value 1. How am I getting 1 for the number of partitions? isn't 2 the min number of partitions?
When I do a count on the dataframe, I see that 200 tasks are being launched. IS this due to the spark.sql.shuffle.partitions setting?
I am totally confused! can someone please answer my questions?? Any help would be appreciated. Thank you!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add a text at the end of each lines of downloaded file from mysql? Here is my code who works very well.When i call this file from browser it downloads my file in CSV format.
<?php
/* vars for export */
// database record to be exported
$db_record = 'people';
// optional where query
$where = 'WHERE 1 ORDER BY 1';
// filename for export
$csv_filename = 'exported.csv';
// database variables
$hostname = "localhost";
$user = "root";
$password = "";
$database = "db1";

// Database connecten voor alle services
mysql_connect($hostname, $user, $password)
or die('Could not connect: ' . mysql_error());

mysql_select_db($database)
or die ('Could not select database ' . mysql_error());
// create empty variable to be filled with export data
$csv_export = '';
// query to get data from database
$query = mysql_query("SELECT * FROM ".$db_record." ".$where);
$field = mysql_num_fields($query);
// create line with field names
for($i = 0; $i < $field; $i++) {
  $csv_export.= mysql_field_name($query,$i).';';
}
// newline (seems to work both on Linux & Windows servers)
$csv_export.= '
';
// loop through database query and fill export variable
while($row = mysql_fetch_array($query)) {
  // create line with field values
  for($i = 0; $i < $field; $i++) {
    $csv_export.= '"'.$row[mysql_field_name($query,$i)].'";';
  }
  $csv_export.= '
';
}
// Export the data and prompt a csv file for download
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=".$csv_filename."");
echo($csv_export);
?>

Assume that the files generated is like this:
"name", "age", "country"
"Gulizer", "21", "Kurdistan"
"Pierre", "20", "France"

What i want is retreive age again and put it at the and of each lines with some text like
"name", "age", "country", "text_added"
"Gulizer", "21", "Kurdistan", "The age of Gulizer is 21"

Is it possible?

A: I found the solution by myself and share with you
I added
echo "text_added;";

just after
for($i = 0; $i < $field; $i++) {$csv_export.= mysql_field_name($query,$i).';';}
$csv_export.= '\n';

and changed
for($i = 0; $i < $field; $i++) {
    $csv_export.= '"'.$row[mysql_field_name($query,$i)].'";';
  }
  $csv_export.= '
';
}

to
        for($i = 0; $i < $field; $i++) { $csv_export.= '"'.$row[mysql_field_name($query,$i)].'";'; }
$csv_export.= '
'.$row['age'].'years old";';
}

and finally i got this result:
text_added;name;age;country
"21 years old"; "Gulizer"; "21"; "Kurdistan"
"20 years old"; "Pierre"; "20"; "France";

exactly what i want.


text:
Q: limit string to first 5 words or first 42 characters in PHP If I have a string in PHP that is obnoxiously long string in PHP and I want to shorten it and then append something to it.
I want to shorten it to the first 6 words or 42 characters, whatever is shorter and then append a '...' to it if it was shortened.
The only case it would not be shortened and the '...' not added would be if it was originally less than 6 words or 42 characters.
How can I do this in PHP?
Logically, I would think I would split the string by white-space and then add each thing before the white-space in an array and take only the first 6 elements out of that array and write them to a new string.
Here is the code I have so far:
str_1 = 'The quick brown fox jumped over the lazy dog';
$words = explode(" ", $str_1);
$counter = 0;
str_2 = '';
foreach($words as $word){
    if($counter < 5){
        //append $words[counter] to str_2;
        counter++;
    }
    else{
        break;
    }
}

I don't know how to do the rest for character count or comparison or appending.
Does anyone have any ideas?

A: count words (assumes spaces delimit words):
$words = explode(' ', $string);
$wordCount = count($words );

count characters
$length = strlen($string);

together
if($wordCount > 5) {
    $words = array_slice($words, 0, 5);
    $string = implode(' ', $words);
    $length = strlen($string);
}
if($length > 42) {
    $string = substr($string , 0, 42);
}

A: This will give you the first 6 words, or the first n words where the total length of the words is less than 42.
$words = explode(' ', $string);
$newstring = "";
$i=0;
while (strlen($newstring . $words[$i]) <= 42) && $i < 5) {
   $newstring .= $words[$i];
}
if (strlen($string) > strlen($newstring)) $newstring .= "...";

A: This function I made seems pretty tidy:
function truncate($input, $maxWords, $maxChars)
{
    $words = preg_split('/\s+/', $input);
    $words = array_slice($words, 0, $maxWords);
    $words = array_reverse($words);

    $chars = 0;
    $truncated = array();

    while(count($words) > 0)
    {
        $fragment = trim(array_pop($words));
        $chars += strlen($fragment);

        if($chars > $maxChars) break;

        $truncated[] = $fragment;
    }

    $result = implode($truncated, ' ');

    if ($input == $result)
    {
        return $input;
    }
    else
    {
        return preg_replace('/[^\w]$/', '', $result) . '...';
    }
}

Some tests:
$str = 'The quick brown fox jumped over the lazy dog';

echo truncate($str, 5, 42); // The quick brown fox jumped...
echo truncate($str, 3, 42); // The quick brown...
echo truncate($str, 50, 30); // The quick brown fox jumped over the...
echo truncate($str, 50, 100); // The quick brown fox jumped over the lazy dog

It won't cut words in half either, so if a word pushes the character count over the supplied limit, it will be ignored.

A: $string = "Your Text Here";
$string_length = 80; // give a random character value including whitespace.
if(strlen($string)>$string_length){
do{
    $new_string = substr($string,0,$string_length);
    $string_length++;
    }while(ctype_graph(substr($new_string,-1)));
  }
else {
   $new_string = $string;
}

echo $new_string;


text:
Q: SQL Server constraint on delete I created this table:
CREATE TABLE OfficialEmployee
(
    EID Integer not null foreign key references Employee(EID),
    StartWorkingDate date not null ,
    Degree char(20) not null,
    Department char(50) not null,
    DID Integer not null foreign key references Department(DID)
);

which references the table Employee by the DID:
CREATE TABLE Employee
(
    EID Integer not null PRIMARY KEY,
    FirstName char(30) not null,
    LastName char(30) not null,
    BirthDate date not null,
    CellPhoneNumber Integer not null,
    City char(30) not null,
    StreetName char(30) not null,
    Number Integer not null,
    Door Integer not null
);

CREATE TABLE Department
(
    DID Integer not null PRIMARY KEY,
    Name char(30) not null,
    Description char(200) not null,
    Manage Integer not null FOREIGN KEY REFERENCES OfficialEmployee(EID)
);

and I want to make a constraint that when OfficialEmployee is deleted, the record of his in Employee will be deleted too only if he is not a manager (in the Department table) else it will (using cascade).
How can I do that?
(I'm using SQL Server)

A: Assuming that the description you want to avoid is 'Manager', here is a simple trigger.
CREATE TRIGGER deleteEmployeeTrigger
ON dbo.OfficialEmployee
FOR DELETE
AS
    DELETE FROM dbo.Employee
    WHERE EID IN (SELECT deleted.EID FROM deleted)
      AND NOT EXISTS (SELECT * FROM Department
                      WHERE Manage = deleted.EID AND Description = 'Manager')

A: In SQL Server, you have to remember that deleted (and inserted can have more than one record.
So, do this using JOIN:
CREATE TRIGGER deleteEmployeeTrigger
ON dbo.OfficialEmployee
FOR DELETE AS
BEGIN
    DELETE e
        FROM dbo.Employee e JOIN
             dbo.deleted dd
             ON e.EID = dd.EID LEFT JOIN
             dbo.department d
             ON d.manage = dd.EID
    WHERE d.manage IS NULL;
END;


text:
Q: Spring-Boot Quartz Job is not running I just started to create Quartz Scheduled Jobs in a dynamic way. So there is a QuartzConfig class where I create a SchedulerFactoryBean, JobDetailFactoryBean and CronTriggerFactoryBean. Wherein the Job and CronTrigger beans are prototype ones.
@Configuration
public class QuartzConfig {

    @Autowired
    ApplicationContext context;;

    @Bean
    public SchedulerFactoryBean quartzScheduler(){
        SchedulerFactoryBean quartzScheduler = new SchedulerFactoryBean();
        quartzScheduler.setOverwriteExistingJobs(true);
        quartzScheduler.setSchedulerName("job-scheduler");
        AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
        jobFactory.setApplicationContext(context);
        quartzScheduler.setJobFactory(jobFactory);
        return quartzScheduler;
    }

    @Bean
    @Scope(value = "prototype")
    public JobDetailFactoryBean getJobBean(){
        JobDetailFactoryBean bean = new JobDetailFactoryBean();
        bean.setJobClass(DailyJob.class);
        bean.setGroup("daily-group");
        bean.setName("daily-name");
        bean.setBeanName("daily-name");
        bean.getJobDataMap().put("daily", "daily");
        return bean;
    }

    @Bean
    @Scope(value = "prototype")
//    @Lazy(value = true)
    public CronTriggerFactoryBean getCronTriggerBean(String cron){
        CronTriggerFactoryBean bean = new CronTriggerFactoryBean();
        bean.setCronExpression(cron);
        bean.setJobDetail(getJobBean().getObject());
        bean.setGroup("daily-group");
        return bean;
    }
}

In my Controller class I want to create the jobs by request. I autowire SchedulerFactoryBean to set the quartz trigger to the bean.
@Controller
public class JobController {

    @Autowired
    SchedulerFactoryBean quartzScheduler;

    @Autowired
    ApplicationContext context;;

    @ResponseBody
    @RequestMapping("/job/create/daily")
    public String dailyJob(){
        CronTriggerImpl cron = (CronTriggerImpl) context.getBean("getCronTriggerBean","30 * * ? * MON-FRI");
        Trigger[] triggers = { cron };
        quartzScheduler.setTriggers(triggers);
        return "dailyJob";
    }
}

Everything works without creating an error and the Job and the Trigger are set to the quartzScheduler (see it in debug mode). But the Job is never running. What do I miss?
And dont to forget, there is a class which implements Job:
@Component
public class DailyJob implements Job{

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("Daily Job runs!");
    }
}

A: Try addding "@EnableScheduling" to your configuration

A: Here is what worked for me:
@Controller
public class JobController {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private ApplicationContext context;

    @ResponseBody
    @RequestMapping("/job/create/daily")
    public String dailyJob() throws SchedulerException {
        JobDetail jobDetail = context.getBean(JobDetail.class);
        Trigger cronTrigger = context.getBean(Trigger.class, "30 * * ? * MON-FRI");

        scheduler.scheduleJob(jobDetail, cronTrigger);

        return "dailyJob";
    }
}

You have to use Scheduler instead of SchedulerFactoryBean as the purpose of the latter is to create the actual scheduler that will operate on jobs.
Also if you use scheduler.scheduleJob(cron) it woun't schedule the job because it isn't in the job store yet, so you'll need to create a job using it's details and associate cron expression with it.


text:
Q: Is there a way to disable automatic JSON PATCH application in Wildfly when using HTTP-PATCH Resources in JAX-RS on Wildfly (tested with 14 and 18), some automagic happens that calls the same resource path using GET, applies the changes from the JSON-PATCH and calls the actual method with the result.
$ curl localhost:8080/so/auto/Bob -H 'Content-Type: application/json-patch+json' -X PATCH -d '[{"op":"replace","path":"/age","value":24}]' -v
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> PATCH /so/auto/Bob HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.64.1
> Accept: */*
> Content-Type: application/json-patch+json
> Content-Length: 43
>
* upload completely sent off: 43 out of 43 bytes
< HTTP/1.1 200 OK
< Connection: keep-alive
< Transfer-Encoding: chunked
< Content-Type: application/json
< Date: Tue, 26 Nov 2019 12:45:51 GMT
<
* Connection #0 to host localhost left intact
{"age":24,"name":"Bob"}

Is there a way to disable this behaviour (to make #patchManual work)?
$ curl localhost:8080/so/manual/Bob -H 'Content-Type: application/json-patch+json' -X PATCH -d '[{"op":"replace","path":"/age","value":24}]' -v
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> PATCH /so/manual/Bob HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.64.1
> Accept: */*
> Content-Type: application/json-patch+json
> Content-Length: 43
>
* upload completely sent off: 43 out of 43 bytes
< HTTP/1.1 400 Bad Request
< Connection: keep-alive
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 41
< Date: Tue, 26 Nov 2019 12:42:58 GMT
<
* Connection #0 to host localhost left intact
not a json patch: {"name":"Bob","age":24}

Code to reproduce the issue:
package so;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonPatch;
import javax.json.JsonStructure;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PATCH;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

@Path( "/" )
public class MyPatchResource
{
    public static class Data
    {
        public String name;
        public int    age;
    }

    @GET
    @Produces( MediaType.APPLICATION_JSON )
    @Path( "auto/{name}" )
    public Data read( @PathParam( "name" ) String name )
    {
        Data result = new Data();
        result.name = name;
        result.age = 42;
        return result;
    }

    @PATCH
    @Path( "auto/{name}" )
    @Consumes( MediaType.APPLICATION_JSON_PATCH_JSON )
    @Produces( MediaType.APPLICATION_JSON )
    public Data patchAuto( Data patched )
    {
        return patched;
    }

    @PATCH
    @Path( "manual/{name}" )
    @Consumes( MediaType.APPLICATION_JSON_PATCH_JSON )
    @Produces( MediaType.APPLICATION_JSON )
    public JsonObject patchManual( @PathParam( "name" ) String name, JsonStructure patch )
    {
        if ( !(patch instanceof JsonArray) )
        {
            throw new WebApplicationException( Response.status( Status.BAD_REQUEST )
                    .type( MediaType.TEXT_PLAIN )
                    .entity( "not a json patch: " + patch )
                    .build() );
        }

        JsonPatch jsonPatch = Json.createPatch( patch.asJsonArray() );
        JsonObject original = readManual( name );

        return jsonPatch.apply( original );
    }

    @GET
    @Path( "manual/{name}" )
    @Produces( MediaType.APPLICATION_JSON )
    public JsonObject readManual( @PathParam( "name" ) String name )
    {
        return Json.createObjectBuilder()
                .add( "name", name )
                .add( "age", 42 )
                .build();
    }
}

A: So I kind of found a solution...
1) Define a custom http method
@Target( { ElementType.METHOD } )
@Retention( RetentionPolicy.RUNTIME )
@HttpMethod( "JSONPATCH" )
@Documented
public @interface JSONPATCH
{}

2) Use the method in the business resource
-    @PATCH
+    @JSONPATCH
    @Path( "manual/{name}" )
    @Consumes( MediaType.APPLICATION_JSON_PATCH_JSON )
    @Produces( MediaType.APPLICATION_JSON )
    public JsonObject patchManual( @PathParam( "name" ) String name, JsonStructure patch )

3) create a prematching ContainerRequestFilter that moves PATCH requests to JSONPATCH
@Provider
@PreMatching
public class JsonPatchEnableFilter implements ContainerRequestFilter
{
    @Override
    public void filter( ContainerRequestContext ctx ) throws IOException
    {
        if ( ctx.getMethod().equals( HttpMethod.PATCH )
                && MediaType.APPLICATION_JSON_PATCH_JSON_TYPE.isCompatible( ctx.getMediaType() ) )
        {
            ctx.setMethod( "JSONPATCH" );
        }
    }
}

this disables the original behaviour completely by bypassing the filter, which could probably be tuned by adding additional logic to the filter.


text:
Q: ReactJS: React Component not rendering ContactList.js
    var React = require('react');
    var Contact = require('./contact.js');

    var ContactList = React.createClass({
         render: function() {
           return(

Contacts

                           Name
                           Number
                           Email

                              {
                                this.props.contacts.map(function(contact, index) {
                                  <Contact contact={contact} key={index} />
                                })
                              }

           )
        }

Contact.js
var React = require('react');

var Contact = React.createClass({
  render: function() {
      return(

          {this.props.contact.name}
          {this.props.contact.phone}
          {this.props.contact.email}

      )
  }
})

module.exports = Contact;

Basically, i am able to get the contacts data from firebase in console but i want to display all the contacts i saved in the table. Behind the scenes, there is react-flux setup. State 'contacts' is basically an object inside an array, when i go to react tools, i can't see Contact component there, also if i try to console.log something to verify nothing works in Contact component, it seems like props is not passing to Contact component, also sometimes i get
[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. don't know whether it is because of this.
Can somebody explain me what is wrong ? Thanks in advance!!.

A: You need to send props to ContactList.js i.e, the response.data that you get after hitting firebase.
Something like this:-
React.render(<ContactList contacts= 'your response object' />);

Check whether your passing or not.
To solve it more easily you can use React.Component ,
ContactList.js
 import React from 'react';
    import Contact from './contact'

       class ContactList extends React.Component {
         {contacts}=this.props;
             render(){
               return(

Contacts

                               Name
                               Number
                               Email

                                  {
                                    contacts.map(function(contact, index) {
                                      <Contact contact={contact} key={index} />
                                    })
                                  }

               )
            }
        }
export default ContactList

Contact.js
import React from 'react'

class Contact extends React.Compponet{
{contact}=this.props;
  render() {
      return(

          {contact.name}
          {contact.phone}
          {contact.email}

      )
  }
}

export default Contact

You have to pass the props to the ContactList class which would internally pass it to Contact.
Thank you.

A: You need to return the Contact component inside the ContactList component like this:
this.props.contacts.map(function(contact, index) {
        return <Contact contact={contact} key={index} />
    })

or, you can use arrow function:
this.props.contacts.map((contact, index) => <Contact contact={contact} key={index} />)


text:
Q: Firefox scaling issues causes pixelated / blurry borders github repo with shortest code replicating problem
Basically i have a webpage that i have scaled down using the "viewport" meta tag.
<meta name="viewport" content="width=device-width, initial-scale=0.25">

The issue is that Firefox renders ALL my curved borders really blurry.
If an element has the following CSS applied while being viewed from a Bugzilla mobile browser, the resulting borders are really blurry/pixelated.

.element {
  font-size: 40px;
  text-align: center;
  border: 4px solid black;
  border-radius: 40px;
}

@media screen {
  .element {
    font-size: 4vw;
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=0.25">
  <title>Document</title>
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <div class="element">
    Lorem Ipsum
  </div>
</body>

</html>

Screenshot of webpage in Chrome (devtools Mobile browser):

Screenshot of webpage in Firefox (devtools Mobile browser):

From what i've found online it seems Firefox has a long history of scaling based rendering bugs but this is the first time ive seen issues with curved borders.

A: I think this is what  that is related to background bleed and you may probably find its reason in this discussion https://bugzilla.mozilla.org/show_bug.cgi?id=921341
To answer your question which has already been asked in this thread div border radius problem (on firefox and opera)
I recommend you using these properties in your css regarding with the mentioned answer

*-moz-background-clip

*-webkit-background-clip

*background-clip


text:
Q: Memory consumption for importing numerical data from an ascii file I am importing a file which contains  data consinsting of 8918347 lines and 6 columns of the following type:
1187.40   725.79     4.04    -7.51  0103753  0913
1363.31   724.57     0.00     0.00  0103754  0913
 564.34   725.77     0.00     0.00  0103755  0913
1174.40   726.31     0.00     0.00  0103756  0913
 527.56   728.31    -3.82     1.38  0103757  0913
 543.29   727.94    -0.80     0.24  0103758  0913
1510.04   729.10     0.00     0.00  0103760  0913
1565.91   738.97     1.80     1.37  0103762  0913
. . .

input = Import["data.txt", "Table"];

The file is accessible here:
https://drive.google.com/open?id=19o4_YruFGJh3tBgV7GlClcbvcvl0MsNf

*

*Before I import the data Wolfram Mathematica has allocated 431 MB (fresh started)

*During the reading the allocated memory of Wolfram Mathematica goes
up to about 8700 MB.

*Then still during the line is executed the
memory slowly goes down to 2330 MB and the line is finally executed.

The Import takes on my computer 135 sec.
I would like to understand:

*

*Why does this up and down of allocated memory occurs during importing.

*Why ist so much memory (2330 MB - 431 MB = 1899 MB) used?
If I assume that each number uses 8 Byte. Then this results in:
8*8918347*6 Bytes = 428080656 Bytes = 408.35 MB

My computer system is: Windows 10 Pro newest update, Ram: 32 GB, Notebook Dell Precision M4800, Intel Core i7-4940MX 3.1GHz

A: I can only guess that the inner workings of the parsing of data with an unknown shape may be complicated. The memory used contains several copies of the data been processed.
If you want to have some fun seeing how Mathematica works inside, look at Trace. I suggest you start using trace in much simpler expressions. If you need to Trace more complex expressions see this questions, to trace to a file
An alternative that uses much less memory and it's faster:
path = "20180720_01_data.txt"

First@AbsoluteTiming[
  data2 =
    ReadList[path, {Number, Number, Number, Number, Number, Number}];
  ]
(* 19.5111 *)

Compared with
First@AbsoluteTiming[
  data1 = Import[path, "Table"];
  ]
(* 172.437 *)

Check that the data is the same.
data1 == data2
(* True *)

Even better, with ReadList and family of function for Streams and Low-Level Input and Output  you could choose which lines and columns to Read and what to Skip.


text:
Q: Callback on ascx files When I try to run .PerformCallback command on .ascx file I got an error. Here is the error alert..

How can i resolve it?

A: Most likely, you do not restore page's controls hierarchy after it has been changed once.
Use recommendations from the http://www.devexpress.com/Support/Center/KB/p/K18291.aspx KB Article to resolve this issue.


text:
Q: How to prevent escape characters from changing the output of a randomly generated Python string? This code outputs a string of randomly generated characters. For
example: V86Ijgh(!y7l0+x
import string
import random

password = ''.join([random.choice(string.printable) for i in range(15)])

print(password)

In the case that an escape character like \n appears
V86Ijg\n!y7l0+x

and creates the output:
V86Ijg
!y7l0+x

because it initialized a new line
rather than printing out:
V86Ij\n(!y7l0+x

like before.
What's the best way at avoiding the intended output of an escape character such as creating a new line, tab, etc, from being interpreted? I have no choice over the input because it is randomized. I want to know how to output the string in its raw form without removing characters from the original string. I want the password to be displayed as it was generated.

A: You should encode your string with escape characters if you want it to keep the special characters escaped, i.e.:
print(password.encode("unicode_escape").decode("utf-8"))
# on Python 2.x: print(password.encode("string_escape"))

Using repr() will add single quotes around your string.

A: You could make your own set of characters to select frome by taking out all whitespace characters from string.printable, using set operators:
chars = ''.join(set(string.printable) - set(string.whitespace))

password = random.choice(chars)

key_length = 1
while(key_length < 15):
        password += random.choice(chars)
        key_length = key_length + 1

print(password)

Note that this whole loop can be replaced by the list comprehension:
password = ''.join([random.choice(chars) for _ in range(15)])

Edit If you want to keep the escape and whitespace characters, but just want to print the password to your console, use the repr() function:
print(repr(password))


text:
Q: If $a_1, a_2, ..., a_m$ each divide $n$, prove that $lcm(a_1,a_2, ..., a_m) | n$. If $a_1, a_2, ..., a_m$ each divide $n$, prove that $lcm(a_1,a_2, ..., a_m) | n$.
I see that essentially says show that the lcm of factors of $n$ divide $n$ and this makes sense intuitively, but I can't seem to show it.  I can see that if $\gcd(a_i,a_j)=1$ then $a_ia_j = lcm(a_i,a_j) | a$, but when $\gcd(a_i,a_j) \neq 1$ I get stuck.

A: Let the prime factorization of $n$ be
$$n = \prod_{j=1}^q p_j^{v_j}.$$
Now since $a_k|n$ we have
$$a_k = \prod_{j=1}^q p_j^{w_{j,k}}$$
where $w_{j,k}\le v_j.$ We also have that
$$L = \mathrm{lcm}(a_1, a_2,\ldots, a_m)
= \prod_{j=1}^q p_j^{\max_k w_{j,k}}.$$
Note however that $\max_k w_{j,k} \le v_j$ and hence $L|n$ and we have
the claim.

A: That $\ a_1,\ldots,a_k\mid m\,\Rightarrow\,{\rm lcm}(a_1,\ldots,a_k)\mid m\ $ is a prototypical  Euclidean descent.
The set $M$ of all positive common multiples of all $\,a_i$ is closed under positive subtraction, i.e. $\,m> n\in M$ $\Rightarrow$ $\,a_i\mid m,n\,\Rightarrow\, a_i\mid m\!-\!n\,\Rightarrow\,m\!-\!n\in M.\,$ Thus, by induction, we deduce that $\,M\,$ is closed under mod, i.e. remainder, since it arises by repeated subtraction, i.e. $\ m\ {\rm mod}\ n\, =\, m-qn = ((m-n)-n)-\cdots-n.\,$ Thus the least $\,\ell\in M\,$ divides every  $\,m\in M,\,$ else $\ 0\ne m\ {\rm mod}\ \ell\ $ is in $\,M\,$ and smaller than $\,\ell,\,$ contra minimality of $\,\ell.$


text:
Q: TypeScript: number|undefined variable produces string output In our application we recently faced a hard to find bug, and it turned out that one of our TypeScript number|undefined variable strangely produced a string output.
I managed to narrow down the a situation and ended up with the following code:
  let stringUndef: string | undefined = undefined;
  let numUndef: number | undefined = undefined;

  //Does NOT compile = ✔
  // stringUndef = "1";

  //Does NOT compile = ✔
  // if (Math.floor(Math.random() * 2) === 0) {
  //   stringUndef = "1";
  // }

  //Does NOT compile = ✔
  // let intArr1 = [1]
  // for(var i = 0;i<intArr1.length;i++) {
  //   stringUndef = "1";
  // }

  //Strangely DO COMPILE = ❗
  //Console Output: "1" - String output from a number|undefined variable = ??
  let intArr2 = [1]
  intArr2.forEach(function() {
    stringUndef = "1";
  });

  numUndef = stringUndef

  console.log(numUndef)

Tried with different TS version at: https://www.typescriptlang.org/play
Being new to TypeScript my questions are:
Is this the expected behviour (a number|undefined can indeed contain a string)?
Why does the code compile with index based iteration but fails to compile using foreach?
What is the best practice in this situation to avoid similar unexpected type violation?


text:
Q: VBA to bold calculated period in email message using WordEditor I'm writing a vba script to automate a weekly email task, and I'm using WordEditor to insert the text message. In the email message, there are months calculated by function Format(DateAdd("m", -1, Now()), "Mmmm") and I want to highlight them in Bold and red colour. Can someone tell me the code to do it?
Sub EmailAllOpenPOs()

Dim ol As Outlook.Application
Dim mi As Outlook.MailItem
Dim doc As Word.Document
Dim MsgText As String

Set ol = New Outlook.Application
Set mi = ol.CreateItem(olMailItem)

With mi
    .Subject = "Purchase Orders Review & Approval Process (REVIEW & ACTION REQUIRED) as of " & Format(Now(), "d/m/yy")
    .Display
End With

Set doc = mi.GetInspector.WordEditor

MsgText = vbNewLine
doc.Range(0, 0).InsertBefore MsgText

MsgText = "Dear all," & vbNewLine & vbNewLine & _
        "There are some POs related to " & Format(DateAdd("m", -1, Now()), "Mmmm") & " and " & Format(Now(), "Mmmm") & " still open." & vbNewLine & vbNewLine & _
        "Could you please review and advise a.s.a.p. if you require finance to accrue them for this month end?"

doc.Range(0, 0).InsertBefore MsgText

Set doc = Nothing

End Sub

A: Add this before Set doc = Nothing:
Dim formatRng As Word.Range
Set formatRng = doc.Range.Duplicate
With formatRng
    .Find.Execute Format(DateAdd("m", -1, Now()), "Mmmm") & " and " & Format(Now(), "Mmmm")
    .Font.Bold = True
    .Font.ColorIndex = wdRed
End With
Set formatRng = Nothing

If you only want to bold and red the month only (without the "and"):
Dim formatRng As Word.Range
Set formatRng = doc.Range.Duplicate
With formatRng
    .Find.Execute Format(DateAdd("m", -1, Now()), "Mmmm") & " and " & Format(Now(), "Mmmm")
    With .Words(1).Font
        .Bold = True
        .ColorIndex = wdRed
    End With
    With .Words(3).Font
        .Bold = True
        .ColorIndex = wdRed
    End With
End With
Set formatRng = Nothing


text:
Q: filtering pos-tag results based on tag patterns and other tags original sentence
key_list= ['techniques from nonlinear analysis and partial differential equations form the basis for these studies .','differential equations are cool.' 'it is not too great of an equation']
    Spacy Tagging.
[[['techniques', 'NNS'], ['from', 'IN'], ['nonlinear', 'JJ'], ['analysis', 'NN'], ['and', 'CC'], ['partial', 'JJ'], ['differential', 'JJ'], ['equations', 'NNS'], ['form', 'VBP'], ['the', 'DT'], ['basis', 'NN'], ['for', 'IN'], ['these', 'DT'], ['studies', 'NNS'], ['.', '.']],
[['differential', 'JJ'], ['equations', 'NNS'], ['are', 'VBP'], ['cool', 'JJ'], ['.', '.']],
[['it', 'PRP'], ['is', 'VBZ'], ['not', 'RB'], ['too', 'RB'], ['great', 'JJ'], ['of', 'IN'], ['an', 'DT'], ['equation', 'NN']]]

I am using a wordnet to make things easier, but is there a way i can get the all the nouns of a sentence as well as tag patterns like [RB,RB,JJ] &[JJ,NN]?
required output.
[['techniques' ,'nonlinear analysis', 'differential equations', 'basis','studies'],['differential equations'],['not too great','equation']]

A: You need something like this if I understand your question correctly
import spacy
from spacy.matcher import Matcher

nlp = spacy.load('en_core_web_sm')
matcher = Matcher(nlp.vocab)

text= """techniques from nonlinear analysis and partial
     differential equations form the basis for these studies.
     Differential equations are cool. It is not too great of an equation"""
doc = nlp(text)

pattern1 = [{"TAG": {"IN": ["NN", "NNS"]}}]
pattern2 = [{"TAG": "RB"},{"TAG": "RB"}, {"TAG": "JJ"}]

matcher.add("matcher", [pattern1, pattern2])

for sent in doc.sents:
    matches = matcher(sent)
    for match_id, start, end in matches:
        print(sent[start:end])


text:
Q: Robotium: SVG/Bitmap NullPointerException error I'm testing a part of this Android application using Robotium which lets the user doodle on the canvas. The strokes are stored as SVG elements (a custom class) in a java.util.List. I simulate a line drawing gesture via solo.drag and print the Generation IDs of the two bitmaps - before drawing and after drawing. The generation IDs are different from each other, which means the bitmap has been modified. But the SVG element list is null (I get a NullPointerException at the second-last line of the following snippet). How is this so?
Following is the code:
Bitmap testBitmap = (([package.name].MainActivity) solo.getCurrentActivity()).getPaintView().getBitmap();
int emptyBitmapGenID = testBitmap.getGenerationId();
Log.d(this.getClass().getName(), ""+emptyBitmapGenID);

solo.drag(strokeFromX, strokeToX, strokeFromY, strokeToY, strokeStepCount);
solo.clickOnScreen(10, 10); //To release the touch

int strokedBitmapGenID = testBitmap.getGenerationId();
Log.d(this.getClass().getName(), ""+strokedBitmapGenID);

solo.waitForActivity(MainActivity.class);
List<[package.name].SVG.SVG_Element> elementList = (([package.name].MainActivity) solo.getCurrentActivity()).getRenderManager().getCurrDisplayList(false);

if(elementList==null)
{
    Log.d(this.getClass().getName(), "SVG element list null!");
}

Log.d(this.getClass().getName(), ""+elementList.toString());
[package.name].SVG.SVG_Stroke stroke = ([package.name].SVG.SVG_Element)elementList.get(0);
Log.d(this.getClass().getName(), stroke.toString());

This problem arises only some of the times. Following is the log when it runs fine:
06-19 11:22:43.210: D/[package.name].test.Utils(11520): 31
06-19 11:22:46.435: D/[package.name].test.Utils(11520): 41
06-19 11:22:46.435: D/[package.name].test.Utils(11520): [<g class='stroke' id='520c7ff6-1800-4f0c-a544-8be164a6eeca' transform='matrix(1.0,0.0,0.0,1.0,0.0,0.0)'><path d='M 255.40 138.30 L 259.39 143.62 L 263.38 148.94 L 267.37 154.26 L 271.36 159.57 L 275.35 164.89 L 279.34 170.21 L 283.33 175.53 L 287.32 180.85 L 291.31 186.17 L 295.30 191.49 L 299.29 196.81 L 303.29 202.13 L 307.28 207.45 L 311.27 212.77 L 315.26 218.09 L 319.25 223.40 L 323.24 228.72 L 327.23 234.04 L 331.22 239.36 L 335.21 244.68 L 339.20 250 L 343.19 255.32 L 347.18 260.64 L 351.17 265.96 L 355.16 271.28 L 359.15 276.60 L 363.14 281.91 L 367.13 287.23 L 371.13 292.55 L 375.12 297.87 L 379.11 303.19 L 383.10 308.51 L 387.09 313.83 L 391.08 319.15 L 395.07 324.47 L 399.06 329.79 L 403.05 335.11 L 407.04 340.43 L 411.03 345.74 L 415.02 351.06 L 419.01 356.38 L 423.00 361.70 L 426.99 367.02 L 430.98 372.34 L 434.97 377.66 L 438.97 382.98 L 442.96 388.30 L 446.95 393.62 L 450.94 398.94 L 454.93 404.26 L 458.92 409.57 L 462.91 414.89 L 466.90 420.21 L 470.89 425.53 L 474.88 430.85 L 478.87 436.17 L 482.86 441.49 L 486.85 446.81 L 490.84 452.13 L 494.83 457.45 L 498.82 462.77 L 502.81 468.09 L 506.81 473.40 L 510.80 478.72 L 514.79 484.04 L 518.78 489.36 L 522.77 494.68 L 526.76 500 L 530.75 505.32 L 534.74 510.64 L 538.73 515.96 L 542.72 521.28 L 546.71 526.60 L 550.70 531.91 L 554.69 537.23 L 558.68 542.55 L 562.67 547.87 L 566.66 553.19 L 570.65 558.51 L 574.65 563.83 L 578.64 569.15 L 582.63 574.47 L 586.62 579.79 L 590.61 585.11 L 594.60 590.43 L 598.59 595.74 L 602.58 601.06 L 606.57 606.38 L 610.56 611.70 L 614.55 617.02 L 618.54 622.34 L 622.53 627.66 L 626.52 632.98 L 630.51 638.30 L 634.50 643.62 L 638.49 648.94 L 642.49 654.26 L 646.48 659.57 L 650.47 664.89 ' stroke='black' stroke-width='6' fill='none' stroke-linejoin='round' stroke-linecap='round' stroke-opacity='1'/></g>]

A: This problem was resolved after I updated Robotium to version 5.2.1. I had been using version 5.0.1 earlier.


text:
Q: how to install virtualenv on Ubuntu 20.04 GCP instance? I am trying to install python3 virtualenv. I get the following message when I try to run virtualenv.
virtualenv
Command 'virtualenv' not found, but can be installed with:
apt install python3-virtualenv

but if I run install command, I get the following error.
apt install python3-virtualenv
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package python3-virtualenv

For python3 -m venv, I get message to install using apt-get install python3-venv
but when I try it, I get the same message.
sudo apt-get install python3-venv
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package python3-venv is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package 'python3-venv' has no installation candidate

I am running this as root.
wget also works.

A: This will definitely work:
sudo apt-get update

sudo apt-get install python3-virtualenv

A: AFAIU the latest versions of Ubuntu removed Python2 altogether so Python3 is now just the Python. Try:
apt-get update
apt-get install python3-virtualenv

A: The below is very similar to the answer by phd, but my freshly installed Ubuntu 20.04 still requires the python version number:
apt-get update
apt-get install python3-virtualenv

A: I was getting the error E: Unable to locate package python3-virtualenv
 because I had to run apt-get update first. This was my brand new GCP instance.
Reference: first comment of the first answer in this thread.
Unable to locate package virtualenv in ubuntu-13 on a virtual-machine
Thank you all.

A: sudo apt install python3-virtualenv

A: I also got that problem and was able to solve it by follow means:
software-properties-gtk

After clicking enter a window pops up. Then you have to check the first 4 boxes, close it and refresh it.
After that the problem should be solved and you're ready to go

A: try type in terminal:
sudo apt-get install python3.8-venv

and then try again install virtualenv

A: try the following
sudo apt install python3-pip
pip install virtualenv
virtualenv xyz-venv

A: First get the updated information and then install the virtual environment with below two command simultaneously.
sudo apt update
sudo apt install python3-virtualenv

A: For this issue:
sudo apt-get install python3-venv
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package python3-venv is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package 'python3-venv' has no installation candidate

I discovered that I had to first use sudo -s to use root privileges. And then run:
apt-get update
apt-get install python3-venv

And it worked. I was working on Ubuntu 18.04.5 LTS


text:
Q: how to display user information in php? I am trying to figure out how to display user information after they've logged in. I am not sure whether I should create a single php file which would display user information depending on the session or should I create different files for different users. I am also having trouble grabbing the header.
here's my code for login.php
<?php
session_start();

require 'dbh.php';

$username = $_POST['uname'];

$password = $_POST['pwd'];

$sql = "SELECT * FROM  registeredusers WHERE UserName = '$username'";

$result = mysqli_query($connection,$sql);

$row = mysqli_fetch_assoc($result);

$hashed_Password = $row['Password'];

$Dehash = password_verify($password,$hashed_Password);

if($Dehash == 0){

echo "username or password is incorrect";

exit();

} else{

$sql = "SELECT * FROM  registeredusers WHERE  UserName='$username' AND Password='$hashed_Password'";

$result = mysqli_query($connection,$sql);

if (!$row=mysqli_fetch_assoc($result)){

echo "Your User Name or Password is incorrect";

}

else {

$userid = $row['id'];

$_SESSION['UserName'] = $row['UserName'];

header("Location: userhomepage.php?user_id=".$userid);

}

}

?>

The following code redirects to userhomepage.php and the user ID is in the url can someone also tell me how do I grab the user ID from the url? I only started coding in PHP a week ago I am fairly new so if guys have any pointers for me that would be great.

A:
I am not sure whether I should create a single php file which would display user information depending on the session or should I create different files for different users.

You should create a single page that displays user information based on session... you don't want to have to hand-make a new page every time a user signs up!

how do I grab the user ID from the url

echo $_GET["user_id"];


text:
Q: Android selector draw doesn't overlap My problem is when my CheckableLinearLayout is checked my draw from the selector can't overlap the unchecked image.
My CheckableLinearLayout
public class CheckableLinearLayout extends LinearLayout implements Checkable {
    private boolean mChecked;
    private static final String TAG = CheckableLinearLayout.class
            .getCanonicalName();
    private static final int[] CHECKED_STATE_SET =
        { android.R.attr.state_checked };

    public CheckableLinearLayout(final Context context) {
        super(context);
        setClickable(true);
        setLongClickable(true);
    }

    public CheckableLinearLayout(final Context context,
                                 final AttributeSet attrs) {
        super(context, attrs);
        setClickable(true);
        setLongClickable(true);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public CheckableLinearLayout(final Context context,
                                 final AttributeSet attrs,
                                 final int defStyle) {
        super(context, attrs, defStyle);
        setClickable(true);
        setLongClickable(true);
    }

    @Override
    public void setChecked(final boolean checked) {
        mChecked = checked;
        refreshDrawableState();
    }

    @Override
    protected int[] onCreateDrawableState(final int extraSpace) {
        final int[] drawableState =
            super.onCreateDrawableState(extraSpace + 1);
        if (isChecked())
            mergeDrawableStates(drawableState, CHECKED_STATE_SET);
        return drawableState;
    }

    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();
        final Drawable drawable = getBackground();
        if (drawable != null) {
            final int[] myDrawableState = getDrawableState();
            drawable.setState(myDrawableState);
            invalidate();
        }
    }

    @Override
    public boolean performClick() {
        Toast.makeText(getContext(), "click", Toast.LENGTH_SHORT).show();
        if (isChecked()) {
            toggle();
            return false;
        } else
            return super.performClick();

    }

    @Override
    public boolean performLongClick() {
        toggle();
        Toast.makeText(getContext(), "long click", Toast.LENGTH_SHORT).show();
        return super.performLongClick();
    }

    @Override
    public boolean isChecked() {
        return mChecked;
    }

    @Override
    public void toggle() {
        setChecked(!mChecked);
    }

    @Override
    public Parcelable onSaveInstanceState() {
        // Force our ancestor class to save its state
        final Parcelable superState = super.onSaveInstanceState();
        final SavedState savedState = new SavedState(superState);
        savedState.checked = isChecked();
        return savedState;
    }

    @Override
    public void onRestoreInstanceState(final Parcelable state) {
        final SavedState savedState = (SavedState) state;
        super.onRestoreInstanceState(savedState.getSuperState());
        setChecked(savedState.checked);
        requestLayout();
    }

    // /////////////
    // SavedState //
    // /////////////
    private static class SavedState extends BaseSavedState {
        boolean checked;
        @SuppressWarnings("unused")
        public static final Parcelable.Creator<SavedState> CREATOR;
        static {
            CREATOR = new Parcelable.Creator<SavedState>() {
                @Override
                public SavedState createFromParcel(final Parcel in) {
                    return new SavedState(in);
                }

                @Override
                public SavedState[] newArray(final int size) {
                    return new SavedState[size];
                }
            };
        }

        SavedState(final Parcelable superState) {
            super(superState);
        }

        private SavedState(final Parcel in) {
            super(in);
            checked = (Boolean) in.readValue(null);
        }

        @Override
        public void writeToParcel(final Parcel out, final int flags) {
            super.writeToParcel(out, flags);
            out.writeValue(checked);
        }

        @Override
        public String toString() {
            return TAG + ".SavedState{"
                    + Integer.toHexString(System.identityHashCode(this))
                    + " checked=" + checked + "}";
        }
    }
}

My layout.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/topics_preview_main_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:id="@+id/favorites_header_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="6dp"
        android:layout_marginRight="6dp"
        android:layout_marginTop="2dp"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/favorites_header_title"
            style="@style/CardText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="4dp"
            android:layout_marginLeft="6dp"
            android:layout_marginRight="6dp"
            android:layout_marginTop="4dp"
            android:background="@drawable/card"
            android:gravity="left"
            android:paddingBottom="10dp"
            android:paddingLeft="5dp"
            android:paddingTop="10dp"
            android:text="@string/favorites_header" />

        <ui.CheckableLinearLayout
            android:id="@+id/favorites_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="4dp"
            android:layout_marginLeft="6dp"
            android:layout_marginRight="6dp"
            android:layout_marginTop="4dp"
            android:background="@drawable/card_selector_w_shadow"
            android:clickable="true"
            android:longClickable="true"
            android:orientation="vertical"
            android:paddingBottom="16dp" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:paddingLeft="8dp"
                android:paddingRight="8dp" >

                <TextView
                    android:id="@+id/favorites_title"
                    style="@style/CardTitle"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="title" />
            </LinearLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_marginTop="4dp"
                android:background="@color/C_Favorites_Pink" />

            <LinearLayout
                android:id="@+id/favorites_description_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:orientation="vertical"
                android:padding="4dp" >

                <TextView
                    android:id="@+id/favorites_description"
                    style="@style/CardText"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="8dp"
                    android:ellipsize="end"
                    android:maxLines="4"
                    android:text="Lorem ipsum ..." />
            </LinearLayout>
        </ui.CheckableLinearLayout>
    </LinearLayout>

</FrameLayout>

card_selector_w_shadow-> this draw will call the selector
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item>
        <shape
            android:dither="true"
            android:shape="rectangle" >
            <corners android:radius="2dp" />

            <solid android:color="#ccc" />
        </shape>
    </item>
    <item android:bottom="2dp">
        <shape
            android:dither="true"
            android:shape="rectangle" >
            <corners android:radius="2dp" />

            <solid android:color="@android:color/white" />

            <padding
                android:bottom="8dp"
                android:left="8dp"
                android:right="8dp"
                android:top="8dp" />
        </shape>
    </item>
    <item android:drawable="@drawable/drawable_states"/>

</layer-list>

My drawable_states
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/checked_background"
          android:state_checked="true"/>
</selector>

This is what's happening:

This is what I intend:

I think this is because my CheckableLinearLayout only changes the state of the children, so the draw only overlap the children. Any advices?


text:
Q: How to write if else statements using protractor in typescript  var newfilter = browser.$('.filter-names')
                        .$('ul sd-action-trigger[text="New Filter  "]')
                        .$('a');

 newfilter.isPresent().then((isPresent: boolean,) => {
     if (isPresent) {

     } else {

     }
 });

I dont know but it gives me error.Basically i want to chck in my code id New filter is present do if part otherwise else part.It gives me error that expected 2 arguments but got 1


text:
Q: While Loop while(1) vs while(3) or any digit for that matter When using the while loop what does it mean to write while(1) vs any other digit?
In my program while(1) is giving me the same answers as while(3)
int num1;
int loopcount;

while(1) {
    printf("enter your positive number:");
    scanf("%d",&num1);
    if(num1>0) {
        break;
    }
}

A: In C, any integer value other than 0 is treated as true for conditional statements.

A: In C, 0 can mean 'false' in certain contexts, and non-zero can mean 'true'.


text:
Q: React-Native AsyncStorage: I retrieve an array, but then it becomes only a single object of the array I'm using AsyncStorage to store and retrieve an array of objects. The structure of the array is like this:
const tracks = [
    {
        title: title1,
        exercises: [
            {
                object1Info...
            },
            {
                object2Info...
            }
        ]
    },
    {
        title: title2,
        exercises: [
            {
                object1Info...
            }
        ]
    },
    {
        title: title3,
        exercises: [
            {
                object1Info...
            }
        ]
    }
]

As you can see, the objects in the array do themselves contain arrays, which again contain objects.
I'm storing the array like this:
const storeData = async (array) => {
    try {
        const stringifiedArray = JSON.stringify(array)
        await AsyncStorage.setItem('@tracks_array', stringifiedArray)
    } catch (e) {
        console.log("Error saving data")
    }
}

This seems to work fine. I then retrieve the data like this:
const retrieveData = async () => {
    try {
        const jsonValue = await AsyncStorage.getItem('@tracks_array');
        console.log('Parsed value: ' + JSON.parse(jsonValue)); //This prints 'Parsed value: [object Object],[object Object],[object Object],[object Object]'
        return jsonValue !== null ? JSON.parse(jsonValue) : null;
    } catch (e) {
        console.log("Error retrieving data")
    }
}

This seems to work fine as well.
I have the array stored also as state. So what I want to do is add an object to the array in state, store that new array in the AsyncStorage, and then retrieve the array and set this new array back to state. Storing the object seems to have no problems.
When I retrieve the new array, and console.log(JSON.parse(jsonValue)) inside retrieveData, it prints [object Object],[object Object],[object Object],[object Object]. However after I call const newData = retrieveData(), console.log(newData) prints just [object Object]. This is my first time using AsyncStorage so I must be misunderstanding something. Why does it only return one object, instead of the whole array?
EDIT: Sharing the whole component code:
import {
    StyleSheet,
    ScrollView,
    View,
    Text
 } from 'react-native';
 import Modal from 'react-native-modal';
 import AsyncStorage from '@react-native-community/async-storage'
 import Track from './Track.js';
 import New from './New.js';

class Main extends Component {
    constructor(props) {
        super(props);

        this.state = {
            tracksData: tracks,
            newTrack: false,
            newExercise: false
        }

        storeData(this.state.tracksData);
    }

    renderTracks(data) {
        console.log('Main data = ' + data)
        return data.map((item, i) => {
            console.log('Item = ' + item)
            return (
                <Track key={i} data={item} />
            )
        });
    }

    render() {
        return (
            <ScrollView horizontal={true} style={styles.Main}>
                {this.renderTracks(this.state.tracksData)}
                <Track data={{title: 'NewTrack', exercises: 'NewTrack'}} newTrackBox={this.toggleTrackBox} />
                <Modal isVisible={this.state.newTrack} coverScreen={true}>
                    <New type={'track'} visible={this.toggleTrackBox} add={(name) => this.addTrack(name)}/>
                </Modal>
            </ScrollView>
        );
    }

    toggleTrackBox = () => {
        this.setState({
            newTrack: !this.state.newTrack
        })
    }

    addTrack = (name) => {
        this.setState({
            newTrack: false
        });

        var newTracks = this.state.tracksData;
        newTracks.push({title: name, exercises: []})

        console.log('newTracks = ' + newTracks)
        storeData(newTracks);

        this.updateData();
    }

    updateData() {
        var newData = retrieveData();

        console.log('newData = ' + newData)

        setTimeout(() => {
            console.log('Retrieved data = ' + newData);
            if (newData) {
                this.setState({
                    tracksData: newData
                });
                console.log("Data updated");
                return true;
            } else {
                console.log("Data couldn't be retrieved");
                return false;
            }
        }, 5000)
    }
}

const storeData = async (value) => {
    try {
        const stringifiedArray = JSON.stringify(value)
        console.log('Value to store: ' + value)
        console.log('Stringified value to store: ' + stringifiedArray)
        await AsyncStorage.setItem('@tracks_array', stringifiedArray)
        //alert("Success saving data!")
    } catch (e) {
        console.log("Error saving data")
        alert("Error saving data");
    }
}

const retrieveData = async () => {
    try {
        const jsonValue = await AsyncStorage.getItem('@tracks_array');
        console.log('Stringified value retrieved: ' + jsonValue)
        console.log('Parsed value: ' + JSON.parse(jsonValue))
        return jsonValue !== null ? JSON.parse(jsonValue) : null;
    } catch (e) {
        console.log("Error retrieving data")
        alert("Error retrieving data");
    }
}

const tracks = [ //each member of this array is sent to a Track
    {
        title: 'Pull-up', // used in Track
        exercises: [ // each member of this array is sent to an Exercise by Track
            {
                name: 'Pull-up', // used in Exercise
                setStart: 2, // this and below used to calculate no of tiles and their contents, which are then sent to Tile
                setEnd: 3,
                repStart: 5,
                repEnd: 8,
                isInSeconds: false,
                inProgress: null,
                completed: true
            },
            {
                name: 'Weighted Pull-up',
                setStart: 3,
                setEnd: 3,
                repStart: 5,
                repEnd: 8,
                isInSeconds: false,
                inProgress: [3, 5],
                completed: false
            }
        ]
    },
    {
        title: 'Dip',
        exercises: [
            {
                name: 'Dip',
                setStart: 2,
                setEnd: 3,
                repStart: 5,
                repEnd: 8,
                isInSeconds: false,
                inProgress: null,
                completed: true
            }
        ]
    },
    {
        title: 'Squat',
        exercises: [
            {
                name: 'Pistol squat',
                setStart: 2,
                setEnd: 3,
                repStart: 5,
                repEnd: 8,
                isInSeconds: false,
                inProgress: [2, 8],
                completed: false
            }
        ]
    }
]

const styles = StyleSheet.create({
    Main: {
        flex: 1,
        flexDirection: 'row',
        backgroundColor: '#022763'
    }
})

export default Main;

Also, I should have mentioned, the actual error I'm getting is:
TypeError: undefined is not a function (near '...data.map...')

A: "retrieveData" is async function and hence returns a Promise.
What happened was it didn't finish retrieving the data and hence newData got 1 object out of all the array.
Try changing updateData like this:
updateData() {
    var newData = retrieveData().then(data => {
        console.log('newData = ' + newData)
        setTimeout(() => {
            console.log('Retrieved data = ' + newData);
            if (newData) {
                this.setState({
                    tracksData: newData
                });
                console.log("Data updated");
                return true;
            } else {
                console.log("Data couldn't be retrieved");
                return false;
            }
        }, 5000)
    };
}

A: I've figured out the issue. I was retrieving data with AsyncStorage, then setting that data to the state something like this:
var newData = asyncRetrieveDataFunction();

this.setState({state1: newData})

However, because I declared the retrieveData() function as async, it was setting the state before the data had finished retrieving. The solution was to use the then keyword and change it to something like this:
asyncRetrieveDataFunction().then(data => this.setState({state1: data}));

This ensures that the data has been returned BEFORE assigning it to a state.


text:
Q: How to dynamically create a class out of the DataContext, in WPF? Is it possible to dynamically get the binding properties for a view into a class and manipulate it in run time.
for example, if the DataContext is of type User that has 10 properties, but the bound properties are only 4, can I make a class that has these 4 properties only?

A: Doable, but difficult.

*

*You must parse the visual tree, and visit every control using VisualTreeHelper (see: https://stackoverflow.com/a/874426/275330).

*For every control you can get a list of its dependency properties (see https://stackoverflow.com/a/26367132/275330)

*Then for each separate dependency property you can check if its value is set locally (see: Knowing if a DependencyProperty has not been set in XAML). If so - you have the value you need.

I've never used 1+2+3 together, so I don't know what additional difficulties you may have.


text:
Q: PHP mysqli results array
Just learning PHP so please be kind.

I have a mysqli query which I need to pull specific results from.
For example; I need to pull the 1, 4, 7, 10, etc row, and then go back and pull the 2, 5, 8, 11, etc, row, and then go back and finally pull the 3, 6, 9, 12, etc row.  And I also need to reference each field separately.

What is the best way to do this?

The reason behind all of this is the way I'm having to display the results.
I know I can do this in ASP by moving the pointer, but I have no idea about PHP.

FYI PHP version 5.3.6.

Thanks.

A: You can use the mysqli_fetch_all method on the result of your query:
$result = mysqli_query($db_handle, "SELECT...");
$rows = mysqli_fetch_all($result);

OR, if you don't have mysqlnd, you can do this:
for ($rows = array(); $tmp = mysqli_fetch_array($result);)
    $rows[] = $tmp;

$rows will contain all of the rows, so you can access each row by whatever index you want.
So if you want the 1, 4, 7, 10th row, you can do this:
for ($i = 1; $i <= 10; $i += 3) {
    $rows[$i]["fieldname"]; // do your stuff
}


text:
Q: Call AlpineJS function from javascript I have a modal that i show or hide using alpine js.
When I press a button I check a bool and if it's true then I want to close that modal, to do so I have to interact with Alpines' data.
Is there a way to call Alphines' functions from JS?
I've tried using custom event but that doesn't seem to work
let event = new CustomEvent("closeModal", {}); window.dispatchEvent(event)
Then in the modals' div
x-show="isOpen()" @closeModal.window="close"
EDIT:
Thanks to pthomson answer I was able to make it work and I also found a way without using events
<div x-data>
    <button type="button" @click="$store.modal.open()">Open Modal</button>
    <div x-show="$store.modal.isOpen()">
        //Modal content
    </div>
</div>

<script>
    document.addEventListener('alpine:init', () => {
        Alpine.store('modal', {
            show:false,
            isOpen() {
                return this.show;
            },
            open(){
                this.show=true;
            },
            close(){
                this.show =false;
            }
        })
    })

    function closeModal(){
        Alpine.store("modal").close();
    }
</script>

A: I do this with an Alpine Store value and a custom event (on the document, but it would also bubble up to window if you want). The alpine:init event is registering the two document listeners.
Your button would dispatch this closemodal event (escape keydown also hides the modal in this example).
I have style="display: none" on the div to keep it hidden before alpine:init is called during page load... maybe an x-cloak on the div would achieve the same desired (initially hidden) effect.
NOTE: I include this single modal partial on all pages that need modal functionality. So it ends up being a single Alpine Store variable that all pages share, since they all share the same modal partial view in the page markup.
<script>
        document.addEventListener('alpine:init', () => {
            Alpine.store('openmodal', false);

        document.addEventListener('openmodal', () => {
           Alpine.store('openmodal', true);
        })
        document.addEventListener('closemodal', () => {
           Alpine.store('openmodal', false);
           // clear modal content here if you want
        })
    });
</script>

<div
        x-show="$store.openmodal"
        style="display: none"
        x-on:keydown.escape.prevent.stop="$dispatch('closemodal');"
        role="dialog"
        aria-modal="true"
        class="fixed inset-0 overflow-y-auto"
    >
.. modal content
</div>

then somewhere else you have your button
<button onclick="$dispatch('closemodal');">close</button>

EDIT: based on your feedback, there are other ways to achieve what you are trying to do... not sure how your isOpen() function is getting the proper value to return, but your div can just listen for that button to raise the custom closemodal event.. for instance calling your isOpen function and passing in the state, but you get the idea? <div x-on:closemodal.window="isOpen(false)"> basically the opposite of what you asked for: alpine listen for call from javascript.


text:
Q: Is there some type of json mashup? I have a number of jsons and I want to manually select some parts of it to create a new Z json one. Is there any software that do that or I have to program that?
Example:
X is a temperature JSON:
{
    "temperature" : 20,
    "standard" : "Celsius"
}

Y is a wind JSON:
{
    "windSpeed": 12,
    "unit" : "Knot"
}

I want a Z json that would be a selection of the X + Y, for instance I want only the speed and temperature:
{
    "temperature" : 20,
    "windSpeed" : 12
}

My question is, is given a static X and Y is there a way to build Z without manually taking out the fields of X and Y? I mean is there a gui or technique that allows me to produce a JSON from other JSONS?

A: You'll have to manually program it to parse the JSON and output a new one.  Should be pretty easy, though, to be honest.  Just select based on a keyword and then pass it into the new JSON object.


text:
Q: ViewPager with PagerAdapter does not show anything My ViewPager does not show anything. And I don't have any idea why it's empty. Do you have idea to solve that? Here is my code:
CustomPageAdapter.java
public class CustomPageAdapter extends PagerAdapter implements ValueEventListener {

Context mContext;
private Context context;
private HashMap<String, Araba> arabalar;
private DatabaseReference databaseReference;
private String userId;
private LayoutInflater inflater;
private List<String> arabaPlakalari;

public CustomPageAdapter(@NonNull Context context,
                    @NonNull List<String> arabaPlakalar,
                    final DatabaseReference databaseReference,
                    final String userId) {

    this.context = context;
    this.arabaPlakalari = arabaPlakalar;
    arabalar = new HashMap<>();
    this.databaseReference = databaseReference;
    this.userId = userId;
    databaseReference.child("Arabalar")
            .child(userId)
            .addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    String plaka = dataSnapshot.getKey();
                    if(arabalar.get(plaka) == null){
                        databaseReference.child("Arabalar")
                                .child(userId)
                                .child(plaka).addValueEventListener(CustomPageAdapter.this);
                    }

                    notifyDataSetChanged();
                }

                @Override
                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onChildRemoved(DataSnapshot dataSnapshot) {
                    String plaka = dataSnapshot.getKey();
                    if(arabalar.get(plaka) != null){
                        arabaPlakalari.remove(plaka);
                        arabalar.remove(plaka);
                        databaseReference.child("Arabalar")
                                .child(userId)
                                .child(plaka)
                                .removeEventListener(CustomPageAdapter.this);
                    }

                    notifyDataSetChanged();
                }

                @Override
                public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
}

@Override
public Object instantiateItem(ViewGroup container, int position)
{
    String plaka = arabaPlakalari.get(position);
    Araba arabaBilgisi = arabalar.get(plaka);
    TextView muayeneTarihiTextView;
    TextView emisyonTarihiTextView;
    TextView sigortaTarihiTextView;
    TextView kaskoTarihiTextView;

    View viewLayout = LayoutInflater.from(context).inflate(R.layout.list_item_custom, container, false);
    muayeneTarihiTextView = (TextView) viewLayout.findViewById(R.id.muayeneTarihiTextView);
    kaskoTarihiTextView = (TextView) viewLayout.findViewById(R.id.kaskoTarihiTextView);
    emisyonTarihiTextView = (TextView) viewLayout.findViewById(R.id.emisyonTarihiTextView);
    sigortaTarihiTextView = (TextView) viewLayout.findViewById(R.id.sigortaTarihiTextView);

    muayeneTarihiTextView.setText(arabaBilgisi.getEditTextEmisyonTarihi());
    kaskoTarihiTextView.setText(arabaBilgisi.getEditTextKaskoTarihi());
    sigortaTarihiTextView.setText(arabaBilgisi.getEditTextSigortaTarihi());
    emisyonTarihiTextView.setText(arabaBilgisi.getEditTextEmisyonTarihi());
    container.addView(viewLayout);
    return viewLayout;
}

@Override
public int getCount() {
    return arabalar.size();
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return false;
}

@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
    Araba araba = dataSnapshot.getValue(Araba.class);
    String plaka = dataSnapshot.getKey();
    araba.setEditTextPlaka(plaka);
    arabalar.put(plaka, araba);
    if(!arabaPlakalari.contains(plaka)){
        arabaPlakalari.add(plaka);
    }

    notifyDataSetChanged();
}

@Override
public void onCancelled(DatabaseError databaseError) {

}

YaklasanlarFragment.java (It's fragment)
public class YaklasanlarFragment extends Fragment {

String userId;
FirebaseAuth firebaseAuth;
DatabaseReference dref;
ListView listview;
ArrayList<String> list=new ArrayList<>();
public ViewPager viewPager = null;
PagerAdapter adapter;
public  YaklasanlarFragment(){}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view= inflater.inflate(R.layout.activity_yaklasanlar_fragment, container, false);
    firebaseAuth=FirebaseAuth.getInstance();
    userId=firebaseAuth.getCurrentUser().getUid().toString();
    dref = FirebaseDatabase.getInstance().getReference();
    viewPager = (ViewPager) view.findViewById(R.id.viewPager);
    adapter=new CustomPageAdapter(getActivity(), new ArrayList<String>(),  dref, userId);
    viewPager.setAdapter(adapter);
    return view;
}

}
yaklasanlar_fragment.xml
<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="wrap_content"
    android:layout_height="545dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentBottom="true"
    android:layout_alignParentTop="true">
</android.support.v4.view.ViewPager>

list_item_custom.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_yaklasanlar_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.yunus.ototakip.YaklasanlarFragment">

<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="wrap_content"
    android:layout_height="545dp"
    android:layout_alignParentStart="true"
    android:layout_alignTop="@+id/linearLayout"
    android:layout_alignParentBottom="true">
</android.support.v4.view.ViewPager>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_marginTop="49dp"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:id="@+id/linearLayout">

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal" >

        <RelativeLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@color/divide1">

            <TextView
                android:id="@+id/muayeneTarihiTextView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:gravity="center"
                android:text="Muayene Tarihi bitimine"
                android:textColor="@color/beyaz"
                android:textSize="17sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_marginBottom="75dp"
                android:gravity="center"
                android:text="GÜN KALDI"
                android:textColor="@color/beyaz"
                android:textSize="17sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/muayeneFark"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="230dp"
                android:text="0"
                android:textAlignment="center"
                android:textColor="@color/beyaz"
                android:textSize="36sp"
                android:textStyle="bold" />
        </RelativeLayout>

        <RelativeLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@color/divide2">

            <TextView
                android:id="@+id/sigortaTarihiTextView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:gravity="center"
                android:text="Sigorta Tarihi bitimine"
                android:textColor="@color/beyaz"
                android:textSize="17sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/sigortaFark"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_marginBottom="75dp"
                android:gravity="center"
                android:text="GÜN KALDI"
                android:textColor="@color/beyaz"
                android:textSize="17sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/textView8"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="230dp"
                android:text="0"
                android:textAlignment="center"
                android:textColor="@color/beyaz"
                android:textSize="36sp"
                android:textStyle="bold" />
        </RelativeLayout>
    </LinearLayout>

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal" >

        <RelativeLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@color/divide1">

            <TextView
                android:id="@+id/kaskoTarihiTextView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:gravity="center"
                android:text="Kasko Tarihi bitimine"
                android:textColor="@color/beyaz"
                android:textSize="17sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/textView10"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_marginBottom="75dp"
                android:gravity="center"
                android:text="GÜN KALDI"
                android:textColor="@color/beyaz"
                android:textSize="17sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/kaskoFark"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="230dp"
                android:text="0"
                android:textAlignment="center"
                android:textColor="@color/beyaz"
                android:textSize="36sp"
                android:textStyle="bold" />
        </RelativeLayout>

        <RelativeLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@color/divide3">

            <TextView
                android:id="@+id/emisyonTarihiTextView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:gravity="center"
                android:text="Emisyon Değişim Tarihine"
                android:textColor="@color/beyaz"
                android:textSize="17sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/textView13"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_marginBottom="75dp"
                android:gravity="center"
                android:text="GÜN KALDI"
                android:textColor="@color/beyaz"
                android:textSize="17sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/emisyonFark"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="230dp"
                android:text="0"
                android:textAlignment="center"
                android:textColor="@color/beyaz"
                android:textSize="36sp"
                android:textStyle="bold" />
        </RelativeLayout>
    </LinearLayout>

</LinearLayout>

A: The problem was isViewFromObject method. I forgot to write inside of the method. And if you're gonna use the ViewPager you have to add destroyItem() method as well.
@Override
public boolean isViewFromObject(View view, Object object)
{
    return view==object;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object)
    {
        ((ViewPager) container).removeView((View) object);
    }


text:
Q: Maven discovery completed without finding any extensions I have installed eclipse 4.3 on my system and recently installed the Maven integration plugin. I get the following error:

Discovery completed without finding any extensions. Please check your network connection and try again.

The catalog url is http://download.eclipse.org/technology/m2e/discovery/directory-1.4.xml
Note: No proxies, no network issues

A: I was having the same issue on Mac OS X 10.8.5 with eclipse-kepler and Java 1.7_40 update.  I resolved it by reverting to an older (Java 1.6) version of Java.
You can find more details here about the details causing the issue:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=417241
Hope this helps
~J

A: There is a Java update 1.7.0_45 which fixes that problem.


text:
Q: MySQL JOIN very slow for no apparent reason MySQL version 8.0.17:
SELECT b.ColB
FROM Table2 b
JOIN Table1 a ON a.ColA = b.ColA
WHERE b.ColB = 1234 -- some number

With the JOIN, this query takes about 2 seconds to run, without the JOIN it is almost instant. This is just a minimal example, the actual case requires the WHERE condition to cover multiple values (e.g. WHERE b.ColB BETWEEN 1000 AND 2000) - which takes a very very long time...
Structure of Table1 (irrelevant columns and indexes removed for brevity):
CREATE TABLE `Table1` (
  `ColA` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`ColA`)
) ENGINE=InnoDB AUTO_INCREMENT=138221783 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

Structure of Table2 (irrelevant columns and indexes removed for brevity):
CREATE TABLE `Table2` (
  `ColA` int(11) NOT NULL,
  `ColB` int(11) NOT NULL,
  PRIMARY KEY (`ColA`,`ColB`),
  KEY `FK_Table2_Table1_idx` (`ColA`),
  KEY `FK_Table2_Table3_idx` (`ColB`),
  CONSTRAINT `FK_Table2_Table1` FOREIGN KEY (`ColA`) REFERENCES `Table1` (`ColA`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

This is the CSV of the explain on this query:
id,select_type,table,partitions,type,possible_keys,key,key_len,ref,rows,filtered,Extra
1,SIMPLE,rc,NULL,ref,"PRIMARY,FK_Table2_Table1_idx,FK_Table2_Table3_idx",FK_Table2_Table3_idx,4,const,607,100.00,"Using index"
1,SIMPLE,r,NULL,eq_ref,PRIMARY,PRIMARY,4,Table2.ColA,1,100.00,"Using index"

Some extra info running this SELECT COUNT(*) FROM Table1 took 8.735 seconds and returned 1947948.
Running this SELECT COUNT(*) FROM Table2 took 168.422 seconds and returned 19486319.
Why is the JOIN causing the query to run so very slowly?

A: If the only index is PRIMARY KEY(colA, colB) and the WHERE clause is testing colB=constant, then there is no usable index.
If this is a many-to-many mapping table you need to add INDEX(colB, colA) to allow for efficiently going from B to A.

A: To reduce the number of Rows that have to be joined reduce the number of rows as much as you can.
For your qiery
Use
SELECT b.ColB
FROM (SELECT * FROM Table2 WHERE ColB = 1234) b
JOIN Table1 a ON a.ColA = b.ColA

Instead of the SELECT * FROM Table2, you must use only the column that you actually need.


text:
Q: Can I use mutate filter in Logstash to convert some fields to integers of a genjdbc input? I am using genjdbc input plugin for Logstash to get data from a DB2 database. It works perfectly, I get in Kibana all the database columns as fields.
The problem I have is that in Kibana all fields are string type, and I want the numeric fields to be integers. I have tried the following code, but the result is the same that if no filter clause exists.
Can someone help me solving this? Thanks in advance!
The logstash.conf code:
  input {
    genjdbc {
      jdbcHost       => "XXX.XXX.XXX.XXX"
      jdbcPort       => "51260"
      jdbcTargetDB   => "db2"
      jdbcDBName     => "XXX"
      jdbcUser       => "XXX"
      jdbcPassword   => "XXX"
      jdbcDriverPath => "C:\...\db2jcc4.jar"
      jdbcSQLQuery    => "SELECT * FROM XXX1"
      jdbcTimeField => "LOGSTAMP"
      jdbcPStoreFile => "C:\elk\logstash\bin\db2.pstore"
      jdbcURL => "jdbc:db2://XXX.XXX.XXX.XXX:51260/XXX"
      type => "table1"
    }
    genjdbc {
      jdbcHost       => "XXX.XXX.XXX.XXX"
      jdbcPort       => "51260"
      jdbcTargetDB   => "db2"
      jdbcDBName     => "XXX"
      jdbcUser       => "XXX"
      jdbcPassword   => "XXX"
      jdbcDriverPath => "C:\...\db2jcc4.jar"
      jdbcSQLQuery    => "SELECT * FROM XXX2"
      jdbcTimeField => "LOGSTAMP"
      jdbcPStoreFile => "C:\elk\logstash\bin\db2.pstore"
      jdbcURL => "jdbc:db2://XXX.XXX.XXX.XXX:51260/XXX"
      type => "table2"
    }
  }

  filter {
    mutate {
      convert => [ "T1", "integer" ]
      convert => [ "T2", "integer" ]
      convert => [ "T3", "integer" ]
    }
  }

  output {
    if [type] == "table1" {
      elasticsearch {
        host => "localhost"
        protocol => "http"
        index => "db2_1-%{+YYYY.MM.dd}"
      }
    }
    if [type] == "table2" {
      elasticsearch {
        host => "localhost"
        protocol => "http"
        index => "db2_2-%{+YYYY.MM.dd}"
      }
    }
  }

A: What you have should work as long as the fields you are trying to convert to integer are names T1,T2,T3 and you are inserting into an index that doesn't have any data.  If you already have data in the index, you'll need to delete the index so that logstash can recreate it with the correct mapping.


text:
Q: How can increase image processing FPS in YOLOv7 using Azure CLoud I am developing the framework for Image processing using the Deep learning neural network YOLOv7. I have 20000 live data stream images per second, which is produced by the real-time machine. I want to handle these 20000Frames in minimal time using the current GPU architecture. Is this possible for I can increase the processing FPS using any open-source tools-techniques? multithreading or Kafka Concept.
Any suggestion or idea will be appreciated.
Note: I am using the NGINX server and docker-Kubernetes combo.


text:
Q: Проблема со swipe у ViewPager при обновленных Сервисах Google Play Добрый день!
Столкнулся с такой проблемой: имеется ViewPager с тремя элементами. У среднего элемента вот такая структура

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <fragment
            android:id="@+id/newMap"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            class="com.google.android.gms.maps.SupportMapFragment"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            />
  <FrameLayout
            android:id="@+id/mLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />

</RelativeLayout>

При этом если свайпать от края экрана, то все перелистывается хорошо, иначе, если это делать по середине элемента, то ничего не происходит. У боковых элементов без карты все работает хорошо.
Выяснил, что это происходит с обновленными Сервисами Google Play от 6 августа, ставил предыдущую версию (v 3.1.59) все прекрасно работает.
Есть идеи, как с этим бороться?
A: Проблема решена следующим образом

uiSettings.setAllGesturesEnabled(false);


text:
Q: error: PostgreSQL/15/lib/timescaledb-2.9.3.dll Unable to load library The specified module could not be found i have problem when i install timescaledb.
i installed postgresql-15.2-1-windows-x64, timescaledb-postgresql-15_latest-windows-amd64.
i followed install manual.
but i have error message which is '오류:  "C:/Program Files/PostgreSQL/15/lib/timescaledb-2.9.3.dll" 라이브러리를 불러 올 수 없음: The specified module could not be found.' when i write 'CREATE EXTENSION IF NOT EXISTS timescaledb;' on postgres cmd.
how can i fix it?
i tried that move files(ssleay32.dll , libeay32.dll) to C:\Program Files\PostgreSQL\15\bin folder.
but i have same problem.

A: Please, check if the configuration parameter shared_preload_libraries is in the postgresql.conf file and it matches the TimescaleDB .dll folder.
If the dll is not located there, you may need to move the library to the correct directory or update the configuration file to reflect the correct path.
Have you checked any different errors in the server logs?
Also, the troubleshooting doc can be useful: https://wiki.postgresql.org/wiki/Extension_build_troubleshooting
and a recent question on timescaledb forum: https://www.timescale.com/forum/t/how-to-install-timescale-db-on-window/1274


text:
Q: Excel 2016 (Office 365) Series Data Display Order I have run into a seemingly simple problem that I can't seem to figure out even though I have found countless topics about it on the internet. What I am trying to do is simply make one series of data in an Excel chart show as visible on top of any other series data that I have showing on the same chart.
Typically, I would just go to the "Source Data" option window from the right click menu and either move up or move down the data series to re-order them appropriately. However, no matter which order I have the series in some of the data points on my most prominent series are getting covered up by other data point markers from data points.
So my question is; are you aware of any other "features" that Excel may have that would counteract the standard series data order sequence of how the series look plotted on the screen?

A: There are a few behaviors you need to understand.
Series on secondary axes appear in front of those on primary axes.
In a combination chart, series chart types have a hierarchy as well. Areas are always in back, then bars and columns, then lines, then XY Scatter. But within line series, and within scatter series, if one has markers and no line, it will appear in front of another with markers and lines or just with lines, despite the plot order of the series.
Confused yet?


text:
Q: Spring Security bcrypt doesn't match I use the BCryptPasswordEncoder.
My password after hashed looks like that:

$2a$04$oPljpAgVziMVABHS.z.znOhhu7oi8N5pxt0MS6IbOTWn.onfulrZe.

When I test, it writes on the console that the password doesn't look like BCrypt.
I tested it with http://regexr.com with the regex in BCryptPasswordEncoder class (\A\$2a?\$\d\d\$[./0-9A-Za-z]{53}) but it doesn't match.
I've try with a A in beginning and it's matched.
I've retry with my app and I've the same error.
Do you know what append?
EDIT
Encoders.java
public class Encoders {

    @Bean
    public PasswordEncoder oauthClientPasswordEncoder() {
        return new BCryptPasswordEncoder(4);
    }
    @Bean
    public PasswordEncoder userPasswordEncoder() {
        return new BCryptPasswordEncoder(8);
    }
}

SecurityConfig.java
@Configuration
@EnableWebSecurity
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
@Import(Encoders.class)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder userPasswordEncoder;

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(userPasswordEncoder);
    }
}

ResourceServerConfig.java
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "resource-server-rest-api";
    private static final String SECURED_READ_SCOPE = "#oauth2.hasScope('read')";
    private static final String SECURED_WRITE_SCOPE = "#oauth2.hasScope('write')";
    private static final String SECURED_PATTERN = "/api/**";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .antMatchers(SECURED_PATTERN).and().authorizeRequests()
                .antMatchers(HttpMethod.POST, SECURED_PATTERN).access(SECURED_WRITE_SCOPE)
                .anyRequest().access(SECURED_READ_SCOPE);
    }
}

AuthorizationServerConfig.java
@Configuration
@EnableAuthorizationServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Import(SecurityConfig.class)
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder oauthClientPasswordEncoder;

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Bean
    public OAuth2AccessDeniedHandler oauthAccessDeniedHandler() {
        return new OAuth2AccessDeniedHandler();
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()").passwordEncoder(oauthClientPasswordEncoder);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager).userDetailsService(userDetailsService);
    }
}

data.sql
INSERT INTO OAUTH_CLIENT_DETAILS(CLIENT_ID, RESOURCE_IDS, CLIENT_SECRET, SCOPE, AUTHORIZED_GRANT_TYPES, AUTHORITIES, ACCESS_TOKEN_VALIDITY, REFRESH_TOKEN_VALIDITY)
 VALUES ('moha_security', 'resource-server-rest-api', 'A$2a$04$oPljpAgVziMVABHS.z.znOhhu7oi8N5pxt0MS6IbOTWn.onfulrZe',
 'read', 'password,authorization_code,refresh_token,implicit', 'USER', 10800, 2592000);

My request in postman
curl -X POST \
  http://localhost:8080/oauth/token \
  -H 'Postman-Token: 75a237ed-2e27-4af6-bca5-de558627f460' \
  -H 'cache-control: no-cache' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -F grant_type=password \
  -F username=201806ALE199501 \
  -F 'password=$2a$08$c.LqCdhrpAiF2Qn7yPGEw.6uL/phlSDW.QNXfMMWtnzSVX/paf2nK' \
  -F client_id=moha_security

My result in IntelliJ Console
2018-10-22 14:48:05.180  WARN 3483 --- [nio-8080-exec-5] o.s.s.c.bcrypt.BCryptPasswordEncoder     : Encoded password does not look like BCrypt

A: Your code is totally OK.
From wikipedia:
The prefix "$2a$" or "$2b$" (or "$2y$") in a hash string in a shadow password file indicates that hash string is a bcrypt hash in modular crypt format. The rest of the hash string includes the cost parameter, a 128-bit salt (Radix-64 encoded as 22 characters), and 184 bits of the resulting hash value.
About the A, it's just confusing,
Here is a small explanation:
When should I use \A in a regex?

A: I believe you are missing user roles definitions. Populate your roles in your database first.


text:
Q: code of website's navigation (about columns and rows) I'm writing to leave a question about my code while I'm coding.
I'm working on transferring the navigation design of the website to the code. If you look at the website navigation layout design attached as an image, there are 10 rows and 8 columns. So I wrote the code like this.
enter image description here
What I think is the problem is that without any text, the height setting value of 10% is not reflected. I would like to ask for your help on where and how to fix this.
In addition, I'm not a coding expert, so if you could answer me with a specific code test, I'd really appreciate it.
Thank you for your help in advance.
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Column 1

Column 2

Column 3

Column 4

Column 5

Column 6

Column 7

Column 8

Column 8

A: In this case, you can use CSS grid. So I recomment to follow attached link for comprehensive guide to CSS grid.
This is an example of using grid.
NOTE: I have change your HTML structure.

.container {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr;
}

header {
  display: grid;
  grid-template-columns: 1fr 7fr;
  grid-template-rows: 1fr 1fr;
  grid-template-areas: "logo nav" "logo notice";
}

.logo {
  background: red;
  grid-area: logo;
  padding: 10px;
  text-align: center;
}

nav {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-area: nav;
}

.notice {
  background: blue;
  grid-area: notice;
  padding: 10px;
}

nav a {
  padding: 10px;
  border-right: 1px dashed gray;
  text-align: center;
}

main {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  grid-template-rows: repeat(8, 1fr);
}

main>div {
  padding: 10px;
  border-right: 1px dashed gray;
  border-bottom: 1px dashed gray;
  text-align: center;
}

Logo

        About
        Exibition
        Shop

        En

Space for Notice

A

B

C

D

E

F

G

H

A

B

C

D

E

F

G

H

    </main