text:
Q: Why doesn't my controller return a token to Postman I'm developing an API with Spring with Security and JWT, and this is the controller method to login, and the login return a but in Postman it doesn't show the token in the body.
This is the login method controller:
@RestController
@RequestMapping("/auth")
@CrossOrigin
public class AuthController {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    BookingUserService bookingUserService;
    @Autowired
    RoleService roleService;

    @Autowired
    JWTUtil jwtUtil;

    @PostMapping(path = "/register")
    public ResponseEntity<?> registerUser(@Valid @RequestBody BookingUser registerBookingUser) {
        if (bookingUserService.existsByEmail(registerBookingUser.getEmail())) {
            return ResponseEntity.ok("Email already exists");
        }
       BookingUser bookingUser = new BookingUser(registerBookingUser.getName(), registerBookingUser.getLastName(), registerBookingUser.getEmail(), passwordEncoder.encode(registerBookingUser.getPassword()), registerBookingUser.getCity(), registerBookingUser.getRole());
       Role role = new Role();
       role = roleService.findByName(String.valueOf(RoleName.client)).get();
       if(registerBookingUser.getRole().equals("admin"))
           role = roleService.findByName(String.valueOf(RoleName.admin)).get();
       bookingUser.setRole(role);
       bookingUserService.createUser(bookingUser);
       return ResponseEntity.status(HttpStatus.CREATED).body("User successfully created");
    }

    @Deprecated
    @PostMapping(path = "/login")
    public ResponseEntity<?> loginUser(@RequestBody AuthenticationRequest request) {
        try {
            Authentication authentication = authenticationManager.authenticate
                    (new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword()));
            SecurityContextHolder.getContext().setAuthentication(authentication);
            String jwt = jwtUtil.generateToken(authentication);
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            //user = (Optional<BookingUser>) authentication.getPrincipal();
            AuthenticationResponse response = new AuthenticationResponse(jwt);
            System.out.println("JWT AHHHHH: ");

            if(!jwt.isEmpty()){
                return new ResponseEntity<>("Hiii", HttpStatus.OK);
            } else {
                return new ResponseEntity<>("AHHHHHH", HttpStatus.OK);
            }

        } catch (BadCredentialsException e) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
    }
}

This the JwtUtil
@Component
public class JWTUtil {
    private static final String KEY = "mG9\\n2,^obBu[8n.~MpVzbB5tHnuYF<KRE/LnQrQ<q@]wQP46vo^x{3vEN?3uN/E";
    @Deprecated
    public String generateToken(Authentication authentication) {
        BookingUser user = (BookingUser) authentication.getPrincipal();
        Map<String, Object> claims = new HashMap<>();
        claims.put("lastname", user.getLastName());
        claims.put("name", user.getName());

        return Jwts.builder()
                .setSubject(user.getUsername())
                .addClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
                .signWith(SignatureAlgorithm.HS256, KEY).compact();
    }
    public Boolean validateToken(String token, UserDetails userDetails) {
        return userDetails.getUsername().equals(extractUsername(token)) && !isTokenExpired(token);
    }
    public String extractUsername(String token) {
        return getClaims(token).getSubject();
    }
    public Boolean isTokenExpired(String token) {
        return getClaims(token).getExpiration().before(new Date());
    }
    @Deprecated
    private Claims getClaims(String token) {
        return Jwts.parser().setSigningKey(KEY).parseClaimsJws(token).getBody();
    }
}

This the JwtEntryPoint
@Component
public class JwtEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
            throws IOException, ServletException {
    }
}

AuthenticationResponse
@Setter
@Getter

public class AuthenticationResponse {
    private String jwt;

    public AuthenticationResponse(String jwt) {
        this.jwt = jwt;
    }
}

AuthController
@RestController
@RequestMapping("/auth")
@CrossOrigin
public class AuthController {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    BookingUserService bookingUserService;
    @Autowired
    RoleService roleService;

    @Autowired
    JWTUtil jwtUtil;

    @PostMapping(path = "/register")
    public ResponseEntity<?> registerUser(@Valid @RequestBody BookingUser registerBookingUser) {
        if (bookingUserService.existsByEmail(registerBookingUser.getEmail())) {
            return ResponseEntity.ok("Email already exists");
        }
       BookingUser bookingUser = new BookingUser(registerBookingUser.getName(), registerBookingUser.getLastName(), registerBookingUser.getEmail(), passwordEncoder.encode(registerBookingUser.getPassword()), registerBookingUser.getCity(), registerBookingUser.getRole());
       Role role = new Role();
       role = roleService.findByName(String.valueOf(RoleName.client)).get();
       if(registerBookingUser.getRole().equals("admin"))
           role = roleService.findByName(String.valueOf(RoleName.admin)).get();
       bookingUser.setRole(role);
       bookingUserService.createUser(bookingUser);
       return ResponseEntity.status(HttpStatus.CREATED).body("User successfully created");
    }

    @Deprecated
    @PostMapping(path = "/login")
    public ResponseEntity<?> loginUser(@RequestBody AuthenticationRequest request) {
        try {
            Authentication authentication = authenticationManager.authenticate
                    (new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword()));
            SecurityContextHolder.getContext().setAuthentication(authentication);
            String jwt = jwtUtil.generateToken(authentication);
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            //user = (Optional<BookingUser>) authentication.getPrincipal();
            AuthenticationResponse response = new AuthenticationResponse(jwt);
            System.out.println("JWT AHHHHH: ");

            if(!jwt.isEmpty()){
                return new ResponseEntity<>("Hiii", HttpStatus.OK);
            } else {
                return new ResponseEntity<>("AHHHHHH", HttpStatus.OK);
            }

        } catch (BadCredentialsException e) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
    }
}

AuthenticationRequest
@Setter
@Getter

public class AuthenticationRequest {
    private String email;
    private String password;
}

A: You are not returning the token in any way, only the text "Hiii" or "AHHHHHH".
if(!jwt.isEmpty()){
    return new ResponseEntity<>("Hiii", HttpStatus.OK);
} else {
    return new ResponseEntity<>("AHHHHHH", HttpStatus.OK);
}

Try something like the following:
AuthenticationResponse response = new AuthenticationResponse(jwt);

if(!jwt.isEmpty()){
    return new ResponseEntity<>(response, HttpStatus.OK);
} else {
    return new ResponseEntity<>("AHHHHHH", HttpStatus.OK);
}


text:
Q: How can I fetch rows with most recent timestamp for each key value table structure: id|emp_id|latitude|longitude|timestamp
I have a table of current_location data. Each row has a id,emp_id, a timestamp, and other fields. I want to select a single row with latest timestamp for each emp_id, including some of the other fields.

A: I think you need to use sub query
SELECT * from (SELECT * FROM emp_locations order by timestamp desc) as temp_table group by emp_id;

redpajama_set_name: RedPajamaStackExchange


text:
Q: IOS/Objective-C: Sum Integer in Core Data I am trying to get the sum of an NSNumber attribute from core data.  According to this question on SO, all you need to do is put some code in the NSManagedObject class for the entity.  However, when I try to access this method, I get a wrong answer, namely 0 when I know the sum should be higher than that.
Is it correct that the following code is a good way to 'get' a sum from core data?  And, if so, what is the proper way to call it as I am not getting a valid sum?
Thanks for any suggestions.
For Class named Points with an Integer64 attribute named points
.h file
@property (nonatomic, readonly) NSNumber* sumPoints;

.m file
-(NSNumber*) sumPoints
{
    return [self valueForKeyPath:@"Points.@sum.points"];
}

Calling from another class that imports this class:
 return [_Points.sumPoints intValue];
//Is returning 0 when sum should be much higher


text:
Q: Return type of multi-valued Entity properties I'm using App Engine's Datastore entities in my current project, and I have a multi-valued property for one of the entities. Now, my question is simple, if I store String objects as the values in the multi-value property by passing a String ArrayList as the value in the setProperty("myPropertyName", myArrayList) of my entity, what object will I receive when I run the following:
myEntity.getProperty("myPropertyName");

From my observation it doesn't seem to return an ArrayList, even though ArrayList is a Collection and, according to the documentation, getProperty() returns a Collection object.

A: The list of supported types can be found here: https://developers.google.com/appengine/docs/java/datastore/entities#Java_Properties_and_value_types.
Strongly consider using a JSON string as GAEfan suggested.
Edit:
According to the OP's comment below, you can store and get multiple values in the datastore as follows:
myEntity.setProperty("myPropertyName", myArrayListOfStrings)
List<String> myValues = myEntity.getProperty("myValueName");


text:
Q: Increase a div height automatically (100% parent) leaving a top and bottom margin? http://jsfiddle.net/YumHS/
In the page given in the jsfiddle der is a sidebar in the cont div.

sidebar

The sidebar has a right border. Der is a 10px margin in the top side of the sidebar. Similarly I want 10 margin in the bottom part also. I have used 100% height so that div.sidebar fills up entire screen. But with this method margin is not available at bottom since i'm using a sticky footer. What can I do for this? Please help.
Check the jsfiddle for the demo, to understand my question

A: See the fiddle for code and demo
Fiddle: http://jsfiddle.net/YumHS/2
Demo: http://jsfiddle.net/YumHS/2/embedded/result/
Updated fiddle: 1280 x 800 Resolution as per your requirement.
http://jsfiddle.net/YumHS/5/embedded/result/
To get the desired output i use image of 1px x 2000px. and adjust the position of background image see the css below, you can set the height( see 110%;) of background image as you want.
.sidebar {
    position: fixed;
    top: 100px;
    width: 227px;
    /*border-right: 1px solid #949698;*/
    height: 100%;
    background: url("http://img152.imageshack.us/img152/8141/fullbar.png") no-repeat right 110%;
}

In my system it is looking like below image:

Updated fiddle http://jsfiddle.net/YumHS/11/embedded/result/ -  with 2px space space in sidebar and footer.


text:
Q: Accessing views in relative way I'm new to xcode and I've one basic question about relative accessing views in ViewController.
Here is the situation in ViewController:
View
  1
    1.1
  2

Questions:

*

*How can I access 2 from View

*How can I access 1.1 from 2

*How can I access from 1.1 to View

Thank you very much, single lines of code will be perfect answer.

A: *

*You can use tagging. I don't prefer this method but it's fast to implement. See viewWithTag:.

*Or you can save view as instance variables.


text:
Q: Put a class with certain class in front of group of divs I'm making a list of multiple divs and one of those divs will have the class current.
For example:

 more html

 more html

 more html

 more html

Now this class might be on any of the divs depending on what user was selected before. (not really relevant. just fyi)
And now I want the div with current to always be the first one shown in the row.
I was thinking about removing the div with jquery and then append it to the row, but I don't think this is the cleanest way.

A: You can do this with display:flex and order:

.row {
    display:flex; /* set flex on the parent */
}

