text:
Q: Bootstrap 5 - problem changing column order I'm upgrading to Bootstrap 5 and can't get the column re-ordering to behave how I want. I have 3 columns: a title, an image, and a paragraph of text. On larger screens I want the image on the left with the title on the right and the paragraph of text directly below the title. On smaller screens, I want the three columns stacked vertically in the order of title, image, paragraph of text. Using .order I can mostly get things working how I want, except on larger screens I can't get the paragraph of text to appear directly below the title, rather it appears under the title but below the image albeit on the right. How can I push this third column up beside the image to appear directly below the title?
Here's my code so far:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

title

lorem ipsum

A: Basically not possible with display flex and order only.
So either you need to:

*

*Switch to grid

*Display with 2 different blocks or lines using .d-{breakpoint}-{value}
Bootstrap 5 display doc
Different options, but the first is the most light:
Option 1 - Added only 1 line and some display class

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

title

lorem ipsum

lorem ipsum

Option 2 - Added only 1 block and some display classes

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

title

lorem ipsum

title

lorem ipsum

Option 3 - Display grid

@media (min-width: 992px){
  .grid-temp-1{
     grid-template: "a b" 0fr
                    "a c" 1fr
                    "a c" 1em / 33% 1fr;
  }
  .grid-temp-1 > div:nth-child(1) {
    grid-area: b;
  }
  .grid-temp-1 > div:nth-child(2) {
    grid-area: a;
  }
  .grid-temp-1 > div:nth-child(3) {
    grid-area: c;
  }
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

title

lorem ipsum

A: Go with two column layout. You can nest the heading and the paragraph inside one column.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

Hello World

Lorem ipsum


text:
Q: Using html link as form button I have a login form where a user (that is not logged yet) can insert his login and password, after filling these fields the user has to press a submit button.
What i'm trying to do is: Replace the normal submit button for a $html->link with some css styles.
So is there anyway I can use something like this:

  <?php echo $html->link(__("Sign In", true), array("type" => "Sign In", 'class'=>'licitate')); ?>

Instead of:
 echo $form->end(__('Sign In',true));

to create a submit button for a small login form?
My css code:
.licitateThis{position:relative;float:left;width:100%;}
.licitateThis a.licitate{display:block;float:left;padding:2px 0 4px;width:100%;background-color:#eee;text-shadow:#fff 1px 1px 1px;text-decoration:none;font-weight:bold;font-size:115%;border:1px solid #fff;border-radius:3px;text-align:center;letter-spacing:-0.02em;text-transform:uppercase;-moz-border-radius:4px;-webkit-border-radius:4px;border-radius:4px;}
.licitateThis a.licitate:hover,.licitateThis:hover a{background-color:#0071bb;text-shadow:#666 1px 1px 1px;color:#fff;}

PS:
The form im trying to submit its a login form, and its located at default.ctp so it can be used in every pages.
Problem solved:
CSS (created a new class):
.loginSubmit {color:#0071bb;outline:none; display:block;float:left;padding:2px 0 4px;width:100%;background-color:#eee;text-shadow:#fff 1px 1px 1px;text-decoration:none;font-weight:bold;font-size:115%;border:1px solid #fff;border-radius:3px;text-align:center;letter-spacing:-0.02em;text-transform:uppercase;-moz-border-radius:4px;-webkit-border-radius:4px;border-radius:4px;}
.loginSubmit:hover {background-color:#0071bb;text-shadow:#666 1px 1px 1px;color:#fff;}

PHP:
 <button type="submit" class="loginSubmit">Sign In</button>
 <?php echo $form->end(); ?>

Thanks.

A: What are you trying to do here?  Any reason why you need to use anchor  tag for your submit button?
If all you want is to make your submit button look like a link, then you can do that using css.
Or if you just want to put your submit button somewhere else other than beside the </form> tag, then you can just put <button type="submit" class="licitate">Sign In</button> anywhere inside the form and use <?php echo $form->end(); ?> to close the form.

A: His problem is that an anchor tag can't submit the form without javascript. $html->link makes a link, not a input type of submit, not a button of type submit.
If you want to simply use a button, write the CORRECT html for it by hand.
    ... other form code here
    <button type="submit" class="licitation">
        Sign In
    </button>
    <?php echo $form->end( );

A: if i understand the wuestion right you want to try if your user is already logged in ?
if so  first create a function which checks if a user is logged in or not.
Then check it

  <?php if(userisalreadyloggedin())
   echo ' Singin';
  ?>

A: yes but it's usually not a good idea. you are going to have to use javascript..

with cakephp maybe
<?php echo $html->link(__("Sign In", true), array("type" => "Sign In", 'class'=>'licitate', 'onClick' => 'document.formName.submit()')); ?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL-proxy load-balancer issues I tried to configure mysql-proxy 0.8.2. There are two hosts behind it: M1 (10.10.10.1) and M2 (10.10.10.2).
There is a MySQL replication between M1 and M2. M1 is master, M2 is slave. All request what type is "write", forwarding to M1 correctly and replicate this record immediately from M1 to M2.
But if request type is "read", the proxy can't forward to M2, only to M1. I checked these packets with tcpdump, and I saw that every packet received on M1. The connection from proxy to MySQL servers are working perfectly checking with telnet & MySQL command.
When I shutdown the M1 server, all request (read/write) sent to another (M2) server. After M1 server is turned off, M2 is working well. Every record is available.
I don't understand why mysql-proxy is not forwarding the read packet to M2 too, while M1 is available. What is the problem? Or this is how it should normally run?
This is my config:
[mysql-proxy]
daemon = true
user = mysql
proxy-skip-profiling = true
keepalive = true
max-open-files = 2048
event-threads = 50
pid-file = /var/run/mysql-proxy.pid
log-file = /var/log/mysql-proxy.log
log-level = debug
admin-address = 10.10.10.5:4401
admin-username = admin
admin-password = xxxxxxx
proxy-address = 0.0.0.0:3307
proxy-read-only-backend-addresses = 10.10.10.2:3306
proxy-backend-addresses = 10.10.10.1:3306

plugin-dir=/usr/local/lib/mysql-proxy/plugins
plugins=proxy,admin,debug,replicant

LUA_PATH = /usr/lib/mysql-proxy/lua/proxy/?.lua
LUA_CPATH = /usr/lib/mysql-proxy/lua/?.so
admin-lua-script=/opt/mysql-proxy-0.8.2/admin.lua
proxy-lua-script=/usr/local/lib/mysql-proxy/lua/proxy/rw-splitting.lua
proxy-lua-script=/usr/local/lib/mysql-proxy/lua/proxy/balance.lua
proxy-lua-script=/opt/mysql-proxy-0.8.2/riporter.lua

A: There was some issues with that option in the past, but not in the version you're using.
The --proxy-read-only-backend-addresses will not cause the proxy to forward the read requests into the backends specified on that option.
For that, you'll need to change a lua script (or write a new one) that reads the read-only-backend-addresses option(s) and define the behaviour your want.
You can read more about this here.
Hope this gives you some clues for further research.


text:
Q: Which is a more maintainable way to construct objects? I am trying to learn design patterns, best practices, etc. There is a particular problem that always confuses me.
Abstraction is more important or KISS (keep it simple and stupid).
Suppose I need to construct an object which several properties. There are 2 ways:
1) Instantiate the object and pass properties to the constructor.
$user = new user($user_detail_array); // one line code is enough

Benefits of this method:

*

*Code is small.

*Very good Abstraction.

*Short code so easily manageable.

Negatives:

*

*Adding new code causes problem,

*Difficult to follow DRY (don't repeat yourself).

*Violates single responsibility rule

2) Instantiate the object and set each property individually.
$user = new user();
$user->setName($name);
$user->setEmail($email);
$user->setGender($gender);
so on....

Benefits:

*

*it's easy to understand.

*Easy to change.

*It looks better.

Negatives:

*

*it's not good abstraction.

*All methods are visible.

*Long code to write. Trying to over follow KISS itself become difficult.

*Communication between classes become tough. Too many classes to communicate. So many public functions.

*It will be like procedure code.

In general what is the better way? If it depends on situation, when is the first approach better than the second? Why? I found that both approaches caused problems. The first method makes the code too abstract. The second method makes code too long and unmanageable.

A: I think you just misunderstood some concepts. First of all, KISS doesn't mean that you should write bad code without using abstraction. In fact, abstraction is one of the most powerful things that helps programmers write simple code.
The way you are going to design your program always depends on situation. If you are writing script that should run only once, do not even think about abstraction. It would be an overkill. However, if the lifetime of your program is pretty long, try to use abstraction and provide clients of your user class with intuitive and simple interface. Imagine, that code using user wants to change just it's name. In your first way they should provide user with the whole new array. In the second way you have just to call method setName. That's it.
To summarize: when you are designing a class, do not think about simplicity of writing this code. You should rather think about simplicity of using the class you are currently writing.

A: $userBuilder = new UserBuilder();
$userBuilder.name = $name;
// and so on
$user = $userBuilder -> build();

It's abstract, doesn't repeat anything, and it adds another pattern (Builder).

A: The reality is that I don't think there's much difference between your two examples.
Take the first example $user = new user($user_detail_array);. Yes this seems shorter, but in reality, what will we see usually before this line?
$user_detail_array = {
    "name" => "Bill",
    "email" => "billg@microsoft.com",
    "gender" => "male"
};
$user = new user($user_detail_array);

Wow, now it doesn't look so different from the second method...
$user = new user();
$user->name = "Bill";
$user->email = "billg@microsoft.com";
$user->gender = "male";

My point is, every property of the user entity will appear next to a => (assignment) at some point in the program. Whether it's in array keys, properties of a builder object, or directly on the entity itself - they have to be assigned some time.
I think the best thing to do in this case is keep the assignments (=>) as close to the entity as possible, so it's most clear what is being assigned and where it is being assigned to.

A: Another thing about abstraction is that You don't need to set name, email and gender separately.
You can simply abstract them into the array and create a new setter:
$user->setUserDetail($userDetailArray);


text:
Q: What is an appropriate pattern for handling a queue of network events in C++? I'm writing an application that sends and receives messages over the network and pushes them into a std::deque queue. and I'm looking for the appropriate programming pattern to handle all of the different possible types of messages that it could receive.
Each type message will have a completely different set of data. For example:

*

*Connection success

*Disconnecting

*Another peer connected

*

*Peer name

*Peer address

*Other peer state

*Sync object state

*

*location delta

*rotation delta

*other object state

*Meta Event A

*

*Some data

*Meta Event B

*

*Some data

Etc.
My initial reaction is to create a base class Message and then create subclasses ObjectSyncMessage, MetaEventAMessage, PeerConnectedMessage, etc. because each message requires completely different member variables than the other events.
I get stuck when I go to process my message queue. Everything I've read says to avoid using a switch and to determining which class a message belongs to (see here).
Is there a better way to approach this problem? I don't think that I want the messages themselves to act upon the state of the rest of my application, but rather act as data bags, and let me manage my application state in the class that works through the queue.

A: While processing the messages in the queue, you probably want to call a processing function that is specific to the most-derived type of the message you are looking at. The one place where that information is naturally available is in the message itself.
A design pattern that comes in useful here is the Visitor pattern. This leads to a design where the specific Message classes know how to process themselves, by calling a function that is specific for that message type on a MessageHandler object.
class Message;
class ObjectSyncMessage;
class PeerConnectedMessage;

class IMessageHandler {
public:
  void HandleGenericMessage(Message*);
  void HandleObjectSyncMessage(ObjectSyncMessage*);
  void HandlePeerConnectedMessage(PeerConnectedMessage*);
};

class Message {
public:
  virtual void Handle(IMessageHandler* handler)
  {
    handler->HandleGenericMessage(this);
  }
  //... other methods
};

class ObjectSyncMessage : public Message {
public:
  // override of base-class function
  virtual void Handle(IMessageHandler* handler)
  {
    handler->HandleObjectSyncMessage(this);
  }
  //... other methods
};

class PeerConnectedMessage : public Message {
public:
  // override of base-class function
  virtual void Handle(IMessageHandler* handler)
  {
    handler->HandlePeerConnectedMessage(this);
  }
  //... other methods
};

// in the queue handling function:
Message* aMessage = // read from queue
aMessage->Handle(aMessageHandler);


text:
Q: How do I properly use Sharp GP2Y0A21YK0F sensor? I've recently obtained Sharp GP2Y0A21YK0F IR distance sensor and I'm not sure how to make a proper circuit for output measurement, since I'm getting lots of noise. The only thing datasheet mentions is that there should be a \$10 \mbox{ } \mu F\$ capacitor on power pins as close to sensor as possible. Well, I soldered it directly to the sensor's power pins and it didn't help.
Here's what the output looks on the scope:

The fat line at the bottom of the screen is the actual expected output and when I move my hand near the sensor, the line moves as expected, but the peaks remain the same.
Using an LC filter did remove the peaks, but I'd like to know if there's some industry standard way of solving the problem I have.

A: These sensors really put a lot of noise on the line. I'm using here a similar sensor (the GP2D120XJ00F). First, add another 100nF ceramic cap parallel to the existing 10µF cap. This helps to better damp the changes in current consumption of this sensor. Additionally, I added a low-pass filter to the output (10k resistor and 100nF capacitor), to smooth the output signal. (I then use an averaging filter in the MCU when reading the input, but then I don't have the need for really fast reaction times).

A: Your problem maybe because of 60 Hz power noise. It comes from light bulb. Using 60 hz noise filter is invertible. So, use high frequency for sending data and first some high pass filter for removing this noise and at last a low pass filter to improve signal could help you. I had same project and use this solution.


text:
Q: How Python treats numbers with 0 at the beginning? I want Python recognize numbers like 030 as 30. for some reason, when I write "print 030" it returns 24, when I write "print 020" it returns 16. What's the reason and How can I make it treat it as 30?
Thanks

A:
How can I make it treat it as 30?

Just write 30 normally, or if you accept this number as a string,
>>> int('030')
30

will work just as expected.

A: A leading 0 signals 'octal' format, i.e. base 8.
print "0{}".format(30)

--output:--
030

How can I make it treat it as 30?

You can never make python 2.x treat 030 as 30.

A: most languages treat numbers starting with 0 as octal numbers, so 30 octal = 3 * 8 = 24

A: One way that I could think of is this.
n='030'
n=n[1:]
n=int(n)

Now n has the number that can be treated like integer 30


text:
Q: MixedLM usage for model fit I want fit my sample data to mixed panel regression using MixedLM however for my input sm.MixedLM.from_formula("TOTCOST~YEAR",dat,groups=dat["NI"]) I am facing the following error:
ValueError Traceback (most recent call last)
<ipython-input-40-38fa54e8b448> in <module>()
----> 1 sm.MixedLM.from_formula("TOTCOST~YEAR",dat,groups=dat["NI"])

C:\Users\Harshita Jaiswal\Anaconda2\lib\site-packages\statsmodels\regression\mixed_linear_model.pyc in from_formula(cls, formula, data, re_formula, subset, *args, **kwargs)
    651                                                subset=None,
    652                                                exog_re=exog_re,
--> 653                                                *args, **kwargs)
    654
    655         # expand re names to account for pairs of RE

C:\Users\Harshita Jaiswal\Anaconda2\lib\site-packages\statsmodels\base\model.pyc in from_formula(cls, formula, data, subset, *args, **kwargs)
    145         (endog, exog), missing_idx = handle_formula_data(data, None, formula,
    146                                                          depth=eval_env,
--> 147                                                          missing=missing)
    148         kwargs.update({'missing_idx': missing_idx,
    149                        'missing': missing})

C:\Users\Harshita Jaiswal\Anaconda2\lib\site-packages\statsmodels\formula\formulatools.pyc in handle_formula_data(Y, X, formula, depth, missing)
     63         if data_util._is_using_pandas(Y, None):
     64             result = dmatrices(formula, Y, depth, return_type='dataframe',
---> 65                                NA_action=na_action)
     66         else:
     67             result = dmatrices(formula, Y, depth, return_type='dataframe',

C:\Users\Harshita Jaiswal\Anaconda2\lib\site-packages\patsy\highlevel.pyc in dmatrices(formula_like, data, eval_env, NA_action, return_type)
    295     eval_env = EvalEnvironment.capture(eval_env, reference=1)
    296     (lhs, rhs) = _do_highlevel_design(formula_like, data, eval_env,
--> 297                                       NA_action, return_type)
    298     if lhs.shape[1] == 0:
    299         raise PatsyError("model is missing required outcome variables")

C:\Users\Harshita Jaiswal\Anaconda2\lib\site-packages\patsy\highlevel.pyc in _do_highlevel_design(formula_like, data, eval_env, NA_action, return_type)
    150         return iter([data])
    151     design_infos = _try_incr_builders(formula_like, data_iter_maker, eval_env,
--> 152                                       NA_action)
    153     if design_infos is not None:
    154         return build_design_matrices(design_infos, data,

C:\Users\Harshita Jaiswal\Anaconda2\lib\site-packages\patsy\highlevel.pyc in _try_incr_builders(formula_like, data_iter_maker, eval_env, NA_action)
     55                                       data_iter_maker,
     56                                       eval_env,
---> 57                                       NA_action)
     58     else:
     59         return None

C:\Users\Harshita Jaiswal\Anaconda2\lib\site-packages\patsy\build.pyc in design_matrix_builders(termlists, data_iter_maker, eval_env, NA_action)
    704                             factor_states[factor],
    705                             num_columns=num_column_counts[factor],
--> 706                             categories=None)
    707         else:
    708             assert factor in cat_levels_contrasts

C:\Users\Harshita Jaiswal\Anaconda2\lib\site-packages\patsy\design_info.pyc in __init__(self, factor, type, state, num_columns, categories)
     86         if self.type == "numerical":
     87             if not isinstance(num_columns, int):
---> 88                 raise ValueError("For numerical factors, num_columns "
     89                                  "must be an int")
     90             if categories is not None:

ValueError: For numerical factors, num_columns must be an int

Any help will be appreciated. Thank you


text:
Q: Can address value of a static variable match with a heap allocated address? Some snippets of the code I have is below
static const int s_kVar1 = 0;
static const int s_kVar2 = 1;

...

void foo()
{
    MyObject *o = new MyObject();
    // Is it ever possible that (o == &s_kVar1) or (o == &s_kVar2)
}

A: The short answer is NO. Different objects are guaranteed to have different addresses. Global (s_kVar) and dynamically allocated objects (o) go in different memory regions.
P.S. But yes, you can abuse the language to break that guarantee. You can construct two different objects in the same memory location.

A: No. Static variables are stored in .BSS or .DATA segments depending on whether they are initialized or uninitialized(0 initialized). In your case,
static const int s_kVar1 = 0; will go in .BSS and
static const int s_kVar2 = 1; will go in .DATA
Heap is for dynamic allocations.
BTW i don't see why you use static const at file scope . const makes internal linkage by default and global variables have static lifetime. Unless of course you're using C where i can see it being useful.


text:
Q: postgresql numeric to timestamp conversion timezone issue I am trying to convert a numeric to timestamp in postgresql. However, it always converts it in EST timezone. Before running the query, I try the following.
set time zone 'UTC+10';

select to_timestamp(r.date/1000) as current_email_timestamp
FROM email;

However, It the timestamp always seem to be in US timezone. The emails are mostly sent during working hours but when I change the numeric back to timestamp with above query, it shows all the emails at night time
Could it be that the timestamp in numeric was stored in US timezone, or could it be that when converting back from numeric to timestamp, it is not coverting the timezone correctly.
Can someone please tell me how to fix this
Regards
Arif

A: You can use the at time zone modifier:
select to_timestamp(1411738200),
       to_timestamp(1411738200) at time zone 'America/Chicago',
       to_timestamp(1411738200) at time zone 'UTC+10'

Your postgres installation probably defaults to EST.


text:
Q: @Input('index') stays zero with ngfor loop create.component.html
<app-product
  *ngFor="let product of (products | async); let i = index"
  [index]="i"
  [product]="product">
</app-product>

product.component.ts
export class ProductComponent implements OnInit, OnChanges {
  @Input('index') index: number;
  constructor(private store: Store) {
    this.index = 0;
    console.log(this.index)
  }
}

How comes my index does not gets updated with the input field if i display index in create.component.html i can see ngfor properly gives the value 1 to the input field

A: You set index always to zero (0) in constructor and prints the value with console.log after that assignment. It's clear that it's always zero on your console.
this.index = 0;
console.log(this.index)

Also the input is not yet set in constructor by Angular. Use the Angular life cycle methods like OnInit (ngOnInit).
Some hints:

*

*Input name is not recommended / necessary. (Same name as property)

*Set the default value directly on your property declaration.

*In general, use Angular lifecycle events rather than the constructor.

This works (tested):
<app-product
  *ngFor="let product of products | async; let i = index"
  [index]="i"
  [product]="product"
></app-product>

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-product',
  template: '<div>{{index}} - {{ product | json }}</div>',
})
export class ProductComponent {
  @Input() index = 0;
  @Input() product: unknown;

