text:
Q: Google App Engine App added to google site used to work but now giving an error I created an app in Java in Eclipse on Google App Engine.  For about a year now, I've had that app embedded in a google site iframe as a gadget.  I added it using the "add gadget by URL" option and put in the URL of the app: https://mycompany-helpdesk.appspot.com (where mycompany is my company's actual name).
This has been working flawlessly for about a year.  Recently I made a small change to the Java code, and it seemed like about a week after that change, the app will not display in Google sites anymore.
The app works just fine if I navigate straight to its URL https://mycompany-helpdesk.appspot.com.
I removed the gadget iframe on my google site and then tried to add it back, but the error I'm getting now is:
The gadget you added is not valid

Unsupported feature: org.apache.shindig.common.xml.XmlException: The markup in the document preceding the root element must be well-formed. At: (1,3)

I have a couple of these apps and I tried using the other one, but I get the same error. I've tried to add them on other google sites and even created a fresh one and still get the same error. I've spent days googling this but I don't think I've found anything that applies to my situation.
Did something change where suddenly it is not possible to do this anymore?  If I can't embed the app this way any more, does anyone know of another way that I might be able to do this?
UPDATE:  When I am editing the site, under Insert > More gadgets, if, instead of using the "Add Gadget by URL" link (which is what I've been using to insert this gadget) I use the "Include gadget (iframe)" gadget developed by Scott Johnston, then my apps will appear in Firefox and Safari, but not Chrome.  This is not useful to me as our employees primarily use Chrome.
I think I'm just going to abandon Google Sites and redo the page in GAE.  Hope this helps someone else who has been banging their head against their desk as I have been.
Update:  I noticed that suddenly all the embedded apps on my test pages were working, so I reverted to an old version of the google site where the app was still embedded.  Voila, it works again.  Now if I can just figure out how to add in another embedded app I'll be good to go.  It had been working in Safari and Firefox but that doesn't seem to be working now...


text:
Q: How to simply output a binary file in Perl and read it from Android (Java)? What am I missing in my code? Maybe headers (I tried a lot of them). The picture is received on the client side, but it cannot read it (meaning it must have been corrupted, either information is added or subtracted).
The server side is:
my $file = "<The path of the file>";

my $length = (stat($file)) [10];
print "Content-type: image/jpg\n";
print "Content-length: $length \n\n";

#open FH,"$file";
#binmode STDOUT;
#while(<FH>){ print }
#close FH;

binmode STDOUT;
open my $file_s,'<', $file || die "Could not open $file: $!";
my $buffer = "";

while (read($file_s, $buffer, 1024)) {
    print $buffer;
}
close($file_s);

The Android side is:
String filename = Environment.getExternalStorageDirectory().getPath() + "/somename.jpg";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("<some url>");
StringBuilder response = new StringBuilder();
Charset chars = Charset.forName("UTF-8"); // Setting up the encoding

try {
    HttpResponse httpResponse = httpclient.execute(httppost);
    if (httpResponse.getStatusLine().getStatusCode() == 200) {
        HttpEntity messageEntity = httpResponse.getEntity();
        InputStream is = messageEntity.getContent();
        long filesize = httpResponse.getEntity().getContentLength();
        FileOutputStream fileOutput = new FileOutputStream(new File(filename));
        byte[] buffer = new byte[1024];

        int len;
        while ((len = is.read(buffer, 0, 1024)) > 0) {
            fileOutput.write(buffer, 0, len);
        }

        fileOutput.close();
    }
}
catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

A: The right code for Perl is:
my $file = "<The path of the file>";

my $length = (stat($file)) [10];
print "Content-type: application/binary\n";
print "Content-length: $length \n\n";

open FH,"$file";
binmode STDOUT;
while(<FH>){
    print
}
close FH;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Strange behaviour insert_one mongocxx 3.6 Working with mongocxx I am trying to retrieve the object id assigned by mongodb when I insert a new object in a collection(insert_one method), and convert this id into a string. This is the code:
  const mongocxx::database& db = _pClient->database(_dbName.c_str());
  mongocxx::collection& collection = db.collection(collectionName.c_str());
  auto retval = collection.insert_one(view);
  bsoncxx::oid oid = retval->inserted_id().get_oid().value;
  std::string str = oid.to_string()

Unfortunately it looks like when I try to convert the object id to a string the string is unreadable (corrupted like). I am using mongocxx version 3.4 and mongodb 4.0.28 (the two versions should be compatible according to the mongodb website). Do you know what could be the problem here?
Here what I can see through the debugger: visual studio debugger
Here what I can see thorugh the mongodb client: mongodb client

A: The debugger is showing you the individual bytes in decimal.
I used the mongo shell to convert these to hex, you can see that it is indeed the ObjectID you were looking for, it just looks strange in decimal
mongos> [98,3,-24,41,-88,89,0,0,-93,0,88,-78].map(n=>("0" +((n & 255).toString(16))).slice(-2)).join("")
6203e829a8590000a30058b2


text:
Q: Convert SQL into CriteriaBuilder statement Can you help me converting this SQL statement into a CriteriaBuilder statement? The problem I have is with the INNER JOIN statement.
SELECT th.id, th.date, th.exercise_id
FROM traininghistory th
INNER JOIN (
  SELECT exercise_id, MAX(date) as maxdate
  FROM traininghistory
  group by exercise_id
  ) AS tm on tm.exercise_id = th.exercise_id AND th.date = tm.maxdate
WHERE th.accountid = :accountId

@Entity
public class TrainingHistory {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @NotNull
    public Long id;

    public Long accountId;

    @ManyToOne
    public Exercise exercise;

    public Date dateDone = new Date();

    public WellBeing wellBeing;

    public int weight;

    public int repetitions;

    public int duration;
}

A: Found a solution by reformulating the query without the INNER JOIN. The following SQL query achieves the same result as the SQL query in the question, but was translatable for me into Criteria API.
FROM traininghistory th
WHERE th.datedone in (
SELECT MAX(tm.datedone)
  FROM traininghistory tm
  GROUP BY tm.exercise_id
)
AND th.accountid = :userId

So using that as a basis the statement using Criteria API is as follows:
// define query
CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
CriteriaQuery<TrainingHistory> query = cb.createQuery(TrainingHistory.class);
Root<TrainingHistory> root = query.from(TrainingHistory.class);
query.select(root);

// define subquery
Subquery<Integer> subquery = query.subquery(Integer.class);
Root<TrainingHistory> rootSubquery = subquery.from(TrainingHistory.class);
Expression<Integer> max = cb.max(rootSubquery.get(TrainingHistory_.DATE_DONE));
   subquery.select(max);
   subquery.groupBy(rootSubquery.get(TrainingHistory_.exercise));

// compose whole query
query.where(
   cb.and(
      cb.in(root.get(TrainingHistory_.DATE_DONE)).value(subquery),
      cb.equal(root.get(TrainingHistory_.ACCOUNT_ID), userId)
  )
);

return this.entityManager.createQuery(query).getResultList();


text:
Q: How to make `npm install ` actually install `@myfancyname/package_a` Let's say I published few years back a npm package package_a.
Now I actually "namespaced" all my packages under @myfancyname/package_a.
Is there a way to transform package_a install process so that
npm install -g package_a
actually just run
npm install -g @myfancyname/package_a
(of course this should work also for npm install package_a -> npm install @myfancyname/package_a)
This might be bad practice, so please advice in this case as well.

A: TL;DR: It's likely that the best solution is to use npm deprecate on your old package to provide people with a message directing them to the new package name.
This issue in the npm issue tracker suggests contacting support@npmjs.com. The issue is quite old, though, and also only seems to suggest contacting support for a large number of packages. Although the issue may be out of date, if there's a better way to do things, I'm sure the support team would redirect you there.
That said, while that npm issue title asks about a redirect (implying, to me at least, automatic redirect like what you want), the answers seem to be more about "redirecting" by informing users. Chances are, that's the recommended way, for better or worse. So you can use npm deprecate on your old package to provide people with a message directing them to the new package name.


text:
Q: Count strings with a certain condition I have the following dataset
 #mydata
 Factors    Transactions
  a,c             2
  b               0
  c               0
  d,a             0
  a               1
  a               0
  b               1

I'd like to count those factors who had transactions.For example, we had two times "a" with transaction. I can write a code to give me my desirable outcome for each variable separately. The following is for "a".
 nrow (subset (mydata,mydata$Transaction > 0 & length(mydata[grep("a", mydata$Factors),] )> 0))

But I have too much variables and do not want to repeat a code for all of them. I would think there should be a way to write a code to give me the results for all of the variables. I wish to have the following out put:
#Output
a    2
b    1
c    1
d    0

A: Equivalent data.table option:
library(data.table)

setDT(df)[, .(Factors = unlist(strsplit(as.character(Factors), ","))),
      by = Transactions][,.(Transactions = sum(Transactions > 0)), by = Factors]

#   Factors Transactions
#1:       a            2
#2:       c            1
#3:       b            1
#4:       d            0

A: You could create a table using the unique values of the Factor column as the levels. Consider df to be your data set.
s <- strsplit(as.character(df$Factors), ",", fixed = TRUE)
table(factor(unlist(s[df$Transactions > 0]), levels = unique(unlist(s))))
#
# a c b d
# 2 1 1 0

Wrap in as.data.frame() for data frame output.
with(df, {
    s <- strsplit(as.character(Factors), ",", fixed = TRUE)
    f <- factor(unlist(s[Transactions > 0]), levels = unique(unlist(s)))
    as.data.frame(table(Factors = f))
})
#   Factors Freq
# 1       a    2
# 2       c    1
# 3       b    1
# 4       d    0

A: With tidyverse packages, assuming your data is strings/factors and numbers,
library(tidyr)
library(dplyr)

       # separate factors with two elements
df %>% separate_rows(Factors) %>%
  # set grouping for aggregation
  group_by(Factors) %>%
  # for each group, count how many transactions are greater than 0
  summarise(Transactions = sum(Transactions > 0))

## # A tibble: 4 x 2
##   Factors Transactions
##     <chr>        <int>
## 1       a            2
## 2       b            1
## 3       c            1
## 4       d            0

You could also avoid dplyr by using xtabs, though some cleaning is necessary to get to the same arrangement:
library(tidyr)

df %>% separate_rows(Factors) %>%
  xtabs(Transactions > 0 ~ Factors, data = .) %>%
  as.data.frame() %>%
  setNames(names(df))

##   Factors Transactions
## 1       a            2
## 2       b            1
## 3       c            1
## 4       d            0

A full base R equivalent:
df2 <- do.call(rbind,
               Map(function(f, t){data.frame(Factors = strsplit(as.character(f), ',')[[1]],
                                             Transactions = t)},
                   df$Factors, df$Transactions))

df3 <- as.data.frame(xtabs(Transactions > 0 ~ Factors, data = df2))
names(df3) <- names(df)

df3
##   Factors Transactions
## 1       a            2
## 2       b            1
## 3       c            1
## 4       d            0

A: We can use cSplit from splitstackshape to split the 'Factors' into 'long' format and grouped by 'Factors' we get the sum of logical column ('Transactions > 0`).
library(splitstackshape)
cSplit(df1, "Factors", ",", "long")[, .(Transactions=sum(Transactions > 0)),.(Factors)]
#   Factors Transactions
#1:       a            2
#2:       c            1
#3:       b            1
#4:       d            0

Or using base R
with(df1, table(factor(unlist(strsplit(Factors[Transactions>0], ",")),
           levels = letters[1:4]) ))

#  a b c d
#  2 1 1 0

data
df1 <- structure(list(Factors = c("a,c", "b", "c", "d,a", "a", "a",
"b"), Transactions = c(2L, 0L, 0L, 0L, 1L, 0L, 1L)), .Names = c("Factors",
"Transactions"), class = "data.frame", row.names = c(NA, -7L))


text:
Q: Powershell "Start-process" not running as scheduled task Have two powershell scripts that I edited from XP to run in Win Server 2k8 R2.
They run fine when executed by manually in powershell, but if scheduled and run as domain admin, they perform all file operations they're supposed to; except they don't do a start-process that sends the file to the SFTP site it needs to go to.
They're launched by running powershell.exe with arguments as such:
-noprofile -ExecutionPolicy Bypass -file C:\Users\administrator\Documents\script1.ps1

Again, like I mentioned previously, they run fine and launch the start-process as requested if you manually run them and only run the file operations if they're scheduled and skip the start-process.
The start-process is as follows:
start-process -FilePath "c:\Program Files (x86)\Tumbleweed\STClient\stclient.exe" -ArgumentList "httpsu://www.securesiteexample.org/incoming/ $filename /prefNoAskSched /hidden /log /Remote-Site return /quitWhenDone"

What am I missing?

A: Add some code to check to make sure the process is getting launched.
$FileName = 'c:\test\test.txt';
$ArgumentList = "httpsu://www.securesiteexample.org/incoming/ $filename /prefNoAskSched /hidden /log /Remote-Site return /quitWhenDone";
$ExePath = 'c:\Program Files (x86)\Tumbleweed\STClient\stclient.exe';

$Process = Start-Process -FilePath $ExePath -ArgumentList $ArgumentList -PassThru;

# If $Process variable is null, then something went wrong ...
if (!$Process) {
    # Process did not start correctly! Write the most recent error to a file
    Add-Content -Path $env:windir\temp\sftp.log -Value $Error[0];
}

A: In your Task, go to Actions pane, edit and remove anything from start in field.


text:
Q: VBA to add new sheet in a closed excel without opening & get the sheet name added? I have an excel "Closed.Xls" which is not opened currently.
Please let me know how to add new sheets in to this closed excel file. I know how to add new sheets in current excel.
Dim WS as Worksheet
Set WS = Sheets.Add

Please let me know how to

*

*add new sheets in a closed excel using VBA, and

*get the name of the sheet added

Note: I don't want to rename the sheet.
Thanks

A: To get the sheet name use a worksheet variable, ie
Sub Added()
    Dim Wb As Workbook
    Dim ws As Worksheet

    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
        .EnableEvents = False
    End With

    Set Wb = Workbooks.Open("c:\Temp\closed.xls")
    Set ws = Wb.Sheets.Add
    Debug.Print ws.Name
    Wb.Save
    Wb.Close

    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
        .EnableEvents = True
    End With
End Sub

A: It is possible to add a sheet without opening the workbook by using the Microsoft.ACE.OLEDB.12.0 provider:
set cn = new adodb.connection

with cn
   .provider = "Microsoft.ACE.OLEDB.12.0"
   .connectionstring = "Data Source=" & strSomeFilename & ";Extended Properties=""Excel12.0;"""
   .open
end with

set cmd = new adodb.command
cmd.activeconnection = cn
cmd.commandtext = "CREATE TABLE MySheet (ID char(255))"
cmd.execute

This will add a heading "ID" to cell A1 of the new sheet. You can probably find a way to delete/change it if necessary.

A: Something like this will will do what you want. It is not possible without opening the workbook but if you turn off screen updating it gives the appearance of not being opened.
Option Explicit
Sub Add_Sheet_ClosedBook()
    Dim bk As Workbook
    Dim sh As Worksheet
    Dim shName As String

    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
    Set bk = .Workbooks.Open _
    ("Path to Book.xls")
    End With

    With bk
        Set sh = .Sheets.Add
        shName = sh.Name
        .Save
        .Close
    End With

    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
    End With
End Sub


text:
Q: Why does had seem to be mandatory here I have  had replies to this question but none of them explained me why !!
"I wasn't expecting you to contact me again!!
I (had) tried to contact you so many times and did not receive an answer that I had completely forgotten that I had made an order.I was surprised to receive your email today
1°Would like to know why "had" seems to be mandatory here
The meaning is not very clear . It is not because I was surprised to receive an email today that I had tried to contact him before . To make sure it was before "had" seems to me obligatory (but I may be wrong). If it is the case can somebody explain me why!!!!
2 ° Does it convey the meaning : that first I made an order , then tried to email the seller without any luck(did not answer) then had forgotten this order until I received this message

A: Your interpretation in (2) seems correct to me.
The speaker was not expecting to hear from their correspondent again because they had earlier tried repeatedly to contact them, without success. The enquiries were about an order, which the speaker had since forgotten about until they received this message.


text:
Q: Session variable works on local server, but not on hosting server with symfony2.8 I have done an App with symfony 2.8 which works well on local server but not on hosting server; all codes like $this->get('session')->set('non',$variable); generate an error and sent me on a 503 error page. some one has an idea?
this is the proper code:
public function indexAction(Request $request) {

    if ($request->isMethod('POST')) {

        $semester = $request->get('smt');
        $request->getSession()->set('semester', $semester);//generate an error: same with  $this->get('session')->set('semester', $semester)
        return $this->redirect($this->generateUrl('httc_enrollment_registration'));
    }

    $f = $request->get('update');

    if ($f == 1) {
        $request->getSession()->set('update_formb', 1);//generate and error: same with $this->get('session')->set('update_formb', 1);
    } else {
        $this->get('session')->set('update_formb', 0); //generate the same error
    }

  return $this->render('HTTCEnrollmentBundle:Enrollment:index.html.twig');

}

A: Try to set in config.yml
session:
     handler_id:  ~

A: the problem was DoctrineBunle which was for the 5.5+ Php version. so i took another version and it works. thanks for you help.


text:
Q: Passing string back in popViewControllerAnimated I have a UIViewController(1), I press on a view in that controller and it then push's another UIViewController(2) with a full screen UITableView in it.
I then press on a cell in the UITableView and want to pass back to UIViewController(1) a string in the UITableView. I have tried using the below delegete method but it doesn't work, please can somebody advise.
UIViewController2.h
@protocol SecondDelegate <NSObject>
-(void) secondViewControllerDismissed:(NSString *)stringForFirst;
@end

@interface ViewController2 : UIViewController
{
    id myDelegate;
}
@property (nonatomic, assign) id<SecondDelegate> myDelegate;
@end

and
UIViewController2.m (inside didSelectRowAtIndexPath)
    [self.myDelegate secondViewControllerDismissed:@"the string I'm passing"];

and
UIViewController1.h
import "ViewController2.h"
    @interface ViewController1 : UIViewController <SecondDelegate>

@end

and
UIViewController1.m
- (void)secondViewControllerDismissed:(NSString *)stringForFirst
{
    NSString *myString = stringForFirst;
    self.myLabel.text = myString;
}

A: A few things:

*

*remove id myDelegate; inside your @interface ViewController2

*change your @property (nonatomic, assign) id... to @property (nonatomic, weak) id..., that is just safer (see why)

Regarding your question: you present the view via a segue!? Therefore you need to overwrite the prepareForSegue method, extract the destinationViewController from the segue and set its delegate property to self. Without that, your ViewController2 never gets a valid delegate set. All that needs to be done in the viewController presenting the ViewController2:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    [super prepareForSegue:segue sender:sender];
    if ([segue.identifier isEqualToString:@"yourCustomSegueIdentifier"]) {
        ViewController2 *controller = (ViewController2*)segue.destinationViewController;
        controller. myDelegate = self;
    }
}

Either set an identifier of your segue in the storyboard and use the same identifier in the ode above or remove the if all together (unclean).


text:
Q: Tangent bundle of the incidence variety and its Chern class I am trying to learn about Thom polynomials and I often find arguments in the literature that just make no real sense to me. Maybe it is due to my lack of knowledge in $K$ - theory. I apologize for the lengthy post, but maybe someone knows these things well.
Let $P := \mathbb{C}P^n$, $N := \mathbb{C}P^{n*}$ and set $X := P\times N$. Denote by $p_1:X\rightarrow P$ and $p_2: X\rightarrow N$ the natural projections. Let $V = \mathbb{V}(F)\subset P$ be a hypersurface of degree $d$ and $H = \{(x,a^*)\in P\times N:\text{ }a^*(x) = 0\}$ be the incidence variety of points and lines in $P$. In fact, $H$ can be realized as the zero-set (zero-scheme) of a section of the line bundle $p_1^*\mathcal{O}_P(1)\otimes p_2^*\mathcal{O}_N(1)$ over $X$.
Also, the polynomial $F$ defines a section of the line bundle $p_1^*\mathcal{O}_P(d)$ over $X$. Hence, there is an induced section of the rank $2$ vector bundle $E =p_1^*\mathcal{O}_P(d)\oplus (p_1^*\mathcal{O}_P(1)\otimes p_2^*\mathcal{O}_N(1))$ over $X$. Its zero-set (zero-scheme) is the subvariety $M :=\{ (x,a^*)\in V\times N:\text{ }a^*(x) =0\}$, i.e. the incidence variety of points in $V$ and lines in $P$.
Define $f:M\rightarrow N$ by composing $p_2:X\rightarrow N$ with the inclusion $i:M\hookrightarrow X$, i.e. $f = p_2\circ i$. I am interested in computing the total Chern class $c(f^*TN-TM)$, where $f^*TM-TN$ is the virtual bundle living in the $K$ - group of $M$.
The claim is: $$TM = i^*(TX-E)\text{ and hence } f^{*}TN - TM = i^{*}(E - p_1^*TP).$$
It appears to me that these are just standard calculations in $K$ - groups but I don't get it.

A: I now have some idea on how to prove these relations. Consider a real vector bundle $\pi:E\rightarrow X$ of rank $k$, where $E$ and $X$ are $C^\infty$ manifolds and let $X$ be $n$,-,dimensional. If $s$ is a section transverse to the zero - section, then its zero set $Z(s) = \{x\in X|\text{ }s(x)=0_x\in E_x\}$ is a submanifold of $X$. What's more, on local bundle charts $U\subset X$, the restriction $s|U$ is a submersion in points $x\in U$ with $s(x) = 0$, meaning $\text{im}(ds(x))= \mathbb{R}^k$.
Let $M := Z(s)$, then the tangent space $T_xM$ can be identified with $\text{ker}(ds(x))$ and the normal space is isomorphic to $\mathbb{R}^k$, which follows from the canonical exact sequence
$$0\rightarrow T_xM = \text{ker}(ds(x))\rightarrow T_xX\rightarrow N_xM = T_xX/T_xM\rightarrow 0.$$
Hence, $TX = TM \oplus i^*E$, where $i:M\hookrightarrow X$ is the inclusion. This proves $$TM = TX-i^*E\in K_0(X)$$
The second identity follows from $TX = TP\oplus TN$.
Although the computation above is valid for real vector bundles, I think we can interpret any complex vector bundle as a real vector bundle of twice the rank. Also $\mathbb{C}P^n$ is a $2n$ - dimensional real manifold...


text:
Q: In @SpringBootTest, how do I get a fasterxml objectMapper to include a field from my model? I'm using Spring Boot 2.1 with Java 11.  I have annotated my User model with fasterxml annotations so that my password can be accepted for POST requests, but not returned for other REST requests ...
@Data
@Entity
@Table(name = "Users")
public class User implements UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID id;

    private String firstName;
    private String lastName;

    @NotBlank(message = "Email is mandatory")
    @Column(unique=true)
    private String email;

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String password;
    private boolean enabled;
    private boolean tokenExpired;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
        name = "users_roles",
        joinColumns = @JoinColumn(
          name = "user_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(
          name = "role_id", referencedColumnName = "id"))
    private Collection<Role> roles;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String getUsername() {
        return email;
    }

    @Override
    public boolean isAccountNonExpired() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isAccountNonLocked() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        // TODO Auto-generated method stub
        return false;
    }

    @PrePersist @PreUpdate
    private void prepare(){
        this.email = this.email.toLowerCase();
    }
}