.row .col-md-4 {
    order:2;     /* set default order to be same so they keep their original order */
}

.row .col-md-4.current {
    order:1;       /* make current a lower order so it goes to the front */
}

1 more html

2 more html

3 more html

4 more html

A: There are a bunch of ways to use jQuery's DOM manipulation selectors to do this, but an easy one-liner is:
$('div.current').insertBefore('div.col-md-4:first')

$('div.current').insertBefore('div.col-md-4:first');

 more html

 more html

 more html

 more html

A:

First

Second

This will result in [Second, First] order. If you want to change order then just change element.style.order = xx with JavaScript.
There is a good guide on Flex from css-tricks.

A: With pure CSS you could just float that particular div a different direction to the rest. I have created a fiddle you can follow.
https://jsfiddle.net/w6hhqxvq
.row{
   width: 100%;
}
.col-md-4{
width: 25%;
height: 200px;
background: yellow;
float: right;
}

.col-md-4.current{
float: left;
background: blue;
}


text:
Q: What is coordinate format on QGIS georeferencing I watch tutorial from this video https://www.youtube.com/watch?v=THRa2OHpL0k, and found the coordinate from the image are about 7 digits number.

e.g. N8352000, N8356500, E247500, etc

I want to recreate what in the video did, but I only have a degree minute second coordinate.

e.g. 0°30'0" N, 128°30'0"E, etc

What is the coordinate system from the video? And how to change my degree coordinate to be like in the video. I think I'll try to do it in EPSG 2857 Pseudo Mercator, if that'll be in concern while converting it.

A: As it says in the video at about 1:40 the EPSG used here is 24879, but as @Ian Turton points out, that does not mean, that yours should be the same. To change the coordinates in your system you have to go to Transormation Paramters (via settings in the Georeferencer) and set the Target SRS to the correct SRS (what ever your data have).


text:
Q: Move unique files from a folder with duplicates files Well to put it simply, I have duplicate files in a folder, with this form:
file.ext
file(1).ext
file(2).ext
file(3).ext
otherfile.ext
otherfile(1).ext
otherfile(2).ext
...

I want to move only file.ext and otherfile.ext to another folder. Is it possible to do it in bash?
I thought that maybe awk would be helpful?

A: In bash:
shopt -s extglob # activates extended pattern matching features
mv !(*\(+([0-9])\)).ext /path/to/target/

The regular expression matches all files, that don't end with (n).ext, where n is one or more numbers: +([0-9]).
You can check it with echo:
echo !(*\(+([0-9])\)).ext

Prints:
file.ext otherfile.ext

A: It depends. If we can assume that any file whose name contains ( should be ignored, you could just do:
shopt -s extglob ## turns on fancy glob patterns
mv !(*\(*) /path/to/target

If you can have other names that contain ( or if you need to only move those files which are duplicated, you can do:
for f in *\(*; do
    ## Does this file have an original?
    [[ -e "${f%%(*}.${f##*.}" ]] &&
        ## Move the original
        mv "${f%%(*}.${f##*.}" /path/to/target;
done

A: Try something like that:
$ ls  *ext | grep -P '[^)]\.ext' | xargs -iXXxxFILEXXxx mv XXxxFILEXXxx target/

grep will filter out files with brackets in names and xargs will run command mv on results. The ugly XXxxFILEXXxx label is for placing file names as mv argument.


text:
Q: Polygon intersection using turf js I have given this code for intersection:
function intersectPolyByPolyFC(poly,fcPoly){
        var fgp=[];//variable for feature group
        var bbPoly=turf.bboxPolygon(turf.bbox(poly));//polygon representation of the bounding box of a reference polygon
        for(var i=0;i<fcPoly.features.length;i++){//loop through the feature collection of polygons
            var bb=turf.bboxPolygon(turf.bbox(fcPoly.features[i]));//variable bb represents each polygon for feature collection
            if(turf.intersect(bbPoly,bb)){//condition to check if the two bounding boxes intersect
                var int= turf.intersect(poly,fcPoly.features[i]);
                if(int){
                    int.properties=fcPoly.features[i].properties;
                    fgp.push(int);
                }
            }
        }
        return turf.featureCollection(fgp);
    }

and the function definition I have given as
var bufline=turf.buffer(line,0.05,{units:"kilometers"});
var intBUOWL= intersectPolyByPolyFC(bufline, lyrBUOWL.toGeoJSON());
L.geoJSON(intBUOWL,{style:{color:'red',weight:5}}).addTo(mymap);

When I am drawing a line over a polygon for intersection I am getting this error
Uncaught TypeError: Cannot read property 'map' of undefined
    at Object.t.collect (turf.min.js:1)
    at summarizePointsByLine (buffer.html:440)
    at NewClass.<anonymous> (buffer.html:155)
    at NewClass.fire (Events.js:190)
    at NewClass._fireCreatedEvent (leaflet.draw.js:8)
    at NewClass._fireCreatedEvent (leaflet.draw.js:8)
    at NewClass.completeShape (leaflet.draw.js:8)
    at HTMLAnchorElement.handler (DomEvent.js:92)

How can I resolve this error?


text:
Q: Creating a custom column after groupby in csv, pandas Given the below csv file:
ID  A   B   C   R1  R2
-----------------------
1   A1  B1  C1  abc ghi
1   A1  B1  C2  def jkl
2   A2  B3  C1  mno stu
2   A2  B3  C2  pqr vwx

Need below output with a new column 'R':
ID  A   B  R
-------------------------
1   A1  B1 (abc, def) & (ghi, jkl)
2   A2  B3 (mno, pqr) & (stu, vwx)

Assume only C1, C2 values for column C
import pandas as pd
df = pd.read_csv(r'file.csv')
grouped_df = df.groupby(['ID', 'A', 'B'])

# Here how do we create our new and custom column?

A: You could use agg, ''.join and filter:
df.groupby(['ID','A','B'])
  .agg(lambda x: '('+', '.join(x)+')')
  .filter(like='R').agg('&'.join,1)
  .reset_index().rename(columns={0:'R'})

Details
df.groupby(['ID','A','B']).agg(lambda x: '('+', '.join(x)+')')
#                 C          R1          R2
#ID A  B
#1  A1 B1  (C1, C2)  (abc, def)  (ghi, jkl)
#2  A2 B3  (C1, C2)  (mno, pqr)  (stu, vwx)

df.groupby(['ID','A','B']).agg(lambda x: '('+', '.join(x)+')').filter(like='R')
#                  R1          R2
#ID A  B
#1  A1 B1  (abc, def)  (ghi, jkl)
#2  A2 B3  (mno, pqr)  (stu, vwx)

df.groupby(['ID','A','B']).agg(lambda x: '('+', '.join(x)+')').filter(like='R').agg('&'.join,1).reset_index()
#   ID   A   B                      0
#0   1  A1  B1  (abc, def)&(ghi, jkl)
#1   2  A2  B3  (mno, pqr)&(stu, vwx)

df.groupby(['ID','A','B']).agg(lambda x: '('+', '.join(x)+')').filter(like='R').agg('&'.join,1).reset_index().rename(columns={0:'R'})
#   ID   A   B                      R
#0   1  A1  B1  (abc, def)&(ghi, jkl)
#1   2  A2  B3  (mno, pqr)&(stu, vwx)

A: In [54]: df
Out[54]:
   ID    A   B   C   R1   R2
0   1   A1  B1  C1  abc  ghi
1   1   A1  B1  C2  def  jkl
2   2   A2  B3  C1  mno  stu
3   2   A2  B3  C2  pqr  vwx

In [55]: grouped_df = df.groupby(['ID', 'A', 'B'])[["R1","R2"]].agg(tuple).reset_index()

In [56]: grouped_df["R"] = grouped_df["R1"].astype(str) + " & " + grouped_df["R1"].astype(str)

In [57]: grouped_df.drop(["R1","R2"],axis=1,inplace=True)

In [58]: grouped_df
Out[58]:
   ID    A   B                                R
0   1   A1  B1  ('abc', 'def') & ('abc', 'def')
1   2   A2  B3  ('mno', 'pqr') & ('mno', 'pqr')


text:
Q: Android HashMap - What Does This Code Do? const-string v1, "12345678"

const-string v2, "George#1"

invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

and
const-string v1, "12345678"

const-string v2, "12345678 transaction"

invoke-virtual {v0, v1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

Sorry for the very newbie question but was wondering what these pieces of code do?
Thanks

A: v0 v1 v2 are the register address in the Dalvik Virtual Machine.
const-string v1, "12345678"

creates a String "12345678" and save it to the register v1.
invoke-virtual {v0, v1, v2}

calls the method put(..) and it takes three parameters v0 is 'this', v1 is "12345678" and v2 is "George#1"


text:
Q: How to use case structure for comparing string So i have a table in excel with different names. I am trying to parse through the table and depending on the name in each cell, change the cell background color.
I tried to use a switch control, but its not working for me as some of the names are being skipped. So all I get it, some cells colored correctly and some cells not colored at all. This is the code
Sub selectAll()
    Sheets("Assignments").Activate
    Dim cell As Range
    For Each cell In Range("D7:X48")
        Select Case cell.Text
            ct Case cell.Text
            Case "John H."
                cell.Interior.ColorIndex = 6
            Case "Eve J."
                cell.Interior.ColorIndex = 4
            Case "Sam M."
                cell.Interior.ColorIndex = 46
            Case "Jeremy E."
                cell.Interior.ColorIndex = 46
        End Select
    Next
End Sub

A: Why not conditional formatting? If you still want to do it with VBA then read on...
Your code is not working as expected i.e some cells are getting skipped, most probably because there are spaces in the cell or the case (UPPER/LOWER/MIXED) is different.
This is how I would do it. (UNTESTED)
Sub selectAll()
    Dim cell As Range

    With Sheets("Assignments")
        For Each cell In .Range("D7:X48")
            Select Case UCase(Trim(cell.Value))
                Case "JOHN H.": cell.Interior.ColorIndex = 6
                Case "EVE J.": cell.Interior.ColorIndex = 4
                Case "SAM M.", "JEREMEY E.": cell.Interior.ColorIndex = 46
            End Select
        Next
    End With
End Sub

If you want to partially check for a string in the cell then use INSTR with vbTextCompare

A: If some are coloring correctly and some are not, it suggests to me that the some of the cells do not match the text you are looking for. Is there hidden whitespace in the cells that are not being colored?
I would also put in a case else at the end of it with a msgbox or something similar to alert you to when something doesnt match one of your cases. Then you will have a specific instance to investigate. Always important to have a catch all at the end.


text:
Q: Criteria ilike mechanizm How do I write a custom Creteria API in order to find a unique result,
matching the longest sequence in a database?
If I have the request string "V1234" it should be matched to V123
V1234 -> V123

If I have the request string "V12XXX" it should be matched to V12
If I have the request string "V" it should be matched to  V

A: You can sort your values by length desc, and then iterate these values to check whether match, if matched break.
public static void main(String[] args) {
    List<String> values = Arrays.asList("V", "V1", "V12", "V123");
    Collections.sort(values, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return o2.compareTo(o1);
        }
    });

    String[] test = new String[]{"V123456", "V127896", "V1877", "V2394"};
    for (String s : test) {
        for (String str : values) {
            if (s.contains(str)) {
                System.out.println(str);
                break;
            }
        }
    }
}

A: You could make your own Criterion implementation similar to LikeExpression but with the operands reversed. Then to find the longest you have to sort. Unfortunately I don't think you can sort by the length of your field without creating a custom Order implementation.
criteria.add(new InverseLikeExpression(value, "yourProperty", MatchMode.START)
    .addOrder(OrderByLength.desc("yourProperty"))
    .setMaxResults(1);

With HQL this is a bit easier:
where :value like yourProperty || '%' order by length(yourProperty) desc


text:
Q: Facebook Connect with Java Smack 4 With this example I'm trying to get the number of Facebook friends to connect, but I get an error
       XMPPConnection connection = new XMPPTCPConnection("chat.facebook.com");
       connection.connect();
       connection.login("asdd@asd.com", "pass");
       Roster roster = connection.getRoster();
       Collection<RosterEntry> entries = roster.getEntries();
       System.out.println(entries.size() + " buddy(ies):");

output:
23, 2014 2:23:04 PM org.jivesoftware.smack.filter.IQReplyFilter accept
WARNING: Rejected potentially spoofed reply to IQ-packet. Filter settings: packetId=JR6jj-0, to=null, local=null, server=chat.facebook.com. Received packet with from=asdd@asd.com@chat.facebook.com
I'm using version Smack4.0.3


text:
Q: Change "oo" to "00" in a string using some loop Need to hep to change multiple characters in a string using some loop without built-in functions in PHP.
<?php
       $givenString = "School";
       $i=0;
    while($givenString[$i]){
        $i++;
        if($givenString[$i] == o){
        $givenString[$i] = 0;
        }
    }

    echo $givenString;
    ?>

Result: Sch0ol
Required Result: Sch00l

A: Because your loop logic is out of order. Feed in the string "ooooo" and you'll get "o0ooo" out. It skips the first letter because the first thing you do is move the index ahead, and it stops after the first replacement because you're testing the character that you just replaced, and "0" type-juggles to boolean as false.
Move $i++ to the end of the loop and you'll get "00000", but also Warning: Uninitialized string offset 6. This is because you're relying on the error to break the loop. You need to bound the loop on the length of the string, not the content.
So:
$givenString = "oooooo";
$i=0;
$c=strlen($givenString);
while($i<$c){
    if($givenString[$i] == 'o'){
        $givenString[$i] = 0;
    }
    $i++;
}

echo $givenString;

or we can condense that with for loop:
$givenString = "oooooo";
for( $i=0, $c=strlen($givenString); $i<$c; $i++ ){
    if($givenString[$i] == 'o'){
        $givenString[$i] = 0;
    }
}

echo $givenString;

For completeness, the un-quoted o in your post only works because pre-8.0 PHP assumed that unquoted constants were just "oopsies" meant to be strings and replaced them with their string equivalent, issuing a Notice like Notice: Use of undefined constant o - assumed 'o', which can potentially have serious side-effects.
This error also indicates that you're using a version of PHP that is no longer supported, and you should ensure that you are writing code on a supported version.

A: In your current code, you are replacing all o to 0 which is off-track with respect to replacing oo to 00 and also skipping the current o at hand doesn't make sense. Also, as already pointed out, matching a string with a string is better than comparing with just o directly.

You can instead match o with o and check if string contained a previous o or not. If it did, mark both previous and current location as 0, or else, leave it as is. Since you didn't wish to use inbuilt functions, you can use null-coalescing operator(??) to check with the length of the string as well.
<?php

function modify($string){

  for($i = 1; ($string[$i] ?? false) !== false; ++$i){
    if($string[ $i ] === 'o' && $string[$i - 1] === 'o'){
      $string[ $i ] = $string[$i - 1] = '0';
    }
  }

  return $string;
}

Online Demo


text:
Q: The method startActivity(Intent) is undefined for the type SMSBroadcastReceiver I'm using the class SMSBroadcastReceiver to very time I receive a sms it creates a event on my calender the code is like this
package com.arnaldo.smscal;

    import java.util.GregorianCalendar;

    import android.content.BroadcastReceiver;
    import android.content.ContentResolver;
    import android.content.ContentUris;
    import android.content.Context;
    import android.content.Intent;
    import android.content.SharedPreferences;

import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.Contacts;
import android.provider.CalendarContract.Events;
import android.provider.Contacts.People;
import android.provider.Contacts.Phones;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class SMSBroadcastReceiver extends BroadcastReceiver{

    private static final ContentResolver ContentResolver = null;
    private static final Context Context = null;

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
            Bundle bundle = intent.getExtras();           //---get the SMS message passed in---
            SmsMessage[] msgs = null;
            String msg_from;

            if (bundle != null){
                //---retrieve the SMS message received---
                try{
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    msgs = new SmsMessage[pdus.length];
                    for(int i=0; i<msgs.length; i++){
                        msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                        msg_from = msgs[i].getOriginatingAddress();
                        String msgBody = msgs[i].getMessageBody();
                        Log.e(msg_from, msgBody);

        String contact;
                        Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(msg_from));
                        Cursor cs= context.getContentResolver().query(uri, new String[]{PhoneLookup.DISPLAY_NAME},PhoneLookup.NUMBER+"='"+msg_from+"'",null,null);

                        if(cs.getCount()>0)
                        {
                         cs.moveToFirst();
                         contact=cs.getString(cs.getColumnIndex(PhoneLookup.DISPLAY_NAME));
                         Log.e("Foi de", contact);

                         //------------//

                         Intent calIntent = new Intent(Intent.ACTION_INSERT);
                         calIntent.setType("vnd.android.cursor.item/event");
                         calIntent.putExtra(Events.TITLE, "My House Party");
                         calIntent.putExtra(Events.EVENT_LOCATION, "My Beach House");
                         calIntent.putExtra(Events.DESCRIPTION, "A Pig Roast on the Beach");

                         GregorianCalendar calDate = new GregorianCalendar(2012, 9, 5);
                         calIntent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true);
                         calIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, calDate.getTimeInMillis());
                         calIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, calDate.getTimeInMillis());

                         startActivity(calIntent);

                         //------------//

                        }

                    }
                }catch(Exception e){
                           Log.w("Exception caught",e.getMessage());
                }
            }
        }
    }
}