  constructor(private store: Store) {
    // Expected to be zero. Because input not yet set by Angular.
    console.log(this.index);
  }

  ngOnInit() {
    // Expected to be >= 0. Because you can access the input now. Or use
    console.log(this.index);
    // Here you can also do stuff with this.store.
  }
}

Trivia: You could also use OnChanges to handle every input change.


text:
Q: Exception in the allocation for the servlet I'm fighting the whole day with this: I want to call the connect service method from AuthentificationService I have this exception (the rest of the code at the bottom):
06-May-2015 14:29:45.986 SEVERE [http-nio-8082-exec-28] org.apache.catalina.core.ApplicationContext.log StandardWrapper.Throwable
 com.sun.jersey.spi.inject.Errors$ErrorMessagesException
    at com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
    at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)
    at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
    at com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:491)
    at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:321)
    at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
    at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
    at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:376)
    at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:559)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1241)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:847)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

06-May-2015 14:29:45.986 SEVERE [http-nio-8082-exec-28] org.apache.catalina.core.StandardWrapperValve.invoke Exception lors de l'allocation pour la servlet net.iots.iotshub.web.service.AuthentificationService
 com.sun.jersey.spi.inject.Errors$ErrorMessagesException
    at com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
    at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)
    at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
    at com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:491)
    at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:321)
    at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
    at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
    at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:376)
    at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:559)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1241)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:847)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

