Q:

How can I implement trust only one specific certificate (my own) using code, in ServerCertificateValidationCallback

Context
The client code have to connect to a remote web api. SSL is mandatory because of sensitive information exchanged on the wire. We have our self issued certificate a
In the project there is no currently what is properly configured in the remote IIS, and everything tested OK, except the certificate is not trusted.
I know I can install the certificate on the local machine and trust in it. However for some reasons (for example, there are Xamarin Android clients too) it is not a suitable solutions.
Current workaround is to simply ignore the certificate error in code, which is working both on desktop both on Android Xamarin:
ServicePointManager.ServerCertificateValidationCallback =
(s, certificate, chain, sslPolicyErrors) =>
{
    // Here I would like to check against that the certificate
    // is the specific one I issued, and only that case return with true

    // if (what is the most suitable to write here?)
    return true;
};

Question
Note: this is development/testing phase. In production there will be a certificate installed created by a trusted certificate authority.
Now I have bad feeling about accepting anything, so I would like to narrow it.
How to check against that the certificate is the specific one I issued, and only that case return with true.
Is that a working idea to run the code, place a breakpoint, and get the certificate.Thumbprint, then write an if to check against it?
(edit)
...or better... get the PublicKeyString and checking against it?

A:

Checking against thumbprint is IMHO an OK option. With thumbprint you can narrow the trust to exactly one certificate.
Checking against public key or Subject Key Identifier is also OK but you will expand the trust to the same key pair. There can be several certificates issued on the same public key (with or without the same Distinguished Name).
As @bartonjs stated another option is to check raw data. This approach has the same power as checking against thumbprint. The benefit of this would IMO be that when you look at the code a year from now you will still know what certificate you trust :)
Anyway when checking against the exact certificate keep in mind that the certificate will expire someday (i.e. let's encrypt issues a 3 month certificate if I remember correctly) and your application will have to be redeployed with a new certificate check. You would have to keep track of expiration date of the certificate.


Q:

Interface with non-copyable features

I am trying to implement a logging factory and I have used an interface so that I can swap loggers whenever I like.
Here is the interface
class ILogger
{
public:

    //Only allow string input. The entire ARC is going to be non-unicode.
    virtual void log(std::string message, eLogLevel level=DEBUG) = 0;

protected:
    virtual ~ILogger(void){};

private:
    // No one can create an ILogger as it is abstract but should also
    // disallow copying... why copy a logger? Only one per file. Besides want to
    // force people to use the factory.
    /*ILogger(const ILogger&);
    ILogger& operator=(const ILogger&);*/ // REMOVED THIS BECAUSE OF ERROR

};

And here is a derived class (header)
class GenericLoggerImpl :
    public ILogger
{
public:
    virtual ~GenericLoggerImpl(void);
    virtual void log(std::string message, eLogLevel level=DEBUG);

private:
    GenericLoggerImpl(void); //USE THE FACTORY
    std::tr1::shared_ptr<GenericLogger> pImpl; //This is the implementation
    friend class LoggerFactory; // class LoggerFactory can now build these
};

And CPP
GenericLoggerImpl::GenericLoggerImpl(void):pImpl()
{
    pImpl = std::tr1::shared_ptr<GenericLogger> (new GenericLogger()); //This is the implementation
}

GenericLoggerImpl::~GenericLoggerImpl(void)
{
}

void GenericLoggerImpl::log(std::string message, eLogLevel level)
{
    pImpl->logMsg(message.c_str(),level);
}

Now here is the problem. See in the ILogger interface, I have commented out a private section of code? Well that is intended to stop anyone copying an ILogger derived class (like boost::noncopyable does). This makes sense (to me anyway) as it disallows separate instances of loggers from accessing the same file, and make the user go through my handy LoggerFactory.
When these lines are included then I get the following error:

genericloggerimpl.cpp(6) : error C2512: 'ILogger' : no appropriate default constructor available

What is that about? I do not want these objects to be copyable. How can I do that?

A:

The existence of any user-defined constructor (which includes a copy-constructor) will prevent the compiler from generating a default-constructor. Your subclass GenericLogger relies on the existence of a default-constructor for ILogger (it is implicitly called, since it is not specified otherwise in the initialization-list of the constructor of GenericLogger), hence the error.
To fix the problem, simple declare a protected trivial default constructor for ILogger:
ILogger() {}


Q:

error in vba excel textbox when cancelled

Sub search()

Columns("J:K").Select
Selection.EntireColumn.Hidden = False

ActiveSheet.PivotTables("PivotTable15").PivotSelect "device[All]", xlLabelOnly _
    + xlFirstRow, True

Cells.Find(What:=InputBox("Please enter the PartID", "Search"), _
After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False).Activate

ActiveCell.Offset(0, 1).Select
Selection.ShowDetail = True

Selection.Copy
Sheets("interface").Select
Range("L501").Select
ActiveSheet.Paste

Columns("J:K").Select
Selection.EntireColumn.Hidden = True
Range("A2").Select

 End Sub

I have this code on my sub button but there is an error when i cancel the input box that shows.. the error is: "Unable to set the ShowDetail property of the Range class".the error highlighted is:
 Selection.ShowDetail = True

A:

The error comes because it doesn't find anything. You can trap the error in many ways, one of which would be:
Sub search()
dim sPartID as string
Columns("J:K").Hidden = False

ActiveSheet.PivotTables("PivotTable15").PivotSelect "device[All]", xlLabelOnly _
    + xlFirstRow, True

sPartID=InputBox("Please enter the PartID", "Search")
if len(sPartID)=0 then exit sub

Cells.Find(What:=sPartID, _
After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False).Activate

ActiveCell.Offset(0, 1).ShowDetail = True

Selection.Copy Sheets("interface").Range("L501")

Columns("J:K").EntireColumn.Hidden = True
Range("A2").Select

End Sub


Q:

Google Admin SDK: Directory Users: How to get User phone numbers using Java client?

I successfully authenticate using a Service Account and can list the users in my company's Google Directory.
However I want to list Users' telephone numbers.
I used the java quickstart example code and it works. However it is only printing the User's primary email address.
I wanted to use the User.getPhones() method to get the list/array of phone numbers for each user but the Java API returns "Object" see the Google java API
I know that the real result of the Google request is JSON and a User has an Array of Phones which have a "type" and a "value" eg work: num (Admin SDK User Representation)
I know that the google Java client is using a Google specific Jackson2 implementation,
com.google.api.client.json.jackson2.JacksonFactory

How can I influence it to produce UserPhone objects and not just java.lang.Object?
Cheers
Karl

A:

I have come up with the following method that translate the generic List of ArrayMaps of <String,Object> objects in the Admin SDK.
It requires the following imports:
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.ArrayMap;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

Here's the method that does the parsing:
public <T extends GenericJson> List<T> parse(Object genericItem, Class<T> clazz){
     List<T> result = new ArrayList<T>();
     if (genericItem != null){
         try {
             Constructor<T> constructor = clazz.getConstructor(new Class[0]);    // find the default constructor of the input class type
             List<ArrayMap<String,Object>> objects = (List<ArrayMap<String,Object>>)genericItem;
             for (ArrayMap<String,Object> object: objects){
                T id = constructor.newInstance(); // call the default constructor
                for (int i = 0; i < object.size(); i++)
                    id.put(object.getKey(i), object.getValue(i));
                result.add(id);
            }
        } catch (NoSuchMethodException ex) {
               Logger.getLogger(ListArrayMapParser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            Logger.getLogger(ListArrayMapParser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(ListArrayMapParser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(ListArrayMapParser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalArgumentException ex) {
            Logger.getLogger(ListArrayMapParser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvocationTargetException ex) {
            Logger.getLogger(ListArrayMapParser.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return result;
}

This works like this:
List<UserPhone> phones = parser.parse(user.getPhones(), UserPhone.class);
List<UserExternalId> externalIds = parser.parse(user.getExternalIds(),    UserExternalId.class);
List<UserOrganization> organizations = parser.parse(user.getOrganizations(), UserOrganization.class);
List<UserEmail> userEmails = parser.parse(user.getEmails(), UserEmail.class);

Once you've done this you can update the phones, externalIds,... and then do user.setPhones(phones) and the User object will handle the new objects fine when saving.
I don't think you can have the API return the parsed result automatically for you today.


Q:

Install Shield LE - Error 6058 ... merging Visual C++ 10.0 CRT in 64bit

I'm trying to compile an install shield project. It's a 64 bit program.
I keep getting this error, although it does compile OK and installs OK:
Error   16  -6058: Error merging Visual C++ 10.0 CRT (IA64) with module ID C:\Program Files (x86)\Common Files\Merge Modules\Microsoft_VC100_CRT_ia64.msm   ISEXP : error : -6058: Error merging Visual C++ 10.0 CRT (IA64) with module ID C:\Program Files (x86)\Common Files\Merge Modules\Microsoft_VC100_CRT_ia64.msm

Any idea how can tell it NOT to try and merge ? (I can let it install the CRT ad a redistributable instead)

A:

Ok, so it's like this:
Was detected as a dependency by mistake:

Adding merge module 'Visual C++ 10.0
  CRT (IA64)' that is a dependency of
  component
  'MyProjectName.Primary_output'

So you go to:
Specify application Data -> Files
Right click on the specified project that had the dependency.
Choose Dependencies from scan at build.. find that unwanted file, and uncheck it.


Q:

How is the number of views limited?

I want to figure out the main effectivity issues of the Android layouts and views. I'm doing a research now but maybe somebody has answers already.
I have a RelativeLayout that is populated with views dynamically. Basically, the application loads a forum thread in XML and then renders the discussion tree so each message is displayed in its own group of views. I've decided not to use WebView because I want to implement some client-side functions that should be easier to do on custom views than on HTML page.
However this approach has a major flaw: it's heavy.
The first problem (which I've solved) was nesting of views. This is not an issue now, my layout is almost flat so the maximum depth is 10-12 (counting from the very top PhoneWindow$DecorView, the actual depth depends on data).
Now I've reached the next limit that is somehow connected to (or caused by) resource consumption of the views. After loading the data, the application hangs for a while to build the layout (creates the views and populates them with the data), and the hang time seems to grow linear with the data size; and if the data is large enough, the view will never appear (eventually the system suggests closing the application because it isn't responding).
Now the questions:

Does memory consumption depend significantly on the view class? In other words, is there any major difference between a Button and a TextView, or an ImageView? I can attach a click handler to any view so they don't differ much in usage.
Do background images affect the performance? If the same image is set in N views, will it make the layout N times heavier? (I understand that this question may look silly but anyway.)
Are nine-patch images significantly heavier than regular ones? What is better: to create N views where each has some background images, or to make one view that is N times wider and has a repeating background?
Given some layouts, what should be optimized first: overall number of views, nesting levels, or something else?
The most interesting. Is that possible to measure or at least estimate the resources consumed by the activity and its views? If I make some change, how could I see that I'm going the right way?

UPDATE
Thanks to User117, some questions that I asked above are now answered. I've used the Hierarchy Viewer and optimized my layout: compared to what I had before, the overall number of views is now reduced almost twice, and the nesting is also reduced.
However the application still hangs on a large forum thread.
UPDATE 2
I've connected the debugger to my device and found that the application gets out of memory.
But what is very unexpected for me is that the error occurs after I populate the layout. The sequence is as follows:

All my views are added. I can see a slight slow down as they are being added.
Almost nothing happens for a couple of seconds. During that time, a few info messages are spawned in the log, they are identical: [global] Loaded time zone names for en_US in XXXXms, the only difference is number of milliseconds.
The out of memory error message is spawned: [dalvikvm-heap] Out of memory on a N-byte allocation (the actual size varies). The long error reporting starts.

What does this mean? Looks like the rendering have its own demands that may be considerable.
UPDATE 3
At last I've found the core issue. Here is a screenshot from my application, see an explanation below the image.

Each message consists of a round button that shows or hides the replies and a red content frame to the right of the button. This is very simple and requires only 6 views including the layouts.
The problem is the indentation with these connection lines that show which message is related to which.
In my current implementation, the indentation is built of small ImageView's, each containing a square image that shows either empty space, or a vertical line, or a T-like connector, or a L-like corner. All these views are aligned to each other within the large RelativeLayout that holds the whole discussion tree.
This works fine for small and medium trees (up to few hundreds of messages), but when I try to load a large tree (2K+ messages), I get the result explained in UPDATE 2 above.
Obviously, I have two problems here. I spawn large number of views that all consume memory, and these views are ImageView's that require more memory for rendering because they render a bitmap and therefore create graphics caches (according to explanation given by User117 in the comments).
I tried disabling loading the images into the indentation views but got no effect. It seems like adding that huge number of views is quite enough to eat all available memory.
My other idea was to create an indentation image for each message that would contain all pipes and corners, so each message would have the only indentation view instead of 10 or 20. But this is even more consuming: I've got out of memory in the middle of populating the layout. (I cached the images in a map so two bitmaps with identical sequence of images weren't created, that didn't help.)
So I'm coming to conclusion that I'm in a dead end.  Is it ever possible to draw all these lines at once?

A:

Different View's are different kinds of  Object. Some only draw() light weight stuff, some can hold large Bitmap Objects, and handler Objects and so on. So, yes different View's will consume different amount of RAM.
If same Bitmap object is shared among views, There's only one Object in RAM, each View will have a reference variable pointing to that object. But, not so when View draws: Drawing same Bitmap n times at n places on screen will consume n times CPU and generate n different bitmap_cache for each View.
Each side of a 9-patch image is actually bigger by 2 pixels from the original image. They are not much different as a file. When they are drawn, both can be scaled and will take almost equal space. The only difference is that 9-Patch are scaled differently.

Setting the background of the larger, parent view is better when the child views are transparent, and background will show through.
You can save a small image and set a tiled background so that it can fill a large area.

Nesting is to be optimized first, because all of the views might not be visible at a given time, let's say only a few views are visible in scrolling layout. Then you can cut down on total number of views used. Take cues from ListView: Given that user will be only seeing a sub set of total data at a time, it re-cycles the views. and saves a lot of resources.
SDK provides Hierarchy Viewer tool for this purpose. It shows a full tree structure of a running Layout, also places red flags for the sluggish parts of the layout.

A good layout is that which:

Easy to be measured (avoid complex weighted widths, heights and alignments). For
example instead of doing layout_gravity="left" for each each child, parent can have gravity="left".
Has less depth, each overlapping view adds another layer to be composited while screen is drawn. Each nested View Structure, asks for a chained layout call.
Is smart and re-cycles Views rather than create all of them.
Reuses its parts: tags like <merge> and <include>.

Update:
Answers to this question, show many approaches for a tree view in android.


Q:

set value of new field depending on other field

i want setting value of new field depending on other field .to consider i want remove like_count after setting like_status's value.
First Try:
my model.py:
class Post(Model):
       title = models.CharField( max_length=100)
       like_count =  models.IntegerField(default=0)

and now i want adding new field to Post's model that shown me is post liked yet or not:
class Post(Model):
       title = models.CharField( max_length=100)
       like_count =  models.IntegerField(default=0)
       like_status = models.BooleanField(default=False if str(F('like_count')) == 0 else True)

after running migration ,all value of like_status is True while exist some Post's object with like_count=0

second try:
adding like_status with False default value:
class Post(Model):
       title = models.CharField( max_length=100)
       like_count =  models.IntegerField(default=0)
       like_status = models.BooleanField(default=False)

then trying updating like_status field :
Post.objects.all().update(like_status=True if F('like_count')>0 else False)

the error:
'>' not supported between instances of 'F' and 'int'

and trying :
Post.objects.all().update(like_status=True if int(F('like_count'))>0 else False)

error:
int() argument must be a string, a bytes-like object or a number, not 'F'

i can achieve my goal by running script but i want know the way of doing this process without scripting.thank you for your time

A:

You can use Model methods to set the value of like_status:
class Post(models.Model):
    title = models.CharField( max_length=100)
    like_count =  models.IntegerField(default=0)

    @property
    def like_status(self):
        if self.like_count == 0:
           return False
        else :
           return True


Q:

flex.l:17:8: error: invalid type argument of ‘->’ (have ‘YYSTYPE’ {aka ‘int’}) "int" {yylval->fn = 11; return TYPE; }

I'm tring to create a compiler in flex and bison, but when i try to compile my code I'm getting this type of error
how can i resolve this problem??
flex.l:17:8: error: invalid type argument of ‘->’ (have ‘YYSTYPE’ {aka ‘int’}) "int" {yylval->fn = 11; return TYPE; }

this is flex file
%option header-file="flex.lex.h"
%{
  #include "bison.tab.h"
  #include "dichiarazioni.h"
 %}
 %%
 "global_variables" { return VAR; }
 "events"   { return EVENT; }
 "commands"             { return COMMAND; }
 "state"                    { return STATE; }
 "actions"              { return ACTION; }
 "char" {yylval->fn = 10; return TYPE; }
 "int"  {yylval->fn = 11; return TYPE; }
 "float"    { yylval->fn = 12; return TYPE; }
 "double" { yylval->fn = 13; return TYPE; }
 "void" { yylval->fn = 14; return TYPE; }
 "inc"                  { yylval->fn = 24; return OPERATORE; }
 "dec"                  { yylval->fn = 25; return OPERATORE; }
 "set"                  { yylval->fn = 26; return OPERATORE; }
 print_schermo_message  { yylval->fn = 40; return PRINT; }
 [0-9]+                     { return NUMBER; }
 ([a-z]+[_a-z0-9]*)     { return ALPHA; }
 "+"                        { yylval->fn = 20; return OPERATORE; }
 "-"                        { yylval->fn = 21; return OPERATORE; }
 "*"                        { yylval->fn = 22; return OPERATORE; }
 "/"                     { yylval->fn = 23; return OPERATORE; }
 ">"            { yylval->fn = 1; return CMP; }
 "<"            { yylval->fn = 2; return CMP; }
 "!="           { yylval->fn = 3; return CMP; }
 "=="           { yylval->fn = 4; return CMP; }
 ">="           { yylval->fn = 5; return CMP; }
 "<="           { yylval->fn = 6; return CMP; }
 "&&"           { yylval->fn = 7; return CMP; }
 "||"           { yylval->fn = 8; return CMP; }
%%

A:

The type of the semantic value (yylval) is normally defined in tbe grammar file using a %union declaration. Since you don't show your grammar file, it's impossible to be more precise about what's wrong but the fact that the compiler believes that yylval is an int suggests that you have not provided any declaration. (int is the default type.)
In any case, unless you have requested a reentrant parser, yylval will normally be a union (or scalar) and not a pointer.
Please see the bison manual for more details on how you declare and use semantic values.


Q:

setTimeout inside iteration of iteration

I have the code below and i would like to put a setTimeout between each iteration of Myurl. There are a number of classes and each of them contains a number of elements.
//Some calculations before...
var i = 0;
async.whilst(
function () {
    return i <= thefooz.length - 1;
},
function (innerCallback) {

    //Some calculations where I get classes array.

    async.forEachOfSeries(classes, function (Myurl, m, eachDone) {
        // Here I want a delay
        async.waterfall([
            function (next) {
                connection.query(
                    'SELECT * FROM mydata WHERE UrlLink=? LIMIT 1', [Myurl],
                    next
                );
            },
            function (results, fields, next) {
                if (results.length !== 0) {
                    console.log("Already Present");
                    return next();
                }
                console.log("New Thing!");
                request(options2, function (err, resp, body) {
                    if (!err && resp.statusCode == 200) {
                        var $ = cheerio.load(body);
                        //Some calculations, where I get AllLinks.
                        var post = {
                            ThisUrl: AllLinks[0],
                            Time: AllLinks[1],
                        };
                        var query = connection.query('Insert INTO mydata Set ?', post, next);
                    };
                });
            }
        ], eachDone);

    }, function (err) {
        if (err) throw err;
    });
    setTimeout(function () {
        i++;
        innerCallback();
        console.log("Done");
    }, 20000);

    //Some calculations after...

So how could I set a delay between each Myurl in async.waterfall? Say I want a 5 seconds delay. I managed to set setTimeout between
each async.whilstiteration but not between each async.forEachOfSeries iteration. It simply does not wait, instead it continues to loop until each async.forEachOfSeries is done and then calls the async.whilst setTimeout.
EDIT:
Queue solution does not work. That solution seems to just go to next page, and next page and so on, without outputting to my database. Of course I could apply it in the wrong way, but I really tried to do exactly as the example said.

A:

First we must implement a simple queue
Queue
function Queue() {
  var obj = {};
  var queue = [];
  var _delay;

  function next() {
    // If queue is empty stops execution
    if(queue.length == 0) return;

    // Prepare next call to next
    setTimeout(next, _delay);
    // Take out an element from the queue and execute it.
    (queue.shift())();
  }

  // Add a new function to the queue
  obj.add = function (myFunc) {
    queue.push(myFunc);
  };

  // Start the queue execution passing the delay between each call
  obj.run = function(delay) {
    _delay = delay;

    // call next function
    next();
  }

  return obj;

}

Then we use it inside the code
// create the queue
var myQueue = Queue();

async.forEachOfSeries(classes, function (Myurl, m, eachDone) {
  // Add the function to the queue
  myQueue.add(executeWaterfall.bind(this));
}, function (err) {
  if (err) throw err;
});

// Start the queue with 5 second delay
myQueue.run(5000);

function executeWaterfall() {
  async.waterfall([
    function (next) {
      connection.query(
        'SELECT * FROM mydata WHERE UrlLink=? LIMIT 1', [Myurl],
        next
      );
    },
    function (results, fields, next) {
      if (results.length !== 0) {
        console.log("Already Present");
        return next();
      }
      console.log("New Thing!");
      request(options2, function (err, resp, body) {
        if (!err && resp.statusCode == 200) {
          var $ = cheerio.load(body);
          //Some calculations, where I get AllLinks.
          var post = {
            ThisUrl: AllLinks[0],
            Time: AllLinks[1],
          };
          var query = connection.query('Insert INTO mydata Set ?', post, next);
        };
      });
    }
  ], eachDone);
}

This is far from optimal because anyway you are falling in what is called the Pyramid of doom
Bonus
Pyramid of doom
When handling asynchronous operations in succession with normal callbacks, you'll end up nesting calls within each other; with this nesting comes more indentation, creating a pyramid (pointing to the right), hence the name "Pyramid of Doom".
Solution
In this case is better to use some promise pattern to save your code from the pyramid of doom and facilitate the solution of this kind of issues.

More Info
PromiseJS

A:

I think you don't fully understand how setTimeout works:
(function () {
    var seconds=0;
[1,2,3].forEach(function(value) {
    setTimeout(function() {
        console.log('Showing value '+value+ 'at '+Date());
    },1000*seconds++);
})
})()

This code, for each element, creates a callback function to be executed after a second. Please note that JS is single threaded, so what the code really does is adding "executions" to a queue. So if the current execution does not stop, the callbacks are not called. So the time (in millis) that you pass to the setTimeout function as second parameter is just the minimum time to have that code executed.
Then, the execution of those callbacks is made in FIFO order.
UPDATE: Here is an example of what I'm explaining:
function myFunction() {
    var test=0;
    setTimeout(function(){
        console.log("This is the current value of test: "+test);
    }, 0);
    console.log("This is run first");
    for (var i=0;i<50;i++) {
        test++;
    }
    console.log("Main thread ending, not the callbacks will be executed");
}

The setTimeout will wait 0 (zero) before executing, but as the main thread has not finished, it cannot be executed. Then, when the loop ends, the callback is executed, finding that test is 50, not 0.


Q:

How to set my regex to return in only one line?

My input information can be: "abc1-abc-ab-0/1/2" OR "abc1-abc-0/1/2". I need a help to get my return variable in one line. In my regex code, I'm gettint two lines of maches. Can anyone help me?
[root@server]# echo "abc1-abc-ab-0/3/7" | grep -oP '^(([a-zA-Z0-1]){4})-(([a-zA-Z]){3})|-(([a-zA-Z]){2})'
abc1-abc
-ab

A:

Two ways to collect output of a command on one line:
echo $( command )

command | xargs echo


Q:

Casting error with a native SQL query JPA Eclipse Link

I'm working with JPA implemented with EclipseLink. I need to do a native SQL query about my MRAEmpleado entity.
This is my code:
    private List<MRAProyecto> ordenarProyectos (){
      Query q = em.createNativeQuery("Select *From MRAProyecto ORDER BY PROY_ID");
       return (List<MRAProyecto>)q.getResultList();
    }
        List<MRAProyecto> consultaProyectos = startup.ordenarProyectos();
        System.out.println("Lista de proyectos ordenados por su identificador");
         for (MRAProyecto proyecto:(List<MRAProyecto>)consultaProyectos){

             System.out.println(proyecto.toString());
        }

but This error is launched when I execute my application:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to entity.MRAProyecto
at Startup.main(Startup.java:39)

I have tried with all casting posibilities, but the cast error doesn't dissapear.

A:

Use the following call to do the parse.
Query     createNativeQuery(java.lang.String sqlString, java.lang.Class resultClass)
          Create an instance of Query for executing a native SQL query.
http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#createNativeQuery%28java.lang.String,%20java.lang.Class%29
You need to define in resultSetClass the entitiy you want to retrieve


Q:

Why are the icon classes not getting changed when using event listeners to detect changes?

I was trying to do my own take of this: https://codepen.io/codifiedconcepts/pen/bwgxRq
I've made a few tweaks, but when I change the time in the drop-downs, the icons don't change as intended. I've tested it by manually changing the time and the icons changed, and I've tested the event listeners by adding an alert box - everything is fine.
But when I go to change on the drop-down themselves, the icons don't change. I just can't seem to get it to work.

  let wakeTime = 7;
    let noon = 12;
    let lunch = 12;
    let evening = 17;
    let dinner = 18;
    let bed = 21;

    //Setting time up
    let showCurrentTime = () => {
        const clock = document.getElementById('clock');
        let currentTime = new Date();
        let hours = currentTime.getHours();
        let minutes = currentTime.getMinutes();
        let seconds = currentTime.getSeconds();
        let meridian = "AM";

             if (hours >= noon)
          {
              meridian = "PM";
          }

          if (hours > noon)
          {
              hours = hours - 12;
          }

        // Set Minutes
        if (minutes < 10)
        {
            minutes = "0" + minutes;
        }

        // Set Seconds
        if (seconds < 10)
        {
            seconds = "0" + seconds;
        }
            //Putting it all together
            let clockTime = `${hours}:${minutes}:${seconds}  ${meridian}!`;
            clock.innerText = clockTime;
    };

    //Getting the clock to update on its own so it changes pictures and messages
    let updateClock = () => {
        let time = new Date().getHours();
        let message = document.getElementById('message');
        let icon = document.getElementById('food-icon');

        if(time === wakeTime){
            icon.classList.remove('fa-smile');
            icon.classList.add('fa-clock');
            message.textContent = 'Wakey wakey!';
        } else if (time === lunch){
            icon.classList.remove('fa-smile');
            icon.classList.add('fa-hotdog');
            message.textContent = "I'm hungry."
        } else if (time === dinner ) {
            icon.classList.remove('fa-smile');
            icon.classList.add('fa-utensils');
            message.textContent = "Can I have more food?";
        } else if (time === bed){
            icon.classList.remove('fa-smile');
            icon.classList.add('fa-bed');
            message.textContent = "YAWN";
        } else if (time >= noon ) {
            icon.classList.add('fa-smile');
            message.textContent = "Good afternoon!"
        } else if (time < noon) {
            icon.classList.add('fa-smile');
            message.innerHtml = "Good morning!";
        } else if (time >= evening) {
            icon.classList.add('fa-smile');
            message.textContent = "Good evening!";
        }
        showCurrentTime();
    };
    updateClock();

    //Getting the clock to increment once a second
    const oneSecond = 1000;
    setInterval(updateClock, oneSecond);

    const wakeSelect = document.querySelector('#wakeSelect')
    wakeSelect.addEventListener('change', function() {
        wakeTime = wakeSelect.value;
    });

    const lunchSelect = document.querySelector('#lunchSelect')
    lunchSelect.addEventListener('change', () => {
        lunch = lunchSelect.value;
    });

    const dinnerSelect = document.querySelector('#dinnerSelect')
    dinnerSelect.addEventListener('change', () => {
        dinner = dinnerSelect.value;
    });
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Vanilla JS Clock</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">

What time is it!?

        Clock goes here

Hello!

        Choose wake up time:
        <select id="wakeSelect">
            <option value="1">1 AM</option>
            <option value="2">2 AM</option>
            <option value="3">3 AM - 4AM</option>
            <option value="4">4 AM - 5AM</option>
            <option value="5">5 AM - 6AM</option>
            <option value="6">6 AM - 7AM</option>
            <option value="7">7 AM - 8AM</option>
            <option value="8" selected>8 AM - 9AM</option>
            <option value="9">9 AM - 10AM</option>
            <option value="10">10 AM - 11AM</option>
            <option value="11">11 AM - 12PM</option>
            <option value="12">12 PM - 1PM</option>
            <option value="13">1 PM - 2PM</option>
            <option value="14">2 PM - 3PM</option>
            <option value="15">3 PM - 4PM</option>
            <option value="16">4 PM - 5PM</option>
            <option value="17">5 PM - 6PM</option>
            <option value="18">6 PM - 7PM</option>
            <option value="19">7 PM - 8PM</option>
            <option value="20">8 PM - 9PM</option>
            <option value="21">9 PM - 10PM</option>
            <option value="22">10 PM - 11PM</option>
            <option value="23">11 PM - 12AM</option>
            <option value="24">12 AM - 1AM</option>
          </select>

         Choose lunch time
            <select id="lunchSelect">
              <option value="1">1 AM - 2AM</option>
              <option value="2">2 AM - 3AM</option>
              <option value="3">3 AM - 4AM</option>
              <option value="4">4 AM - 5AM</option>
              <option value="5">5 AM - 6AM</option>
              <option value="6">6 AM - 7AM</option>
              <option value="7">7 AM - 8AM</option>
              <option value="8">8 AM - 9AM</option>
              <option value="9">9 AM - 10AM</option>
              <option value="10">10 AM - 11AM</option>
              <option value="11">11 AM - 12PM</option>
              <option value="12" selected>12 PM - 1PM</option>
              <option value="13">1 PM - 2PM</option>
              <option value="14">2 PM - 3PM</option>
              <option value="15">3 PM - 4PM</option>
              <option value="16">4 PM - 5PM</option>
              <option value="17">5 PM - 6PM</option>
              <option value="18">6 PM - 7PM</option>
              <option value="19">7 PM - 8PM</option>
              <option value="20">8 PM - 9PM</option>
              <option value="21">9 PM - 10PM</option>
              <option value="22">10 PM - 11PM</option>
              <option value="23">11 PM - 12AM</option>
              <option value="24">12 AM - 1AM</option>
            </select>

            Choose dinner time
            <select id="dinnerSelect">
              <option value="1">1 AM - 2AM</option>
              <option value="2">2 AM - 3AM</option>
              <option value="3">3 AM - 4AM</option>
              <option value="4">4 AM - 5AM</option>
              <option value="5">5 AM - 6AM</option>
              <option value="6">6 AM - 7AM</option>
              <option value="7">7 AM - 8AM</option>
              <option value="8">8 AM - 9AM</option>
              <option value="9">9 AM - 10AM</option>
              <option value="10">10 AM - 11AM</option>
              <option value="11">11 AM - 12PM</option>
              <option value="12">12 PM - 1PM</option>
              <option value="13">1 PM - 2PM</option>
              <option value="14">2 PM - 3PM</option>
              <option value="15">3 PM - 4PM</option>
              <option value="16">4 PM - 5PM</option>
              <option value="17">5 PM - 6PM</option>
              <option value="18" selected>6 PM – 7PM</option>
              <option value="19">7 PM - 8PM</option>
              <option value="20">8 PM - 9PM</option>
              <option value="21">9 PM - 10PM</option>
              <option value="22">10 PM - 11PM</option>
              <option value="23">11 PM - 12AM</option>
              <option value="24">12 AM - 1AM</option>
            </select>

A:

The problem is that you are trying to compare variables of different types using === which compares the values and the data type. So when you were doing this in updateClock:
if(time === wakeTime)

it was failing even if the values were the same because time is a number and wakeTime is a string. There are 2 ways you can change the code to fix this:

Compare the values only and not the types using == : if(time == wakeTime)

Or change the string to a number using the Number or parseInt functions, e.g. if(time === Number(wakeTime))

I've changed this below in your updateClock function, you can see it working here! I've also fixed the incorrect icon classes not being removed (see the update below):

let wakeTime = 7;
    let noon = 12;
    let lunch = 12;
    let evening = 17;
    let dinner = 18;
    let bed = 21;

    //Setting time up
    let showCurrentTime = () => {
        const clock = document.getElementById('clock');
        let currentTime = new Date();
        let hours = currentTime.getHours();
        let minutes = currentTime.getMinutes();
        let seconds = currentTime.getSeconds();
        let meridian = "AM";

             if (hours >= noon)
          {
              meridian = "PM";
          }

          if (hours > noon)
          {
              hours = hours - 12;
          }

        // Set Minutes
        if (minutes < 10)
        {
            minutes = "0" + minutes;
        }

        // Set Seconds
        if (seconds < 10)
        {
            seconds = "0" + seconds;
        }
            //Putting it all together
            let clockTime = `${hours}:${minutes}:${seconds}  ${meridian}!`;
            clock.innerText = clockTime;
    };

    //Getting the clock to update on its own so it changes pictures and messages
    let updateClock = () => {
        let time = new Date().getHours();
        let message = document.getElementById('message');
        let icon = document.getElementById('food-icon');

        if(time == wakeTime){
            changeIcon(icon, 'fa-clock');
            message.textContent = 'Wakey wakey!';
        } else if (time == lunch){
            changeIcon(icon, 'fa-hotdog');
            message.textContent = "I'm hungry."
        } else if (time == dinner ) {
            changeIcon(icon, 'fa-utensils');
            message.textContent = "Can I have more food?";
        } else if (time == bed){
            changeIcon(icon, 'fa-bed');
            message.textContent = "YAWN";
        } else if (time >= noon ) {
            changeIcon(icon, 'fa-smile');
            message.textContent = "Good afternoon!"
        } else if (time < noon) {
            changeIcon(icon, 'fa-smile');
            message.innerHtml = "Good morning!";
        } else if (time >= evening) {
            changeIcon(icon, 'fa-smile');
            message.textContent = "Good evening!";
        }
        showCurrentTime();
    };
    updateClock();

    //Getting the clock to increment once a second
    const oneSecond = 1000;
    setInterval(updateClock, oneSecond);

    const wakeSelect = document.querySelector('#wakeSelect')
    wakeSelect.addEventListener('change', function() {
        wakeTime = wakeSelect.value;
    });

    const lunchSelect = document.querySelector('#lunchSelect')
    lunchSelect.addEventListener('change', () => {
        lunch = lunchSelect.value;
    });

    const dinnerSelect = document.querySelector('#dinnerSelect')
    dinnerSelect.addEventListener('change', () => {
        dinner = dinnerSelect.value;
    });

function changeIcon(iconElement, newIconClass){
    // remove all existing icon classes
    iconElement.classList.forEach(className => {
        // check for classes starting with "fa-" but are not "fa-5x"
        if (className.startsWith('fa-') && className!=('fa-5x'))
            iconElement.classList.remove(className);
    });
    // now add the new class
    iconElement.classList.add(newIconClass);
}

What time is it!?

        Clock goes here

Hello!

        Choose wake up time:
        <select id="wakeSelect">
            <option value="1">1 AM</option>
            <option value="2">2 AM</option>
            <option value="3">3 AM - 4AM</option>
            <option value="4">4 AM - 5AM</option>
            <option value="5">5 AM - 6AM</option>
            <option value="6">6 AM - 7AM</option>
            <option value="7">7 AM - 8AM</option>
            <option value="8" selected>8 AM - 9AM</option>
            <option value="9">9 AM - 10AM</option>
            <option value="10">10 AM - 11AM</option>
            <option value="11">11 AM - 12PM</option>
            <option value="12">12 PM - 1PM</option>
            <option value="13">1 PM - 2PM</option>
            <option value="14">2 PM - 3PM</option>
            <option value="15">3 PM - 4PM</option>
            <option value="16">4 PM - 5PM</option>
            <option value="17">5 PM - 6PM</option>
            <option value="18">6 PM - 7PM</option>
            <option value="19">7 PM - 8PM</option>
            <option value="20">8 PM - 9PM</option>
            <option value="21">9 PM - 10PM</option>
            <option value="22">10 PM - 11PM</option>
            <option value="23">11 PM - 12AM</option>
            <option value="24">12 AM - 1AM</option>
          </select>

         Choose lunch time
            <select id="lunchSelect">
              <option value="1">1 AM - 2AM</option>
              <option value="2">2 AM - 3AM</option>
              <option value="3">3 AM - 4AM</option>
              <option value="4">4 AM - 5AM</option>
              <option value="5">5 AM - 6AM</option>
              <option value="6">6 AM - 7AM</option>
              <option value="7">7 AM - 8AM</option>
              <option value="8">8 AM - 9AM</option>
              <option value="9">9 AM - 10AM</option>
              <option value="10">10 AM - 11AM</option>
              <option value="11">11 AM - 12PM</option>
              <option value="12" selected>12 PM - 1PM</option>
              <option value="13">1 PM - 2PM</option>
              <option value="14">2 PM - 3PM</option>
              <option value="15">3 PM - 4PM</option>
              <option value="16">4 PM - 5PM</option>
              <option value="17">5 PM - 6PM</option>
              <option value="18">6 PM - 7PM</option>
              <option value="19">7 PM - 8PM</option>
              <option value="20">8 PM - 9PM</option>
              <option value="21">9 PM - 10PM</option>
              <option value="22">10 PM - 11PM</option>
              <option value="23">11 PM - 12AM</option>
              <option value="24">12 AM - 1AM</option>
            </select>

            Choose dinner time
            <select id="dinnerSelect">
              <option value="1">1 AM - 2AM</option>
              <option value="2">2 AM - 3AM</option>
              <option value="3">3 AM - 4AM</option>
              <option value="4">4 AM - 5AM</option>
              <option value="5">5 AM - 6AM</option>
              <option value="6">6 AM - 7AM</option>
              <option value="7">7 AM - 8AM</option>
              <option value="8">8 AM - 9AM</option>
              <option value="9">9 AM - 10AM</option>
              <option value="10">10 AM - 11AM</option>
              <option value="11">11 AM - 12PM</option>
              <option value="12">12 PM - 1PM</option>
              <option value="13">1 PM - 2PM</option>
              <option value="14">2 PM - 3PM</option>
              <option value="15">3 PM - 4PM</option>
              <option value="16">4 PM - 5PM</option>
              <option value="17">5 PM - 6PM</option>
              <option value="18" selected>6 PM – 7PM</option>
              <option value="19">7 PM - 8PM</option>
              <option value="20">8 PM - 9PM</option>
              <option value="21">9 PM - 10PM</option>
              <option value="22">10 PM - 11PM</option>
              <option value="23">11 PM - 12AM</option>
              <option value="24">12 AM - 1AM</option>
            </select>

Note: you have other problems with your logic removing your icons. For example you are only removing the fa-smile class from if (time==wakeTime) so if you changed lunch time for example, then the icon would be something else and you are not removing it. You can change it so that it removes all existing classes instead of specific ones.
UPDATE - remove all existing fa- icon classes:
The most flexible way to do this is probably to remove any icon classes starting with fa-, so you don't have to keep a list.
The following function looks for all classes starting with fa- except fa-5x (because you need that for the size), and removes them. You can also pass in the new icon class:
function changeIcon(iconElement, newIconClass){
    // remove all existing icon classes
    iconElement.classList.forEach(className => {
        // check for classes starting with "fa-" but are not "fa-5x"
        if (className.startsWith('fa-') && className!=('fa-5x'))
            iconElement.classList.remove(className);
    });
    // now add the new class
    iconElement.classList.add(newIconClass);
}

To use it, you just need to do the following!
if(time == wakeTime){
    changeIcon(icon, 'fa-clock');
    message.textContent = 'Wakey wakey!';
}
// etc


Q:

Python Skip/Delete Non-Decodable Characters

I'm currently converting some customer-entered strings as part of a json. I've already made a dict out of the strings, and now am just doing:
json.dumps(some_dict)

Problem is, for some of the customer entered data, it seems they've somehow entered garbled stuff and trying to dump to json breaks the whole thing:
{'FIRST_NAME': 'sdffg\xed', 'LAST_NAME': 'sdfsadf'}

Which then gets me:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 6: ordinal not in range(128)

I have no control over where the data comes from, so I can't prevent this upfront. So, now that this bad data already exists, I was thinking of just replacing unknown/bad characters with some placeholder character, or deleting them. How can I do this?

A:

{'FIRST_NAME': 'sdffg\xed', 'LAST_NAME': 'sdfsadf'}

is a Python dictionary whose keys and values are byte strings. That cannot be represented in JSON because JSON don't have any concept of bytes. JSON string values are always Unicode, so to faithfully reproduce a Python dict, you have to make sure all the textual keys and values are unicode (u'...') strings.
Python will let you get away with 'FIRST_NAME' because it is limited to plain ASCII; most popular byte encodings are ASCII supersets, so Python can reasonably safely implicitly decode the string as ASCII. But that is not the case for strings with bytes outside the range 0x00-0x7F, such as 'sdffg\xed'. You should .decode the byte str to a unicode string before putting it in the dictionary. (Really you should try to ensure that your textual data is kept in Unicode strings for all of your application processing, converting to byte strings only when input is loaded from a non-Unicode source and when output has to go to a non-Unicode destination. So you shouldn't have ended up with byte content in a dictionary at this point. Check where that input is coming from - you probably should be doing the decode() step further up.)
You can decode to Unicode and skip or replace non-ASCII characters by using:
>>> 'sdffg\xed'.decode('ascii', 'ignore')
u'sdffg'
>>> 'sdffg\xed'.decode('ascii', 'replace')
u'sdffg\uFFFD' # U+FFFD = �. Unicode string, json.dump can serialise OK

but it seems a shame to throw away potentially useful data. If you can guess the encoding that was used to create the byte string you can keep the subset of non-ASCII characters that are recoverable. If the byte 0xED represents the character U+00ED i-acute (í), then .decode('iso-8859-1') or possibly .decode('cp1252') may be the encoding you are looking for.


Q:

Bug script para deletar todo o banco SQL SERVER

Eu tenho o script abaixo para dropar TUDO do banco de dados, mas em um dos banco que eu tenho o processamento que precisa deste script acontece um bug, por algum motivo ele não consegue rodar na primeira vez que eu executo, mas na segunda roda sem nenhum impedimento. Segue script
DECLARE @ALT_TAB varchar(250)
DECLARE @COMANDO varchar(8000)

/***********  DROP CONSTRAINTS  ********************/
SET  @COMANDO = ''
DECLARE vendor_cursor CURSOR FOR
  SELECT ('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME+ '] DROP CONSTRAINT [' + CONSTRAINT_NAME + '];') as ALT
  FROM information_schema.table_constraints
  WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'

OPEN vendor_cursor
FETCH NEXT FROM vendor_cursor INTO @ALT_TAB

WHILE @@FETCH_STATUS = 0
 BEGIN
  IF ISNULL(@ALT_TAB, '') <> ''
  SET @COMANDO = @COMANDO + ISNULL(@ALT_TAB, '') + CHAR(13)

  FETCH NEXT FROM vendor_cursor INTO @ALT_TAB
 END

CLOSE vendor_cursor;
DEALLOCATE vendor_cursor;

EXEC(@COMANDO)
/**********************************************************/

/***********  DROP TABLES  **********************/
SET  @COMANDO = ''
DECLARE tables_cursor CURSOR FOR
 SELECT 'DROP TABLE ' + TABLE_NAME + ';'
 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME <> 'sysdiagrams'
 ORDER BY TABLE_NAME

OPEN tables_cursor
FETCH NEXT FROM tables_cursor INTO @ALT_TAB

WHILE @@FETCH_STATUS = 0
 BEGIN
  IF ISNULL(@ALT_TAB, '') <> ''
  SET @COMANDO = @COMANDO + ISNULL(@ALT_TAB, '') + CHAR(13)

  FETCH NEXT FROM tables_cursor INTO @ALT_TAB
 END

CLOSE tables_cursor;
DEALLOCATE tables_cursor;

EXEC(@COMANDO)

Os erros apresentados são:
 (Obs.: O NOME_TABELA é sempre o nome de uma tabela diferente)
Mensagem 105, Nível 15, Estado 1, Linha 1
Unclosed quotation mark after the character string 'CT_ENTIDADE_PRINCIPAL'.
Mensagem 102, Nível 15, Estado 1, Linha 1
Incorrect syntax near 'CT_ENTIDADE_PRINCIPAL'.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.

O que poderia estar acarretando nesse erro?
Por que somente neste banco de dados ocorre esse erro?
Por que se eu executar duas vezes o script ele funciona?
Obrigado pela atenção!

A:

A variável @COMANDO era varchar(8000), mas a quantidade de CONSTRAINT fazia o comando estourar esse tamanho, por causa disso a ultima linha ficava cortada. Aí se eu executasse a segunda vez ele terminava de deletar o resto das CT que faltavam e funcionava. Consegui ver isso fazendo um SELECT no @COMANDO.
Se alterar o @COMANDO para varchar(MAX) passa a funcionar independente do tamanho do banco.
@Murilo que deu a ideia de como descobrir o problema.


Q:

Inline function and global variable issue in Javascript

I have some code here : http://bitbucket.org/natim/lo53_tp1/src/tip/part3/camions/medias/js/tracking.js
That I use to draw some information about trucks direction.
The problem come from a function defined in a for loop like this one :
...

for(i = 0; i < nb_trucks; i++)
{
    ...

    contentString = '
'+ trucks[i]['name'] + '
';

    current_window = new google.maps.InfoWindow({
        content: contentString
    });

    infosWindow.push(current_window);

    current_marker = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(trucks[i]['end']['lat'], trucks[i]['end']['lon']),
        draggable: false,
        title: trucks[i]['name']
    });
    markers.push(current_marker);

    google.maps.event.addListener(current_marker, 'click', function() {
        current_window.open(map, current_marker);
    });
}

In this code, you can see the last block
    google.maps.event.addListener(current_marker, 'click', function() {
        current_window.open(map, current_marker);
    });

And my problem is that current_marker in the addListener parameters is different from the one inside the function.
The current_window and the current_marker inside the function is overide at each loop turn.
How can I get it right ?
Thanks

A:

Wrap it in a closure (just this little section, no other changes) so you get the variable you want, like this:
(function(marker) { //a copy is passed, accessible as marker inside this function
  google.maps.event.addListener(marker, 'click', function() {
    current_window.open(map, marker);
  });
})(current_marker); //pass in the current value

This doesn't reference the same variable that's changing every loop, a copy of it is passed into the closure, so each time you run this it gets a copy of what current_marker is that that time passed in.  If you're more curious about this, there are some great answers explaining closures in this question.


Q:

define a regular expression in python

I am trying to use regular expressions in python to say a 4 characters string with 1st character being a digit and 3 other characters being either a digit or a capital letter.
Here's examples of patterns that should match 1CTT, 2IR8, 35TR, 4T1R
I tried many ways, here's the last code I tried :
exp=re.compile("[0-9]{1}([A-Z0-9]{3})")

Thank you for your help !

A:

The expression you've tried last, looks correct and should match the provided test strings. Though you don't have to specify {1} and there is no need for a capturing group (the parenthesis):
>>> import re
>>> text = "text, 1CTT, 2IR8, 35TR, 4T1R, smth else"
>>> pattern = re.compile(r"[0-9][A-Z0-9]{3}")
>>> pattern.findall(text)
['1CTT', '2IR8', '35TR', '4T1R']

You might need to additionally add the word boundary constraint (thanks to @Jon Clements):
>>> text = "text, 1CTT, 2IR8, 35TR, 4T1R, smth else, 35TT35XYZ"
>>> pattern = re.compile(r"\b[0-9][A-Z0-9]{3}\b")
>>> pattern.findall(text)
['1CTT', '2IR8', '35TR', '4T1R']


Q:

MS Access Update with addition

I'm working with MS Access and would like to how to update the data correctly..here is the code i use on my button click event with no luck
OleDbCommand cmd = new OleDbCommand("SELECT * FROM ItemTemp WHERE ITEM='" + txtItemname.Text + "'", GetConnection());
OleDbDataReader reader = cmd.ExecuteReader();

//check if this item exist on the table ItemTemp
if (reader.HasRows == true)
{
    // item exists, do below action
    OleDbCommand cmde = new OleDbCommand("UPDATE ItemTemp SET QUANTITY=QUANTITY + @QUANTITY, PRICE=PRICE + @PRICE WHERE ITEM='" + txtItemname.Text + "'", GetConnection());
    cmde.Parameters.AddWithValue("@QUANTITY", txtItemquantity.Value); //numericupdown control
    cmde.Parameters.AddWithValue("@PRICE", txtItemprice.Text); //textbox control
    cmde.ExecuteNonQuery();
}

data on database BEFORE updating:
ID    |    ITEM    |    QUANTITY    |    PRICE
1     |    ITEM1   |        1       |    400

data on database AFTER updating:
ID    |    ITEM    |    QUANTITY    |    PRICE
1     |    ITEM1   |       11       |    400400

data on database which i want it to be AFTER updating:
ID    |    ITEM    |    QUANTITY    |    PRICE
1     |    ITEM1   |        2       |    800

i do believe my command is correct if not my bad..there's no other than this code on my button click event. any ideas?

A:

First you should be sure that the database fields Quantity and Price are oo numeric type. If they are Text then your query concatenate the string values passed as parameters with the string present  in the database column.
Second, when you pass the parameters with AddWithValue the framework infers the datatype for you looking at the datatype of the passed value. In your case you pass a string and and the database engine sees a string that will be concatenated to the existing value. You need to convert before passing to an appropriate datatype
Finally, use allways parametrized query for every thing you pass to the database engine, especially if the value passed comes from an input textbox.
 OleDbCommand cmd = new OleDbCommand("SELECT * FROM ItemTemp WHERE ITEM=@item", GetConnection());
 cmd.Parameters.AddWithValue("@item", txtItemName.Text);
 OleDbDataReader reader = cmd.ExecuteReader();

 //check if this item exist on the table ItemTemp
 if (reader.HasRows == true)
 {
     OleDbCommand cmde = new OleDbCommand("UPDATE ItemTemp SET QUANTITY=QUANTITY + @QUANTITY," +
     "PRICE=PRICE + @PRICE WHERE ITEM=@item, GetConnection());
     cmde.Parameters.AddWithValue("@QUANTITY", Convert.ToInt32(txtItemquantity.Value));
     cmde.Parameters.AddWithValue("@PRICE", Convert.ToDecimal(txtItemprice.Text));
     cmde.Parameters.AddWithValue("@item", txtItemName.Text);
     cmde.ExecuteNonQuery();
 }


Q:

Short story where a character moves through dimensions via mental exercises

It's been about 25 years since I read a story in an anthology.  The only details I remember from it are that a guy is told that if, while walking down a road (or something similar), he mentally forces himself to think of dimensions opposite of what they are (down is up, left is right, etc.), he will be able to move into another dimension.  He succeeds, but that's all I remember of the story.

A:

"The Gostak and the Doshes" by Miles J. Breuer, M.D.; first published in Amazing Stories, March 1930, reprinted in a number of anthologies and in Avon Fantasy Reader No. 10, 1949 which is available at the Internet Archive. There's a review at Alex Kasman's Mathematical Fiction site. The full text is available at Wikisource.
If you read it in an anthology around 1985, that could have been The Arbor House Treasury of Science Fiction Masterpieces (which was republished in slightly abridged form as Great Tales of Science Fiction), or perhaps Amazing Stories: 60 Years of the Best Science Fiction.
Here is an excerpt from the story:

"According to fiction writers, to switch into the t dimension, some sort of apparatus with an electrical field ought to be necessary. It is not. You need nothing more to rotate into the t dimension than you do to stop the moon and make the trees move as you ride down the road; or than you do to turn the cubes upside down. It is a matter of relativity."
I had ceased trying to wonder or to understand.
"Show me!" was all I could gasp.
"The success of this experiment in changing from the z to the t co-ordinate has depended largely on my lucky discovery of a favourable location. It is just as, when you want the moon to ride the tree-tops successfully, there have to be favourable features in the topography or it won't work. The edge of this building and that little walk between the two rows of Norway poplars seems to be an angle between planes in the z and t dimensions. It seems to slope downward, does it not?—Now walk from here to the end and imagine yourself going upward. That is all. Instead of feeling this building behind and above you, conceive it as behind and below. Just as on your ride by moonlight, you must tell yourself that the moon is not moving while the trees ride by. Can you do that? Go ahead, then." He spoke in a confident tone, as though he knew exactly what would happen.

The title is explained in the Wikipedia article on Gostak:

Gostak is a meaningless noun that is used in the phrase "the gostak distims the doshes", which is an example of how it is possible to derive meaning from the syntax of a sentence even if the referents of the terms are entirely unknown.
[. . . .]
Coined in 1903 by Andrew Ingraham, the sentence became more widely known through its quotation in 1923 by C. K. Ogden and I. A. Richards in their book The Meaning of Meaning (p. 46).
Ogden and Richards refer to Ingraham as an "able but little known writer", and quote his following dialogue:
"Suppose someone to assert: The gostak distims the doshes. You do not know what this means; nor do I. But if we assume that it is English, we know that the doshes are distimmed by the gostak. We know too that one distimmer of doshes is a gostak. If, moreover, the doshes are galloons, we know that some galloons are distimmed by the gostak. And so we may go on, and so we often do go on."
[. . . .]
In Amazing Stories, Dr. Miles Breuer wrote a story, now considered a classic, titled "The Gostak and the Doshes" whose protagonist pops into an alternate world in which the phrase is a political slogan that induces sufficient umbrage throughout the populace to declare justified, righteous war. Other writers have picked up on the reference, notably David Gerrold.

A:

This sounds to me like a Roger Zelazny story, but I'm not quite sure from your description.  It could be one of the short stories he wrote in the Amber universe, but it actually makes me think of "Roadmarks", which would be a short book rather than a short story.  Hope that helps.


Q:

Convert date format to string in Pandas

For one date column, which has na values, with format 2019/1/1, how could I convert it to string column with format 2019-01-01? Thanks

A:

One possible solution with Series.dt.strftime and Series.replace:
df['date']=pd.to_datetime(df["date"],errors='coerce').dt.strftime('%Y-%m-%d').replace('NaT','')


Q:

Create a Raspberry Pi webserver with a domain name

I just set up my Apache web-server (following a tutorial from Jeremy Morgan), and since I have a domain name (pillower.com) registered with GoDaddy, I was wondering how I could link them. Would changing the forwarding settings on GoDaddy be my best bet?

A:

You will have to forward port 80 to your Raspberry Pi. Then you have to tell GoDaddy that you want them to have the IP of your domain name updated as soon as you get a new IP (Dynamic DNS). Maybe you should use GoDaddy with DynDNS.


Q:

How to consume third party .flow files?

I'm working on adding flow to a React.js app. I've used flow-typed to add several packages, which seems to be working.
This issue is that I'm using the Material-UI beta. They don't have a repo in flow-typed, but they do provide Component.js.flow files.
However, I'm getting this error:
Error: src/NotFound/NotFound.js:6
  6: import Button from 'material-ui/Button'
                        ^^^^^^^^^^^^^^^^^^^^ material-ui/Button. Required module not found

Error: src/NotFound/NotFound.js:8
  8: import { withStyles } from 'material-ui/styles'
                                ^^^^^^^^^^^^^^^^^^^^ material-ui/styles. Required module not found

My .flowconfig:
[ignore]
<PROJECT_ROOT>/node_modules/.*
<PROJECT_ROOT>/build/.*
<PROJECT_ROOT>/scripts/.*
<PROJECT_ROOT>/coverage/.*
<PROJECT_ROOT>/config/.*
.*\.test\.js

[include]

[libs]
<PROJECT_ROOT>/flow-typed/.*

[lints]

[options]
emoji=true

I've tried several solutions in support forums, but I'm still not understanding how to wire this up.
Important package versions:
react@15.5.4
material-ui@1.0.0-beta.8
flow-bin@0.54.0

A:

Flow doesn't think material-ui exists because you're explicitly ignoring all files within node_modules in your .flowconfig. Remove the first line under [ignore] (<PROJECT_ROOT>/node_modules/.*) and you should be good to go.
Note that some other libraries may cause flow issues. You should just ignore those selectively, rather than blanket ignore all 3rd party libs.


Q:

Create autoincrement ID with Strings Like USER101,USER102 in NetBeans IDE with MySql database

I'm using Netbeans as my IDE and MySQL as my database, I want to create auto increment id coming up with Strings Like USER101, USER102,... How can I create this auto-increment id? I tried this method do generate auto-increment id  in integer

A:

If id is your auto increment column, make a second generated column with
 CONCAT(''USER'',id);

As generating formula.
The next code would change a column to generate automatocally the USER101 depending on the id from the autoincrement.
ALTER TABLE `testdb`.`testtable`
CHANGE COLUMN `columname`  CHAR(50) NULL GENERATED ALWAYS AS (CONCAT('USER',id));

But i don't know how you make this in NEtbeans and google also didn't help.


Q:

Call function from calling object

This is for a personal project. Not assignment or work.
Say I have an object, objA that has a function callB().
When I run callB() it calls a function in object B. The function in objB can have calls to functions in objA.
Eg. objA calls callB().
Inside callB() there is a function like setObjAName() which sets a variable on objA.
How would I do this in Java? How do I reference objA from objB?

A:

The simplest method is to simply pass a reference to A in with the method call, which will allow for B to access any of A's public methods.
public class ClassA {

    public String someAVar;

    public void callB(ClassA a){
        //do stuff
        ClassB b = new ClassB();
        b.setObjA(this,"newValue");
    }
}
public class ClassB{
    public void setObjA(ClassA A, String newValue){
        A.someAVar = newValue;
    }
}

Alternatively you might want the variable to be settable without passing in a particular instance, in which case static methods and variables are your friend.
public class ClassA {

    public static String someAVar;

    public void callB(){
        //do stuff
        ClassB b = new ClassB();
        b.setObjA("newValue");
    }
}

public class ClassB{
    public void setObjA(String newValue){
        ClassA.someAVar = newValue;
    }
}


Q:

style any element after one specific element

Given a set of paragraphs in a random order

 red

 green

 blue

 purple

Two rules :

All paragraphs placed after the red will have a backround-color red.
All paragraphs after the blue will have the color blue

How to do it with CSS ?
Note that the order is random, and inserting some custom class in the html is not possible.
The example below is here to SHOW the visual of the result, its code is not correct.

 red

 green

 blue

 purple

A:

Use the General sibling combinator ~ to target all next adjacent siblings:

.red ~ p {
  background-color: red;
}

.blue ~ p {
  color:blue;
}

 red

 green

 blue

 purple


Q:

Notification android show date

On the right side of notification android is showing time. It is possible to show both, date and time as I didn't found any notification api to set the date. Or it is android behaviour to show only time?

A:

You can try use RemoteViews for customize a notification layout.
With RemoteViews you can easily control interface and action with notification.
Refer more than here: https://developer.android.com/reference/android/widget/RemoteViews.html.


Q:

Implementing WebSocket in Java Swing Application

I created a small java swing application and I want to use WebSocket for the transferring of data from the server to the client. Can someone give me a step by step instructions on how to do it? I'm using JBoss application server.

A:

One Approach is to use Jetty WebSocket Client API, Hopping that you already implemented Server Side Web Socket
Tutorial
Maven Dependency

          org.eclipse.jetty.websocket
           websocket-client
           ${project.version}

  package examples;

 import java.net.URI;
 import java.util.concurrent.TimeUnit;
 import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
 import org.eclipse.jetty.websocket.client.WebSocketClient;

 public class SimpleEchoClient {

public static void main(String[] args) {
    String destUri = "ws://echo.websocket.org";
    if (args.length > 0) {
        destUri = args[0];
    }
    WebSocketClient client = new WebSocketClient();
    SimpleEchoSocket socket = new SimpleEchoSocket();
    try {
        client.start();
        URI echoUri = new URI(destUri);
        ClientUpgradeRequest request = new ClientUpgradeRequest();
        client.connect(socket, echoUri, request);
        System.out.printf("Connecting to : %s%n", echoUri);
        socket.awaitClose(5, TimeUnit.SECONDS);
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        try {
            client.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
}


Q:

Why do answerers get a penalty for user removal?

Today I was notified about a novel event regarding my reputation.

It appears a user account was deleted, whose question was answered by me and also up-voted. So 10+15(accepted)=25 was deducted from my account!
Why did I receive a penalty for that? Doesn't this rule discourage a user from providing answers?

A:

No, the reason is that the user no longer exists, so does their up-vote really count anymore? I lean towards the current policy on this. Consider that some users are removed for nefarious reasons (e.g. voting irregularities) and the fact that a vote belongs to someone. So, when a user gets deleted, their questions become disassociated from them, their rep disappears, and all of their votes are revoked.
Now, if that person had down-voted you, I bet you wouldn't be complaining that you get +2 rep back.


Q:

Compactness of normed linear spaces

For a normed linear space $(X,||\cdot||)$ I want to show
a)For a continuous map $f : X \to \mathbb{R}$ the set $$f^{-1}(r):=\{x\in X: f(x)=r\} \subset X$$ is closed.
b) $$S(0,r)=\{x\in X: ||x||=r\}\subset X$$ is closed and bounded.
c) Provide an example that $S(0,r)$ is in general not compact.
I believe these questions lead on from eachother but I have a couple of things which confuse me.
My attempt at a):
Suppose we let $y$ be a limit point of $f^{-1}(r)$. So there is a sequence $\{y_n\}$ such that $y_n \in \{ x \in X : f(x)=r\}$ for all $n$ and $\lim_{n \to \infty} y_n = y$. Since $f$ is continuous we then have $f(y)= \lim_{n \to \infty}f(y_n)=\lim_{n \to \infty} r= r.$ Hence $ y \in f^{-1}(r)$, so $f^{-1}$ contains all of its limit points and is closed.
I understand this is a proof and generally 'show that' questions have a more direct approach so perhaps this is the wrong approach. Any feedback on my attempt is much appreciated.
Also in regards to b) and c), as far as I understood a compact space is one which is closed and bounded. But then b) and c) would contradict eachother so is this not the case all the time?

A:

a) Your approach is correct, but it's simpler to say that, since $\{r\}$ is closed and $f$ is continuous, $f^{-1}(r)$ is closed.
b) It is closed by a) and it is bounded because each of its elements has norm $r$.
c) If $X$ is, say, the space of all bounded sequences of real numbers and if the norm of a sequence $(a_n)_{n\in\mathbb N}$ is $\sup_{n\in\mathbb N}|a_n|$, then the set $S(0,r)$ is closed and bounded, but not compact.


Q:

Rust Hamming Code Quizzer

I am currently learning Rust. To allow myself to practice, I created the following program that helps the user to practice hamming codes (the goal is for the user to use this program to be able to write the hamming code for a particular code word). I am aware of a very small algorithmic error in the program that appears with a particular length of code word, but I am not interested in fixing that because the goal of the program is to practice Rust. As such, I am interested in feedback relating to my use of Rust to write idiomatic and efficient code (if I didn't care about speed, I would use Java, but it isn't good enough in testing for my applications). Because I am still using Rust, I can't use the features whose syntax I have not yet learned. For example, I can't create my own structs (or any other types for that matter) or use traits on them, even though both would probably be useful in this context. Although feedback on what other features should be used in this context would be useful, I am most interested in feedback about what I did use.
main.rs:
use rand::prelude::*;
use std::collections::HashMap;
use std::io;

fn main() {
    let mut base_codes = create_all_base_codes(4);
    base_codes.shuffle(&mut rand::thread_rng());

    let mut correct = 0;
    for base_code in &base_codes {
        println!("Enter the hamming code for {}.", reverse_string(&base_code));
        let mut guess = String::new();
        io::stdin().read_line(&mut guess).expect("Failed to read guess.");
        let correct_hamming_code = create_hamming_code(&base_code);
        if guess.trim() == correct_hamming_code {
            correct += 1;
            println!("Your guess is correct.");
        } else {
            println!("Your guess is incorrect. The correct hamming code is: {}", reverse_string(&correct_hamming_code));
        }
    }

    println!("You got {}/{} correct, or {}%.", correct, (&base_codes).len(), ((correct*100) as f64)/(base_codes.len() as f64));
}

fn reverse_string(string: &String) -> String{
    string.chars().rev().collect() //I don't really understand what this is doing fully, I got it from stack overflow
}

fn create_hamming_code(base_code: &String) -> String {
    //create parity bit array
    let mut parity_bits: HashMap<u64, u32> = HashMap::new(); //key is the index in hamming_code, value is the number of 1 bits that fall under this index
    let mut hamming_code = Vec::new();

    for char in (&base_code).chars() {
        while is_power_of_two(hamming_code.len() as u64+1) {
            parity_bits.insert((hamming_code.len()+1) as u64, 0);
            hamming_code.push('h');
        }

        hamming_code.push(char);
    }

    //count bits
    let mut index = 1;
    for char in &hamming_code {
        match char {
            '0' => (),
            '1' => {
                for i in 0..64 {
                    if is_bit_one(index, i) {
                        match parity_bits.get_mut(&((1 << i) as u64)) {
                            Some(count) => *count += 1,
                            None => panic!("Invalid data structure.") //is there some way that I can make this check only happen in debug builds, without unsafe{}?
                        }
                    }
                }
            },
            'h' => (),
            _ => panic!("Illegal character in intermediate hamming code: {}", char) //is there some way that I can make this check only happen in debug builds, without unsafe{}?
        }
        index = index + 1;
    }

    //fill in parity bits
    for (index, count) in &parity_bits {
        hamming_code[*index as usize-1] = get_odd_parity_bit(*count);
    }

    let mut hamming_code_string = String::new();
    for c in hamming_code {
        hamming_code_string.push(c);
    }

    hamming_code_string
}

fn get_odd_parity_bit(count: u32) -> char{
    if count % 2 == 0 {
        '0'
    }else{
        '1'
    }
}

fn is_power_of_two(number: u64) -> bool{
    if number == 0 {
        return false;
    }

    let mut one_found_so_far = false;
    for i in 0..64 {
        if is_bit_one(number, i) {
            if one_found_so_far {
                return false;
            } else {
                one_found_so_far = true;
            }
        }
    }

    true
}

#[test]
fn test_is_power_of_two(){
    assert!(!is_power_of_two(0));
    assert!(is_power_of_two(1));
    assert!(is_power_of_two(2));
    assert!(!is_power_of_two(3));
    assert!(is_power_of_two(4));
    assert!(!is_power_of_two(5));
    assert!(!is_power_of_two(6));
    assert!(!is_power_of_two(7));
    assert!(is_power_of_two(8));
    assert!(!is_power_of_two(9));
    assert!(!is_power_of_two(10));
}

fn is_bit_one(number: u64, bit: u8) -> bool{
    debug_assert!(bit < 64); //spending CPU cycles on this in release builds doesn't matter in this case, but it is good practice in a systems language to not waste CPU cycles if not needed
    (number >> bit as u64) & 0x1 == 1
}

#[test]
fn test_is_bit_one(){
    assert_eq!(is_bit_one(0, 0), false);
    assert_eq!(is_bit_one(0, 1), false);
    assert_eq!(is_bit_one(1, 0), true);
    assert_eq!(is_bit_one(1, 1), false);
    assert_eq!(is_bit_one(2, 0), false);
    assert_eq!(is_bit_one(2, 1), true);
    assert_eq!(is_bit_one(3, 0), true);
    assert_eq!(is_bit_one(3, 1), true);
}

fn create_all_base_codes(length: u32) -> Vec<String> {
    match length {
        0 => vec![],
        1 => vec!["0".to_string(), "1".to_string()],
        _ => {
            let mut codes = Vec::new();
            let smaller_vector = create_all_base_codes(length-1);

            for code in smaller_vector {
                codes.push(code.clone() + "0");
                codes.push(code + "1");
            }

            return codes;
        }
    }
}

#[test]
fn test_create_all_base_codes(){
    let codes = create_all_base_codes(3);
    assert_eq!(codes.len(), 8);

    let required_codes = vec!["000", "001", "010", "011", "100", "101", "110", "111"];
    for required_code in &required_codes {
        assert!(codes.contains(&required_code.to_string()));
    }
}

cargo.toml:
[package]
name = "hammingcodequiz"
version = "0.1.0"
authors = [""]
edition = "2018"

[dependencies]
rand = "0.7.3"

A:

string.chars().rev().collect()

chars() returns an iterator that gives one char (unicode scalar) of the string at a time.
rev() reverses an iterator
collect() is a generic function that can build various types from an iterator. Types like String implement FromIterator interface to work with it.

let mut parity_bits: HashMap<u64, u32> = HashMap::new()

You generally don't need to specify types. Rust will guess them from the usage. let mut parity_bits = HashMap::new() may be enough.
(&base_code).chars()

You almost never need to borrow a type before calling a method. The . operator does it automatically when necessary.
    let mut hamming_code_string = String::new();
    for c in hamming_code {
        hamming_code_string.push(c);
    }

    hamming_code_string

Can be simplified to hamming_code.into_iter().collect() on the same principle as reversing a string. into_iter() gives owned values instead of references.


Q:

what to do with obsolete comments

Suppose I place an answer comment (e.g. elaborate your answer, don't provide only a link bladibla) and the person adjusts the answer and it's worth a +1. Meanwhile, my comment has been upvoted as well, but is now, obviously, obsolete. Do I remove my comment?

A:

Yes.

A:

Remove it if there's no redeeming value. Some comments can present information even if they address for edit requests which had been commenced, so this is more case-by-case.

A:

Yes, indeed. What's more, if you find such comments posted by others, flag them as obsolete. Comments are supposed to be transient and mods can and will delete them without warning.
Such flags help keep the site free of clutter and give mods a warm fuzzy sense of being useful :)


Q:

How to "allocate" enough vertical space above the baseline in a  element to support  elements

I am trying to create a series of "blocks" on the screen that are consistently placed, but I'm having trouble when one of them has ® in it, and that makes it take up more vertical space:

Each block looks like this in code (see example #2 for runnable code snippet):

Text goes here

The dashed rectangles are the p.bingo element that contains the desired text.
Each div.bin element is a horizontal container using flex to add equal space around the p.bingo element.
Each div.myblock element is an overall container that adds vertical padding and constrains the overall width

In each of the p.bingo elements, I want to add enough room between the text baseline and the top of the element so that the vertical space is consistent. How would I do this?
I tried adding min-height, and it fixes the difference in the block heights, but then the baseline positions aren't consistent. (See example #2)

Example #1.

div.container {
  position: relative;
}
div.myline {
  display: inline-block;
}
div.myblock {
  width: 120px;
  padding: 10px;
  background: #aaff88;
  font-family: Arial, sans-serif;
}
div.bin {
  display: flex;
}
span.glue {
  flex: 1;
  max-height: 0;
}
p.bingo {
  margin: 0;
  border: 1px dashed green;
}
div.show-baseline {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  margin: 10px;
  min-height: 2.8ex;
  border-bottom: 1px dashed green;
}

    Spiffy hair!

    Spiffy® hair!

      Vacuum grease

Example #2:

div.container {
  position: relative;
}
div.myline {
  display: inline-block;
}
div.myblock {
  width: 120px;
  padding: 10px;
  background: #aaff88;
  font-family: Arial, sans-serif;
}
div.bin {
  display: flex;
}
span.glue {
  flex: 1;
  max-height: 0;
}
p.bingo {
  margin: 0;
  border: 1px dashed green;
  min-height: 3.2ex;
}
div.show-baseline {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  margin: 10px;
  min-height: 2.8ex;
  border-bottom: 1px dashed green;
}

    Spiffy hair!

    Spiffy® hair!

      Vacuum grease

A:

There's a hack for ensuring that  and  don't negatively affect line-height, and aligning them correctly can be achieved with a combination of vertical-align: baseline and position: relative, and then setting the corresponding top offset:
sup, sub {
  vertical-align: baseline;
  position: relative;
}

sup {
  top: -0.4em;
}

sub {
  top: 0.4em;
}

This can be seen in the following:

div.container {
  position: relative;
}

div.myline {
  display: inline-block;
}

div.myblock {
  width: 120px;
  padding: 10px;
  background: #aaff88;
  font-family: Arial, sans-serif;
}

div.bin {
  display: flex;
}

span.glue {
  flex: 1;
  max-height: 0;
}

p.bingo {
  margin: 0;
  border: 1px dashed green;
}

div.show-baseline {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  margin: 10px;
  min-height: 2.8ex;
  border-bottom: 1px dashed green;
}

sup,
sub {
  vertical-align: baseline;
  position: relative;
}

sup {
  top: -0.4em;
}

sub {
  top: 0.4em;
}

          Spiffy hair!

          Spiffy® hair!

          Vacuum grease


Q:

Laravel Eloquent and time comparrison

I was trying to use an advanced where to pull entries using Laravel Eloquent that included a date comparison. While I found another way to run a date comparison (another foreach after I pulled the records), it still bugs me why this wasn't working. Just curious if anyone else had some feedback on it. Here's what I had:
$surveys = Survey::where('is_published', 1)
                ->whereNull('closes_at')
                ->orWhere('closes_at', '>', date('Y-m-d H:i:s'))
                ->whereHas('assigned', function($q){
                    $q->where('employee_id', Session::get('employee_id'));
                })->orWhere('assigned_to_all', 1)
                ->orderBy('updated_at', 'desc')
                ->orderBy('created_at', 'desc')
                ->get();

So what I was trying to do was pull all surveys that were:

published
either they were assigned to everyone OR it was specifically assigned to them (the 'assigned' module).
where closes at (deadline) was either null or not closed.

If I pull it from the database, it's fine. Just couldn't pull the right ones using Eloquent. I tried a couple different date calls and none of them were working.
Anyone have any tips?

A:

You are pulling surveys where 'is_published'= 1 and ( closes_at was null or closes_at > current time or assigned_to_all = 1 or specifically assigned to them). Try this:
$surveys = Survey::where('is_published', 1)
            ->where(function($query){
                $query->whereNull('closes_at')
                    ->orWhere('closes_at', '>', date('Y-m-d H:i:s'));
            })
            ->where(function($query){
                $query->whereHas('assigned', function($q){
                        $q->where('employee_id', Session::get('employee_id'));
                    })
                ->orWhere('assigned_to_all', 1);
            })
            ->orderBy('updated_at', 'desc')
            ->orderBy('created_at', 'desc')
            ->get();


Q:

Different circular sectors as new logo of the International System

This question does not ask the user to provide me a full MWE, but simply to obtain any information step by step as to create different circular sectors.

This image is taken from the site: https://www.inrim.it/sites/default/files/mediaroot/eventi/logo_nuovosi.png
I have read the only the manual pgf-pie to build pie charts and with lot of sincerity I have seen the responses of users and I have been so scared (see here: Multi-layer Donut Pie).
In fact, I was wondering if you need very much code to make a frontal one that is not in 3D.
I would like to make it because I absolutely don't like some symbols like $\Delta v$ and $K_{\text{cd}}$.
So I only ask users for the simplest steps and no complete MWE.
Thank you (excuse me very much for not having added the link of the image and I have not specified that it serves only me and will not be published, or used improperly).

A:

The following code seems sufficiently simple and solves the rotation issue with the letters in the bottom blocks.
\documentclass[border=3mm]{standalone}

\usepackage[dvipsnames]{xcolor}
\usepackage{tikz}

\usepackage{arev}

\begin{document}
\Large

\begin{tikzpicture}[scale=1.3]
% -----------------------------------
% the \foreach-part
\foreach\n/\k/\l/\o
    [evaluate={\n as \p         using int((\n-3)*(\n-4))},
     evaluate={\n as \angle     using (90+360/14-360/7*\n)},
     evaluate={\n as \Angle     using (90+360/14-360/7*(\n+1))},
     evaluate={\n as \nsegment  using (360/7*\n)}
    ]
    in
    {0  /red/kg/$h$,
     1  /orange/m/$c$,
     2  /yellow/s/$\Delta v$,
     3  /Green/A/$e$,
     4  /RoyalBlue/K/$k$,
     5  /violet/mol/$N_A$,
     6  /Blue/cd/$K_{\textnormal{\scriptsize cd}}$%
    }
    {\fill[draw=white,line width=2.5pt,fill=\k!90!black,domain=\angle:\Angle,variable=\t]
        plot ({2*cos(\t)},{2*sin(\t)})
        -- (0,0)
        -- cycle;
     \fill[white,opacity=.4,domain=\angle:\Angle,variable=\t]
        plot ({1.2*cos(\t)},{1.2*sin(\t)})
        -- (0,0)
        -- cycle;
     \ifnum\p=0
        \path
            node[white,rotate=180-\nsegment] at (90-\nsegment:1.6) {\l}
            node[rotate=180-\nsegment,font=\small] at (90-\nsegment:.95) {\o};
     \else
        \path
            node[white,rotate=-\nsegment] at (90-\nsegment:1.6) {\l}
            node[font=\small,rotate=-\nsegment] at (90-\nsegment:.95) {\o};
     \fi
    }
% -----------------------------------
\node[circle,font=\huge,fill=white,inner sep=7pt] (0,0) {SI};
\end{tikzpicture}
\end{document}

A:

Perhaps something like this:

You can get the colours of your logo by looking through the xcolor manual. If you really want the K, A and s rotated as in the OP this can be done but the rotations below are more natural.
Here is the code:
\documentclass[tikz, border=2mm]{standalone}

\begin{document}

  \begin{tikzpicture}
    \foreach \top/\mid/\col [count=\c,
                  evaluate=\c as \st using {360/7*(\c-1)+1},
                  evaluate=\c as \en using {360/7*\c-1},
                  evaluate=\st as \se using {(\st+\en)/2}
    ] in {m/c/orange,
          kg/h/red,
          cd/K_cd/purple,
          mol/N_A/purple,
          K/k/blue,
          A/e/green,
          S/\Delta v/yellow} {
       \draw[\col,fill=\col!80] (\st:1)--(\st:2)
           arc [start angle=\st, end angle=\en, radius=2]
           --(\en:1)
           arc [start angle=\en, end angle=\st, radius=1];
       \draw[\col,fill=\col!50] (\st:0.5)--(\st:1)
           arc [start angle=\st, end angle=\en, radius=1]
           --(\en:0.5)
           arc [start angle=\en, end angle=\st, radius=0.5];
       \node[white,rotate=\se-90,font=\bfseries] at (\se:1.5){\top};
       \node[rotate=\se-90,font=\scriptsize] at (\se:0.75){$\mid$};
    }
  \end{tikzpicture}

\end{document}


Q:

Twitter api GET Call {"errors":[{"code":32,"message":"Could not authenticate you."}]}

I am trying do GET call for twitter  through SFDC here is the apex class code ..
String consumKey       =EncodingUtil.urlEncode(apiData.Oauth_Consumer_Key__c,'UTF-8');
      String othNonce =Encodingutil.urlEncode(oathNonce, 'UTF-8');
      signature =Encodingutil.urlEncode(signature, 'UTF-8');
      String othToken =Encodingutil.urlEncode(apiData.Oauth_Token__c, 'UTF-8');

            HttpRequest req = new HttpRequest();

            req.setEndpoint('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=tesr_s&count=10');

            req.setMethod('GET');

            string reqstring = 'OAuth oauth_consumer_key="'+consumKey+'",'+
                               'oauth_token="'+othToken+'",'+
                               'oauth_signature_method="HMAC-SHA1",'+
                               'oauth_timestamp="'+timestamp+'",'+
                               'oauth_nonce="'+othNonce+'",'+
                               'oauth_version="1.0",'+

                req.setHeader('Authorization',reqstring);
                req.setHeader('Content-Type', 'application/x-www-form-urlencoded');

                Http http = new Http();
                HTTPResponse res = http.send(req);
                system.debug('req  () ===>>>>>'+req);
                system.debug('res.getBody() ===>>>>>'+res.getBody());
                return res.getBody();

Getting below error .
{"errors":[{"code":32,"message":"Could not authenticate you."}]}.

System.HttpRequest[Endpoint=https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=Test&count=10,
  Method=GET] 23:26:47.0 (901503445)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:586
  23:26:47.0
  (901599227)|CALLOUT_RESPONSE|[102]|System.HttpResponse[Status=Authorization
  Required, StatusCode=401] 23:26:47.0
  (901616748)|HEAP_ALLOCATE|[102]|Bytes:90

A:

You need to be added Remote Sites to get access to twitter api.
To add a remote site setting:

From Setup, enter Remote Site Settings in the Quick Find box, then select Remote Site Settings.
Click New Remote Site.
Enter a descriptive term for the Remote Site Name.
Enter the URL for the remote site.(https://api.twitter.com/1.1/)
Optionally, enter a description of the site.
Click Save.

Apex Code :
 public class Scontroller
        public String sBody{get;set;}
        public String tweets{get;set;}
        public String access_token {get;set;}
        public Scontroller()
        {
            String keyencoded = EncodingUtil.urlEncode('CYXp886M6g04xwouOHLYg4UJf','UTF-8');
            String secretkeyencoded = EncodingUtil.urlEncode('5qC4A3JZDF8you0VtKx95AJqROlXi2oihTkJgVNNsv8pVQ2cjT', 'UTF-8');
            String sFinal = keyencoded + ':' + secretkeyencoded;
            Blob headerValue = Blob.valueOf(sFinal);
            HttpRequest req = new HttpRequest();
            req.setEndpoint('https://api.twitter.com/oauth2/token');
            req.setMethod('POST');
            String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
            req.setHeader('Authorization', authorizationHeader);
            req.setBody('grant_type=client_credentials');
            Http http = new Http();
            HTTPResponse res = http.send(req);

            JSONParser parser = JSON.createParser(res.getBody());
            while(parser.nextToken() != null)
            {
                if(parser.getCurrentToken() == JSONToken.FIELD_NAME)
                {
                    String fieldName = parser.getText();
                    parser.nextToken();
                    if(fieldName == 'access_token')
                    {
                        access_token = parser.getText();
                    }

                }
            }

        }

        public String gettweetsss(){

            HttpRequest req2 = new HttpRequest();

                req2.setEndpoint('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterdev&count=12');
                req2.setMethod('GET');

                //Call Bearer token Method
                String authorizationHeader = 'Bearer ' + access_token;
                req2.setHeader('Authorization', authorizationHeader);

                Http http = new Http();
                HTTPResponse res = http.send(req2);

                tweets = res.getBody();
                return tweets;
        }

May be this community answers could you more insight on this,
https://twittercommunity.com/t/errors-message-could-not-authenticate-you-code-32/1223/35


Q:

Selectively inline functions (for debugging purposes)?

What I'd love to have is a build configuration where functions are not inlined, except some selected functions (that may or may not be inlined, that would be up to the compiler).
Even better would be some kind of an "inlining level", where I could specify such a level for each function, plus a minimum level when building, and only functions above the min level would be allowed to be inlined. I know there's no standard solution for this, but compiler-specific hacks would be just as welcome.
I'd like to be able to step through most of my functions non-inlined in a debugger, but a selected few of them should be inlined, partly for performance reasons, and partly to avoid crazy-deep call stacks. The code involves some pretty nasty template metaprogramming, but that part is mostly done, so I'd like to concentrate on the rest. So it would be nice to have the functions that belong to the template metaprograms inlined, but not the other inline functions.
Is there any way to achieve something like this?

A:

Depending on your compiler, yes.  For g++, the following will work:
void foo() __attribute__ ((noinline));
void foo() __attribute__ ((always_inline));

On MSVC++:
__declspec(noinline) void foo();
__forceinline void foo();

Note that g++ requires that the attributes be applied only to prototypes, not definitions.  So if your function is definition-only (no separate prototype) then you must create a prototype in order to apply the attribute.  MSVC does not have this requirement.
__forceinline specifically has some exceptions.  Make sure you read them carefully so you know whether or not it will have any effect in your particular situation.  g++ does not document any exceptions to the always_inline attribute, but some things are readily apparent (inlining a call to a virtual method will only work when the method is called statically, for example).
You can generalize this with macros:
#ifdef _MSC_VER
 #define NOINLINE(x) __declspec(noinline) x
 #define INLINE(X) __forceinline x
#else
 #ifdef __GNUC__
  #define NOINLINE(x) x __attribute__ ((noinline))
  #define INLINE(x) x __attribute__ ((always_inline))
 #else
  #error "I don't know how to force inline/noinline on your compiler."
 #endif
#endif

INLINE(void foo());
NOINLINE(void foo());