the problem is the  startActivity(calIntent);
I have the error "The method startActivity(Intent) is undefined for the type SMSBroadcastReceiver"
Please HELP

A: use context since it is passed into the onReceive function:
      context.startActivity(intent);


text:
Q: Scale down Heroku DB from production to hobby Is it possible to scale down a Heroku DB from production to hobby (the free Dev plan), as long as we stay within the row limits? A site I'm working on requires a production-grade DB for a few weeks, but then it'll be quiet for a while. Haven't been able to find any info on this.

A: It shouldn't be a problem.  Heroku has a guide to upgrade with backups, so I'd recommend taking a backup of your current database, downloading it to your local computer, then spinning up a development database.
Once the development (free) DB is ready, restore from the pgbackup on your local.  As long as you're under the row limit, you should be fine.
Obviously, you'd want to put the site in maintenance mode when you do all of this - but it shouldn't be down for more than 5-10 minutes.


text:
Q: getIntent, Can't get my activity to get the latest intent I'm sure this is a failure in  my understanding of intents but I have an ExpandableListView of items and when I click on an item it launches the first one OK but for each time after that it only launches the first one again no matter which on I click on. The request debugs as OK but the received intent always debugs as if the first one was sent. After a half a day stuck on it and Google failing me, I need some help.
Activity #1 Mainfest
<activity
        android:name="com.h17.gpm.ActivityToDoList"
        android:launchMode="singleInstance"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="com.h17.gpm.TODO" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
</activity>

Activity #1 Code
Intent launch = new Intent(ActivityToDoList.this, ActivityToDoEdit.class);
launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
launch.putExtra("Action._ID", a.get_ID());
Log.d("ACTIVITYLAUNCHTEST", "Launch["+a.get_ID()+"]");
startActivity(launch);

Activity #2 Mainfest
<activity
        android:name="com.h17.gpm.ActivityToDoEdit"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="com.h17.gpm.TODO.EDIT" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
</activity>

Activity Code #2
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_todo_edit);
    Intent i = getIntent();
    Bundle extras = null;
    if(i != null)
        extras = i.getExtras();
    if (extras != null){
        action_id = extras.getLong("Action._ID");
        Log.d("ACTIVITYLAUNCHTEST", "Receive["+action_id+"]");
    }
}

I've read from other posts that getIntent returns the first Intent so also tried
@Override
protected void onNewIntent(Intent intent){
    Bundle extras = null;
    if(intent != null)
        extras = intent.getExtras();
    if (extras != null){
        action_id = extras.getLong("Action._ID");
        Log.d("ACTIVITYLAUNCHTEST", "Receive New Intent["+action_id+"]");
    }
    setIntent(intent);
}

I've also tried a lot of combinations of Intent Flags and Launch Modes in the Manifest but for the life of me the first time always comes up as
Launch[1]
Receive[1]

and the second time
Launch[2]
Receive[1]

and from then on no matter what value I send the activity launches with the first value, 1 and the onNewIntent never seems to fire.
The complete function that generates the intent
private void loadLists(){
    ExpandableListView expandableList = (ExpandableListView) findViewById(R.id.expandableListViewToDoLists);
    expandableList.setClickable(true);
    adapter = new ActionListsExpandableAdapter(getApplicationContext());
    expandableList.setAdapter(adapter);
    expandableList.setOnChildClickListener(new OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {

            Action a = (Action) parent.getExpandableListAdapter().getChild(groupPosition, childPosition);
            if (startedForResult){
                Intent data = new Intent();
                data.putExtra("Action._ID", a.get_ID());
                data.putExtra("Action.SUBJECT", a.getSUBJECT());
                setResult(RESULT_OK, data);
                finish();
            }else{
                ActionList al = (ActionList) parent.getExpandableListAdapter().getGroup(groupPosition);
                Intent launch = new Intent(ActivityToDoList.this, ActivityToDoEdit.class);
                launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                launch.putExtra("Action._ID", a.get_ID());
                Log.d("ACTIVITYLAUNCHTEST", "Launching activity with intent for Action ID ["+a.get_ID()+"]");
                launch.putExtra("ActionList._ID", al.get_ID());
                launch.putExtra("ActionList.position", childPosition);
                startActivity(launch);
            }

            return false;
        }
    });
}