However, when trying to run an integration test, the password is not getting translated by "objectMapper.writeValueAsString".  Here is my test ...
@SpringBootTest(classes = CardmaniaApplication.class,
webEnvironment = WebEnvironment.RANDOM_PORT)
public class UserControllerIntegrationTest {

    @Autowired
private TestRestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private IUserRepository userRepository;

    @Test
    @WithUserDetails("me@example.com")
    void registrationWorksThroughAllLayers() throws Exception {
        final String email = "newuser@test.com";
        final String firstName = "first";
        final String lastName = "last";
        final String password = "password";
        User user = getTestUser(email, password, firstName, lastName, Name.USER);

        ResponseEntity<String> responseEntity = this.restTemplate
            .postForEntity("http://localhost:" + port + "/api/users", user, String.class);
    assertEquals(201, responseEntity.getStatusCodeValue());

        final User createdUser = userRepository.findByEmail(email);
        assertNotNull(createdUser);
        assertNotNull(createdUser.getPassword());
    }

    @Test
    @WithUserDetails("me@example.com")
    void getDetailsAboutMyself() throws JsonProcessingException, JSONException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails user = (UserDetails) authentication.getPrincipal();
        final User foundUser = userRepository.findByEmail(user.getUsername());
        ResponseEntity<String> responseEntity = this.restTemplate
            .getForEntity("http://localhost:" + port + "/api/users/" + foundUser.getId(), String.class);
        assertEquals(200, responseEntity.getStatusCodeValue());
        // assert proper response
        final String userAsJson = objectMapper.writeValueAsString(user);
        assertEquals(userAsJson, responseEntity.getBody());
        JSONObject object = (JSONObject) new JSONTokener(userAsJson).nextValue();
        // Verify no password is returned.
        assertNull(object.getString("password"));
    }
    ...
}