My Web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>AuthentificationService</servlet-name>
        <servlet-class>net.iots.iotshub.web.service.AuthentificationService</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AuthentificationService</servlet-name>
        <url-pattern>/rest/authentificationService</url-pattern>
    </servlet-mapping>
</web-app>

My Servlet class:
@Path("authentificationService")
@ApplicationPath("/rest")
@Produces(value = MediaType.APPLICATION_JSON)
@Consumes(value = MediaType.APPLICATION_JSON)
public class AuthentificationService extends AbstractService {

    @GET
    @Produces(value = {MediaType.APPLICATION_JSON})
    @Path("connect")
    public User connect(@QueryParam("user") String id, @Context HttpServletRequest request) {
        JUser user = null;
        User connectedUser = null;
        try {
            user = new ObjectMapper().readValue(id, JUser.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new WebApplicationException();
        }
        ..................
        request.getSession().setAttribute("connectedUser", connectedUser);

        return connectedUser;
    }

    @GET
    @Path("disconnect")
    public void disconnect(@Context HttpServletRequest request) {
        request.getSession().removeAttribute("connectedUser");
        request.getSession().invalidate();
        System.out.println(" LogOut ");
    }

    @GET
    @Path("isConnected")
    @Produces(value = {MediaType.APPLICATION_JSON})
    public User isConnected(@Context HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        System.out.println(" isConnected ");
        if (session != null) {
            if (session.getAttribute("connectedUser") != null) {
                return (User) session.getAttribute("connectedUser");
            } else {
                return null;
            }
        } else {
            return null;
        }

    }
}

my AngularJS service:
cmlAppModule.factory('AuthentificationService', function ($resource) {

    return $resource('rest/authentificationService/:path',
            {path: '@path'},
    {
        disconnect: {
            method: 'GET',
            params: {
                path: "disconnect"
            }
        },
        isConnected: {
            method: 'GET',
            params: {
                path: "isConnected"
            }
        },
        connect: {
            method: 'GET',
            params: {
                path: "connect"
            }
        }
    });
});

Please if can anyone help me with this and provide the possible solution for it..
Thanks,

A: There are so many things wrong on so many levels

*

*There is no such word as "Authentification". It's "Authentication" :-)

*@ApplicationPath should be used on the application configuration class, not on your resource classes. For example
@ApplicationPath("/rest")
public class AppConfig extends PackagesConfig {
    public AppConfig() {
        super("the.packages.to.scan.for.resources.and.provders");
    }
}

With this, you can get rid of our web.xml (or at least your attempted servlet configuration). This does pretty much the same thing. Change the package name to the package of your resources. And remove the @ApplicationPath from the resource class.

*In your web.xml, you can't do
<servlet>
    <servlet-name>AuthentificationService</servlet-name>
    <servlet-class>
        net.iots.iotshub.web.service.AuthentificationService
    </servlet-class>
</servlet>

unless AuthentificationService is an actual Servlet (which I can't tell as I don't know what AbstractService is. In any case, even if it was, this configuration still wouldn't work.


text:
Q: Record Types for Opportunity Product object? It seems we are not allowed to create record types on the opportunity product object.  I have a use case where I would like to show different fields based on the product type selected.
Is there a workaround that can be done for this?  I've done some scouring online, but have not been able to find any viable solution.

A: To answer your question, currently this feature is not available as per salesforce standard functionality.
If you need this functionality Please upvote the Idea. Once we got the sufficient votes then it will be consider and available in the future releases.

A: I want to share the workaround.
My Solution So, what I created was a custom object and created the bare minimum # of fields that my reps need to update that mirror the Opp Product fields and created a generic master record type Then, I created two process builders that-

*

*Whenever an Opp Product of a certain type is created, it creates a matching custom object record. This same process builder also has the custom object continually referencing the Opp Product record. For added security, I created a boolean on the Opp Product that gets set to true to prevent any more custom object records being created. (Our org has code to refresh the opp products every four hours so this works for us)

*I then created the same exact process builder but reversed it (minus new record creations). So, anytime you make a change to the custom object record, it will update the Opp Product record and reference where needed. As for the Owner and the Name standard fields I simply mapped over the Opp name and Opp owner. I then created a custom report type that was Opportunities with Opportunity Products with Custom Object (If you can't tell yet, I haven't been able to come up with a name for the object yet)
This is a great solution for my company as it allows us to even further analyze that area of our business. Hope this helps!


text:
Q: OSX, static variable sharing same address In OSX I have the following code. Using gcc 4.0.1. I'm new to OSX development so I'm not sure what other system information would be useful here...
static int     textstrArgs[] = { 1, 1, 1 };

void func()
{
    static int first = 1;
    if (first)
    {
        first = 0;
        // stuff
    }
    /* other stuff */
}

where func() is declared as 'extern' and is called from another library.
The problem is that the address of 'texstrArgs[2]' and 'first' is the same. That is, when the application loads it's putting both of these variables at the same spot in memory. When func() is called the first = 0 is clobbering the value in the static textstrArgs array.
Would could I be doing that would cause this to occur?
Thanks for any help anyone can give.

A: I doubt that they are actually sharing the address. I believe it's more likely that you are accessing the array out of bounds or something similar.
Try printing the address of both variables. That will show you if your suspicion is correct.

A: Just a hunch - try changing:
static int textstrArgs[] = { 1, 1, 1 };

to
static int textstrArgs[3] = { 1, 1, 1 };

One other thing - are you actually referencing textstrArgs anywhere ? If not then it may be that it's getting optimised away.


text:
Q: Lattice isomorphism between $(\{A \subset \mathbb{N} : A$ is finite$\}, \cup, \cap)$ and $(\mathbb{N},lcm,gcd)$. My problem is to know if there exists a lattice isomorphism between $B = (\{A \subset \mathbb{N} : A$ is finite$\}, \cup, \cap)$ and $C = (\mathbb{N},lcm,gcd)$. I think that is posible because have the same cardinality ($\mathbb{N}$), both have a minimum ($\emptyset$ and 1 respectively) and neither have maximum.
I tried to define a function (candidate to isomorphism) from B to A starting sending $\emptyset$ to the 1 and the sets of one element to the primes "in order" ($\{1\}$ to 2, $\{2\}$ to 3, $\{3\}$ to 5, ...) and then I need to define that sends the $\{1,2\}$ to 2*3=6 and so on. But that function isn't a surjection.
I also know that is enough to find a bijective homomorphism.

A: Wikipedia notes the algebraic and order-theoretic definitions of lattices are equivalent, so we may as well discuss if there is an order isomorphism from $(\mathcal{P}_{\mathrm{fin}}(\mathbb{N}),\subseteq)$ and $(\mathbb{N},\mid )$.
The answer is no, for $(\mathbb{N},\mid )$ has elements that cover one atom but no other atoms (squares of primes) and $(\mathcal{P}_{\mathrm{fin}}(\mathbb{N}),\subseteq)$ doesn't (it's not possible for a set to strictly contain one singleton set but no other singleton sets).
It's kind of like comparing $2^{\mathbb{N}}$ to $\mathbb{N}^{\mathbb{N}}$ with lexicographic orderings, except your two lattices are sublattices of these comprised of functions with finite support.


text:
Q: Save string format specifiers (%@, %d, etc.) in NSString for future placeholder use? I have a long string I want to retrieve from a URL and store at app launch. Later, I want to insert individual values into that string.
I'd like to do something like this:
NSString *numberLine = @"1 %@ 3 %@ 5 %@";

//... (later) ...

NSString *final = [NSString stringWithFormat:numberLine, @"two", @"four", @"six"];

NSLog(@"%@", final); //Should output "1 two 3 four 5 six"

I want the @"two" to be inserted into the placeholder %@ that was earlier saved into numberLine.
Is there a good way to accomplish something like this?
So far my only thought is to do something like:
NSString *script = @"width = PLACEHOLDERpx";
script = [script stringByReplacingOccurrencesOfString:@"PLACEHOLDER" withString:@"12"];

A: What you are describing is a template. You want to leave placeholders in a string that will be filled out with data. While you could use %@ and %d through a string that gets difficult as the string grows more complex. You may want to use a template library like Mustache for Objective-C. This will let you write expressions like this:
Hello {{SomeVariable}}

All you have to do is pass in an NSDictionary with keys that correspond to the data you want to render. So for the example above you might do the following:
NSString *result = [GRMustacheTemplate renderObject:[NSDictionary dictionaryWithObject:@"World" forKey:@"SomeVariable"];
                                         fromString:@"Hello {{SomeVariable}}"
                                              error:NULL];

This will produce a result string Hello World.


text:
Q: Updating user information with extending fields on one page I want to update current user profile. User has one-to-one UserExtend model, so I would like to update the extending fields on the same submit event as well.
class UserExtend(models.Model):
    user = models.OneToOneField(User)
    town = models.CharField(max_length=100, blank=True)
    age = models.IntegerField(blank=True)
    organization = models.CharField(max_length=100, blank=True)
    tel = models.CharField(max_length=15, blank=True)