A: May be this is a good reference for you.
To me it seems like onNewIntent (with FLAG_ACTIVITY_SINGLE_TOP) like onCreate will be called if app is not destroyed. Hope is helpful to you. It works for me in my case.
For further reference  see
Android: get most recent intent


text:
Q: Memory Error for 20-dimensional numpy matrix in python I tried to create a 20-dimensional numpy matrix in python:
C_shape=[]

for NOP_i in range(0,NOP):                   #NOP=15
    C_shape.append(mpar_val_points[NOP_i])   #mpar_val_points =[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3]
C_shape.append (p_val_points)                #p_val_points=4
C_shape.append (wkat_val_points)             #wkat_val_points=4
C_shape.append (T_val_points)                #T_val_points=4
C_shape.append(t_val_points)                 #t_val_points=11
C_shape.append(NOC)                          #NOC=4

C=np.zeros(C_shape)

I received the following error:
MemoryError:
I want to create a matrix filled with zeros and fill it with float values afterwards.
I have already installed the 64 bit Python version. Does anyone know how I can handle this problem? I already thought about creating some txt.files to save parts of the matrix..
Thank you!

A: As far as I see, you are trying to create a 20 dimensional matrix of dimensions 3x3x3...x3x4x4x4x11x4 (spare me from writing the 15 '3's). Which amounts to 40406522112 elements within that matrix.
Assuming that each number only takes 1 byte (which is definitely not the case for floats, but lets use it as simplification) that makes 40406522112 bytes which is around 38 GB. If we consider that each number takes 64 bytes, we get 64 times the RAM mentioned before. I really doubt that your computer has that much RAM memory and so does numpy. That is the reason for numpy raising the error.
As for how to solve it, I can only think to process the matrix in chunks. And iterating a lot of times over that. It is likely to be slow and will require that you have enough space in your disk to write all those txt files for each chunk of the matrix.


text:
Q: Determining coordinates of a SHP file i have a SHP file of a building converted from a DXF file. This SHP file is unprojected and have no specific coordinates (origin 0,0). I find WGS84 coordinates (lat, long) of this building from Google Maps.
My aim is to replace these coordinates to the SHP file on QGIS.
Could you explain the process step by step?
(I read lots of similar questions, about affine transformation. But i don't know the paramaters.)

What i ask is how to make this transformation in QGIS (step by step)?
SHP file coordinates (not projected)
Scale: 1:142.670.713
X1,Y1: 16.70824, 253.74534
X2,Y2: 1.03521,-6.34918
X3,Y3: 244.00248,-7.49189
Target WGS84 coordinates
X1,Y1: 41.047773, 28.896241
X2,Y2: 41.045452, 28.895929
X3,Y3: 41.045436, 28.899039

I need a second vector layer with coordinates.
I have just a SHP file of a building converted from a DXF file. That is not projected. I know where this building is, and can find the WGS84 coordinates from Google Maps. My aim is add WGS84 coordinates to this SHP file and export to replace the building on Google Maps.
My Questions are:
1) I think my SHP file has measurements in meters and unprojected. I have WGS84 lat long coordinates from Google Maps. How can i project this SHP file, for being ready to transformation?
Right Click -> Set Layer CRS -> Choose WGS84 EPSG: 4326.
Is this enough?
2) qgsAffine plugin just need transformation matrix paramaters.
But the answer of @Jochen Schwarze is a bit complex for me. Is there a online calculator? (Just give the source XYs and target XYs and calculate the parameters.)

I think, I have a projection problem before affine transformation.
I have a DXF file of a building from AutoCAD. I saved this DXF file as a SHP file in QGIS. But this SHP file is converted from a plain DXF file and is not referenced/projected, it is drawn from coordinates 0,0 in AutoCAD in meters. And the drawing has meters, WGS84 has decimal degrees.
When I set Layer CRS as WGS84 in QGIS, the coordinates don't change.
How can I project this SHP file as WGS84 in QGIS?

A: Have a look at How to georeference a vector layer with control points?, in particular the answer concerning the Vector Bender plugin for QGIS. Watch the video and try the plugin, report back if you encounter any issues.

A: I think you have to carry out three transformations, wich are all affine transformations: scale, rotate and translate. I suggest reading about affine transformation on wikipedia: https://en.wikipedia.org/wiki/Affine_transformation
If you basically can carry out an affine transformation, then this might help you to determine the correct parameters: http://docs.safe.com/fme/2016.1/html/FME_Desktop_Documentation/FME_Transformers/Transformers/affiner.htm
The mathematically basics are not restricted to this FME-tool, but (without any comercial interest) I'd say, I like the implemetation.
update/add:
So from your 3 pairs of points (x',y',x,y) by considering the definition of affine transformation (eq. (1))
x' = Ax + By + C
y' = Dx + Ey + F

gives you a linear equation system with 6 variables:
x1' = x1 * A + y1 * B + 1 * C + 0 * D + 0 * E + 0 * F
y1' = 0 * A + 0 * B + 0 * C + x1 * D + y1 * E + 1 * F
x2' = x2 * A + y2 * B + 1 * C + 0 * D + 0 * E + 0 * F
y2' = 0 * A + 0 * B + 0 * C + x2 * D + y2 * E + 1 * F
x3' = x3 * A + y3 * B + 1 * C + 0 * D + 0 * E + 0 * F
y3' = 0 * A + 0 * B + 0 * C + x3 * D + y3 * E + 1 * F

replacing the x, y, x' , y' with your coordinates you have the extended coefficient matrix:
41.047773 16.70824 253.74534 1 0 0 0
28.896241 0 0 0 16.70824 253.74534 1
41.045452 1.03521 -6.34918 1 0 0 0
28.895929 0 0 0 1.03521 -6.34918 1
41.045436 244.00248 -7.49189 1 0 0 0
28.899039 0 0 0 244.00248 -7.49189 1

to solve this you need little python (make use of python numpy module):
http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.linalg.solve.html
import numpy

a = [[16.70824, 253.74534, 1, 0, 0, 0],
     [0, 0, 0, 16.70824, 253.74534, 1],
     [1.03521, -6.34918, 1, 0, 0, 0],
     [0, 0, 0, 1.03521, -6.34918, 1],
     [244.00248, -7.49189, 1, 0, 0, 0],
     [0, 0, 0, 244.00248, -7.49189, 1]]

b = [41.047773,28.896241,41.045452,28.895929,41.045436,28.899039]

numpy.linalg.solve(a,b)

testing this on the python console in QGIS should deliver
array([ -2.38763793e-08,   8.92511774e-06,   4.10455087e+01,
     1.28020915e-05,   4.28122961e-07,   2.88959185e+01])

these are the 6 transformation parameters A,B,C,D,E,F in eq. (1), cp. above.
If you try another pair of values x,y,x'y' putting x and y in the eq. (1) should deliver x' and y'.
as a python function:
def affine(x,y,A,B,C,D,E,F):
    xnew = A*x + B*y + C
    ynew = D*x + E*y + F
    return (xnew, ynew)

A: As a first guess, you can create a custom transverse mercator projection on one of you coresponding points. Preferably the one closest to the DXF origin:
 +proj=tmerc +lat_0=41.045452 +lon_0=28.895929 +k=1 +x_0=1.03521 +y_0=-6.34918 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs

lon_0 and lat_0 are the degree coordinates in WGS84, and x_0 and y_0 the meters coordinates from the DXF.
You can add your meter and degree coordinates as delimited text, assigning the custom CRS for the first and EPSG:4326 for the second. Note that QGIS expects longitude-latitude order for degree coordinates.
This will put at least one point (here No. 2) on the right spot. For use of the Vector bender plugin, it is necessary that both layers are shapefiles and have the same CRS. So you can use Save As ... to a new filename and the local UTM zone 35N EPSG:32635 on both layers.
With the Vector bender plugin, you can now connect the "meters" and "degree" points to get the transformation. If your control points get shifted correctly, you can do the same with the whole DXF layer.


text:
Q: Does intellij run maven as a different user? I have configured the enforcer to check for some properties. These are exported as environment variables in my .profile file in my home dir. The build from the console runs fine.
The build from intellij (doubleclicking the goals in the maven menu) fails, as enforcer cannot find the properties...What is going wrong here and how to fix it?
My first guess is that intellij is running maven as a different user but I'm not sure how to verify it or what to do about it.
NOTE: I am not asking for a workaround. One would be to set the properties in maven Runner settings of intellij, a second - to set the properties in /etc/profile. But I would like to avoid them.
EDIT :  I have tried restarting intellij, the X server and the machine - to no effect on the enforcer. printenv in a fresh console shows my variables as expected. Starting intellij from the same console leads to the same build failure.
Thank you.

A: Each program has its own environment.  If you change the environment settings in .profile or the like, it doesn't change the setting for running programs.  When one program runs another program it inherits the settings/environment of its parent. It doesn't load the settings again.
What you could be finding is that changes you make after IntelliJ has started, have no effect from programs IntelliJ runs.  The same thing would happen if you opened a command window, changed the settings and run a new programs (the shell would keep the settings it had when it started) To fix this you need to re-start IntelliJ.  If you run it from the command line, make sure its a new window.

This unit test should dump the environment.
@Test
public void dumpEnv() {
    for (Map.Entry<String, String> entry : new TreeMap<String, String>(System.getenv()).entrySet()) {
        System.out.println(entry);
    }
}

A: .profile is only executed when you log on using KSH. If you use BASH, it has no effect.
.bashrc (if you use BASH) is a much more suitable place because it's executed every time you start a shell (shell scripts, new terminal windows, etc).
For KSH, .kshrc has the same effect.
To make sure the variables are there, use set (no options) to list all of them or set|greppattern to search. As soon as they show up in a new terminal window, they should be there from inside your IDE, too.
[EDIT] If set can see them, so can IntelliJ. The only thing left is that IntelliJ could clean the environment when it starts Maven.
To test that, rename mvn to mvn.orig and create a new script mvn with this content:
#!/bin/bash
set > $HOME/mvn_env.log
mvn.orig "$@"

This script dumps the environment as mvn sees it to $HOME/mvn_env.log. If the variables are missing, then IntelliJ cleans the environment.


text:
Q: Get the open graph image for a webpage? (The way facebook embeds a thumbnail image when you share its link) On my webpage I want to share a link - let's say to this wikipedia page for Superhero
In the code for that page there is the following code in the head tag:
<meta property="og:image" content="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Connecticut_ComiCONN_Superhero_Mascot..jpg/640px-Connecticut_ComiCONN_Superhero_Mascot..jpg">

This is the thumbnail for that page that is shown if you share the link on social media. (Most pages now have one).
Is there a way to retrieve that image url to embed on my normal webpage page?
I'm using CSS, HTML and Javascript.

A: You can use https://www.opengraph.io/, for example:

*