The JSON from the objectMapper.writeValueAsString call is
{"id":null,"firstName":"first","lastName":"last","email":"newuser@test.com","enabled":true,"tokenExpired":false,"roles":null,"username":"newuser@test.com","authorities":null,"accountNonExpired":false,"accountNonLocked":false,"credentialsNonExpired":false}

What's the proper way to get my password included as part of the mapping as well as suppressing the password when requesting my entity from read endpoints?

A: This is a common misunderstanding, there was even a bug report for it and they clarified the documentation.
"READ" and "WRITE" are to be understood from the perspective of the Java Property, i.e., when you serialize an Object, you have to read the property and when you deserialize it, you have to write it.
In your case, you want @JsonProperty(access = JsonProperty.Access.READ_ONLY)

A: *

*Using WRITE_ONLY or READ_ONLY will not work in your case. The reason is one call over http needs both. Lets take this.restTemplate.postForEntity as an example. In the sending side, your User java object need to serialised to json so it needs the READ and when the rest endpoint receives the json, it need to deserialise the json into User java object so needs the WRITE. It will be the same scenario for this.restTemplate.getForEntity too

*One solution is to set the password field of User on the GET endpoint to null before returning

*Another solution is create a separate UserDto without password field and return it from GET endpoint

*Another solution is to create two JsonViews where one is with password and other one is without password. Then annotate your endpoints with correct @JsonView


text:
Q: How to use initWithModulus function in MyCrypto library? I use MyCrypto library for a IPhone app.  The program will comunicate with a web service that is writen by WCF.The service will provide a public key by providing modulus and exponent. Thus, we need use initWithModulus to create a public key. The code is as following.
MYPrivateKey *pair = [[MYKeychain defaultKeychain] generateRSAKeyPairOfSize: 2048];
MYPublicKey *pub = pair.publicKey;
NSData * outModulus;
unsigned outExponent;
[pub getModulus:&outModulus exponent:&outExponent];
MYPublicKey *serverKey = [[MYPublicKey alloc] initWithModulus: outModulus exponent: outExponent];
NSString *tmpStr = @"test!";
NSData *tmpData = [tmpStr dataUsingEncoding: NSASCIIStringEncoding];
NSData *crypted = [serverKey rawEncryptData: tmpData];
NSData *crypted2 = [pub rawEncryptData: tmpData];

For test, I use initWithModulus to create a publickey. Then the same data are encrypted with the original key and the new one.  But the lengths of the two encrypted data are different. How shoud I do?

A: What are the mismatched lengths? When I run this code (in the iOS 4 simulator) it works, and the length of the encrypted data is 256 bytes.
If you try encrypting with the original private key and then decrypting with the reconstituted public key, does that work?


text:
Q: PreferenceCategory theme not applied to PreferenceScreen I saw lots of answers and threads regarding this problem alone with tutorials for how to create custom PreferenceCategory. Nothing works for me. My theme just not applied.
PreferenceActivity class:
public class PreferencesActivity extends PreferenceActivity{

private MyPreferenceFragment preferences;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    preferences = new MyPreferenceFragment();
    getFragmentManager().beginTransaction().replace(android.R.id.content, preferences).commit();
}

public static class MyPreferenceFragment extends PreferenceFragment
{
    @Override
    public void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.layout.mypreferences);
    }
}
}

AndroidManifest:
<activity android:name="com.gpsy.preferences.PreferencesActivity"
            android:screenOrientation="portrait" android:configChanges="keyboardHidden|orientation"
            android:theme="@style/Custom">
</activity>

styles.xml:
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="PreferenceListHeader" >
    <item name="android:textColor">#000000</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textSize">12sp</item>
    <item name="android:background">@color/Gray</item>
    <item name="android:paddingTop">6dp</item>
    <item name="android:paddingBottom">6dp</item>
    <item name="android:paddingLeft">12dp</item>
</style>

<style name="Custom" parent="@android:Theme.Light.NoTitleBar">
    <item name="android:listSeparatorTextViewStyle">@style/PreferenceListHeader</item>
</style>
</resources>

mypreferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<PreferenceCategory
        android:title="@string/gps_settings">

    <ListPreference
            android:key="nav_systems_preference"
            android:title="@string/my_nav_app"
            android:summary="summary_checkbox_preference"/>

</PreferenceCategory>
</PreferenceScreen>

Also, I tried to apply theme the following way without success:
setTheme(R.style.Custom);

Tryed to change PreferenceCategory tag to
<PreferenceCategory android:widgetLayout="@style/Custom"
        android:title="@string/gps_settings">

A: Your theme is not working because you did not set android:layout_width and android:layout_weight nor could it be inherited from a parent (which is not given).
For <style name="PreferenceListHeader" >, just add the following:
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>

You don't need setTheme(R.style.Custom); or android:widgetLayout="@style/Custom" then. You can't provide a style to android:widgetLayout, anyway. You would have to provide a layout resource that contains just a TextView. But if you choose to use the style (see above), you don't need to set the layout.


text:
Q: Is this problem of selecting points NP-hard? I have an optimization problem related, in a certain way, to the expression of a set of points with the least number of points and I don't know if it is NP-hard (or not).
More formally, I have a ground set $U$ of points with coordinates $(x_i,y_i)$ for $i=1,...,n$.
Given an integer $k\leq n$, the decision problem consists in finding a subset $I$ (made of $k$ points) of $U$ such that every point of $U$ can be written as the convex combination of at most two points of $I$.
For example, let $U=\{(0,0) ; (1,3) ;(2,6); (3,0);(2,3/2);(4,3);(6,0)\}$.
There is a solution with $k=4$ wich is $I=\{(0,0) ; (2,6); (4,3);(6,0)\}$.
Indeed, we have $(1,3)=\frac{(0,0)+(2,6)}{2}$; $(2,3/2)=\frac{(0,0)+(4,3)}{2}$ and $(3,0)=\frac{(0,0)+(6,0)}{2}$.
IP formulation
Let $C_{ij}$ be the indices of the points belonging to $U$ which can be expressed as a convex combination of $(x_i,y_i)$ and $(x_j,y_j)$.
I think all these $C_{ij}$'s can be computed in $O(n^2)$ time.
Then we can write the following IP with $O(n^2)$ binary variables:
$$
\min x_1+...+x_n
$$
$$\sum_{(i,j)|p\in C_{ij}}y_{ij}\geq 1 \text{ for all } p=1,...,n,$$
$$y_{ij}\leq x_i, y_{ij}\leq x_j \text{ for all } i,j=1,...,n,$$
$$x_i\in\{0,1\} \text{ and } y_{ij}\in\{0,1\} \text{ for all } i,j=1,...,n.$$
I started looking into Garey & Johnson for some similarities with existing problems, but I don't see how to "express" the condition of the convex combination.
Thanks for any advice! (related problems, ...)