    def __unicode__(self):
        return unicode(self.user)

Here is my views.py
def ProfileUpdateView(request):
    user = request.user
    user_form = UserForm(request.POST or None, initial={
        'first_name': user.first_name,
        'last_name': user.last_name,
        'email': user.email
    })
    user_extend_form = UserExtendForm(request.POST or None, initial={
        'user': user,
    })
    contacts = Contact.objects.get(activity=True)
    tels = contacts.tel.all()
    bg = Background.objects.get(activity=True)
    botlinks = Bottom_navigation.objects.all()
    if user_form.is_valid() and user_extend_form.is_valid():
        user_form.save()
        user_extend_form.save()
    c = {'form': user_form, 'extend_form': user_extend_form, 'contacts': contacts, 'tels': tels, 'bg': bg,
         'botlinks': botlinks}
    return render(request, 'posts/user_form.html', c)

and forms.py
class UserForm(forms.ModelForm):

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email']

class UserExtendForm(forms.ModelForm):
    user = forms.ModelChoiceField(queryset=User.objects.all(),widget=forms.HiddenInput())

    class Meta:
        model = UserExtend
        fields = '__all__'

As it can be seen, I decided not to rewrite my ModelForm def function, but to pass two forms in a template with one submit button. Everything is rendered as expected, however when I click the submit I get an error like this:
Traceback:
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  22.                 return view_func(request, *args, **kwargs)
File "/srv/webapps/saunaflame/core/posts/views.py" in ProfileUpdateView
  89.         user_form.save()
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/forms/models.py" in save
  463.                              construct=False)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/forms/models.py" in save_instance
  105.         instance.save()
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/base.py" in save
  710.                        force_update=force_update, update_fields=update_fields)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/base.py" in save_base
  738.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
  822.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert
  861.                                using=using, raw=raw)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
  127.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/query.py" in _insert
  920.         return query.get_compiler(using=using).execute_sql(return_id)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  974.                 cursor.execute(sql, params)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/utils.py" in __exit__
  97.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py" in execute
  124.             return self.cursor.execute(query, args)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/MySQLdb/cursors.py" in execute
  205.             self.errorhandler(self, exc, value)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/MySQLdb/connections.py" in defaulterrorhandler
  36.     raise errorclass, errorvalue

Exception Type: IntegrityError at /posts/profile/update/
Exception Value: (1062, "Duplicate entry '' for key 'username'")

Why django is trying to overwrite the username field for my User instance if I do not pass it to the form?
And is there a better way to update user info with extending fields on a single page?
Thanx.

A: This has nothing to do with having two forms. It's because you're passing initial values, then saving the form, so it's naturally trying to create a new instance with those values, even though they conflict with existing data.
You should be using the instance parameter instead of initial, so that Django knows to update the existing instances.
user_form = UserForm(request.POST or None, instance=request.user)
user_extend_form = UserExtendForm(request.POST or None, instance=request.user.userextend)


text:
Q: IntelliJ Idea does'nt recognize Compatibility Library in ActionBarSherlock I am using IntelliJ Idea CE (which is incredible) and have included ActionBar Sherlock as Library and added it as dependency in my Module (term used in IntelliJ).
ActionBar Sherlock uses android-support-v4.jar and therefore it is not supposed to added as a dependency in my module(app).
In case I add android-support-v4.jar as a dependency in my module I get an error

UNEXPECTED TOP-LEVEL EXCEPTION:

and when I remove it IDE don't recognize the classes in compatibility package and at times it compile the module at times it gives error.
Is there any solution to this?

A: If android-support-v4.jar library is already included in ActionBar Sherlock module, just click on the Export checkbox in the module dependencies configuration on the left of the library name. This will make the library available for your main application.


text:
Q: Coding email signature using style tags after each element? I have to code an email signature and I've never done it before and am fairly new to coding. I have an example in which the style tags are listed directly after each element instead of having  tags independently. For example:
td style="border-right:1px solid rgb(223,223,223);">

example

I'm more used to using style tags. Is there a benefit to doing it in the example code above? Can I use style tags instead? Will this affect whether it is compatible in different email clients?
Any help is appreciated.

A: When coding for email, all (almost) of your HTML should be kept "inline" - in the style of your sample code above. This is because certain email providers strip CSS from the head of your html (Gmail for one).
Hello


text:
Q: How to update all records one field with two other fields combination? I am trying two update all records one field with two other field combination and with a random number as showed below
Table Company
Id  Name   Telephone Total
1   Test1   032       (randomNumber)Test1.032
2   Test2   022       (randomNumber)Test2.022
3   Test3   111       (randomNumber)Test3.111

Total Field should be update as above.
I am using Oracle and i have more than 100.000 records that should be update in this way.
Thanks in advance.

A: Try:
UPDATE  Company
SET total = '('
           || ( trunc( DBMS_RANDOM.VALUE(0,1000) ))
           || ')' || Name || '.' || Telephone


text:
Q: How to redirect user to another page using javascript in php? I want to redirect the user to another page only after displaying a success message. The code below redirects to the another page even if the page is refreshed without submitting any data.
Code Snippet
<?php
// We will store our status message later
$message = '';

// Let's check form submitted
if( isset( $_POST['action'] ) && $_POST['action'] == 'submit' ) {

    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['number'];

    $message_text = $_POST['address'];

        if (isset($_POST['action']))
        {

            // Validate required fields
            if( $name == '' || $email == '' || $message_text == '' ){
                $message = "
Please fill out all required fields.
";
            }

            // send email after validation
            else {

                // Email will be sent at this email
                $mailto = 'nepstarditsolutions@gmail.com';

                // Let's create html email format
                // (You can use html in this email format)

                // Email headers
                $headers = "From: " . strip_tags( $email ) . "\r\n";
                $headers .= "Reply-To: ". strip_tags( $email ) . "\r\n";
                $headers .= "MIME-Version: 1.0\r\n";
                $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

                // Email body
                $message = "";
                $message .= "
Contact Info:
";
                $message .= "
Name:  ". strip_tags( $name ) . "
\r\n";
                $message .= "
Email:  ". strip_tags( $email ) . "
\r\n";

                $message .= "
Contact Number:  ". strip_tags( $phone ) . "
\r\n";
                $message .= "
Alternate Email:  ". strip_tags( $_POST['altemail'] ) . "
\r\n";
                $message .= "
Hosting Package:  ". strip_tags( $_POST['cradio'] ) . "
\r\n";

                $message .= "
Address: ". strip_tags( $message_text ) . "
\r\n";
                $message .= "";

                // Email subject
                $subject = "Contact Info from ".$name;

                // Send email
                $mail_status = @mail( $mailto, $subject, $message, $headers );

                if( $mail_status ){
                    $message = '
Quotation submitted Successfully !
';
                }
                else {
                    $message = '
Error in sending the Quotation !
';
                }

            }
        }
}
?>

I need help in 2 things

*

*Success message should be displayed for 2 seconds (before the redirect).

*How to redirect using JS in php?

A: Standard "vanilla" JavaScript way to redirect a page
You can use the code below to redirect the user after form submission code.
if( $mail_status ){
    echo "

    ";
}

MDN web docs on how setTimeout works
Hope it helps!


text:
Q: IntegrityError: NOT NULL constraint failed PYTHON, SQLite3 Im trying to store my json file to the popNames DB but this error pops up.
My Json file is a dictionary with the country being the key and the person names as key_value. In my DB I want to put the country as the first element as a primary and the names in the subsequent column in the db table
Could anyone help me with this?
enter image description here

A: Every INSERT call creates a new row in the PopNamesDB table. Your code creates many such rows: the first row has a country but NULL for all the other columns. The next N rows each have a null country, a value for colName, and NULL for all the other columns.
An easy way to fix your code is to change your followup INSERT calls (on line 109) to change the row you created earlier, instead of creating new rows.  The query will look something like
cur.execute(''' UPDATE PopNamesDB SET ''' + colName + ''' = ? WHERE country = ?''', (y, c))


text:
Q: C++ Programming the division alogrithm
The division algorithm states that given two integers a and d, with d ≠ 0, there exists unique integers q and r such that a = qd + r and 0 ≤ r < |d|, where |d| denotes the absolute value of d. The integer q is the quotient, r is the remainder, d is the divisor, and a is the dividend. prompt the user for a dividend and divisor and then display the division algorithm's results:

     If a = 17 and d = 3, then q = 5 and r = 2, since 17 = 5 * 3 + 2.
     If a = 17 and d = -3, then q = -5 and r = 2, since 17 = -5 * -3 + 2.