*Make request to https://opengraph.io/api/1.1/site/https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FSuperhero?app_id=f6ef4e6b-4162-40d7-8404-b80736d4bd55 (https://opengraph.io/api/1.1/site/${url_encoded_link}?app_id=${your_api_key}

*Get image URL from the JSON response, which looks like this:

{
   //...
   "openGraph":{
      "title":"Superhero - Wikipedia",
      "type":"website",
      "image":{
         "url":"https://upload.wikimedia.org/wikipedia/commons/d/d6/Connecticut_ComiCONN_Superhero_Mascot..jpg",
         "width":"1200",
         "height":"1005"
      }
   },
   //...
}

Note, that the free tier only allows 100 requests per month. And I'm not affiliated with it.
Alternatively, you can use something like open-graph-scraper - never tried, but looks promising, will require running NodeJS server as far as I understand.
This one parse-open-graph can work in browser, if I understand correctly.


text:
Q: Store xml into xml attribute How can I store a xml document into xml attribute? I have this code but de output give me escape characters, is right left with these escape characters?
public static void main(String[] args) throws TransformerException,
    ParserConfigurationException  {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.newDocument();
        Element organizations = doc.createElement("ORGANIZATIONS");
        doc.appendChild(organizations);
        organizations.setAttribute("xml", "<root><first>01</first><second>02</second></root>");
        DOMSource domSource = new DOMSource(doc);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
        StreamResult sr = new StreamResult(new File("test.xml"));

        transformer.transform(domSource, sr);

    }

output:
<ORGANIZATIONS xml="<root><first>01</first><second>02</second></root>"/>

A: This is correct. The xml should be escaped when set on an attribute.
If you want to see the plain xml, you have to put it on an element and force the usage of CDATA sections for it:
transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "thequalifiednameoftheelement");

CDATA sections cannot be used on attributes... Attributes are not made for being filled with xml documents...


text:
Q: how can i have imageView.animationImages combined with UISwipeGestureRecognizer I have a viewController displaying images and text and the images are loaded and being animated every 15 seconds, I'd like to allow the user to swipe on the image view allowing him to change the image without waiting for the time to pass.
this is what I tried the images are loaded and animated but the swipe gesture doesn't work
self.imageView.animationImages = [self loadImages];
self.imageView.animationDuration = 15;
[self.imageView startAnimating];

swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction:)];
[swipeRight setDirection:(UISwipeGestureRecognizerDirectionRight)];
[self.imageView addGestureRecognizer:swipeRight];

this code is placed in the viewDidLoad method, I saw a solution adding the gesture to the view but I need it only on the imageView

A: I'm answering this in case someone else spends too much time on this one it appears i forgot to enable user interaction add this line:
self.imageView.userInteractionEnabled = YES;


text:
Q: Updating table with DISTINCT function from another table I've created a new table with a few columns, all of which start out as NULL.
I have another table called "items" with a column called "item_type".  This column contains a lot of duplicates.  I want to take the values generated by DISTINCT(item_type) and use them to fill one of the new empty columns in my new table.  I tried this, but I can't get it to work:
UPDATE new_table
SET new_column = DISTINCT(items.item_type)
FROM items

Do I need to generate a new table and then join the two?

A: Better populate the table in such a way:
INSERT INTO new_table(new_column)
SELECT DISTINCT(items.item_type)
FROM items

or
if table is already populated - you need to provide some behavior connecting these tables

A: Assuming the new table is empty:
INSERT new_table
SELECT DISTINCT item_type
FROM items


text:
Q: Migrating whisper database from one graphite to another graphite How can we migrate  whisper database files from one graphite to another graphite node using whisper merge.

A: You can use carbonate or Bucky tools .


text:
Q: No se ha podido cargar el recurso: el servidor ha respondido con el estado 500 () Tengo un proyecto funcionando desde hace varios meses, durante todo este tiempo funcionó perfectamente, pero desde hace un par de días comenzó a arrojarme el famoso error 500 cuando quiero hacer uso de los formularios que implemento en el sitio, intenté volver a versiones anteriores del sitio que tenía respaldadas pero aunque volví a subir versiones anteriores al hosting el error persiste, el error aparece después del paréntesis en la línea
fetch(action, { Tal como se ve en la captura.

Adjunto el codigo:
<code>

function php_email_form_submit(thisForm, action, formData) {
    fetch(action, {
      method: 'POST',
      body: formData,
      headers: {'X-Requested-With': 'XMLHttpRequest'}
    })
    .then(response => {
      if( response.ok ) {
        return response.text()
      } else {
        throw new Error(`${response.status} ${response.statusText} ${response.url}`);
      }
    })
    .then(data => {
      thisForm.querySelector('.loading').classList.remove('d-block');
      if (data.trim() == 'OK') {
        thisForm.querySelector('.sent-message').classList.add('d-block');
        thisForm.reset();
      } else {
        throw new Error(data ? data : 'Form submission failed and no error message returned from: ' + action);
      }
    })
    .catch((error) => {
      displayError(thisForm, error);
    });
  }

</code>


text:
Q: LocalDB em visual Basic não conecta Minha aplicação não conecta ao localDB. Já atualizei o SDT, mudei a connectionstring no App.config mas nada funciona. A parte do código em que estabeleço a conexão é essa:
  Dim conexao As String = "Server = (LocalDB)\MSSQLLocalDB; Database = EquipamentosDB ;IntegratedSecurity=yes; Uid=auth_windows;"

  Dim reader As MySqlDataReader

  conn = New MySqlConnection
  conn.ConnectionString = conexao

    Try
        conn.Open()

    Catch myerro As MySqlException
        MsgBox("Erro de leitura no Banco de dados:" & myerro.Message)

    End Try

Segui o método de configuração do localDB deste link: https://msdn.microsoft.com/pt-br/library/ms233763(v=vs.110).aspx


text:
Q: Generated subview is always behind image view viewController.m
-(void) viewDidLoad
{
    [super viewDidLoad];

    [self addScoreRowViewWithIndexLeft:(++i) andName:[scoreDict objectForKey:@"name"] andScore:[[scoreDict objectForKey:@"points"] integerValue]];
}

-(void) addScoreRowViewWithIndexLeft:(NSInteger)index andName: (NSString *)name andScore: (NSInteger)score {

    UIView *scoreRowView   = [[UIView alloc] initWithFrame:CGRectMake(128, 112 + index * 80, 280, 20)];

    UILabel *indexLabel    = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 20, 20)];

    UILabel *nameLabel     = [[UILabel alloc] initWithFrame:CGRectMake(150, 20, 180, 20)];

    UILabel *scoreLabel    = [[UILabel alloc] initWithFrame:CGRectMake(330, 20, 50, 20)];

    UIColor *color = [UIColor darkGrayColor];

    [indexLabel setText:[@((int)index) stringValue]];
    [indexLabel setFont:[UIFont fontWithName:@"DINAlternate-Bold" size:18]];
    [indexLabel setTextColor:color];

    [nameLabel setText:name];
    [nameLabel setFont:[UIFont fontWithName:@"DINAlternate-Bold" size:18]];
    [nameLabel setTextColor:color];

    [scoreLabel setText:[@((int)score) stringValue]];
    [scoreLabel setFont:[UIFont fontWithName:@"DINAlternate-Bold" size:18]];
    [scoreLabel setTextColor:color];

    [scoreRowView addSubview:indexLabel];
    [scoreRowView addSubview:nameLabel];
    [scoreRowView addSubview:scoreLabel];

    [self.view addSubview:scoreRowView];
}

I added my ImageView in my Storyboard as a subview of my View.
When I delete the ImageView, everything is ok. I get displayed my other code generated subviews. But when I add the ImageView in my Storyboard, it's on top of my other subviews. If I give my ImageView an alpha of 0.3 I can see my subviews shining through.
What's wrong with my code? I also tried;
[self.view bringSubviewToFront:scoreRowView];

but it doesn't work.
What can I do?

A: Try to change zPosition of your ImageView and scoreRowView. You can do this this way:

*

*Connect your ImageView with your ViewController

*In bottom of ViewDidLoad add something like that:
yourImageView.layer.zPosition = 1;
scoreRowView.layer.zPosition = 2;

I'm suspecting that [self.view bringSubviewToFront:scoreRowView]; doesn't work because you invoke it in ViewDidLoad where view in not fully work. You can try to invoke it in e.g. ViewDidAppear and check if that will work.


text:
Q: How do I resolve a Pickling Error on class apache_beam.internal.clients.dataflow.dataflow_v1b3_messages.TypeValueValuesEnum? A PicklingError is raised when I run my data pipeline remotely: the data pipeline has been written using the Beam SDK for Python and I am running it on top of Google Cloud Dataflow. The pipeline works fine when I run it locally.
The following code generates the PicklingError: this ought to reproduce the problem
import apache_beam as beam
from apache_beam.transforms import pvalue
from apache_beam.io.fileio import _CompressionType
from apache_beam.utils.options import PipelineOptions
from apache_beam.utils.options import GoogleCloudOptions
from apache_beam.utils.options import SetupOptions
from apache_beam.utils.options import StandardOptions

if __name__ == "__main__":
  pipeline_options = PipelineOptions()
  pipeline_options.view_as(StandardOptions).runner = 'BlockingDataflowPipelineRunner'
  pipeline_options.view_as(SetupOptions).save_main_session = True
  google_cloud_options = pipeline_options.view_as(GoogleCloudOptions)
  google_cloud_options.project = "project-name"
  google_cloud_options.job_name = "job-name"
  google_cloud_options.staging_location = 'gs://path/to/bucket/staging'
  google_cloud_options.temp_location = 'gs://path/to/bucket/temp'
  p = beam.Pipeline(options=pipeline_options)
  p.run()

Below is a sample from the beginning and the end of the Traceback:
WARNING: Could not acquire lock C:\Users\ghousains\AppData\Roaming\gcloud\credentials.lock in 0 seconds
WARNING: The credentials file (C:\Users\ghousains\AppData\Roaming\gcloud\credentials) is not writable. Opening in read-only mode. Any refreshed credentials will only be valid for this run.
Traceback (most recent call last):
  File "formatter_debug.py", line 133, in <module>
    p.run()
  File "C:\Miniconda3\envs\beam\lib\site-packages\apache_beam\pipeline.py", line 159, in run
    return self.runner.run(self)
    ....
    ....
    ....
  File "C:\Miniconda3\envs\beam\lib\sitepackages\apache_beam\runners\dataflow_runner.py", line 172, in run
    self.dataflow_client.create_job(self.job))
  StockPickler.save_global(pickler, obj)
  File "C:\Miniconda3\envs\beam\lib\pickle.py", line 754, in save_global (obj, module, name))
  pickle.PicklingError: Can't pickle <class 'apache_beam.internal.clients.dataflow.dataflow_v1b3_messages.TypeValueValuesEnum'>: it's not found as apache_beam.internal.clients.dataflow.dataflow_v1b3_messages.TypeValueValuesEnum