A: This problem is reducible from VERTEX-COVER. A rough description: let the input graph to VERTEX-COVER be $G = (V, E)$ with $|V| = n$. Choose integer $n << t = O(n^c)$, and create a convex polygon $P$ on $1 + n + 2t$ vertices $C_0$, $C_1$, $\ldots$, $C_n$, $D_1$, $\ldots$, $D_t$, $E_1$, $\ldots$, $E_t$. Choose vertices $V_1$, $\ldots$, $V_n$ on sides $C_0 C_1$, $\ldots$, $C_{n - 1} C_n$. Now, for each edge $ij \in E$ with $i, j \in V$ and $i < j$ add all points on intersections of $V_i D_k$ and $V_j E_l$ with $1 \leq k, l \leq t$. We choose coordinates in such a way that no point of the plane has more than two diagonals of $P$ passing through it, and no three intersection points share non-trivial common lines together with vertices $P$ (other than diagonals of $P$ when intended).
Obviously, we have to include all vertices of $P$ into $I$. Vertices $V_i$ are already covered by sides of $P$, so we have freedom of including any subset of them. For an edge $ij \in E$ we have to cover all intersections of $V_i D_k$ and $V_j E_l$ either by including one of $\{V_i, V_j\}$ into $I$, or take some of the intersections into $I$; in the latter case, $\Omega(t)$ intersections need to be included, which effectively prohibits us from doing this. We can now see that the minimal size of $I$ is exactly $1 + n + 2t + VC(G)$, where $VC(G)$ is the size of minimal vertex cover of $G$.
The last remark is that we have to make sure that it is possible to choose all coordinates so that length of coordinates of each point is polynomial in $n$, which is technical.


text:
Q: Como inicializo o Maps num lugar específico? Como faço para que o App, no momento que abra o Google Maps, abra com o zoom num lugar específico (por exemplo, numa coordenada específica)? Os códigos da demo ele mostra TODOS os continentes quando inicializo sendo necessário dar zoom até a minha marcação:
       public class MapsActivityWifi extends FragmentActivity {

            private GoogleMap mMap; // Might be null if Google Play services APK is not available.

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

            @Override
            protected void onResume() {
                super.onResume();
                setUpMapIfNeeded();
            }

            /**
             * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
             * installed) and the map has not already been instantiated.. This will ensure that we only ever
             * call {@link #setUpMap()} once when {@link #mMap} is not null.
             *

             * If it isn't installed {@link SupportMapFragment} (and
             * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
             * install/update the Google Play services APK on their device.
             *

             * A user can return to this FragmentActivity after following the prompt and correctly
             * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
             * have been completely destroyed during this process (it is likely that it would only be
             * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
             * method in {@link #onResume()} to guarantee that it will be called.
             */
            private void setUpMapIfNeeded() {
                // Do a null check to confirm that we have not already instantiated the map.
                if (mMap == null) {
                    // Try to obtain the map from the SupportMapFragment.
                    mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                            .getMap();
                    // Check if we were successful in obtaining the map.
                    if (mMap != null) {
                        setUpMap();
                    }
                }
            }

            /**
             * This is where we can add markers or lines, add listeners or move the camera. In this case, we
             * just add a marker near Africa.
             *

             * This should only be called once and when we are sure that {@link #mMap} is not null.
             */
            private void setUpMap() {
                List<MarkerOptions> places = new ArrayList<>();
                mMap.addMarker(new MarkerOptions().position(new LatLng(-23.560334, -46.645547)).title("Marker").snippet("teste"));

            }
        }

A: Use googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng, ZoomLevel)); para posicionar a camera com o nível de zoom ZoomLevelno local representado pelas coordenadas LatLng:
private void setUpMap() {
    LatLng markerPosition = new LatLng(-23.560334, -46.645547);
    List<MarkerOptions> places = new ArrayList<>();
    mMap.addMarker(new MarkerOptions().position(markerPosition)).title("Marker").snippet("teste"));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markerPosition, 15));
}


text:
Q: Comparing Object Fields to a couple million rows with a SearchCursor from arcpy I'm new to GIS.
I'm using arcpy.da.SearchCursor to read from a SQL server, and when I read through the first table I create objects ~350,000 of them.
cursor = arcpy.da.SearchCursor(SktSegmentTable, SktSegmentData, "status = 'A'and lrsn = '754'")
for row in cursor:
    count  += 1
    if(count % 100000 == 0):
        print("Processed %d rows" %count)

    sketchList.append(UnionSketchData(
        row[SktSegmentData.index("lrsn")],
        row[SktSegmentData.index("extension")],
        row[SktSegmentData.index("status")],
        row[SktSegmentData.index("segment_id")],
        row[SktSegmentData.index("vector_start")] )
        )
del cursor

This is working fine and the real problem comes in when I have to read from another table that has around 2.5 million rows.
cursor = arcpy.da.SearchCursor(SktVectorTable, SktVectorData, "status = 'A'") #and lrsn = '97429'")
print("Going into VECTOR TABLE")
countRow = 0
count = 0
for row in cursor:
    count  += 1
    if(count % 10000 == 0):
        print("Processed %d rows" %count)
    if(count % 100000 == 0):
        print("Processed %d rows" %count)
    seqCount = 0
# Do a check for every sketchList obj
    for item in sketchList:
    # Check if lrsn is equal to row's lrsn
        if(row[SktVectorData.index("lrsn")] == item.lrsn):
            # If we have a match on lrsn, then check if the items segment_id is the same
            if(row[SktVectorData.index("segment_id")] == item.segment_id ):
                if(row[SktVectorData.index("extension")] == item.extension ):
                #if The segment_id is the same for the item, append the vector string into seq_numbers
                sketchList[seqCount].seq_numbers.append(row[SktVectorData.index("vector")])
        seqCount += 1
del cursor

This runs incredibly slow and will take around 120 hours on my machine.
Can anyone help me figure out how to make this run quickly?
I've been trying to put the 2.5 million entries into a dict but haven't been able to successfully get that to work.

A: I will not guarantee that this will be faster, because I have not tested it, but I think it will be.
Try copying your SQL Server layer out into a file geodatabase feature class on your C: drive, and then run your code against that instead.
Test smaller rather than larger SQL Server layers first.

A: If you are comparing each entry in the 2,5 million row table with each list element in the 350k list you are doing 2500000*350000 = 875 billion comparisons which should take some time.
You can use sets to check which entries match and only store matches in the dictionary.
Example:
import arcpy

arcpy.env.workspace = r'X:\database.gdb'
data = 'Big_table'
subdata = 'Smaller_table'
fields = ['checkfield1','checkfield2','checkfield3','valuefield']

sublist = [i for i in arcpy.da.SearchCursor(subdata,fields[:-1])]
datalist = [i for i in arcpy.da.SearchCursor(data,fields)]

subset = set(sublist)
dataset = set([v[:-1] for v in datalist])
matches = subset.intersection(dataset)

d = {i[0]:i[-1] for i in datalist if i[:-1] in matches}

sublist = [list(i)+[d[i[0]]] if i in matches else list(i) for i in sublist]


text:
Q: How do I fix a menu from disappearing when I toggle it? It used to work and now I have no idea what I did wrong.  When I toggle the mobile menu, the navigation items don't show up but when I inspect it the browser shows they're there but aren't visible.
Can someone help me figure out this menu problem?  This has stumped me
I tried making the menu links appear at the top with a high z index, different combinations of selecting the a tags in the list items, still nothing.

var $hamburger = $(".hamburger");
  $hamburger.on("click", function(e) {
    $hamburger.toggleClass("is-active");
    // Do something else, like open/close menu
  });

  /* Code for the toggling of the navbar */

let toggleNavStatus = false;

let toggleNav = function () {
    let getMenu = document.getElementById("main-navigation");
    let getSidebar = document.getElementById("bottom-nav-bar");
    let getSidebarUL = document.querySelector(".side-nav ul");
    let getSidebarLinks = document.querySelectorAll(".side-nav a");

    if (toggleNavStatus === false) {
        getSidebar.style.visibility = "visible";
        getSidebar.style.opacity = "1";
        getMenu.style.top = "20px";
        getMenu.style.visibility = "visible";

        getSidebarLinks.forEach((item, index)=>{
          console.log(item);
          item.style.display = "block";
          item.style.opacity = "1";
         })
        getSidebar.style.height = "290px";

        toggleNavStatus = true;
    }

    else if (toggleNavStatus === true) {
        getSidebar.style.visibility = "hidden";
        getSidebar.style.opacity = "1";

         getSidebarLinks.forEach((item, index)=>{
          item.style.opacity = "0";
          item.style.visibility = "hidden";
          item.style.display = "none";
         })
        getSidebar.style.height = "0";

        toggleNavStatus = false;
    }
}
/*
                                Core Styles
*/
body, html {
    margin: 0;
    padding: 0;
}

.container {
    padding: 0 5%;
}

a, p, h1, h2, h3, h4, h5, h6, li {
    font-family: 'Roboto', sans-serif;
}

p {
    font-size: 1.125em;
    font-family: 'Poppins', sans-serif;
}

h1 {
    font-size: 2.5em;
}

h1+h2 {
    font-size: 1.25em;
    font-weight: normal;
}

h2 {
    font-size: 1em;
}

/* Buttons */
.solid {
    background: #000;
    color: #fff;
    font-size: var(--button-reg);
    border: none;
    width: 150px;
    height: auto;
    padding: 10px 25px;
    margin-bottom: 15px;
}

.primary {
    background: var(--primary);
    color: #fff;
    font-size: var(--button-reg);
    border: none;
    width: 150px;
    height: auto;
    padding: 10px 25px;
}

:root {
    --primary: #fdd008;

    --button-reg: 1em;
    --button-sm: .75em;

    --heading: #1a1a1a;
    --p: #4c4c4c;
}

/*
                                Navigation
*/

#top-navbar {
    display: none;
}

.sub-nav {
    visibility: hidden;
    height: 0;
    position: relative;
    z-index: 2000;
    background: #fff;
    display: none;
}

.quote {
    display: none;
}

/* Side Nav */
#main-navigation {
    margin: 0;
    padding-right: 20px;
    position: relative;
    top: -2020px;
    z-index: 2;
    visibility: hidden;
}

#bottom-nav-bar {
    height: 0;
    width: 100%;
    position: absolute;
    top: 0;
    right: 0;
    z-index: 200;
    background: #232b2b;
    transition: .3s ease-in-out;
    visibility: hidden;
    opacity: 0;
}

nav ul li {
    position: relative;
    list-style: none;
    text-align: right;
    padding: 0px;
    top: 50px;
    z-index: 1200;
    margin: 15px 0;
    width: auto;
    font-weight: bold;
    font-size: 10px;
}

.side-nav a {
    text-decoration: none;
    padding: 0;
    margin-bottom: 5px;
    color: #fff;
    font-size: 13px;
    opacity: 0;
    visibility: hidden;
    display: none;
    position: relative;
    z-index: 200;
}

nav img {
    position: absolute;
    top: 15px;
    left: 0;
    z-index: 10;
}

/* Hamburger Menu */
#menu-button {
    position: absolute;
    right: 10px;
    display: flex;
    align-items: center;
    top: 7px;
    width: 60px;
}