The C++ operators for integer division do not conform to the division algorithm. Explain in output displayed to the user of the program when to expect results that disagree with the division algorithm. The program should not attempt to resolve this issue.
Ok, so I've been trying to figure this out for a few days now and I just can't crack it. The only way I can think of solving this is by using mod to find r or using a successive subtraction to find q. However, I'm pretty sure both of those solution don't really count. Is there some other way to solve this problem?
[Edit] I don't think successive subtraction works because that's just Euclid's algorithm so I really wouldn't be using this algorithm and using modulus would just like using the C++ division operator.

A: Here's a hint.  For positive numbers, everything works out ok.
The C++ expression q = 17/3 results in q == 5.
But for negative numbers:
The expression q = -17/3 results in q == -5

A: With the way the question is worded, I'm pretty sure you are supposed to use mod to find r and the division operator to find q. It says straight up "The C++ operators for integer division do not conform to the division algorithm. Explain in output displayed to the user of the program when to expect results that disagree with the division algorithm. The program should not attempt to resolve this issue." This means, don't over-think it, and instead just demonstrate how the operators don't conform to the algorithm without trying to fix anything.
Suppose your code naively uses C++ operators to calculate q and r as follows:
int q = a / d;
int r = a % d;

You then get wrong (in this case, wrong just means they don't "conform" to your algorithm) values for both q and r in the following two cases:

*

*a = -17, b = 3
The code will result in:
q = -5, r = 2
This does not conform to the division algorithm because
-5 * 3 + 2 = -13 so you clearly have the wrong q and r.

*a = -17, b = -3
The code will result in:
q = 5, r = -2
This does not conform to the division algorithm because there is a rule that 0 <=
r < |d|. In other words, r must be positive.
In the other cases, i.e. where both a and d are positive or when a is positive and d is negative, the C++ operators will correctly "conform" to your algorithm.

A: The C++ integer division operator gives the correct result only if both dividend and divisor are positive.  This because it always rounds toward zero

A: As the question doesn't clearly states the problem I presume you want to output the devision like the examples provided, so a simple code would be:
int a=17;
int b=-3;
cout<<"If a="<<a<<"and b="<<b<<"then q="<<a/b<<"and r="<<a%b;


text:
Q: How do I change the font size in Dwarf-fortress? I'm trying of DF 0.34.11 (linux) and was wondering if it's possible to increase the font size. I've looked through the forum without any luck (so far).

A: You have two options: zoom in or use a larger font (or tileset).
To zoom, you can use the mousewheel or the [ and ] keys to zoom in and out, which is good for quickly getting a close up look at something or a quick overview of your domain. It does tend to make things blurry, though. The ZOOM_SPEED setting affects how fast it zooms.
To use a different font, you'll have to edit data/init/init.txt (which is also where you find ZOOM_SPEED). There are a lot of settings here, most of them well documented in the file itself, but the ones you're interested in are FONT, GRAPHICS_FONT, and GRAPHICS_FULLFONT, which control the font in non-tiled, tiled windowed, and tiled fullscreen modes.
The default font is curses_640x300, which is intended for use in an 80x24 tile game window at 640x300 resolution (hence the name), so the tiles are pretty small - 8x12. curses_square_16x16 is a better choice; the tiles are square, and noticeably larger. If you want something different (or larger still), you can download a wide variety of fonts and tilesets from the wiki.

A: Changing PRINT_MODE to TEXT in your data/init/init.txt might help: the game is then rendered with the font you have selected in your terminal.


text:
Q: headless build with CDT using .cproject configuration I have a eclipse project with .project and .cproject, and I want automate the building process, for it I use
./eclipse -nosplash -application org.eclipse.cdt.managedbuilder.core.headlessbuild -data /home/user/workspace/ -build App
but it don't use the .cproject file to build, how I make for the building process use the .cproject configuration?
thanks

A: If your project is a makefile project then simply do what Francois said in the comments.
If you are looking at trying to build a specific configuration, it depends on which CDT Version you have, as if you can do that.
By default the headless builder will build ALL configurations specified in the project. At work we have the original CDT 7.0 version and that one did not support building a specific configuration, but I do see in the notes on CDT 7.0 that it does support building a specific configuration. You would do that by using -build App/Config instead of just -build App.
(Note: at home I have eclipse with CDT 7.0.2 and that does support the headless build of a specific configuration as above, although the usage info still doesn't show support for it, and the upcoming CDT 8.0 does correctly show the usage information).


text:
Q: Auto approve all comments (editor) I unchecked both options in the discussion area (so the one where they need a post to comment and administrator has to approve), but still, my users can't put their comments without me approving it.
Has someone a solution for this glitch? Why on earth can't they post a comment? And if they post one, the second one needs to be approved?

A: Dashboard - options - discussions
Before a comment appears:

*

*An administrator must always approve the comment

*Comment author must fill out name and e-mail

*Comment author must have a previously approved comment

Uncheck at least 1 and 3.

A: I used multiple links in a comment and I saw that there was an option to avoid comments that have more links than 2 in (moderate comments). I set it to 0 and now it works like a charm.
Wordpress, oh Wordpress!


text:
Q: Linux server with JBoss , the system cache increased each day We run an Apache Mod_proxy cluster with 3 JBoss in three dedicated server. Because we need share many files (small object files which our apps need to read/write ) between these JBoss servers ,we using NFS in Apache node and mount them into each JBoss Node as same directory.
Both nodes are installed RHEL 5.4 version and there are in same intranet network. We have 8G RAM in each server.
The problem is we got linux cache increased about 2-3M per minute, in heavy load day (about 100-150 online user ) the server cache will increased to about 3-4G each day.
After run these clean code:
sync
echo 3 > /proc/sys/vm/drop_caches

It will back to normal level:
             total       used       free     shared    buffers     cached
Mem:       8173504     589772    7583732          0      87444      72100
-/+ buffers/cache:     430228    7743276
Swap:      5799928          0    5799928

We want to know are these caused by JBoss open files not closed?
Are they other solutions we can use to share files between servers?
Thanks for any reply.

A: Linux will normally use all available memory. The memory that is not being used by application data will then be used by buffers and caches to speed access to disks and hardware. What you are describing seems like normal behavior. The caches will get smaller to allow application data to grow if needed, unless you change the swapiness vm parameter for the kernel. Swapiness is:

So... swappiness, which is exported to
  /proc/sys/vm/swappiness, is a
  parameter which sets the kernel's
  balance between reclaiming pages from
  the page cache and swapping out
  process memory.

You can read more about it here. Normally the default is ok, and if you are not having any process being killed by lack of memory the caches are nothing to worry about.


text:
Q: Beautiful Soup Find Location of Tag in Source File? I am using BeautifulSoup to extract information from HTML files. I would like to be able to capture the location of the information, that is the offset within the HTML file of the tag that of a BS tag object.
Is there a way to do this?
I am currently using the lxml parser as it is the default.

A: If I'm reading your question correctly, you are parsing some html with BeautifulSoup and then using the soup to identify a tag. Once you have the tag, you are trying to find the index position of the tag within the original html string.
The problem with capturing the index position of a tag using BeautifulSoup is that the soup will alter the structure of the html based on the given parser. The lxml parsing might not provide a character for character representation, especially after finding a tag within the soup.
It's iffy if this will consistently work, but you might try using a string's find method to find the position of your tag's text contents, which should remain largely unchanged.
#!python
# html is a string containing your html document
soup = BeautifulSoup(html,'lxml')
# target is the tag you want to find
target = soup.find('p')
# now we locate the text of the target inside of the html document
html.find((target.text))

This method will not start at the beginning of the tag, but should be able to locate the tag's contents within the html.
If you wanted to know the index of a tag in the body of your soup, that would be much more feasible.


text:
Q: General DB practices for deleting a referenced item Assume I have a theoretical database that lists a bunch of cars that can be rented out. The dealership can add\remove cars from their available inventory.
In psuedo code:
[Dealer]:
    [Id] PKEY
    [Name] NVARCHAR

[Car]:
    [Id] PKEY
    [DealerId] FKEY to [Dealer]
    [LicensePlate] NVARCHAR

A customer comes in and schedules a reservation...
[Customer]:
    [Id] PKEY

[Reservation]:
    [Id] PKEY
    [CarId] FKEY to [Car]
    [Date] -- for simplicity just say that a car can only be rented for a whole day

Now say that a dealership with a car that has been on their lot for years was sold. The dealer needs to remove the car from being available, but doesn't want all historical reservation data deleted. What's the best practice for this?
Some options seem to be:
Option 1. Soft Delete - Add a column on [Car] that signifies that is is no longer available
[Car]:
    [Id] PKEY
    [DealerId] FKEY to [Dealer]
    [LicensePlate] NVARCHAR
    [IsAvailable] BOOLEAN

My only issue with this is that if I had a unique constraint on [LicensePlate], then that would mean I couldn't add the car to another dealership unless I created some sort of *->* relationship (which might get chaotic considering a LicensePlate number can be retired & reused on different cars).
Option 2. Convert past reservations to 1NF - More than likely future reservations would need to be deleted anyway (can't have a reservation on a car not in the dealership). However, reservations in the past are no longer reservations. They're historical data at that point. I could create another table to handle past reservations that do not reference [Car], but instead are in 1NF.
[PastReservation]:
    [Id] PKEY
    [DealerId] FKEY to [Dealer] -- I guess it's not entirely 1NF...
    [LicensePlate] NVARCHAR
    [Date]

Are there other options? Any gotchas I should be aware of with either of these?


text:
Q: Insert "dates" with cmis in custom property type date I have a custom type Clinical Record where some field is cli:date_created. The type of this property is Date.
When I try to set this field (with php) I get Argument of type "string" given but argument of type "\DateTime" was expected.". But I am giving a Date and not a string.
'cli:date_created' => date('d/m/Y',strtotime($resultado[0]['fecha_alta'])),

What do I have to do in order to insert a date? Because I don't want to change the type from date to string in this field.

A: Yes, you do give a string argument as the date function returns string.

Return Values ¶
Returns a formatted date string. If a non-numeric value is used for
  timestamp, FALSE is returned and an E_WARNING level error is emitted.

You need to pass a DateTime instance, e.g. using new \DateTime() constructor or another function that return a DateTime instance such as DateTime::createFromFormat
'cli:date_created' => DateTime::createFromFormat('[yourformat]', $resultado[0]['fecha_alta']),


text:
Q: Prestashop 1.7.3.3 Edit Registration Form I use prestashop 1.7.3.3 e-commerce system.
I need to get a phone number from the customer.
Phone field looks optional. I want to make it mandatory.
How can i do that?
enter image description here

A: You can set that field as mandatory in the BO > Customers > Addresses.


text:
Q: How to attach local functions to document events in Javascript constructor? I am trying to attach to document movemove event in a constructor:
f.js:
function F() {
    var HandleMouseMove = function (event) {
        //this is never called
    };

    $(function () {
        // HandleMouseMove seems to be null at this point
        $(document).mousemove(HandleMouseMove);
    });
}

this is instantiated in another file
app.js
$(function () {
    var f = new F();
});

However when I debug this, the HandleMouseMove function reference seems to be null in the callback. Subsequently it never gets called.
How to attach local functions to document events?

A: There is something else going on here, there was the missing bracket in your app.js, that you say was just a typo.  So here is a working snippet that seems fine,.  It's not in two separate js files, but that should not matter as long as your loading the scripts in the correct order.

function F() {
    var HandleMouseMove = function (event) {
        //this is never called
        console.log("called");
    };

    $(function () {
        // HandleMouseMove seems to be null at this point
        $(document).mousemove(HandleMouseMove);
    });
}

$(function () {
    var f = new F();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


text:
Q: how to run a shell script at the first start of a linux vm I want to know how I can run a shell script at the first start of my Linux VM.
The shell script must be run only once.
I'm on Debian 9.

A: You could use a flag file (/root/.firstrun in my example below) to check whether the script has already been executed or not.
Add this to /etc/rc.local:
if [ ! -e /root/.firstrun ]
then
        /path/to/your_script.sh
        touch /root/.firstrun
fi

Or, if you don't need the script after the execution, you can use the script itself as the flag:
myscript="/path/to/your_script.sh"
if [ -x "$myscript" ]
then
        $myscript && rm -f "$myscript"
fi


text:
Q: How to call Edge Animate's play function from external Javascript I have a symbol on the stage called "cart".... inside the symbol is my graphic that has a motion path put on it to the timeline (it is called "car_v1").
On my stage I have a code to hide the symbol cart with an external CSS class :
sym.$("cart").addClass( "hidden" );  ( this is the css - .hidden { display: none; } )

I have a function that calls an external Javascript file.. from that external file I want to get the timeline animation to work:
Here is the function called:
checkCar();

and here is the function:
function checkCar() {
 if (AdobeEdge.countCar == 5){
 AdobeEdge.getComposition("EDGE-172492634").getStage().$("cart").removeClass( "hidden" ); // this works!
 AdobeEdge.getComposition("EDGE-172492634").getStage().$("cart").play(); //doesn't work!        <----this is the line I need help with!

// sym.getSymbol("cart").play(); // this works inside of edge and the timeline animation runs!!!

 }
}

Can anyone help me get the play function to work from my external Javascript file?

A: ok, got it :)
AdobeEdge.getComposition("EDGE-172492634").getStage().getSymbol("cart").play(); //works!


text:
Q: Android SQLiteException unable to close due to unfinalised statements In my android app when I'm trying to query the database, everything works fine but sometimes I'm getting this exception, not always. I searched for this problem and found solutions that works for others but not for me.
I'm using this code in another thread in AsyncTask
Cursor data = db.rawQuery(sql.toString(), null);

    if (data != null && data.moveToFirst())
    {
        do
        {
            Account acc = new Account();
            acc.setId(data.getLong(0));
            acc.setName(data.getString(1));

            Price balance = new Price(0L, Price.theUnit);
            balance.setAmount(data.getString(2), Price.rial);
            acc.setBalance(balance);

            accounts.add(acc);

        } while (data.moveToNext());
    }

    data.close();
    dbHelper.close();

What is the problem?


text:
Q: Bind to Combobox in Datagrid I want to create a Datagrid, something look like this:
DatagridDesign
To explain: I want to have a Datagrid with some comboboxes (Type, Quantity, Cell), which will have nothing selected but containing items. For simplicity let's say Header(Type: will have options of type1, type2, type3), (Quantity: 1, 2, 3), (Cell: cell1, cell2, cell3). I want the user to select from comboboxes, also when "adding row" will give another row containing items, and so on. In the end I want to save them to the Database.
As I am new to WPF and the concept of binding, I tried something like this:
My VB.Net code:
Imports System.Collections.ObjectModel

Class MainWindow
    Dim appRow As New ObservableCollection(Of Employee)

    Sub New()
    InitializeComponent()
    appRow.Add(New Employee With {.Cell = New ObservableCollection(Of String)({"cell1", "cell2", "cell3"}), .Type = New ObservableCollection(Of String)({"type1", "type2", "type3"})})
    appRow.Add(New Employee With {.Cell = New ObservableCollection(Of String)({"cell1", "cell2", "cell3"}), .Type = New ObservableCollection(Of String)({"type1", "type2", "type3"})})

    DataContext = appRow
    End Sub
End Class

Public Class Employee
    Dim _Type As New ObservableCollection(Of String)
    Dim _Cell As New ObservableCollection(Of String)

    Public Property Type() As ObservableCollection(Of String)
        Get
            Return _Type
        End Get
        Set(ByVal value As ObservableCollection(Of String))
            _Type = value
        End Set
    End Property

    Public Property Cell() As ObservableCollection(Of String)
        Get
            Return _Cell
        End Get
        Set(ByVal value As ObservableCollection(Of String))
            _Cell = value
        End Set
    End Property
End Class

And my Xaml Code:
<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Testing"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">

    <Grid>
    <DataGrid Margin="5" ItemsSource="{Binding}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTemplateColumn Header="Type" Width="*">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox Margin="2" ItemsSource="{Binding Type}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

            <DataGridTemplateColumn Header="Quantity" Width="*">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox Margin="2">
                            <ComboBoxItem Content="1" />
                            <ComboBoxItem Content="2" />
                            <ComboBoxItem Content="3" />
                        </ComboBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

            <DataGridTemplateColumn Header="Cell" Width="*">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox Margin="2" ItemsSource="{Binding Cell}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

    </Grid>

Now, this is working. But I want to set items in the class itself, so when it gets called it initializes with values. So I tried:
Class MainWindow

Sub New()
InitializeComponent()

DataContext = New Employee()
End Sub

End Class
Public Class Employee
    (Same as before...)
    Sub New()
        Cell = New ObservableCollection(Of String)({"cell1", "cell2", "cell3"})
        Type = New ObservableCollection(Of String)({"type1", "type2", "type3"})
    End Sub
End Class

And Xaml stays the same. The same way I bind normal comboboxes to my WPF and that is working. But with Datagrid, it's not. It's also showing no error and runs normally.
Does anyone have an idea what is I am doing wrong? Or how can I get the result that I am trying to get?
I really am stuck here for the last few days! I really appreciate your help and afford!
SideNote: Why Binding in Datagrid so complicated! Any idea where I can get a complete overview? For example (I am still confused why Datacontext, itemsource, ObservableCollection(why list of list of string doesn't work)). Any post or website with a clear concept? I went through a lot of examples and posts, but everybody is having a different approach than another and I am lost after sometimes!

A: ItemsSource should be some kind of sequence (IEnumerable).
Since you are binding DataContext directly, DataContext should be IEnumerable
So instead of single item:
DataContext = New Employee()

you still have to use collection:
Class MainWindow
    Dim appRow As New ObservableCollection(Of Employee)

    Sub New()
    InitializeComponent()

    appRow.Add(New Employee())

    DataContext = appRow
    End Sub
End Class

but initialization happens inside Employee class

or you can add item to Items colection without binding:
Sub New()
    InitializeComponent()

    MyDataGrid.Items.Add(New Employee())
End Sub

changes in xaml:
<DataGrid Name="MyDataGrid" AutoGenerateColumns="False">


text:
Q: How to change alert function to bootstrap modal I wanted to change the following function to bs modal or any other fancy dialogue box.
if (Form::mailer($email, $fname, $lname)) {
    echo
        '<script >
    alert("Thank you for registration.");
    window.location = "../test.php"; <
    /script>';
} else {
    echo ' <
        script >
        alert("Error, please try submitting again. Error code 1");
    window.history.back(); <
    /script>';
}

A: You can replace alert with BoostrapDialog:
Need to add these bootstrap CDN first
https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/css/bootstrap-dialog.min.css
https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/js/bootstrap-dialog.min.js

And then replace the alert method with show method of BootstrapDialog
BootstrapDialog.show({
    message: 'Thank you for registration.'
});

For detail, please refer http://nakupanda.github.io/bootstrap3-dialog/


text:
Q: Remove part of a string before the first forward slash I have a string
NSString *str = @"xyz/en/ABOUT/hello";

I need to remove all characters before the first slash.
My output should be like this :
"/en/ABOUT/hello"
but I cannot simply replace @"xyz", because the contents before the first slash are dynamic.

A: Objective-C
NSString *str = @"xyz/en/ABOUT/hello";
NSUInteger index = [str rangeOfString:@"/"].location;
NSString *myString = [str substringFromIndex:index];
NSLog(@"final string: %@", myString);    // final string:  /en/ABOUT/hello

Swift3
let str = "xyz/en/ABOUT/hello"
let index = str.range(of: "/")?.lowerBound
let myString: String? = str.substring(from: index!)
print("final string: ", myString!)   // final string:  /en/ABOUT/hello

A: first split the string:
NSArray *array1 = [str componentsSeparatedByString:@"/"]

then join the string:
NSString *joinedString = [[array1 subarrayWithRange:NSMakeRange(1, [array1 count] - 1)] componentsJoinedByString:@"/"];

to add the first '/' back
joinedString = [@"/" stringByAppendingString:joinedString]

There should be a regex way of doing this, but rarely using that unless have to.

A: Looks like you're working with a file path. So, use path manipulation methods:
@implementation NSString (MorePaths)

- (NSString *)WSSDroppingFirstRelativePathComponent
{
    NSArray * trailingComponents = [[self pathComponents] WSSDroppingFirst];
    return [NSString pathWithComponents:trailingComponents];
}

@end

@implementation NSArray (Dropping)

- (NSArray *)WSSDroppingFirst
{
    NSRange trailingRange = NSMakeRange(1, [self count] - 1);
    return [self subarrayWithRange:trailingRange];
}

@end

If this is actually a URL, make the category on NSURL instead of NSString.


text:
Q: how to find field that annotated with specific annotation by reflection? How can I find a field that is annotated with annotation when the annotation has a value?
For example I want to find a field in an entity that is annotated with
@customAnnotation( name = "field1" )
private String fileName ;

Is there any way to find this field (fileName in example) directly by reflection (java reflection or reflection library ) and not use the loop and the comparison?

A: Yes there is a good library.
<dependency>
  <groupId>org.reflections</groupId>
  <artifactId>reflections</artifactId>
  <version>0.9.11</version>
</dependency>

And in your code use the reflections like below:
//CustomAnnotation.java

package com.test;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
    String name() default "";
}

and consume like:
Reflections reflections = new Reflections("com.test", new FieldAnnotationsScanner());
Set<Field> fields = reflections.getFieldsAnnotatedWith(CustomAnnotation.class);

for(Field field : fields){
  CustomAnnotation ann = field.getAnnotation(CustomAnnotation.class);
  System.out.println(ann.name());
}


text:
Q: how can i sort a list of string date in specific format in c# i need to sort my list with the following code, this is what i have tried:
var orderedList = dateList.OrderBy(x => DateTime.Parse(x)).ToList();

but since the format of my dates is: dd mmm yyyy the above code is not working as per expectation. does anybody know, how can i apply this format for my order by method? mmm like jan, feb and ...

A: Use ParseExact with specifying format
var orderedList = dateList.OrderBy(x => DateTime.ParseExact(x, "dd MMM yyyy", null)).ToList();

see working example


text:
Q: Can the dot operator have an expression as right operand? Why? Is the following statement legal in any condition?
s.*p = 5;

So,
Can the dot operator have an expression as its right operand? Why?

A: pis a pointer to member and you access the pointed member through a class object s using .*operator.


text:
Q: Is it possible to run a task periodically in Background - iOS 4 I want to poll the location from GPS in the background. So we used a NSTimer and performed periodic checks in the timer tick. In other words, can we schedule NSTimer while the app is in Background?
Thanks in advance

A: You can't periodically execute arbitrary code, but you can get pinged on significant location changes via startMonitoringSignificantLocationChanges in CLLocationManager.


text:
Q: Is that possible get the number from a string when it inclund a keyword? I have several sentences,for example:
the price is 20.3
the size is 20.3
I want use Java Script to get the number when find the price keyword in those sentences.
As I know
x = "the price is 20.3"
y = x.otherTotal.replace(/[^0-9]/ig,"")

can get the number, but when sentence change to
x = "the size is 20.3"

i don't want return the number.

A: You can use includes to check for price keyword.

x = "the price is 20.3";

const regex = /[0-9.0-9]+/;

if(x.includes("price")) {
    console.log(x.match(regex)[0]);
}

A: You could look for price and then get the number.

function getPrice(s) {
    return /price/i.test(s) && s.match(/\d+\.\d*/)[0];
}

console.log(getPrice("the price is 20.3"));
console.log(getPrice("the size is 20.3"));

A: So match the entire string

const x1 = "the price is 20.3"
const x2 = "the size is 20.3"

function getPrice (str) {
  //const match = str.match(/price[^\d]*(\d+\.\d+)$/) // or just was price before numbers
  const match = str.match(/^the price is (\d+\.\d+)$/)
  return match && match[1]
}

console.log(x1, getPrice(x1))
console.log(x2, getPrice(x2))

A: 1) check if if it includes the word
2) Split it
3) Take the last Item
x.includes('price')?x.split(' ')[x.split(' ').length-1]:false


text:
Q: How to read trace file(timeline) in Tensorflow The timeline trace file is introduced here:
https://www.tensorflow.org/versions/r1.1/performance/xla/jit
It seems useful for performance analyzing. But there is something I can't understand.
1, What does "pid" stand for while there are:
    /device:GPU:0/stream:35 Compute (pid 3)
    /device:GPU:0/stream:all Compute (pid 9)
    /job:localhost/replica:0/task:0/device:CPU:0 Compute (pid 5)

2, A same OP can appear in different pids with absolutely different timestamp. What does that mean?
Can anybody help me? Or is there any document about this? Thanks very much!

A: *

*'pid' stands for process identifier.  According to a comment from a developer here, "All of the numeric 'PID's and 'TID's in the UI should be ignored- they were just invented to get CTV [Chrome Trace Visualizer] to lay out the trace better but there's no way to stop the GUI displaying them!"

*This probably means that the OP is running multiple times.


text:
Q: Spring roo and iText PDF unsure how to install? I've got a spring roo project and I would like to have the ability of allowing a user to be able to download a pdf from my project. I know how to generate the PDF but I'm not entirely sure about how to install iText 5.1.2 into my spring Roo project.

A: To add iText to your Maven project, just add the following dependencies:
<dependencies>

  <dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.1.2</version>
  </dependency>

  <dependency>
    <groupId>com.itextpdf.tool</groupId>
    <artifactId>xmlworker</artifactId>
    <version>1.1.0</version>
  </dependency>

  <!-- other dependency -->
</dependencies>


text:
Q: Is Ingress-Nginx able to send unescape header to backend? I'm using Nginx as my Ingress Controller in a Kubernetes deployment where WSO2 Identity Server 5.11 is at the backend.
I have a requirement of authenticating clients against the backend using a X509 certificate.
Also, I have to TLS terminate at Nginx.
I managed to put the corresponding certificate from the handshaking to a header in order to pass the request to the backend like WSO2 Identity Server is expecting.
The issue I'm facing is WSO2 Identity server requires the content of the header to be a standard PEM format, which means not escaped/encoded, just standard Base64 and Nginx send the header escaped (see below for a sample).
I tried using a lua block which effectively unescape the original value to the format I would like to send to the backend, but when the header is received at the backend it's always escaped.
Is there any way to send the content of a header unescaped?
Please help, any comments will be greatly appreciated.
Sample of the escaped certificate received by WSO2 Identity Server:
-----BEGIN CERTIFICATE-----%0AMIIEDjCCAvagAwIBAgIUCG/WzR4Z p1qGX9 lNVU f0K8P4wDQYJKoZIhvcNAQEL%0ABQAwgZYxCzAJBgNVBAYTAkNBMQ8wDQYDVQQIDAZRdWViZWMxETAPBgNVBAcMCE1v%0AbnRyZWFsMRAwDgYDVQQKDAdDaGFrcmF5MQswCQYDVQQLDAJJVDEYMBYGA1UEAwwP%0ASmFpcm8gRmVybmFuZGV6MSowKAYJKoZIhvcNAQkBFhtqYWlyby5mZXJuYW5kZXpA%0AY2hha3JheS5jb20wHhcNMjExMTMwMjEzNTIyWhcNMjIxMTMwMjEzNTIyWjCBmjEL%0AMAkGA1UEBhMCQ0ExDzANBgNVBAgMBlF1ZWJlYzERMA8GA1UEBwwITW9udHJlYWwx%0AEDAOBgNVBAoMB0NoYWtyYXkxCzAJBgNVBAsMAklUMRwwGgYDVQQDDBNjbGllbnRz%0ALmNoYWtyYXkuY29tMSowKAYJKoZIhvcNAQkBFhtqYWlyby5mZXJuYW5kZXpAY2hh%0Aa3JheS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC nYoRD/83%0AW9OYGMyp2wGhoMPcra2rPgHZf5irCupAIY/49gg1dsz/i7UMj2pK0IzW/dsGTdfl%0AGKuM4avKSqyAjlRvOhxk0A5Z/fmghjOiTWtBdp7jQ4zJcM9ip3 W4nRPi8Asv/A %0AeJyHcCCMppv0XguQKEhwusOyQHCNn7iQ0itT1kPfOAACpi0ZrcN777VlVZRu2LsW%0AdJfYUI1 e7u2OygCdL0B3HGbOZixoOJWEyoi1 0jiIxQmnv2ExDsabjbbdllus8 %0AJDdMUtswo xzGAe0IvGhHiFSOgNTSafLrHpYwCpG3/ikKQ SeULDF9yQ7F09bjpk%0AcyY7GgvaFUZ3AgMBAAGjTjBMMB8GA1UdIwQYMBaAFA1dKwqVgKPAg/2ciw6MyKGZ%0AsBg8MAkGA1UdEwQCMAAwHgYDVR0RBBcwFYITY2xpZW50cy5jaGFrcmF5LmNvbTAN%0ABgkqhkiG9w0BAQsFAAOCAQEAutYrzNJs92xXsJh kX7jvK9LZmP5F nsnSOLrM65%0Aa3jv4fkFalFTqx 82ie6ouekaTd9o4JF2jFkmj6B18AteuiM0xesO1ROdp pobZQ%0AfbGT8czViCQjtjiv1OC35unR2AkB9G22jD4OKaAh47T090QHCYGLpLloZrTGISbH%0ArNDGXeZjkTWhymuA1sSRUVIIytHqSzQmNOXC1RHK/ORcy mujOK7zKuLM6jaCgO%0A3FGQ1gh9FF2ooDN8GH9tqo5lzxfKtqd2z4HZ1yQ5QGWTDkHFeOJu6iSzLnO3Nayx%0A6a2 ud8QeN1nZKoMWDy4/BsRilE6Ap/ijQF82g BI/FyUw==%0A-----END CERTIFICATE-----%0A

What I really need to send to the backend:
-----BEGIN CERTIFICATE-----
MIIEDjCCAvagAwIBAgIUCG/WzR4Z p1qGX9 lNVU f0K8P4wDQYJKoZIhvcNAQEL
BQAwgZYxCzAJBgNVBAYTAkNBMQ8wDQYDVQQIDAZRdWViZWMxETAPBgNVBAcMCE1v
bnRyZWFsMRAwDgYDVQQKDAdDaGFrcmF5MQswCQYDVQQLDAJJVDEYMBYGA1UEAwwP
SmFpcm8gRmVybmFuZGV6MSowKAYJKoZIhvcNAQkBFhtqYWlyby5mZXJuYW5kZXpA
Y2hha3JheS5jb20wHhcNMjExMTMwMjEzNTIyWhcNMjIxMTMwMjEzNTIyWjCBmjEL
MAkGA1UEBhMCQ0ExDzANBgNVBAgMBlF1ZWJlYzERMA8GA1UEBwwITW9udHJlYWwx
EDAOBgNVBAoMB0NoYWtyYXkxCzAJBgNVBAsMAklUMRwwGgYDVQQDDBNjbGllbnRz
LmNoYWtyYXkuY29tMSowKAYJKoZIhvcNAQkBFhtqYWlyby5mZXJuYW5kZXpAY2hh
a3JheS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC nYoRD/83
W9OYGMyp2wGhoMPcra2rPgHZf5irCupAIY/49gg1dsz/i7UMj2pK0IzW/dsGTdfl
GKuM4avKSqyAjlRvOhxk0A5Z/fmghjOiTWtBdp7jQ4zJcM9ip3 W4nRPi8Asv/A
eJyHcCCMppv0XguQKEhwusOyQHCNn7iQ0itT1kPfOAACpi0ZrcN777VlVZRu2LsW
dJfYUI1 e7u2OygCdL0B3HGbOZixoOJWEyoi1 0jiIxQmnv2ExDsabjbbdllus8
JDdMUtswo xzGAe0IvGhHiFSOgNTSafLrHpYwCpG3/ikKQ SeULDF9yQ7F09bjpk
cyY7GgvaFUZ3AgMBAAGjTjBMMB8GA1UdIwQYMBaAFA1dKwqVgKPAg/2ciw6MyKGZ
sBg8MAkGA1UdEwQCMAAwHgYDVR0RBBcwFYITY2xpZW50cy5jaGFrcmF5LmNvbTAN
BgkqhkiG9w0BAQsFAAOCAQEAutYrzNJs92xXsJh kX7jvK9LZmP5F nsnSOLrM65
a3jv4fkFalFTqx 82ie6ouekaTd9o4JF2jFkmj6B18AteuiM0xesO1ROdp pobZQ
fbGT8czViCQjtjiv1OC35unR2AkB9G22jD4OKaAh47T090QHCYGLpLloZrTGISbH
rNDGXeZjkTWhymuA1sSRUVIIytHqSzQmNOXC1RHK/ORcy mujOK7zKuLM6jaCgO
3FGQ1gh9FF2ooDN8GH9tqo5lzxfKtqd2z4HZ1yQ5QGWTDkHFeOJu6iSzLnO3Nayx
6a2 ud8QeN1nZKoMWDy4/BsRilE6Ap/ijQF82g BI/FyUw==
-----END CERTIFICATE-----

A: If you have used $ssl_client_escaped_cert in the cert header, it returns the client certificate in the PEM format which is urlencoded.

proxy_set_header X-SSL-CERT ssl_client_escaped_cert;

Intead, try using the $ssl_client_cert as follows.

proxy_set_header X-SSL-CERT $ssl_client_cert;

OR

proxy_set_header X-SSL-CERT $ssl_client_raw_cert;

It will return the client certificate in the PEM format for an established SSL connection without any encoding.
Refer [1] for more information on nginx embedded variables.
Note: Replace X-SSL-CERT with your corresponding HTTP request header name.
If this solution didn't resolve the issue, please attach your nginx.conf configurations for further investigations.
[1] http://nginx.org/en/docs/http/ngx_http_ssl_module.html


text:
Q: Extract names of a dataset with purrr::map2() or purrr::imap() I am trying to use purrr::map2() or purrr::imap() to find a dataset from a large list of datasets where there is a given variable. Essentially, I will loop through the list of datasets and only print the names of the datasets that have the variable of interest. When I do it with purrr::map(), the dataset is unnamed ".x[[i]]". Any help would be greatly appreciated. Thank you
#load packages
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
library(purrr)

#create fictitious datasets
df1 <- tibble(score_a=1:20,
              sex_a=rep(c("M", "F"), 10))
df2 <- tibble(score_b=1:20,
              sex_b=rep(c("M", "F"), 10))
df3 <- tibble(score_c=1:20,
              sex_c=rep(c("M", "F"), 10))

#create a function that returns the dataset that
#contains a given variable
get_dataset_name <- function(data, contains){

  data_var_names <- colnames(data)

  dataname <- deparse(substitute(data))

  if(contains %in% data_var_names){
    return(dataname)
  }
}

#testing the function
get_dataset_name(data=df3, contains="score_c")
#> [1] "df3"

#creating a list of the all datasets
data_list <- list(df1, df2, df3)

#looping through a list of the dataset to find the dataset
#that includes the given variable

map(data_list, get_dataset_name, contains="score_c")
#> [[1]]
#> NULL
#>
#> [[2]]
#> NULL
#>
#> [[3]]
#> [1] ".x[[i]]"

#I was hoping to obtain "df3" instead of  ".x[[i]]"
#I read that purrr::map2() or purrr::imap could solve
#the issue but I am not sure how to set it up
#Any help would be appreciated it

# map2(.x=data_list,
#      .y=names(data_list),
#      ~get_dataset_name(data=.x, contains="score_c"),
#      nest(.x, name=.y)
# )

#imap(data_list, get_dataset_name, contains="score_c")

Created on 2022-09-26 by the reprex package (v2.0.0)

A: Instead of deparse/substitute, try getting indices to the data set names. The indices can be logical or numeric. If the list is a named list then the names can be used to index the list and these values will be returned by the second function, iget_dataset_name.
# load packages
suppressPackageStartupMessages({
  library(dplyr)
  library(purrr)
})

# create fictitious datasets
df1 <- tibble(score_a=1:20,
              sex_a=rep(c("M", "F"), 10))
df2 <- tibble(score_b=1:20,
              sex_b=rep(c("M", "F"), 10))
df3 <- tibble(score_c=1:20,
              sex_c=rep(c("M", "F"), 10))

# create two functions that return indices to the
# data sets that contain the wanted name
get_dataset_name <- function(data, contains){
  data_var_names <- colnames(data)
  contains %in% data_var_names
}
iget_dataset_name <- function(data, col_names, contains){
  data_var_names <- colnames(data)
  i <- which(contains %in% data_var_names)
  col_names[i]
}

# testing the function
get_dataset_name(data=df3, contains="score_c")
#> [1] TRUE

# creating a list of the all datasets
data_list <- list(df1, df2, df3)

# looping through a list of the dataset to find the dataset
# that includes the given variable

map(data_list, get_dataset_name, contains="score_c")
#> [[1]]
#> [1] FALSE
#>
#> [[2]]
#> [1] FALSE
#>
#> [[3]]
#> [1] TRUE

imap(data_list, iget_dataset_name, contains="score_c")
#> [[1]]
#> integer(0)
#>
#> [[2]]
#> integer(0)
#>
#> [[3]]
#> [1] 3

# give the list a names attribute
names(data_list) <- c("df1", "df2", "df3")
# retest the functions
map(data_list, get_dataset_name, contains="score_c")
#> $df1
#> [1] FALSE
#>
#> $df2
#> [1] FALSE
#>
#> $df3
#> [1] TRUE

imap(data_list, iget_dataset_name, contains="score_c")
#> $df1
#> character(0)
#>
#> $df2
#> character(0)
#>
#> $df3
#> [1] "df3"

Created on 2022-09-27 with reprex v2.0.2


text:
Q: Weak$^*$ convergence of sequences in the dual space of a quotient Let $M$ be a closed subspace of a Banach space $X$. Let $q:X\to X/M$ be the quotient map, let $q^*: (X/M)^*\to X^*$ be the conjugate operator of $q$, and
let $(z^*_n)$ be a sequence in $(X/M)^*$.
Is it true that $(z^*_n)$ is $w^*$-convergent in $(X/M)^*$
$\Leftrightarrow(q^* z^*_n)$ is $w^*$-convergent in $X^*$?
Are the following arguments correct?
The direct implication follows from the $w^*$-$w^*$ continuity of $q^*$.
For the converse, if $(q^* z^*_n)$ is $w^*$-null, then $z^*_n(q\,  x) =(q^* z^*_n)(x)$ converges to $0$.

A: Let $(z_n^*)$ be a sequence in $(X/M)^*$. By definition of $q^*$,
$$ q^*(z_n^*)(x) = z_n^*(q(x)) \quad \forall x \in X,$$
If $(z_n^*)$ is $w^*$-convergent, then the right-hand side converges, then both sides converge, proving $\Rightarrow$.
Now assume that the mapped sequence $q^*(z_n^*)$ is $w^*$-convergent. By surjectivity, $q$ has a right inverse, which we denote by $q_r$. For $y \in (X/M)$, we choose $x = q_r(y)$ in the equation above, which gives
$$ q^*(z_n^*)(q_r(y)) = z_n^*(y)$$
By assumption the left-hand side converges, so the right-hand side converges as well, and since $y$ was arbitrary this proves $\Leftarrow$.