A: I've found that your error gets raised when a Pipeline object is included in the context that gets pickled and sent to the cloud:
pickle.PicklingError: Can't pickle <class 'apache_beam.internal.clients.dataflow.dataflow_v1b3_messages.TypeValueValuesEnum'>: it's not found as apache_beam.internal.clients.dataflow.dataflow_v1b3_messages.TypeValueValuesEnum

Naturally, you might ask:

*

*What's making the Pipeline object unpickleable when it's sent to the cloud, since normally it's pickleable?

*If this were really the problem, then wouldn't I get this error all the time - isn't a Pipeline object normally included in the context sent to the cloud?

*If the Pipeline object isn't normally included in the context sent to the cloud, then why is a Pipeline object being included in my case?

(1)
When you call p.run() on a Pipeline with cloud=True, one of the first things that happens is that p.runner.job=apiclient.Job(pipeline.options) is set in apache_beam.runners.dataflow_runner.DataflowPipelineRunner.run.
Without this attribute set, the Pipeline is pickleable. But once this is set, the Pipeline is no longer pickleable, since  p.runner.job.proto._Message__tags[17] is a TypeValueValuesEnum, which is defined as a nested class in apache_beam.internal.clients.dataflow.dataflow_v1b3_messages. AFAIK nested classes cannot be pickled (even by dill - see How can I pickle a nested class in python?).
(2)-(3)
Counterintuitively, a Pipeline object is normally not included in the context sent to the cloud. When you call p.run() on a Pipeline with cloud=True, only the following objects are pickled (and note that the pickling happens after p.runner.job gets set):

*

*If save_main_session=True, then all global objects in the module designated __main__ are pickled. (__main__ is the script that you ran from the command line).

*Each transform defined in the pipeline is individually pickled

In your case, you encountered #1, which is why your solution worked. I actually encountered #2 where I defined a beam.Map lambda function as a method of a composite PTransform. (When composite transforms are applied, the pipeline gets added as an attribute of the transform...) My solution was to define those lambda functions in the module instead.
A longer-term solution would be for us to fix this in the Apache Beam project. TBD!

A: This should be fixed in the google-dataflow 0.4.4 sdk release with https://github.com/apache/incubator-beam/pull/1485

A: I resolved this problem by encapsulating the body of the main within a run() method and invoking run().


text:
Q: How to get Fields of the current class? I am trying to get the fields of the current class. I make the class implement the ICloneable Interface.
Inside the clone() the following line doesn't seem to find any fields. Why though?
foreach (FieldInfo fi in this.GetType().GetFields())
{
}

Many Thanks,

A: That will only find public fields. Look at BindingFlags.
To suggest a better way, just call MemberwiseClone, it will copy all the fields values in the current class/instance.

A: Because only public fields are returned by default.  Use the other overload with BindingFlags.NonPublic.

A: GetFields returns all the public fields of the current Type. http://msdn.microsoft.com/en-us/library/ch9714z3.aspx You may need http://msdn.microsoft.com/en-us/library/6ztex2dc.aspx

A: Use BindingFlags as:
var flags = BindingFlags.NonPublic|BindingFlags.Instance|BindingFlags.Public;
foreach (FieldInfo fi in this.GetType().GetFields(flags))
{
   //...
}

A: Well the only reason why GetFields would be empty is if "no public fields are defined for the current Type" (from MSDN).
More generally, did you know that there already exists a protected method in the Object class that already does what you're trying to do (a shallow copy)? It's called MemberwiseClone
You could use it like this:
public object Clone()
{
    return MemberWiseClone();
}


text:
Q: string.split - by multiple character delimiter },{ i am having trouble splitting a string in c# with a delimiter of "},{".
For example the string "abc},{rfd},{5},{,},{."
Should yield an array containing:
abc
rfd
5
,
.

But I cannot seem to get it to work, even if I try RegEx I cannot get a split on the delimiter.
EDIT: Essentially I wanted to resolve this issue without the need for a Regular Expression. The solution that I accept is;
string Delimiter = "},{";
var Result[] = StringToSplit.Split(new[] { Delimiter }, StringSplitOptions.None);

I am glad to be able to resolve this split question.

A: You can use a regular expression:
var sample = "abc},{rfd},{5},{,},{.";
var result = Regex.Split(sample, Regex.Escape("},{"));
foreach (var item in result)
    Console.WriteLine(item);

A: Using string array in split function
string strMultiChars = "abc},{rfd},{5},{,},{.";
//split by string array
 string[] splitByMultipleSring = strMultiChars.Split(new string[] { "},{" }, StringSplitOptions.None);
 foreach (string s in splitByMultipleSring)
 {
    Console.WriteLine(s);
  }


text:
Q: Facing Warning: Failed prop type: Invalid prop `source` supplied to `Image`. when running jest testcase in react-native (expo) Below is the code for error:  Warning: Failed prop type: Invalid prop 'source' supplied to 'Image'.
const ParentComponent = () => {
 return (
  <Image source={require('app/assets/image.png')}/>
 );
}

I've defined name config in package.json as app
I'm receiving this error when I'm running a jest test.

A: You need to provide relative path to the photo, something like:
  <Image source={require('../../assets/image.png')}/>

(Depends on the file location)


text: Q: Storing negative int and negative constant int in a byte C# I wanted to know why it's possible to store a negative int into a byte but I get errors when I try to store a negative int that is constant into a byte?


text:
Q: Currency Converter /Defining restart_program I'm currently writing a program about Currency Converter on Python and I'm in the last stage where I need help on a question where I ask "Do you want to convert again" and if the answer starts with "n" then I write a message and the program exits. Whereas the problem is that I want the program to restart if the user wants to convert again". I need to define how to restart the program but i'm not sure how. At the end its a else if the user writes anything else except "y" or "n" Help is much appreciated. So far it looks like this:
def restart_programme
answer=str(input('Do you want to convert again?'))
if answer.lower().startswith("n"):
    print("Thank you for using Currency Converter today,Goodbye "+name)
    exit()
if answer.lower().startswith("y") or ("Y"):
restart_programme()

A: Enclose your entire program in a loop.
answer = 'y'
while answer.lower().startswith("y"):

    #Whatever you want to do

    answer=str(input('Do you want to convert again?'))

if answer.lower().startswith("n"):
    print("Thank you for using Currency Converter today,Goodbye "+name)
else:
    #The anything else part

OR
Enclose your entire program in a function and simply call that function again.
def restart_programme():

    #Whatever you want to do

    answer=str(input('Do you want to convert again?'))
    if answer.lower().startswith("n"):
        print("Thank you for using Currency Converter today,Goodbye "+name)
        exit()
    if answer.lower().startswith("y"):
        restart_programme()

restart_programme()

A: python 2.7
def restart_programme():
    answer = raw_input('Do you want to convert again? [Y/n]\n')
    if answer.lower().startswith('n'):
        print('Thank you for using Currency Converter today, Goodbye ' + name)
        quit()
    elif answer.lower().startswith('y'):
        restart_programme()
        print ('Debug: Program will now restart\n\n')
    else:
        print('You didnt choose a valid option')
        raw_input('Press Enter to Restart\n')
        restart_programme()

A: Really that no one who answered before tested their code? Both there are the same problem. You should read this
def got_milk():
    answer = False
    while not answer:
        milk = raw_input('Got Milk?')
        if not milk in ['N', 'No', 'n', 'no']:
            print 'Thanks'
            answer = True

This could be some version of what you expected to do:
def restart_programme():
    check = True
    while check:
        answer=raw_input('Do you want to convert again?').lower()
        if answer.startswith("n"):
            print("Thank you for using Currency Converter today, Goodbye")
            check = False
            exit()
        if answer.startswith("y") or answer.startswith("Y"):
            print "Let's have some more fun."


text:
Q: android - How to Load PreferenceFragment in Fragment I want a code like the following for loading PreferenceFragment into Fragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    int inx = getArguments().getInt("index", 0);
    View view;

    switch (inx){
        case 0:
            view = inflater.inflate(R.layout.a, container, false);
            break;
        case 1:
            view = inflater.inflate(R.layout.b, container, false);
            break;
        case 2:
            view = MyPreferenceFragment();
            break;
        default:
            view = inflater.inflate(R.layout.a, container, false);
    }

    return view;
}

A: Try adding the following to case 2:
getFragmentManager().beginTransaction().replace(android.R.id.content,new {YourSettingsClass} ()).commit();

and declare the fragment in the activity layout.
Check this out for more info How to Load PreferenceFragment in Fragment


text:
Q: TypeError: unhashable type: 'list' when calling .iloc() I'm currently doing some AI research for a project and for that I have to get used to a framework called "Pytorch". That's fine and all but following the official tutorial (found here) the code doesn't run properly.
The idea is that I analyse a set of facial features from a prepared dataset and then do something with it (haven't gotten to that part yet). But when I run this piece of code:
img_name = os.path.join(self.root_dir, self.landmarks_frame.iloc([index, 0]))  # At this point 'index' is 0

The dataset is initialized like this:
face_dataset = fDataset(csv_file='faces/face_landmarks.csv', root_dir='faces/')

And here is where the error pops up:
for i in range(len(face_dataset)):
    sample = face_dataset[i]  # <-- right there

That leads to the getter function:
def __getitem__(self, index):
    img_name = os.path.join(self.root_dir, self.landmarks_frame.iloc([index, 0]))
    image = io.imread(img_name)
    landmarks = self.landmarks_frame.iloc[index, 1:].as_matrix()
    landmarks = landmarks.astype('float').reshape(-1, 2)
    sample = {'image': image, 'landmarks': landmarks}

Found in my FaceLandmarksDataset(Dataset): class I simply get the error of the title. This is strange I find, because I can read the dataset just fine as a frame in PyCharm:

Where the first picture is clearly visible. I have checked as well that it is in the folder that I'm looking in.
Can anyone help out? :)

A: You don't need the parentheses with iloc:
self.landmarks_frame.iloc[index, 0]


text:
Q: Problem switching back from forced SSL on certain pages using mod_rewrite Client wants login pages to load via https.  This is easily accomplished, but since the site uses pretty url's, we now stay in https mode when clicking around after login is finished.  This breaks secure files which are uploaded in the CMS, stored above webroot, and downloaded by streaming through a php script if user has the appropriate permissions.  So, we need to switch back to regular http when we're no longer on a login page.  Here's what I have in my .htaccess file:
RewriteEngine On
Options +FollowSymLinks

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.domain\.com [NC]
RewriteRule ^(login\.php|members\.php)$ https://%{HTTP_HOST}%{REQUEST_URI}
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^(login\.php|members\.php)$ https://www.%{HTTP_HOST}%{REQUEST_URI}

RewriteCond %{HTTPS} on
RewriteCond %{IS_SUBREQ} false
RewriteRule !^(login\.php|members\.php)$ http://%{HTTP_HOST}%{REQUEST_URI}