.hamburger {
    padding: 15px 15px;
    display: inline-block;
    cursor: pointer;
    transition-property: opacity, filter;
    transition-duration: 0.15s;
    transition-timing-function: linear;
    font: inherit;
    color: inherit;
    text-transform: none;
    background-color: transparent;
    border: 0;
    margin: 0;
    overflow: visible;
    position: relative;
    z-index: 2000;
}
.hamburger:hover {
    opacity: 0.7;
    cursor: pointer;
}
.hamburger.is-active:hover {
    opacity: 0.7;
    cursor: pointer;
}
.hamburger.is-active .hamburger-inner, .hamburger.is-active .hamburger-inner::before, .hamburger.is-active .hamburger-inner::after {
    background-color: #fff;
}
.hamburger-box {
    width: 40px;
    height: 24px;
    display: inline-block;
    position: relative;
    z-index: 2000;
}
.hamburger-inner {
    display: block;
    top: 50%;
    margin-top: -2px;
}
.hamburger-inner, .hamburger-inner::before, .hamburger-inner::after {
    width: 30px;
    height: 3px;
    background-color: #fff;
    border-radius: 4px;
    position: absolute;
    transition-property: transform;
    transition-duration: 0.15s;
    transition-timing-function: ease;
}
.hamburger-inner::before, .hamburger-inner::after {
    content: "";
    display: block;
}
.hamburger-inner::before {
    top: -10px;
}
.hamburger-inner::after {
    bottom: -10px;
}

/* * Spring */
.hamburger--spring .hamburger-inner {
    top: 2px;
    transition: background-color 0s 0.13s linear;
    transition-delay: .22s;
}
.hamburger--spring .hamburger-inner::before {
    top: 10px;
    transition: top 0.1s 0.2s cubic-bezier(0.33333, 0.66667, 0.66667, 1), transform 0.13s cubic-bezier(0.55, 0.055, 0.675, 0.19);
    transition-delay: .22s;
}
.hamburger--spring .hamburger-inner::after {
    top: 20px;
    transition: top 0.2s 0.2s cubic-bezier(0.33333, 0.66667, 0.66667, 1), transform 0.13s cubic-bezier(0.55, 0.055, 0.675, 0.19);
    transition-delay: .22s;
}
.hamburger--spring.is-active .hamburger-inner {
    transition-delay: 0.22s;
    background-color: transparent !important;
}
.hamburger--spring.is-active .hamburger-inner::before {
    top: 0;
    transition: top 0.1s 0.15s cubic-bezier(0.33333, 0, 0.66667, 0.33333), transform 0.13s 0.22s cubic-bezier(0.215, 0.61, 0.355, 1);
    transform: translate3d(0, 10px, 0) rotate(45deg);
}
.hamburger--spring.is-active .hamburger-inner::after {
    top: 0;
    transition: top 0.2s cubic-bezier(0.33333, 0, 0.66667, 0.33333), transform 0.13s 0.22s cubic-bezier(0.215, 0.61, 0.355, 1);
    transform: translate3d(0, 10px, 0) rotate(-45deg);
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/hamburgers.css">

    <link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />

    <link href="https://fonts.googleapis.com/css?family=Poppins|Roboto&display=swap" rel="stylesheet">

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

    <title>Valley Construction Supply | Marysville, WA</title>

    <button id="menu-button" class="hamburger hamburger--spring" onclick="toggleNav()" type="button">

    </button>

Marysville, WA

(800) 559-8566

Tacoma, WA

(800) 922-2082

Hours

Mon-Fri: 9am - 5pm

HOME

ABOUT

JOBS

ABOUT VCS

SERVICES

REBAR FABRICATION

HOMECONCRETE

BUILDING MATERIALS

EQUIPMENT AND TOOLS

PRODUCTS

PROMOTIONS

CONTACT

APPLY FOR CREDIT

            <button class="quote" type="button">
                REQUEST A QUOTE
            </button>

when you click the hamburger menu the navigation list is supposed to appear from the top with the slide down menu.  But no links show up.

A: The problem is in your toggleNav() function. If you look at this part of the code:
if (toggleNavStatus === false) {

    getSidebarLinks.forEach((item, index)=>{
        console.log(item);

        // here, you are setting display back to block, BUT visibility stays hidden!
        item.style.display = "block";
        item.style.opacity = "1";
     })

}

else if (toggleNavStatus === true) {

    getSidebarLinks.forEach((item, index)=>{
        item.style.opacity = "0";

        // here, you are setting display to none AND visibility to hidden
        item.style.visibility = "hidden";
        item.style.display = "none";
    })

}

Side note for you: In order to hide an element from the page, you don't need to set both visibility:hidden and display:none. Either one will do the job, although they differ in details. If you are interested, you can learn more about these differences in the following question: What is the difference between visibility:hidden and display:none?


text:
Q: Crystal Report: Date Filter Working Incorrectly I created a Crystal Report on C# Web Application and implemented the date filter function by adding parameter fields. My parameter fields are startdate and enddate.
I have used the record selection formula:
Date({SPR_Reload;1.DateRecorded}) >= {?startdate} and Date({SPR_Reload;1.DateRecorded}) <= {?enddate}

I have also used a stored procedure to retrieve the data I need. I have successfully run the report but I can only retrieve one data.
Situation:
Sample data:
2/1/2014
2/4/2014
2/7/2014
If I've chosen Start Date - 2/1/2014; End Date - 2/7/2014, only one data will be shown.
2/7/2014 will be the one be shown on the report.
How can I show all the data between the chosen dates? Thanks

A: It's already working. It turned out that I forgot to remove the old suppression code.


text:
Q: remove quotes inside quotes regex php My String goes like this:
[...]
if(round($pdf->GetY() >= 140)) {
    $pdf->AddPage();
}
$pdf->Write(6,'Dutzler, Herbert - Letzter' Saibling');
$pdf->Ln(7);
$pdf->SetFont('Helvetica','B',9);
$pdf->SetTextColor(3 [...]

As you can see, FPDF cannot execute this command:
$pdf->Write(6,'Dutzler, Herbert - Letzter' Saibling');

because there is a quote inside quotes and it crashes.
Do you have any idea how I can remove or replace those inner quotes using regex? I have tried many different things, seems not to work properly :(
the code is coming from a huge database, here's a peek at the input code:

[LOOP] $pdf->Write(6,'[title]'); $pdf->Ln(7);
  $pdf->SetFont('Helvetica','B',9); [LOOP]

str_replace doesn't work properly if there are quotes inside [title] so it already fails at $str='[title]'. It's weird, I know.

A: Either escape the inside quote:
$pdf->Write(6,'Dutzler, Herbert - Letzter\' Saibling');

or use double quotes around the string instead of single quotes:
$pdf->Write(6,"Dutzler, Herbert - Letzter' Saibling");

No need for regexp, just write the code correctly in the first place.

A: Have you tried addslashes()? It should add slashes before quotes.


text:
Q: Copy music from Ipod to Ubuntu can anyone please help me for this ? in fact i can see the musics in the ipod but they all are like "HHDW.mp3" "KZDE.mp3" FPPD.mp3" ... and i just can't rename every single song by listening to it ...
Do anyone have a solution for that ?
Thanks

A: You can use the gtkpod Ipod manager which is available from the software center.


text:
Q: Angular/PrimeNG - regex keyFilter with additional restriction of input values I want to create a keyFilter to verify an IP address using IP-regex as follows:
<input pInputText type="text" [(ngModel)]="value1" [pKeyFilter]= "IPAddressKeyFilter" [pValidateOnly]="true" placeholder="0.0.0.0"/>

The IP verification itself works good but it's still possible to enter any other character except of "[0-9.]"
This is due to pValidateOnly set to true. Otherwise every single key stroke is compared to the IP-regex which will fail (refer to post#1 or post#2).

how to block any input except "[0-9.]"?
Some combination of inputMask and keyFilter/regex would be fine. But the inputMask does not work at all for this use case.
Refer to this example @ stackblitz to get a better understanding of the situation.

UPDATE
I implemented some events (thanks to @Morfioss).
I've updated the stackblitz from above.
Summary:

*

*Added Paste-event which was not possible via keyFilter (processes also the IP-regex)

*Implemented KeyDown-event to check if entered key is "[0-9.]".

*Fixed prior Paste-event because "CTRL+V" was also blocked via KeyDown-event ("Backspace", "Del" or any navigation with Arrow-Keys as well => bypassed these cases within the event manually...)

So, this is how it's basically implemented so far:

// component.ts
export class AppComponent {
  IPv4AddressKeyFilter: RegExp =
    /(^\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\s*$)/;

  IPAddressInputOnly: RegExp = new RegExp('[0-9.]');

  valueIPv4: string = '';

  constructor() {}

  ngOnInit(): void {}

  OnIPAddressPaste(event: ClipboardEvent) {
    let clipboardData = event.clipboardData;
    let pastedText = clipboardData.getData('text');

    if (this.IPv4AddressKeyFilter.test(pastedText)) {
      this.valueIPv4 = pastedText;
      return true;
    }

    event.preventDefault();
    return false;
  }

  OnIPAddressKeyDown(event: KeyboardEvent) {
    switch (event.key) {
      case 'Backspace':
      case 'Delete':
      case 'ArrowLeft':
      case 'ArrowRight':
      case 'Home':
      case 'End':
        return true;
    }

    if (event.ctrlKey) {
      switch (event.key) {
        case 'c':
        case 'v':
        case 'x':
          return true;
      }
    }

    if (this.IPAddressInputOnly.test(event.key)) {
      return true;
    }
    event.preventDefault();
    return false;
  }
}
<!-- component.html -->
<input
    pInputText
    type="text"
    [(ngModel)]="valueIPv4"
    [pKeyFilter]="IPv4AddressKeyFilter"
    [pValidateOnly]="true"
    placeholder="0.0.0.0"
    (paste)="OnIPAddressPaste($event)"
    (keydown)="OnIPAddressKeyDown($event)"
  />

Btw. the KeyPress-event would just work fine unlike the KeyDown... Yet it's deprecated (refer to this post)
I've also tried Input, KeyUp, BeforeInput events which not worked as expected... Not sure what's best-practice to use anyway.
Sample code for these is also provided in the stackblitz above.
I'm not 100% satisfied with this solution but it works out for me so far. Would appreciate any comment, opinion or whatsoever.

A: all you need to do is to add an event in the input
:

NumberOnly(e) {
    var regex = new RegExp("[0-9]");
    var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (regex.test(str)) {
      return true;
    }
    e.preventDefault();
    return false;
  }
  onPaste(e) {
    e.preventDefault();
    return false;
  }
html

<input (input)="NumberOnly($event)"/>

also try adding   type="number" in the input in HTML


text:
Q: Project Reactor: Infinite (never ending) Flux I've created a publisher using Flux.create method. Other thread pushes data to the FluxSink, data gets transformed and sent to messaging system. This Flux needs to be around as long as application works.
Here is code:
public MyClass {
  private final FluxSink<Request> requestsSink;
  private final Flux<Request> flux;

  MyClass() {
    this.flux = Flux.<Request>create(sink -> this.requestsSink = sink)
            .bufferTimeout(props.getMaxSize(), props.getMaxTime())
            .flatMap(this::mergeRequests)
            .flatMap(
                req ->
                    remoteApi
                        .getData(req)
                        .onErrorResume(t -> Mono.empty()))
            .doOnNext(this::sendToTopic)
            .onErrorResume(
                t -> {
                  log.warn("error", t);
                  return Flux.empty();
                })
            .subscribe();
  }

  public void pushData(Request request) {
    requestsSink.next(request);
  }

  ... other methods
}

So, I don't care if error happens somewhere in Flux, I just want to log it and continue processing other entries.
For some reason, this flux get's disposed under unknown circumstances (isDisposed returns true). This happens under high load.

*

*How to prevent flux from cancelling/disposing/finishing?

*What are conditions under which flux can be cancelled/disposed/finished?

*How can I debug/log the flow to understand what's the reason for cancelling/disposal?


text:
Q: how to call values in my oop class I am converting my procedural php project to OOP. I stuck on one problem.
What is the best way of retrieving table data?
Passing the id with constructor
new Rate(new Currency($currencyId), $amount);

or first setting the id and calling getId() method?
$currency = (new Currency())->setId($currencyId);
new Rate($currency->getId(), $amount)

A: The Rate object shouldn't care about what $currencyId is, rather the only thing it should know is that there's a currency:
$rate = new Rate(new Currency($currencyId), $amount);

If you want to prevent too many Currency objects from being instantiated, you could introduce a mapper:
$mapper = new CurrencyMapper();
$rate = new Rate($mapper->getCurrencyWithId($currencyId), $amount);

It should be noted that when doing this all objects must be immutable, according to the rules of Flyweight.

A: Ask a question on OOP design and you'll get 100 different answers. There are many different design patterns that will accomplish the same thing.
It is hard to say since we dont see your full design, however given your 2 examples, I would go with the first one.

A: Just from the viewpoint of readability and the number of calls made I'd go with the first one.  The second one makes two separate calls (one to the constructor and another one to set $currencyId).


text:
Q: VB.NET: showing DATE in datagridview bound in a database error I bind table A from mySQL database to a datagridview. One of its columns is "in_Date" with data type DATE(). An exception says

String was not recognized as valid DateTime.Couldn't <> store in
  in_Date column. Expected type is DateTime.

Here's my code in connection:
Dim myconn as MySqlConnection = New MySqlConnection
myconn.ConnectionString = "server=localhost; userid=root; password=pw; database=db"
Dim adapter As MySqlDataAdapter = New MySqlAdapter
Dim table As DataTable = New DataTable
Dim bind As New BindingSource
myconn.Open()
Dim command as MySqlCommand ("select * from db.A;")
adapter.SelectCommand = command
adapter.Fill(table)
bind.DataSource = table
MyDGV.DataSource = bind
adapter.Update(table)
myConn.close()

The table is yet empty. It was fine before when my columns are only in either varchar or int data types. How can I do that with DATE? I don't know what is the problem and how I can solve it. Thank you in advance.


text:
Q: Getting "Expected expression" error when declaring a dictionary in Swift 3, Xcode 8 Working through "Cocoa Programming For OS X", and I am getting an error when declaring a dictionary using Swift 3.0 in Xcode 8 Version 8.0 (8A218a). I think my syntax is correct?
var dictionaryCapitalsByCountry: Dictionary [String: String]()

Shows up in playground with error, "Expected expression"

A: var dictionaryCapitalsByCountry: Dictionary<String, String> = Dictionary<String, String>()

A: Simply mistyped dictionary initialization
should be:


text:
Q: Determine if IPv4 packet is fragmented What is the right way to test if IP packet is a fragment?
Currently I only look at MF (More Fragments) bit in the IPv4 header. Is it sufficient?

A: That is insufficient because the last packet fragment will not have the MF flag set. You must also look at the Fragment offset field, but that by itself is not sufficient because the first packet fragment will have that field set to 0.
If the Fragment Offset field > 0 then it is a packet fragment, or if the Fragment Offset field = 0 and the MF flag is set then it is a fragment packet.


text:
Q: Android trying to create a base class for the Activity classes and app crashes I thought it would be need if I had a base class for all my screens on android.  Then I would not have to retype in the same stuff,....but it crashes when I replace Activty with cBase (my base class)
base class
public class cBase extends Activity{

  public void onCreate(Bundle savedInstanceState) {

  }

}

my class that crashes
public class TellaFortuneActivity extends cBase implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // add the add
    // Create the adView
    AdView adView;
    adView = new AdView(this, AdSize.BANNER, "a14e10cb6b18825");

    // Lookup your LinearLayout assuming it's been given
    // the attribute android:id="@+id/mainLayout"
    LinearLayout layout = (LinearLayout)findViewById(R.id.mainLayout);

    // Add the adView to it
    layout.addView(adView);

    // Initiate a generic request to load it with an ad
    adView.loadAd(new AdRequest());

    // add listeners
    View mAbout = findViewById(R.id.bio);
    mAbout.setOnClickListener(this);

    View mHistory = findViewById(R.id.history);
    mHistory.setOnClickListener(this);

    View mYesNo = findViewById(R.id.butyesno);
    mYesNo.setOnClickListener(this);

    View mSocial = findViewById(R.id.socialgame);
    mSocial.setOnClickListener(this);

    View mWheel = findViewById(R.id.wheelgame);
    mWheel.setOnClickListener(this);

    View mChat = findViewById(R.id.chat);
    mChat.setOnClickListener(this);

    View mTest = findViewById(R.id.test);
    mTest.setOnClickListener(this);

}

public void onClick(View v) {
    Intent i;
    switch(v.getId())
    {

    case R.id.bio:
        // check data first

            i = new Intent(this, cBio2.class);
            startActivity(i);

        break;

    case R.id.history:
            i = new Intent(this, cHistory.class);
            startActivity(i);
        break;

    case R.id.chat:
        i = new Intent(this, cChat.class);
        startActivity(i);
        break;

    case R.id.wheelgame:
        i = new Intent(this,cYesNoCardDeck.class);
        startActivity(i);
        break;

    case R.id.socialgame:
        i = new Intent(this,cSocialGame.class);
        startActivity(i);
        break;

    case R.id.butyesno:
        i = new Intent(this, cYesNoDirections.class);
        startActivity(i);
        break;

    case R.id.test:
        i = new Intent(this, cYesNoShuffle.class);
        startActivity(i);
        break;

       } // end else

   } // end function
} // end class

A: In cBase you should use @Override with the onCreate(Bundle savedInstanceState) method and it MUST also call through to super.onCreate(Bundle savedInstanceState)


text:
Q: Bootstrap 3 Media Queries working on Chrome but not on Mobile devices Ok the question has been asked many time before and I went through each and everyone of them but it didn't worked for me
In mobile view I want to set slideshow col position from Relative to Static which will result into this

But instead I'm seeing this on mobile (adjacent col is overlapping)

which means Col is still in relative position and media Queries are not working on mobile platforms however It does work in Desktop Chrome browser.
I used meta tags and different combinations of min and max values (after confirming screen resolution)
for example
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

 /* Smartphones (portrait and landscape) ----------- */
    @media only screen
    and (min-width : 320px)
    and (max-width : 480px) {

section.banner .slideshow-col{
        position: static;
    }

    /* Smartphones (landscape) ----------- */
    @media only screen
    and (min-width : 320px) {

section.banner .slideshow-col{
        position: static;
    }

 @media (min-width : 700px) {
   section.banner .slideshow-col{
        position: static;

    }

@media (min-width: 992px) {

        section.banner .slideshow-col{
        position: relative;
    }}

@media (min-width: 1200px) {

        section.banner .slideshow-col{
        position: relative;
    }}

My website is here http://
Any hint?

A: Try to use this solutions
@media screen and (max-width: 760px){
    .slideshow-col {
        position: relative;
        height: 300px; <--  height of the slideshow
        // You can use min & max height of slideshow for mobile devices
        height: auto;
        min-height: xxx;
        max-height: xxx;
    }
}


text:
Q: How to prove this simple theorem in Isabelle? I define a very simple function replace which replaces 1 with 0 while preserving other input values. I want to prove that the output of the function cannot be 1. How to achieve this?
Here's the code.
theory Question
  imports Main
begin
fun replace :: "nat ⇒ nat" where
"replace (Suc 0) = 0" |
"replace x = x"

theorem no1: "replace x ≠ (Suc 0)"
  sorry
end

Thanks!

A: There exist several approaches for proving the statement that you are trying to prove.

You can make an attempt to use sledgehammer to find the proof automatically, e.g.
theorem no1: "replace x ≠ (Suc 0)"
  by sledgehammer
  (*using replace.elims by blast*)

Once the proof is found, you can delete the explicit invocation of the command sledgehammer.
Perhaps, a slightly better way to state the proof found by the sledgehammer would be
theorem no1': "replace x ≠ (Suc 0)"
  by (auto elim: replace.elims)

You can also try to provide a more specialized proof. For example,
theorem no1: "replace x ≠ (Suc 0)"
  by (cases x rule: replace.cases) simp_all

This proof looks at the different cases the value of x can have and then uses simplifier (in conjunction with the simp rules provided by the command fun during the definition of your function) to finish the proof. You can see all theorems that are generated by the command fun by typing print_theorems immediately after the specification of replace, e.g.
fun replace :: "nat ⇒ nat" where
  "replace (Suc 0) = 0" |
  "replace x = x"

print_theorems

Of course, there are other ways to prove the result that you are trying to prove. One good way to improve your ability to find such proofs is by reading the documentation and tutorials on Isabelle. My own starting point for learning Isabelle was the book "Concrete Semantics" by Tobias Nipkow and Gerwin Klein.


text:
Q: Why would I get broken lines in a SSRS 2005 line graph My dataset consists of only values > 0 or NULL so I don't understand why my line graph broke at the end of the line and didn't go all the way to the end of the chart.

A: You didn't provide much information but one thing that can happen with charts in Microsoft software is that the X range is usually pulled from the first series. So other series can then be only over part of the chart.


text:
Q: Column name become invalid after referred as result of aggregate function MIN() SELECT cust_detl.*,
       MIN(CREATION_TIMESTAMP) OVER (PARTITION BY CUST_ID) AS MIN_TIMESTAMP
FROM CUST_DETAILS cust_detl
WHERE CREATION_TIMESTAMP=MIN_TIMESTAMP;

Above query select all columns from table CUST_DETAILS with oldest value inCREATION_TIMESTAMP column.
Any idea why MIN_TIMESTAMP encounter as an invalid identifier?
These are the columns that should display:
SELECT
  CUSTOMER_DTL_SEQ.nextval,
  CUST_ID
  CUS_REF_ID
  CUST_NAME
  CUST_ADDRESS
  CREATION_TIMESTAMP
FROM
(
  CUSTOMER_DTL_SEQ.nextval,
   cust_detl.CUST_ID,
   cust_detl.CUST_REF_ID,
   cust_detl.CUST_NAME,
   cust_detl.CUST_ADDRESS,
   cust_detl.CREATION_TIMESTAMP,
    MIN(CREATION_TIMESTAMP) OVER (PARTITION BY CUST_ID) AS min_timestamp
    FROM cust_details cust_detl
  )
 WHERE CREATION_TIMESTAMP = min_timestamp;

I would need to select CREATION_TIMESTAMP column as well, only those columns with minimum timestamp will be selected. The problem is the sequence with nextval is not allowed. I would need sequence in the query as this statment is going to use for INSERT later SELECT...INSERT INTO
The PK need to be incremented.

A: The column name is not yet valid, data is filtered first with the where condition and then on the filtered data, select statement works. You need to put it in sub query before you can use it.
SELECT * FROM
(SELECT cust_detl.*,
        MIN(CREATION_TIMESTAMP) OVER (PARTITION BY CUST_ID) AS MIN_TIMESTAMP
   FROM CUST_DETAILS cust_detl)
WHERE CREATION_TIMESTAMP=MIN_TIMESTAMP;

UPDATE: I don't know what list of columns you have in your table, but if you need only specific columns, then the query goes like this(assuming you need only columns cust_id, column1, column2 and column3 in select list)
SELECT cust_id,
       column1,
       column2,
       column3
  FROM (SELECT cust_detl.cust_id,
               cust_detl.column1,
               cust_detl.column2,
               cust_detl.column3,
               cust_detl.creation_timestamp,
               MIN(creation_timestamp) over(PARTITION BY cust_id) AS min_timestamp
          FROM cust_details cust_detl)
 WHERE creation_timestamp = min_timestamp;

If you still don't get your solution, the post the list of columns from the table and the expected output.
Update2 : Fetch the cursor in the outer query, this query should work fine.
SELECT customer_dtl_seq.nextval,
       cust_id,
       cus_ref_id,
       cust_name,
       cust_address,
       creation_timestamp
  FROM (SELECT cust_detl.cust_id,
               cust_detl.cust_ref_id,
               cust_detl.cust_name,
               cust_detl.cust_address,
               cust_detl.creation_timestamp,
               MIN(creation_timestamp) over(PARTITION BY cust_id) AS min_timestamp
          FROM cust_details cust_detl)
 WHERE creation_timestamp = min_timestamp;


text:
Q: "Can only read from Matlab level 5 MAT-files" I'm trying to load a file from Matlab into my python using mat4py.
I had the following error
ParseError: Unexpected field name length: 43

when using
import h5py
from numpy import ndarray
data_py = loadmat("data.mat")

I followed  the advise here
So,
explore_v73_matfile(file_name="data.mat", fptr=None, path=r"C:/Users/...mypath/data_folder")
data_100E = loadmat("data.mat")

However, now I have a new error:
ParseError: Can only read from Matlab level 5 MAT-files

Unfortunately, I'm not allowed to share data.mat. Does anyone have a clue how to solve this with the little info I can provide?

A: The MAT-File Format documentation (PDF) indicate that the last binary structure of a MAT-File is the "Level 5 MAT-files".

This document describes the internal format of MATLAB Level 4 and
Level 5 MAT-files. Level 4 MATfiles are compatible with versions of
MATLAB up to Version 4. Level 5 MAT-files are compatible with MATLAB
Versions 5 and up.

But the loadmat.py function indicate in the comment of the line 425-429 (as of march 2021):

# Check mat file format is version 5
# For 5 format we need to read an integer in the header.
# Bytes 124 through 128 contain a version integer and an
# endian test string

And loadmat.py output an error if your MAT-Files is not compatible.

 if maj_val != 1:
        raise ParseError('Can only read from Matlab level 5 MAT-files')

So probably that your MAT-Files has been created a long time ago, or with an old matlab version and cannot be read anymore with mat4py.
You should try to read your MAT-File with matlab and save them again.


text:
Q: Помогите с регулярным выражением php Доброй ночи, имею выражение
$string='ГОСТ Р ИСО /МЭК 7498-1-99. Информационная технология. Взаимосвязь
открытых систем. Базовая эталонная модель. Часть 1. Базовая модель (принят и
введен в действие Постановлением Госстандарта России от 18.03.1999 № 78)';
preg_match_all("~ГОСТ\s*Р\s*\w+(\W|\W+)\w+\W\d+\W\d+\W\d+~iu",$string,$matches);
var_dump($matches);

Получаю ответ:
array(2) { [0]=> array(1) { [0]=> string(36) "ГОСТ Р ИСО /МЭК 7498-1-99" } [1]=> array(1) { [0]=> string(2) " /" } }

Помогите понять, откуда берётся второй элемент массива " /". Или подскажите как сделать так, чтобы он находил подстроки ГОСТ Р ИСО /МЭК 7498-1-99 и ГОСТ Р ИСО/МЭК 7498-1-99

A: Шаблон (\W|\W+) является захватывающей подмаской, значение которой при совпадении сохраняется в отдельном буфере (поэтому и присутствует в результате), и означает следующее:

*

*Проверяет текущий символ, который должен быть отличным от буквы, цифры и знака подчёркивания

*Если находит соответствие, сохраняет его в первой захватывающий подмаске и переходит к проверке следующих шаблонов в выражении

*Если соответствия нет, пытается "захватить" 1 и более символов, которые должны быть отличными от буквы, цифры и знака подчёркивания.

В общем случае, чтобы сделать подмаску незахватываемой, можно добавить ?: после (: (?:шаблон1|шаблон2).
В данном случае, чередование и подмаску можно опустить и использовать только \W+.
'~ГОСТ\s*Р\s*\w+\W+\w+\W\d+\W\d+\W\d+~ui'

См. демо регулярного выражения.
Возможно, имеет смысл добавить + (1 и более повторов) после каждого \W:
'~ГОСТ\s*Р\s*\w+\W+\w+\W+\d+\W+\d+\W+\d+~ui'

A: Второй элемент берется в этой строчке: (\W|\W+), т.к. они взяты в скобки. Чтобы их игнорировать, нам достаточно написать ?:
preg_match_all("~ГОСТ\s*Р\s*\w+(?:\W|\W+)\w+\W\d+\W\d+\W\d+~iu",$string,$matches);


text:
Q: Zero before comma in decimal numbers I have this question about decimal numbers from oracle to php. If i have "0,7" on oracle, for example, when i use it on php, it will be ",7", without the zero.
Anyone one knows why? And a possible solution to this? Thanks!

A: If you don't mind doing this for each query, the fastest way would be converting the string to float:
$num = .141592653589793;
echo (float)$num;        // prints 0.141592653589793

A: Whilst I'm not familiar with Oracle, you can re add those zeros with something like this:
function maybe_prefix_zero($input) {
    if( substr($input, 0, 1) === ',' ) return '0' . $input;
        else return $input;
}

A: The best solution that I found is to add zero to number:
$nbr=0.3;
echo $nbr + 0;


text:
Q: grails custom validator: force no message I have a validator and it fills in both password containers with the has-error tag correctly. But how to get rid of one of the two error messages produced by the errors.rejectValue()?
password blank: true, nullable: true, validator: { password, obj, errors ->
    if (obj.password2 != password){
        errors.rejectValue('password', 'invalid.matchingpasswords')
        errors.rejectValue('password2', 'invalid.matchingpasswords')
        return false
    }
}

An other possibility would be, to tell spring to put an has-error tag into the second password container.

A: so a few ideas there I think on of the easiest options would be java script and here is how I would go about it:
<script>
<g:if test="${instance.password.hasErrors()}">
 var msg="${g.message(code:'password.error')}";
 $('#password2')[0].setCustomValidity(msg);
</g:if>
</script>

So as the page loads if password has an error then it creates/ that js msg and password custom validity.
You then create password.error in messages.properties and set that to be the message.
As the user tries to submit form again it will push with that same warning. so you may need some form of other addition such as:
$('#password2').on('change', function() {
  $('#password2')[0].setCustomValidity('');
})

This now tells it to reset the custom validity to nothing when it has a new value. so user can now submit form again.
Rather easy and painless vs having to match error codes / ignoring. Now only validate and return one error for the first password javascript will do the next bit for you

A: This is quite ugly but adding a check in the UserController.groovy:
if (action.equals("edit")) {
    model.fieldList += [property      : 'password2',
                        message       : 'user.password.repeat.label',
                        type          : InputType.PASSWORD,
                        containerClass: userInstance.base.errors?.allErrors?.field.contains("password")?'has-error col-md-6': 'col-md-6',
                        labelClass    : 'col-md-5',
                        inputClass    : 'col-md-7']
}

did the job.


text:
Q: SSIS: How to create custom log files? I would like to create a custom log errors .  I followed the tutorials on msdn but to no avail.  I am just trying to log "Hello" to a file called test.txt.  I have enabled logging and enabled the script task to handle the log i set up.
Any suggestions/tutorials/advice?
I would certainly appreciate it!
Danke

A: General steps are

*

*Create the log connection manager

*Create whatever task you are wanting to log (or you can do it for the entire package)

*In the Event Handlers tab for that task or the package, place whatever you want to happen on the canvas.  If you want to write to a text file, I'd create a script task that would write to your text file.  The file location could be a variable passed from the package so you don't have to go into the script task to change that configuration.

Info on setting variables in the script task:  http://msdn.microsoft.com/en-us/library/ms135941.aspx


text:
Q: AadServiceTemporarilyUnavailable. Logic Apps Error

I am trying to automate data saving email attachments using Azure Logic Apps. But I am getting the above error. Would anyone please help me how to solve this?

A: The following statements are based on our research, please consider if the data is useful.
There might be a situation where Logic App instances run at the same time, or in parallel. Make sure you enable Concurrency Control.

While if you are still receiving the same then we can able to do the error handling using Azure Monitor which catches most things like malformed data.
You can also check Handling error codes in your application which lists some common errors and can Troubleshoot and diagnose workflow failures accordingly.


text:
Q: IE10 and anti-aliasing for rotated images I'm looking for a way to do anti-aliasing on a rotated image with a large border on IE10 on the image above.
I've try -ms-backface-visibility:hidden which fixes it on Chrome, but it doesn't work and I don't find any other information about IE10

A: It seems not to be a CSS problem but a size one's on IE (maybe in order to avoid big calculation on client browser).
The image was a big one (+2K pixel), and the problem disappears when I reduce it under 1000px.


text:
Q: React typing effect on 3 containers with strings I'm trying to create a typing effect in React on 3 containers that are lined up and holding strings within them. The effect should start from the leftmost container after it finishes typing its string, it starts the container that comes after it, and so on.
I started with an idea where I store all the strings in an array and initialize a new array called currentText with a new letter every second but I probably just made things more complicated for myself.
Perhaps there is a simpler solution?
My complicated and not working solution looks like this:
    const [text, setText] = useState([]);
    const [currentIndex, setCurrentIndex] = useState(0);
    const [currentText, setCurrentText] = useState([]);

    // Setting Text Content For Typing
    useEffect(() => {
        if(log && log.length > 0 && text.length == 0){
            log.map((item, key) => {
                let time = item['time'];
                let message = item['message'];
                let event = item['eventid'];
                setText((prev) => [...prev, time, message, event]);
            });
        }
    }, [log, text]);

    useEffect(() => {
            if(currentText?.length < text?.length){
                const interval = setInterval(()=> {

                    // Setting Current index
                    if(currentText?.length !== 0 && currentIndex !== currentText?.length -1) {
                        setCurrentIndex(currentText?.length -1);
                    }

                    // Check if the last index string completed
                    if(currentText[currentIndex]?.length !== text[currentIndex]?.length){
                        let temp = currentText;
                        let lastText = temp[currentIndex];
                        if(lastText) lastText = lastText + text[currentIndex].charAt(lastText?.length -1);
                        else lastText = text[currentIndex].charAt(0);
                        temp[currentIndex] = lastText;
                        setCurrentText(temp);
                    }
                    // If completed open new array element to contain new string
                    else{
                        setCurrentText((prev) => [...prev, ['']]);
                    }
            }, 1000);
            return () => clearInterval(interval);
            }

    }, [currentText, text, currentIndex]);

return (
    <>
       {
          currentText && currentText.length > 0 &&
                    currentText.map((item, key) => {

                                {currentText[key]}
                                {key % 1 ? currentText[key] : currentText[key+1]}
                                {key % 2 ? currentText[key] : currentText[key+2]}

                        })
        }

The log look like this:
[
{time: '2023-02-19 06:25:30', message: 'some message', eventid: 'event_string'},
{time: '2023-02-19 06:25:30', message: 'some message', eventid: 'event_string'},
{time: '2023-02-19 06:25:30', message: 'some message', eventid: 'event_string'},
]

A: // Define an array of log objects
const logs = [
  { time: '2023-02-19 06:25:30', message: 'some message', eventid: 'event_string' },
  { time: '2023-02-19 06:25:30', message: 'some message', eventid: 'event_string' },
  { time: '2023-02-19 06:25:30', message: 'some message', eventid: 'event_string' },
];

// Define a component that renders a paragraph tag with a substring of text
function TextComponent(props) {
  const { index = 0, text } = props;
  return
 {text.substring(0, index)}
;
}

// Define a component that types out the text of its children components
function TypeWriter(props) {

  // Destructure the props and get the number of children
  const { children, charTime = 50 } = props;
  const nChildrens = React.Children.count(children);

  // Throw an error if there are no children
  if (nChildrens < 1) throw new Error('Type writer component must have children');

  // Define the state of the component, which keeps track of which child is currently active and how much of its text has been typed out
  const [activeComponent, setActiveComponent] = React.useState({
    children: 0,
    index: 0,
    length: children[0].props.text.length,
  });

  // Use the useEffect hook to update the state every time the interval elapses
  React.useEffect(() => {
    // Set an interval that updates the state by typing out a single character every time it is called
    const interval = setInterval(() => {
      setActiveComponent((state) => {
        // If the current child's text has been completely typed out, move on to the next child
        if (state.index > state.length) {
          if (state.children < nChildrens - 1)
            return {
              index: 0,
              children: state.children + 1,
              length: children[state.children + 1].props.text.length,
            };

          // If there are no more children, clear the interval and return the current state
          clearInterval(interval);
          return state;
        }

        // Otherwise, update the state to type out the next character
        return { ...state, index: state.index + 1 };
      });
    }, charTime);

    // Return a function to clear the interval when the component unmounts
    return () => {
      clearInterval(interval);
    };
  });

  // Render the children components, with the active child being typed out and the others already fully typed out
  return (

      {React.Children.map(children, (child, index) => {
        return React.cloneElement(child, {
          key: index,
          index:
            index === activeComponent.children
              ? activeComponent.index
              : index < activeComponent.children
              ? child.props.text.length
              : 0,
        });
      })}

  );
}

// Define a component that renders a TypeWriter component with TextComponents as its children
export default function Home() {
  return (
    <TypeWriter>
      {logs.map((log, index) => (
        <TextComponent key={index} text={log.message} />
      ))}
    </TypeWriter>
  );
}


text:
Q: How can i make a button as Set Wallpaper button? The code contains a gallery with one button (which has to be added into your manifest file), I just need a suggestion on the button action; what to put inside "imageIDs* or bitmap to reference to the image which previously is clicked and shown.
Here is the complete code:
package net.keivan.gallery;

import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;

public class GalleryActivity extends Activity {
//---the images to display---
Integer[] imageIDs = {
        R.drawable.pic1,
        R.drawable.pic2,
        R.drawable.pic3,
        R.drawable.pic4,
        R.drawable.pic5,
        R.drawable.pic6,
        R.drawable.pic8,
        R.drawable.pic9,
        R.drawable.pic10,

};

/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Gallery gallery = (Gallery) findViewById(R.id.gallery1);

    gallery.setAdapter(new ImageAdapter(this));
    gallery.setOnItemClickListener(new OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View v,
        int position, long id)
        {

            //---Displays the name of images as just as i click on them---

            Toast.makeText(getBaseContext(),
                    "pic" + (position + 1) + " selected",
                    Toast.LENGTH_SHORT).show();

            //---display the images selected---
            ImageView imageView = (ImageView) findViewById(R.id.image1);
            imageView.setImageResource(imageIDs[position]);

        }
    });
}

//---Set Wallpaper button---

public void onClick(View v) {

    try {

/*at this part can you suggest what to put inside "imageIDs* or *bitmap* to reference
          to the image which previously is clicked and shown*/

/* first.the activity is created second.the image which i clicked is shown third.whin
           the user click on the button the image which previously is clicked on is set as background.*/

                    WallpaperManager.getInstance(this).setResource(imageIDs[position]);

                    //WallpaperManager.getInstance(this).setBitmap(mBitmap);

    } catch (IOException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();
    }

}

///////////////////////////////////////////////

public class ImageAdapter extends BaseAdapter
{
    Context context;
    int itemBackground;

    public ImageAdapter(Context c)
    {
        context = c;
        //---setting the style---
        TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);

        itemBackground = a.getResourceId(
            R.styleable.Gallery1_android_galleryItemBackground, 0);

        a.recycle();
    }

    { getApplicationContext().getWallpaper(); }
    //---returns the number of images---
    public int getCount() {
        return imageIDs.length;
    }

    //---returns the item---
    public Object getItem(int position) {
        return position;
    }

     //---returns the ID of an item---
    public long getItemId(int position) {
        return position;
    }

    //---returns an ImageView view---
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            imageView = new ImageView(context);
            imageView.setImageResource(imageIDs[position]);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
        } else {
            imageView = (ImageView) convertView;
        }
        imageView.setBackgroundResource(itemBackground);
        return imageView;
    }
}

}

A: try {
    // Set background from a resource
    WallpaperManager.getInstance(this).setResource(imageIDs[position]);
    // or set background from a bitmap
    //WallpaperManager.getInstance(this).setBitmap(mBitmap);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

In your manifest file:
<uses-permission android:name="android.permission.SET_WALLPAPER"></uses-permission>


text:
Q: program giving wrong output for a specific input I want to check if a number is prime. Here is my code:
#include <iostream>

using namespace std;

int main(){
    int num;
    int i, k = 0;
    cin >> num;
    for(i = 2; i < num; i++){
        if(num % i == 0){
            k = k + 1;
        }
    }
    if(k > 0){
        cout << "The number is not prime" << endl;
    }else{
        cout << "Prime!" << endl;
    }
    return 0;
}

When I enter 6 , 78, ... etc it's giving the correct output.
But when I'm entering 4294967296 which is not a prime number, it's returning Prime!.

A: That's because 4294967296 is a rather special number. It is 2^32, which is limit of the storage capacity of an int, which typically holds only 32 bits. Thus, your num is interpreted as if it were 0.
The rest follows logically from that overflow misinterpretation. The for loop is never entered, since 2 is not less than 0, so k never gets incremented.
EDIT Actually, in this particular case, it fails for a different reason. std::cin performs truncation on the input, so when you enter 4294967296, num will actually get assigned the value of 2147483647. Your program [correctly] prints that that value is prime. It's just that that's not the number the user had intended to test.

A: You need to validate your input. 4294967296 is too big for 32 bit signed integer, so std::cin truncates it to 2147483647 which is actually prime. You can check that printing your number back to screen. You should also change your loop to:
for(i = 2; i < num / 2; i++)

as it would provide the same result, but decrease calculation time twice.


text:
Q: PayPal integration inside site for different accounts I'm building simple selling site where any user ( seller ) can upload photo and sell it to other users ( buyers )
Seller needs to write his PayPal account when he register, so when buyer order image he get transferred to paypal site, even if he doesn't have PayPal to use outside Card ( that page you often see when you paying something with paypal ), and when buyer pay send those funds to seller and transfer buyer back to site and confirm payment.
When php confirm payment he enable buyer to download image.
Is this possible, and how?
Can someone write me or simple script or tell me where to find examples for this...
It's spread around the web, so anyone should no this...
Thank you!

A: You wouldn't need to store his paypal account when he registers.
And PayPal has written tonnes of infomation in their support sections.
Look up PayPal IPN.

A: Here is first step, creating form, put it where you want your BUY button to be, it can be on any page, you can create it by buttons wizard on PayPal site, just add this notify_url hidden input.
You can edit those fields with php entering amount, item_name, business email, custom...
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="any-email-you-want@domain.com">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="item_name" value="Item Name">
<input type="hidden" name="item_number" value="150">
<input type="hidden" name="amount" value="100.00">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="button_subtype" value="services">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="tax_rate" value="0.000">
<input type="hidden" name="shipping" value="0.00">
<input type="hidden" name="custom" value="user_id_goes_here">
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG.gif:NonHosted">
<input type="hidden" name="notify_url" value="http://checking-url-goes-here/file.php">
<input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>

Second step, checking is it valid payment, file.php ( or any file URL you specify in notify_url hidden input in form above ) :
<?php

$req = 'cmd=_notify-validate';

foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}

$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);

if (!$fp) {

//ERROR READING PAGE - CODE ERROR

} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
if (strcmp ($res, "VERIFIED") == 0) {

//VALID CODE, DO WHATEVER YOU WANT WITH IT HERE, PAYMENT IS CONFIRMED...

}
else if (strcmp ($res, "INVALID") == 0) {

//INVALID CODE

}
}

?>

You can test this code inside:
https://developer.paypal.com/
( PayPal Sandbox )
just replace
www.paypal.com
with
www.sandbox.paypal.com
( you can find it at two places ).
And that's it...
I was asking for this directions, and no one want to direct me here...
I even get -2 rating for this question, but none of those minuses was smart enough to write me those examples, as I ask for...
And I'm the one who deserve minuses?
( I hope someone will find those examples useful )