Everything is working fine except the last line, which is getting confused by the pretty url's and redirecting to view.php (which handles translating pretty url lookup codes to database id's that are used in the querystring) if I use {REQUEST_URI}, and the homepage if I use $1 or the path.
I need to figure out a way to make this rewrite to switch back to http mode bypass the pretty url rewrite, but I don't know how to get the actual address that was typed in rather than what it was rewritten to by Apache.
Please help and thanks in advance!

A: You could grab the original requested URI path from the request line in THE_REQUEST:
RewriteCond %{HTTPS} on
RewriteCond %{IS_SUBREQ} false
RewriteCond %{THE_REQUEST} ^[A-Z]+\ ([^ ]+)
RewriteRule !^(login|members)\.php$ http://%{HTTP_HOST}%1


text:
Q: Would Window.Open() Command Be Considered A Referral? I'm using a local script in Firefox (file:///filepath/...) to open urls. One part of the script uses the window.open() command. A sample of the code is below:
        if(x[i].indexOf('.') > 0) {
            if(x[i].indexOf('://') < 0) {
                window.open('http://' + x[i++]);
            } else {
                window.open(x[i++]);
            }

For the JavaScript experts, when the script is opening a url. Is there anyway the local file (file:///filepath/...) would be considered a referral?
I don't want it to show up as a referring page in analytics. I just want to confirm that the window.open command only opens windows as if I typed them in. Is that correct?

A: I was able to confirm that the window.open command does not act as a referral. By running a few test runs on a site, I was able to verify through analytics that they are direct visits as if you typed them in.
Hope this helps anyone wondering if window.open will reveal their local path.


text:
Q: Need help on unix time stamp Basically, am creating a mailer system to send a mail to my inactive members to do activities in their account if they have not logged in since 30 days.
My previous login date stores in my database in unixtimestamp hence I coded as below.
  select email from myusers where WHERE DATE_ADD(FROM_UNIXTIME(prelogin), INTERVAL 30 DAY) < CURDATE()";

But this code after 30 days it is sending continuos mails almost everyday as I have set cron to run once a day.

A: Assuming you only want an email sent every 30 days, and only if they haven't logged in for 30 days, I suspect the easiest solution will be to have another column in your table called something like last_email_sent_time.
Then, only send an email if it's been at least 30 days since both prelogin and that new column.
And, when you send the email, update that new column to the current date so you won't bother them for another month or so.

On the other hand, if you just want the email sent once after they haven't logged in for thirty days, it's a similar thing.
Create a new column indicating the email has been sent and only send it if that column is false (or N or whatever you want to use to indicate it). Sending it will set that column to true, logging in will set it to false (as well as changing prelogin).

If you don't want to add extra columns (for some bizarre reason), you could simply update prelogin when you send the email, though that's not something I'm comfortable suggesting since it loses information that may be used (or useful) elsewhere.


text:
Q: single HAproxy to expose multiple kubernetes cluster kube-api service Currently we are using haproxy to expose the kube-api using tcp:bind mode which works fine.
We have requirement to keep single haproxy to handle around 4 different cluster kube-api endpoint, in this scenario tcp:bind won't work. We are planning to use acl to match host string for different cluster to route the corresponding backuend using http mode. when we add ssl and we are getting this below error.
Unable to connect to the server: x509: certificate relies on legacy Common Name field, use SANs or temporarily enable Common Name matching with GODEBUG=x509ignoreCN=0

A: #---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    daemon
    user                haproxy
    group               haproxy
    log                 /dev/log local6 notice
    log                 /dev/log local5 info
    maxconn             50000
    #chroot              /var/lib/haproxy
    pidfile             /var/run/haproxy.pid

#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
    mode                 tcp
    option               tcplog
    log                  global
    option               dontlognull
    timeout connect      5000
    timeout client       50000
    timeout server       50000

#---------------------------------------------------------------------
# dedicated stats page
#---------------------------------------------------------------------
listen stats
    mode http
    bind :22222
    stats enable
    stats uri            /haproxy?stats
    stats realm          Haproxy\ Statistics
    stats auth           <mylogin>:<mypass>
    stats refresh        30s

#---------------------------------------------------------------------
# main frontend which proxys to the backends
#---------------------------------------------------------------------
frontend main_https_listen
    bind <ip address>:443
    mode                tcp
    option              tcplog
    log                 global
    tcp-request inspect-delay 5s
    tcp-request content accept if { req.ssl_hello_type 1 }

#---------------------------------------------------------------------
# Common HAProxy nodes configuration
#---------------------------------------------------------------------

# -------------------------------
# ACLs
# -------------------------------

acl acl_SIT_AT35073      req.ssl_sni -i <app_url1>.my.domain.net  # SIT_AT35073 is just an internal code we use, but you can use any alias
acl acl_SIT_AT34305      req.ssl_sni -i <app_url2>.my.domain.net
acl acl_SIT_AT28548      req.ssl_sni -i <app_urlN>.my.domain.net

# -------------------------------
# Conditions
# -------------------------------

use_backend backend_SIT_AT35073 if acl_SIT_AT35073   # same here
use_backend backend_SIT_AT34305 if acl_SIT_AT34305
use_backend backend_SIT_AT28548 if acl_SIT_AT28548

#---------------------------------------------------------------------
# Backends
#---------------------------------------------------------------------

# APP 1
backend backend_SIT_AT35073
    description APPNAME1
    mode tcp
    balance source
    option ssl-hello-chk
    server server_SIT_AT35073_1 <apache_server1>.my.domain.net:443 check
    server server_SIT_AT35073_2 <apache_server2>.my.domain.net:443 check

# APP 2
backend backend_SIT_AT34305
    description APPNAME2
    mode tcp
    balance source
    option ssl-hello-chk
    server server_SIT_AT34305_1 <apache_server3>.my.domain.net:443 check
    server server_SIT_AT34305_2 <apache_server4>.my.domain.net:443 check

# APP N
backend backend_SIT_AT28548
    description APPNAMEN
    mode tcp
    balance source
    option ssl-hello-chk
    server server_SIT_AT28548_1 <apache_server5>.my.domain.net:443 check
    server server_SIT_AT28548_2 <apache_server6>.my.domain.net:443 check

I have used this solution to expose multiple kube-api but I coudn't able to do it using http mode


text:
Q: Trigger error404.json.twig I'm trying to get my customised json error template to be returned by Symfony but it keeps returning the HTML version instead. Using a rest client I have set Accept and Content-Type to "application/json" but only the contents of my error404.html.twig are returned, not the error404.json.twig file.
At the moment I am testing this via a completely invalid URL (i.e. there is no route), but once I have this working I will also be using it for valid URLs which do not lead to resource and internally the code throws a HttpNotFoundException

A: Setting the headers on your request will not actually have any effect on what error template gets returned, despite seeming like that might be the logical path.  The error template that gets generated is based on the request format, which is either set in the _format parameter or manually on the Request object itself.  There's a solution in this post but if you're getting a 404 error, you couldn't exactly set the _format parameter or $request->setRequestFormat('json') call from a Controller in which no route existed.
Symfony has pretty good documentation how to customize error pages, including the path that you'll likely want to take, which is overriding the default ExceptionController.  Essentially you would override the showAction() or findTemplate() method which would take Accept header and check for application/json.  You could also check the Content-Type header as an additional requirement.  So here would be the declaration of your listener:
# app/config/services.yml
services:
    app.exception_controller:
    class: AppBundle\Controller\CustomExceptionController
    arguments: ['@twig', '%kernel.debug%']

Then setting the Twig parameter:
# app/config/config.yml
twig:
    exception_controller:  app.exception_controller:showAction

Now to define your class and override the relevant parts you need.  This first example overrides the showAction() by checking your Accept header and then modifying the Request format:
namespace AppBundle\Controller;

use Symfony\Bundle\TwigBundle\Controller\ExceptionController;

class CustomExceptionController extends ExceptionController
{
    /*
     * {@inheritDoc}
     */
    public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null)
    {
        if (in_array('application/json', $request->getAcceptableContentTypes())) {
            $request->setRequestFormat('json');
        }

        parent::showAction($request, $exception, $logger);
    }
}

Symfony says that the findTemplate() method is the one that locates the template to be used, so you could put the code there instead.  Here's an example of overriding that function, with additional checking ofthe Content-Type header in case you require both conditions to be met:
namespace AppBundle\Controller;

use Symfony\Bundle\TwigBundle\Controller\ExceptionController;

class CustomExceptionController extends ExceptionController
{
    /*
     * {@inheritDoc}
     */
    protected function findTemplate(Request $request, $format, $code, $showException)
    {
        if (in_array('application/json', $request->getAcceptableContentTypes()) &&
            0 === strpos($request->headers->get('Content-Type'), 'application/json')
        ) {
            $format = 'json';
        }

        parent::findTemplate($request, $format, $code, $showException);
    }
}

Of course you can also create an exception listener yourself by working with the kernel.exception event for even further control.
If you use the FOSRestBundle it tries to determine the request format for you via a listener using the Request Accept header and the format priority configuration.  If you use this bundle you might be able to avoid custom coding and just rely on that.


text:
Q: How to prevent a subclass from inheriting a field from the superclass using Hibernate? I have a class A which has a List of a class B. Since the attributes of a A is similar to what a B has, I thought about using inheritance to solve my problem. But I don't want B to have a list to B, and here is my problem. How can I prevent B from inheriting the List of B from the super-class?
The super-class:
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Data
@SuperBuilder
@Inheritance(strategy = InheritanceType.JOINED)
public class A
{
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    protected Integer id;

    @OneToMany(mappedBy = "a")
    private List<B> list = new ArrayList<>();

    // other fields that I want to be inherited...
}

The subclass:
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@SuperBuilder
public class B extends A
{
    @JsonIgnore
    @ManyToOne
    @JoinColumn
    private A a;
}

The JSON returned after creating the class A:
{
               "id": 1,
               // other fields

               "list": [
                   {
                       "id": 2,
                       // inherited fields

                       "list": [], // I want to prevent this!
                   }
               ],
}

And one last thing, the reason why I want to use inheritance in this case instead of creating a B class with its own fields it's because I am using a composite key for solving another problem, and both classes share this composite key.

A: You can either create a dto for class B to specify what you want to show or you can @jsonignore List in class A if you don't need to send A as a JSON


text:
Q: XMLReader not reading in all elements requested So I have this XML
<entry>
<id>ABC123</id>
<title type="text">title </title>
<author xmlns="http://www.w3.org/2005/Atom">
    <name>test.com</name>
</author>
<link rel="self" href="http://www.test.com/asdasd.html"/>
<updated>2012-07-04T06:12:15.337</updated>
<content type="xml">
    <listing systemId="thesystemid" url="www.myurl.com">
        <description>
            This is a description
        </description>
    </listing>
</content>
</entry>

I'm using XMLReader with this code and I'm pulling in the data using this:
$url = $product->content->listing['url'];
$id = $product->id;
$name = $product->title;
$desc = $product->content->listing->description;

Everything is being pulled in perfectly apart from $desc
$product has been set as 'entry'
I just cannot see why, any ideas?
Error is
Notice: Trying to get property of non-object in......

Cheers

A: check this
$aa= '<entry>
     <id>ABC123</id>
     <title type="text">title </title>
     <author xmlns="http://www.w3.org/2005/Atom">
     <name>test.com</name>
     </author>
     <link rel="self" href="http://www.test.com/asdasd.html"/>
     <updated>2012-07-04T06:12:15.337</updated>
     <content type="xml">
     <listing systemId="thesystemid" url="www.myurl.com">
     <description>
        This is a description
     </description>
     </listing>
     </content>
     </entry>';
  $xml = simplexml_load_string($aa);
  echo $xml->content->listing->description;

This will work. Enjoy.


text:
Q: Dynamically expand div upon hiding another I am new to posting on this site, so please excuse any errors I may make.
So as my question states, I'm essentially looking for a way to dynamically expand divs. So far I have a container div with three columns inside it. Each of the columns have a link to some javascript that sets it to disply:none. What I'm looking for a way to do is, for example, if I was to click the hide button in the center column, I want the two outer columns to expand to take up the space left behind. Perhaps a way to increase the width of the two from 33% each to 50% upon hiding the middle one.
So that the two other divs essentially share the newly created space between them.
Here is my html and css as it is just now:
HTML:

test

            Hide

test

            Hide

test

            Hide

CSS:
 #container #col2outer {
 height:200px;
 width: 870px;
 float: left;
 margin: 0;
 padding: 0;
 }

 #container #col1 {
 height:200px;
 width: 33%;
 float: left;
 border-width: 0.5mm; border-style: groove;
 -moz-border-radius: 15px;
 border-radius: 15px;
 }

 #col2outer #col2mid {
 height:200px;
 width: 33%;
 float: left;
 border-width: 0.5mm; border-style: groove;
 -moz-border-radius: 15px;
 border-radius: 15px;
 }

 #col2outer #col2side {
 height:200px;
 width: 33%;
 float: left;
 border-width: 0.5mm; border-style: groove;
 -moz-border-radius: 15px;
 border-radius: 15px;
 }

Thank you in advance for any help, and apologies if this question has already been asked

A: Hy!
You can try something like:
Click on hide button:
$(document).ready(function(){
  $('button').click(function(){
    $('#col1').css("display","none");
    $('#col2mid').css("width","49%");
    $('#col2side').css("width","49%");
  })
});

This is very simple way for resizing divs...
if you want to click on coloumn and then hide/show and resize you will need to rename your columns, or your code will be long...
EDIT:
Something like this:
http://jsfiddle.net/pbnkH/


text:
Q: sbt update is not resolving the latest artifacts from repository My project has few snapshot dependencies in the build.sbt file like this:
Seq("com.asr.project.myproject.urproject" %% "asr-app" % "0.0.0+")

I am executing sbt update to get the latest dependencies.
Prior to this, I have recently published artifacts with latest SNAPSHOT versions for few dependencies.
By the definition sbt update should have checked for the latest dependencies versions on the repository but it doesn't seem to be working like that.

A: sbt uses coursier plugin to manage the dependency tree and the coursier plugin maintains the lifetime of the artifacts in the cache.
When a dependency is downloaded, it is not going to be checked for any updates for next 24 hours(Default).
This behavior can be altered by setting COURSIER_TTL as an environment variable (e.g export COURSIER_TTL=0s). Running sbt update alone will not have any effect without it. https://get-coursier.io/docs/ttl

A: Probably what you need is:
libraryDependencies ++= Seq(
    "com.asr.project.myproject.urproject" %% "asr-app" % "0.0.+"
)

as described in Ivy revisions, or at Fixed and dynamic revisions with more details.


text:
Q: Query with WHERE / sub query containing multiple records This is my query:
SELECT * FROM img_ref WHERE id_img = (SELECT `id_img` FROM img_ref WHERE `id_user`=4)

I'm trying to SELECT records from img_ref WHERE id_img = id_img attached to a specific id_user.
However, the subquery contains multiple rows/results and therefore throws the error "Subquery returns more than one row". How could I modify this statement so that the "WHERE id_img=" part and subquery allow multiple rows?
Thanks for your help in advance.

A: When using a subquery with equals, the subquery can only return a single record.  Normally you would just use IN to return multiple records:
SELECT *
FROM img_ref
WHERE id_img IN (SELECT `id_img` FROM img_ref WHERE `id_user`=4)

For performance reasons (check this post), you may want to move this to a JOIN:
SELECT i.*
FROM img_ref i
    JOIN img_ref i2 ON i.id_img = i2.id_img
        AND i2.id_user=4

*

*SQL Fiddle Demo


text:
Q: Update URL from Input control in Angular when searched for oxy in search textbox  url is:
http://api.abc.com/GetGPs?search=oxy&uid=688-B65-462-F9-7A
and suppose I want to search for cor then url should change the moment I click on search button for cor. It should be like
http://api.abc.com/GetGPs?search=cor&uid=688-B65-462-F9-7A. The json file has same fields so display function in angular will work same as url will change and values too but not the type, name and the no. of fields
code is
  var countryApp = angular.module('countryApp', []);
  countryApp.controller('CountryCtrl', function ($scope, $http){
    $http.get('http://api.abc.com/GetGPs?**search=oxy**&uid=688-B65-462-F9-7A
').success(function(data) {
      console.log(data);
      $scope.dta = data.emp;
    });
     $scope.reset = function () {
    $scope.enteredValue = '';
};
  });

//this is search texbox code
 <input type="text" ng-model="enteredValue" />
<button ng-click="reset()">Clear</button>

// this is filter that I am using
   <tr ng-repeat="x in dta | filter:enteredValue">

1) user input oxy .click search. url initially in http get http://api.abc.com/GetGPs?search=oxy&uid=688-B65-462-F9-7A
. search result displayed in angular
2) User Input cor.click search. URL should be updated itself to
http://api.abc.com/GetGPs?search=cor&uid=688-B65-462-F9-7A
3) display searched result in angular

A: //.js
 countryApp.controller('CountryCtrl', function($scope, $http) {
  $scope.enteredValue = "*";
  $scope.targetUrl = 'url';
  $scope.reset = function() {
    $scope.enteredValue = '';
  };
  $scope.doIt = function() {
    $scope.targetUrl = 'http://api.abc.com/GetGPs?search=' + $scope.enteredValue + '&uid=688-B65-462-F9-7A';
    $http.get( $scope.targetUrl )
      .success(function(data) {
        console.log(data);
        $scope.dta = data.emp;
      });
  };
});

//html
  <input type="text" ng-model="enteredValue" />
  <button ng-click="doIt()">Submit</button>
  <button ng-click="reset()">Clear</button>

https://plnkr.co/edit/6FJMnsA0rW54BLi6u5r7?p=preview plunker.... answer to the above problem by Matthew and its correct


text:
Q: Get value using python selenium How am I able to extract the value "document sent" from the following html code using python library selenium
see code i tried which returns None
print driver.find_element_by_id('errorMessage').get_attribute("value")

html code:

Document sent.

A: Try this:
driver.find_element_by_id("errorMessage").getText();

OR
driver.find_element_by_id("errorMessage").getAttribute("innerHTML");

Hope this helps..

A: Try to use below code to get required text:
from selenium.webdriver.support.ui import WebDriverWait as wait

text = wait(driver, 10).until(lambda driver: driver.find_element_by_id("errorMessage").text)


text:
Q: Multiple fa-heart like count increment and decrement I need to increment the count of a fa-heart value on click and decrement on the second click.
Problem is I have multiple fa-heart in the same page, so unable to increment/decrement on the clicked fa-heart.
Here is my fiddle below
https://jsfiddle.net/mehbub/d9e2qotg/1/

(function() {
  const heart = document.getElementById('heart');
  heart.addEventListener('click', function() {
    heart.classList.toggle('red');
  });
})();

$(document).on('click', ".notliked", function() {
    var $this = $(this);
    $this.removeClass('notliked');
    $this.addClass('liked')
    $count = $('.likes-count');
    $count.text(function(idx, txt) {
    return (+txt == 0) ? 0 : (+txt - 1);
    heart.classList.toggle('grey');

    });

});

$(document).on('click', ".liked", function() {
    var $this = $(this);
    $this.removeClass('liked');
    $this.addClass('notliked');
    $count = $('.likes-count');
    $count.text(function(idx, txt) {
            return +txt + 1;
    heart.classList.toggle('red');

    });

});
$count.text(function(idx, txt) {
   // convert text to number and increment by one
   return +txt + 1;
});
#heart {
  color: grey;
  font-size: 20px;
}

#heart.red {
  color: red;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

robert stephen

 100

James Camroon

 101

John Wick

 37

James Bond

 22

Avengers

 90

I need individual click increment/decrement for each fa-heart to color change to red if increment, or grey if the decrement
Thanks

A: You should remove the duplicate id heart or just remove it since you've already a class heart then attach the click to this common class and toggle the classes liked/notliked, you could use those classes as a rules in your CSS so no need for red/grey classes, something like :

$(document).on('click', ".heart", function() {
  var count = $(this).next('span');

  $(this).toggleClass('notliked liked');

  if ($(this).hasClass('liked')) {
    count.text(Number(count.text()) + 1);
  } else {
    count.text(Number(count.text()) - 1);
  }
});
.heart.notliked {
  color: grey;
  font-size: 20px;
}

.heart.liked {
  color: red;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

robert stephen

 100

James Camroon

 101

John Wick

 37

James Bond

 22

Avengers

 90


text:
Q: Xcode 4 Adding a Sub Project I am looking at somebody else's project and they have another project embedded under 'Other Sources'.  When I click on the project it shows me the build settings etc, and I can expand all the source underneath.
I want to do the same thing, but when I drag an xcodeproj file into my project I don't get the build settings or any of the source shown like in this other project.  How do I do this?

A: Sorry to revamp the old question, but I just got the absolute answer for this problem.... maybe this can help the other....
To add Sub-Project to current project, It just simply drag the .xcodeproj from finder to xcode, place it in your project...
BUT... there is something must be done before doing this.... JUST OPEN ONE XCODE INSTANCE.... So, close the other instance when dragging .xcodeproj to xcode....
If you drag it while opening few xcode instance (opening few project at once), the .xcodeproj that you dragged can't be expanded and not just what you want...
hope this can help the other....
Regards

A: Just be sure that your added project is not open in another Xcode window.
BTW this is still valid with Xcode 7.2 beta.

A: When you drag the new project to the source list in Xcode, make sure you drop it on top of the project header (the thing that you click to get to the build settings and targets).