text:
Q: restarting AsyncTask in Service I have Service and AsyncTask in it, which due to check updatings on the server. It have to be reexecuted if it get some data and also if it doesn't. So my AsyncTask implementation is :
 private class DklabExecute extends AsyncTask<Void, String, Void> {
            int count;

            Calendar calendar = Calendar.getInstance();
             java.util.Date now = calendar.getTime();
             java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
            String url = "http://192.168.0.250:81/?identifier=nspid_"+md5(LoginActivity.passUserId)+
                      ",nspc&ncrnd="+Long.toString(currentTimestamp.getTime());

            HttpGet rplPost = new HttpGet(url);

            protected Void doInBackground(Void... args)
            {

                Log.i("service count", Integer.toString(count));
                count ++;
             Log.i("md5 func", md5(LoginActivity.passUserId));

                String testData = "http://192.168.0.250/app_dev.php/api/comet/testOrder/";

                 JSONParser  parser = new JSONParser();
                 DefaultHttpClient testClient = new DefaultHttpClient();
                 DefaultHttpClient rplClient = new DefaultHttpClient();

                try {

                     List<NameValuePair> params = new ArrayList<NameValuePair>();
                     params.add(new BasicNameValuePair("", ""));
                     HttpGet httpTest = new HttpGet(testData);

                     httpTest.setHeader("Cookie", CookieStorage.getInstance().getArrayList().get(0).toString());
                     rplPost.setHeader("Cookie", CookieStorage.getInstance().getArrayList().get(0).toString());

                    try {

                        httpResponse = rplClient.execute(rplPost);
                    }

                     catch (ClientProtocolException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    Header[] head = httpResponse.getAllHeaders();
                    Log.i("http Response",httpResponse.toString());
                    for (Header one:head)
                    {
                        Log.i("headers",one.toString());
                    }
                    Log.i("response code", Integer.toString(httpResponse.getStatusLine().getStatusCode()));
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                        while ((line = reader.readLine()) != null)
                        {
                            sb.append(line);// + "n");
                        }
                        try
                        {
                            is.close();
                        }
                        catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                    json = sb.toString();
                    Log.i("rpl response",json);
                    if (new JSONArray(json) != null)
                        jArr = new JSONArray(json);
                    else
                        this.cancel(true);
                     JSONObject toObj = jArr.getJSONObject(0);
                     JSONObject data = toObj.getJSONObject(KEY_DATA);
                    if (data.has(KEY_ORDER))
                    {
                        for (Order a : ServiceMessages.orderExport)
                          {
                             Log.i("service before list", a.toString());
                          }
                         Log.i(" ", "  ");
                          for (Order a : DashboardActivityAlt.forPrint)
                          {

                             Log.i("before dashboard list", a.toString());
                          }
                        JSONObject jsonOrder = data.getJSONObject(KEY_ORDER);
                        Gson gson = new Gson();
                        Order orderObj= gson.fromJson(jsonOrder.toString(), Order.class);
                        try
                        {
                            for (ListIterator<Order> itr = orderExport.listIterator(); itr.hasNext();)
                            {
                                Order a = itr.next();

                                Log.i("order count", a.toString());

                                if(orderObj.getOrderid()==a.getOrderid())
                                {
                                    Log.i("Service","order was changed");
                                    a = orderObj;
                                    someMethod("Your order  "+ orderObj.getTitle() + "  was changed");

                                }
                                else
                                {
                                    Log.i("Service","order"+ orderObj.getTitle()+" was added");
    //                              DashboardActivityAlt.forPrint.add(0, orderObj);
                                    ServiceMessages.orderExport.add(0,orderObj);
                                    Log.i("status",Integer.toString(orderObj.getProcess_status().getProccessStatusId()));
                                    someMethod("Your order  "+ orderObj.getTitle() + "  was added");
                                }

                            }
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                        for (Order a : ServiceMessages.orderExport)
                          {

                             Log.i("service after list", a.toString());
                          }
                         Log.i(" ", "  ");
                          for (Order a : DashboardActivityAlt.forPrint)
                          {

                             Log.i("after dashboard list", a.toString());
                          }
//                      intentOrder.putParcelableArrayListExtra("ordersService", orderExport);
                        sendBroadcast(intentOrder);
                        Log.i("after parse order",orderObj.toString());
                        Log.i("orders after updating",DashboardActivityAlt.orders.toString() );
                    }
                    else if (data.has(KEY_MESSAGE))
                    {

                        JSONObject jsonMessage = data.getJSONObject(KEY_MESSAGE);
                        Gson gson = new Gson();
                        Log.i("messages before parse", jsonMessage.toString());
                        for (Order a: DashboardActivityAlt.forPrint)
                        {
                            Log.i("messages count", Integer.toString(a.getCusThread().getMessages().size()));
                        }
                        Log.i("disparse message",jsonMessage.toString());
                        Message message =  gson.fromJson(jsonMessage.toString(),Message.class);
                        Log.i("incomming message",message.toString());
                        JSONObject jsonThread = jsonMessage.getJSONObject(KEY_THREAD);
                        Threads thread =  gson.fromJson(jsonThread.toString(),Threads.class);
                        Log.i("incomming thread",thread.toString());
                        Order orderChanged = new Order();
                        String orderName = null;
                        for(Order as : DashboardActivityAlt.forPrint)
                        {

                            if (as.getOrderid() == thread.getTreadOrder().getOrderid())
                            {
                                orderName = as.getTitle();
                                orderChanged = as;
                                Log.i("messages count after", Integer.toString(as.getCusThread().getMessages().size()));
                            }

                        }
                        Log.i("orderchanged",orderChanged.toString());
                        someMethod("Your order  "+ thread.getTreadOrder().getTitle() + "  was changed. Message was added");
                        orderChanged.getCusThread().addMessage(message);
                        sendBroadcast(intentMessage);
                        Log.i("messages service", "before sleep");

                        Log.i("messages service", "after sleep");

                    }
                    else

                    {

                        this.cancel(true);

                    }

                }
                 catch (IllegalStateException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                } catch (IOException e2) {
                     rplClient.getConnectionManager().shutdown();
                     testClient.getConnectionManager().shutdown();
                     someMethod("You've lost internet connection. You should try later.");
                    e2.printStackTrace();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                return null;
             }
            protected void onPostExecute(Void bitmap) {

                 this.cancel(true);
                 new DklabExecute().execute();
             }
        }

If I send some data to the server, it gives me back in JSON format via rpl server. Everything works good, but the problem is when I get some data from the server, AsyncTask reexecuted in onPostExecute() method and it is the same reapeted one or two times data in my list of orders. If I do not reexecute AsyncTask the listening happens only in onStartCommand() method but not permanently. Tell me please how can I implement this in the best manner...

A: if it's a service there's no reason to use an AsyncTask.
AyncTasks were build to deliver content back on the original thread (normally a UI thread), but services don't have those.
I suggest you use a ScheduledExecutorService instead http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html
 private ScheduledExecutorService executor;

 // call those on startCommand
        executor = Executors.newSingleThreadScheduledExecutor();
        executor.scheduleWithFixedDelay(run, 250,3000, TimeUnit.MILLISECONDS);

and have a Runnable doing the work
private Runnable run = new Runnable() {

      @Override
      public void run() {
              // do your network stuff
      }
};

and don't forget to cancel everything when your service stops
   executor.shutdown();

edit:
or to use a thread in loop you can:
    boolean isRunning;

.
    // this on your start
    Thread t = new Thread(run);
    isRunning = true;
    t.start();

the runnable
private Runnable run = new Runnable() {

      @Override
      public void run() {
              while(isRunning){
                    // do your network stuff
              }
      }
};

and again, don't forget to finish it whenever the service finishes with:
     isRunning = false;


text:
Q: is there a way in Timber to show parent method name in the logs android I know that I can show the method names in Timber and even the line number using something like that
  class MyDebugTree : DebugTree() {

        override fun createStackElementTag(element: StackTraceElement): String? {
            return String.format(
                " [M:%s] [C:%s]",
                element.methodName,
                super.createStackElementTag(element)
            )
        }
    }

but what I want to do is not only to show the method name containing the Timber statement but also the parent method.
Example: I want to show the name of method a
 fun a(){
   b()
}
fun b(){
 Timber.d("statement")
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Put json string into a javascript variable json I have this in my console chrome:
[{"id":40,"endDate":"2017-04-22","dataA":"2017-04-19","nrC":2,"type":"CO","dataD":"2017-04-19","startDate":"2017-04-20"},{"id":40,"endDate":"2017-04-26","dataA":"2017-04-26","nrC":4,"tyoe":"CP","dataD":"2017-04-23","startDate":"2017-04-25"},
This json string is comming from the servlet that calls DAO class to take the information from db.
So, this string is (dynamically) passed into a jsp page from request session...and i put it into var DAYS = '${jsonArrayString}'; then console.log(DAYS); then it prints that json string above.
So...it can print more data then two.
It has to be put into a javascript variable loke this:
var DAYS = '${jsonArrayString}'; //That's what's on my console..and it comes from session into this jsp page

I think it has to be iterated through a foreach and print it in that format.
var USER_DAYS   =   [

                  {
                      id: value from jsonArrayString,
                      date: value from jsonArrayString,
                      title: value from jsonArrayString,
                      start: new Date(value from jsonArrayString),
                      end: new Date(value from jsonArrayString),
                      allDay: true,
                      className: 'done'
                  },
                ];

I tried to put the values manually and it works...like this:
var USER_DAYS   =   [
      {
          id: 1,
          date: '2017-04-05',
          title: 'CO',
          start: new Date(2017, 3, 5),
          end: new Date(2017, 3, 7),
          allDay: true,
          className: 'done'
      },

I don't know hot to put the values from that json string(
Which can be anythong ... more than 2 records)...that why I need to iterate through that json string.
I want the values to be put only in that format, in that variable (var USER_DAYS)
I tried somthing like this, but it does't work:
<c:forEach items="${jsonArrayString}" var="jsonArrayString">
                    {
                        id: '${jsonArrayString.nrC}' ,
                        date: '${jsonArrayString.dataD}' ,
                        title: '${jsonArrayString.type}' ,
                        startDate: '${jsonArrayString.startDate}',
                        endDate: '${jsonArrayString.endDate}',
                        allDay: true,
                        className: 'done'
                    },
</c:forEach>
                ];

or like this:
var USER_DAYS   =   [

                  {
                      id: DAYS.nrC,
                      date: DAYS.dataD,
                      title: DAYS.type,
                      start: new Date(DAYS.startDate),
                      end: new Date(DAYS.endDate),
                      allDay: true,
                      className: 'done'
                  },
             ];

How to do this?

A: try parse to json string into json objects.
Example
   var USER_DAYS = JSON.parse('${jsonArrayString}')

A: JavaScript code runs only on the client side, while JSP on the server. You cannot iterate over the JavaScript variable while the page is rendered at the server.

*

*If you want to serve a page that already contains the data, you should pass the data to the JSP page as a model attribute. To do this, take a look at this post.

*If you want to populate the page with data after it has been loaded to the browser, you have to use a JavaScript library, such as jQuery. In this case, you have to send a request to the server to get the data in JSON format, and then you can manipulate them on the client side.


text:
Q: Avoid Generating a singular matrix in MATLAB How would you generate a random matrix that is not singular in MATLAB.?
I know a matrix determinant can be used to do check this, but after reading MATLAB determinant:
"Using det(X) == 0 as a test for matrix singularity is appropriate only for matrices of modest order with small integer entries. Testing singularity using abs(det(X)) <= tolerance is not recommended as it is difficult to choose the correct tolerance. The function cond(X) can check for singular and nearly singular matrices."
So if I want to generate a big random matrix (axb) a=5000, b=5000, How to do it??.

A: A randomly generated matrix will be full rank (and hence invertible, if square) with probability 1:
A = randn(5000);

you can check this by using min(svd(A)), and verifying that the smallest singular value is larger than zero.
This is a well-known fact, but here's an example paper if you want one.


text:
Q: Convertir archivos alojados en servidor Filezilla a base64 Alguien sabrá como convertir archivos dentro de un servidor ftp, (Filezilla), a "base64", para que luego estos sean visualizados y posiblemente descargados en mi pagina web.
Estoy trabajando con php framework jqwidgets. La idea mía es que de un registro almacenado como "mensaje", pueda tener la facilidad de descargar los archivos que se les adjuntaran. Si es que alguien sabe como, me podría facilitar esto?.
De antemano muchas gracias!.


text:
Q: Realise an auto link to target website title function I want to implement a function, which gets the target html  of a website and converts the given link and the <title> to a html link.
The Code:
<?php
function get_title($url){
  $str = file_get_contents($url);
  if(strlen($str)>0){
    $str = trim(preg_replace('/\s+/', ' ', $str)); // supports line breaks inside <title>
    preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title); // ignore case
    return $title[1];
  }
}
//Example:
echo get_title("http://www.washingtontimes.com/");
?>

The problem:
This process needs time. Imagine, there is a page with 5-20 links.
The solution: I want to convert all urls and save them as html links, so my website won't load too long.
Should I do it like this ? I know, it's better to store raw data in a database, but I can't see another solution...
Greets


text:
Q: Getting Recursive items from SharePoint Calendar Any idea on this below scenario
In the case I have an item that starts at 01/01/2014 and ends at 01/01/2025 with a recurrence every Tuesday, the query returns all items from today until today + year.
That means that if today is 21st of October 2014, the query isn't returning items from 22nd October 2014.
UPDATE: After some tests I have detected a couple strange things:

*

*If I use Year, the query returns what I have explained before.

*If I use Month instead, the query returns all single events in Calendar Date's month. Also, it returns some events outside the month (one or two at most).

*If I use Today, it returns events occurred in today
I can't understand this behaviour, but waiting for a better answer
"<Query>" +
        "<Where>" +
            "<DateRangesOverlap>" +
                "<FieldRef Name='EventDate' />" +
                "<FieldRef Name='EndDate' />" +
                "<FieldRef Name='RecurrenceID' />" +
                "<Value Type='DateTime'>" +
                    "<Year />" +
                "</Value>" +
            "</DateRangesOverlap>" +
        "</Where>" +
        "<OrderBy>" +
            "<FieldRef Name='EventDate' />" +
        "</OrderBy>" +
    "</Query>";

A: The query is returning recurrences of an item that are in the time period you specify.

*

*If you're asking for things in the next year - you're getting that

*If you're asking for recurrances during the day - you're getting that.

*The month one is a litle strange - its returning items that will fit
on a monthly calendar type view which can include a few days from the previous and next
month.

E.g. in this monthly calendar from May 2011 you see 1st May until the 4th June (June is shaded blue)


text:
Q: How to add a custom interceptor to angular 4 app in bootstrap How to add a custom interceptor to angular 4 app in bootstrap
I've made a basic interceptor to eventually set a auth token.
I need help adding the interceptor to the core app module.
This is my interceptor code (very basic at the moment):
import { Injectable } from "@angular/core";
import { ConnectionBackend, RequestOptions, Request, RequestOptionsArgs, Response, Http, Headers } from "@angular/http";
import { Observable } from "rxjs/Rx";

@Injectable();

export class CommonInterceptor implements HttpInterceptor {
    className: string;

    constructor(private logger: Logger) {
        this.className = "CommonInterceptor";
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const started = Date.now();
        return next.handle(req).do(event => {

          console.log("Interceptor");

            if (event.type === HttpEventType.Response) {
                if (this.logger.isDebugEnabled()) {
                    const elapsed = Date.now() - started;
                    this.logger.debug(`${this.className}: Request for ${req.urlWithParams} took ${elapsed} ms.`);
                }
            }
        });

    }
};

This is my app module (very basic app at moment):
import { NgModule } from "@angular/core";
import { routes } from "./app.routes";
import { BrowserModule } from "@angular/platform-browser";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";
import { FormsModule} from "@angular/forms";
import { APP_BASE_HREF, CommonModule, } from "@angular/common";
import { RouterModule } from "@angular/router";
import { HttpModule, HTTP_INTERCEPTORS } from "@angular/http";

import { AppComponent } from "./app.component";
import { HomeModule } from "./components/home/home.module";
import { CommonInterceptor } from "./interceptor";

@NgModule({
  imports: [BrowserModule, FormsModule, RouterModule, CommonModule, HttpModule, RouterModule.forRoot(routes),
  HomeModule
  ],
  providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useClass: CommonInterceptor,
        multi: true
    }
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})

export class AppModule { }

I want to add my CommonInterceptor to the app module.
How do I do that?

A: You need not add it to you bootstrap array to use it.
add
{
        provide: HTTP_INTERCEPTORS,
        useClass: CustomHttp,
        multi: true
},

to your providers array.
Also an ideal interceptor would look like, I couldn't understand your version:
import {Injectable} from '@angular/core';
import {HttpEvent, HttpEventType, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from "rxjs/Observable";
import {Logger} from "../../logger/logger";
import 'rxjs/add/operator/do';

 @Injectable()
export class CommonInterceptor implements HttpInterceptor {

    className: string;
/**
 *
 * @param {Logger} logger
 */
constructor(private logger: Logger) {
    this.className = "CommonInterceptor";
}

/**
 *
 * @param {HttpRequest<any>} req
 * @param {HttpHandler} next
 * @returns {Observable<HttpEvent<any>>}
 */
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const started = Date.now();
    return next.handle(req).do(event => {
        if (event.type == HttpEventType.Response) {
            if(this.logger.isDebugEnabled()){
                const elapsed = Date.now() - started;
                this.logger.debug(`${this.className}: Request for ${req.urlWithParams} took ${elapsed} ms.`);
            }
        }
    });

}
}

Edit
Added the imports

A: in your app.module.ts
`

providers: [
     AccountService,
     AuthJwtService,
      AuthService,
     LocalStorageService,
     SessionStorageService,
     AuthGuardService,
//add this code bellow
     {
       provide: Http,
       useFactory: HttpIntercepter,
       deps: [XHRBackend, RequestOptions]
     }
   ]

`
In you can add simple this function in your customhttp file

export function HttpIntercepter(backend: XHRBackend, options: RequestOptions) {
   return new CustomHttp(backend, options);
 }


text:
Q: I am trying to make a random name generator using a switch This is a project i am working on seperate from school, but is for a school project. i am attempting to make a name generator from a list of set names. I believe i am on the right track, although could be completely off. I am stuck where i am with a few questions.

*

*How to make the loop pause itself after each name

*How to prevent the same name from being generated multiple times

*How to take it from the BlueJ program i am using to an executable file to run on a computer without BlueJ installed.

any help is appreciated
The code i have is as follows
import java.util.*;

class otherNamePicker
{
    static CinReader myRead = new CinReader();
    public static void main(String[] args)
    {
        Scanner readinput = new Scanner(System.in);
        Random myRand = new Random();
        String enterkey = "next name";
        System.out.print(enterkey);
        boolean nextName = true;
    while( nextName )
    {
        int names = myRand.nextInt(8)+1;
        enterkey = readinput.nextLine();
        switch(names)
        {
            case 1:
            System.out.println("JonYoung");
            break;
            case 2:
            System.out.println("SeanWorthington");
            break;
            case 3:
            System.out.println("Katie");
            break;
            case 4:
            System.out.println("Cole");
            break;
            case 5:
            System.out.println("Nico");
            break;
            case 6:
            System.out.println("Mari");
            break;
            case 7:
            System.out.println("Sean");
            break;
            case 8:
            System.out.println("Anthony");
            break;
            //each case being a student's name
        }

    }
}

}


text:
Q: how to delete or replace a word In file directly In a large file, how to replace the certain word?
Is there is a way to delete a particular line or word in file?
EDIT:
My file is quite large.
I cannot load entire file in to buffer and replace the buffer to file

A: read each line from the file into a string, then apply std::string's replace (http://www.cplusplus.com/reference/string/string/replace/)


text:
Q: string.Length vs string.ToCharArray().Length I'm cleaning up some old code that's repeatedly doing myString.ToCharArray().Length; instead of myString.Length.
Before I refactor ToCharArray() out, are there any circumstances where doing so would result in different behavior?

A: No difference : have a look the method code with reflector : it will allocate a char[] based on the length of the string.

A: Both will definitely return the same length, representing the number of characters (chars). There'll be one char per each index of the string (or array), and, then, the following could be worthy of mention:

The Length property returns the number of Char objects in this
  instance, not the number of Unicode characters. The reason is that a
  Unicode character might be represented by more than one Char. Use the
  System.Globalization.StringInfo class to work with each Unicode
  character instead of each Char.

From this you can also deduce that ToCharArray, given that it is "A Unicode character array whose elements are the individual characters of this instance", that they behave the same.
I'm not sure what the not on NullReferenceException is about, as both are susceptible to that, too.

A:
result in different behavior?

Well, as others said, in both ways, result will be the number of char, so, the answer is definitly NO!
But I want to add something different to this answer.
When I decompile String.ToCharArray() method, it looks like:
public unsafe char[] ToCharArray()
{
  int length = this.Length;
  char[] chArray = new char[length];
  if (length > 0)
  {
    fixed (char* smem = &this.m_firstChar)
      fixed (char* dmem = chArray)
        string.wstrcpyPtrAligned(dmem, smem, length);
  }
  return chArray;
}

ToCharArray uses unsafe code that manipulates pointers, along with the private wstrcpyPtrAligned method in the base class library. It is normally faster than doing the same thing in managed code, which has to check array bounds.
But
It makes a complete pass over the string, so if you do not require that, filling character arrays manually may be faster.
Since ToCharArray() method returns a char array, which you can modify in-place. This sometimes improves the performance of code.

A: I don' think it will give different result in any scenario!
but if I use its overloaded method i.e. ToCharArray(int startIndex, int length)
then obviously it can give different value of length property as you give the length.
Also I can not override this ToCharArray() method in my custom class like ToString() method. So If you want to calculate the length only, then using myString.Length makes more sense than using myString.ToCharArray().Length.


text:
Q: How is RAM and Heap Space allocated for a linux/unix command? So when I execute a linux command, say a cat command for this example, on a server with 128 GB of RAM, assuming none of this RAM is currently in use, all is free. (I realize this will never happen, but that's why it's an example)
1) Would this command then be executed with a heap space of all 128 GB? Or would it be up to the linux distro I am using to decide how much heap space is aloocated from the available 128 GB?
2) If so, is there another command line argument that I can pass along with my cat command to reserve more heap space than the system standard?
EDIT: 3) Is there a way which I can identify how much heap space will be allocated for my cat command (or any command), preferrably a built-in command line solution, not an external application. If it's not possible please say so, I am just curious.

A: It would be up to the memory allocator (usually found in the libc) to determine how much heap would be allocated. glibc's allocator doesn't use any environment variables, but other replacements may.

A: When you start a program, some amount of memory is allocated for the program; however, this amount of memory is not the limit to what the program is allowed to use. Whenever more memory is requested, it can be granted up until the system has used up all of the memory.


text:
Q: How to provide data for .po translation files? After running django-admin.py makemessages -l de in Django to create the translation files, you could use a plain text editor or Poedit to fill them out.
Poedit has the advantage that it provides a specialized UI for entering this data. However I keep getting an error message when I switch between the words:

MyBookmarks/locale/de/LC_MESSAGES/django.po:7: header field
  `Project-Id-Version' still has the initial default value

What is this? Has anyone with knowledge of internationalization in Django or general users of po / GNU gettext came across this error message?
Many Thanks,

A: I guess Django leave the header of the .po file customizable by the user, so is up to you to substitute "PACKAGE VERSION" with something more descriptive like "MY FABULOUS APP v.1.0".
To do that on any relevant file in a given path, you can use this command from the command line and in a *nix environment (or anywhere sed and find are available)
find <YOUR_PATH_HERE> -type f -name '*.po' -exec sed -e s'/PACKAGE VERSION/<YOUR_APP_NAME> <YOUR_APP_VERSION>/g' -i.bak {} \;

the command will replace the aforementioned text in every .po file and will save also an unmodified, backup file of each one.
So, in your case the command will be:
find MyBookmarks/ -type f -name '*.po' -exec sed -e s'/PACKAGE VERSION/MyBookmarks v.1.0/g' -i.bak {} \;

I routinely include this command in my fabfile and it solves the issue using POedit 1.5.x (but should work also on previous versions).
NOTE: You have to do that only once for every .po file. Next time you'll launch a ./manage.py makemessages Django will remember the setting.


text:
Q: Using R, how to pivot/transform a dataset whose elements are the result of a function I have the following toy dataset:
z <- c(2,2,3,3,3,4,2,2)
y <- c(6,6,6,5,4,6,6,5)
x <- c(1,1,2,3,5,4,4,3)
df <- cbind(x,y,z)

I would like to figure out how many times an element z appears with an element x for each element y. The resulting dataset should look like the following:
     y(4) y(5) y(6)
x(1)  0    0    2
x(2)  0    0    1
x(3)  0    2    0
x(4)  0    0    2
x(5)  1    0    0

The solution needs to be scalable such that the number of elements in x,y, and z is irrelevant.

A: Your desired result is just a table of x and y.
> table(df[,"x"], df[,"y"])
#
#    4 5 6
#  1 0 0 2
#  2 0 0 1
#  3 0 2 0
#  4 0 0 2
#  5 1 0 0

Maybe converting df to a data.frame might make more sense
> df <- data.frame(df)
> with(df, table(x, y))
#    y
# x   4 5 6
#   1 0 0 2
#   2 0 0 1
#   3 0 2 0
#   4 0 0 2
#   5 1 0 0


text:
Q: IPad mail app does not show old emails – I can't mark them all as read I have started using my iPad again after long inactivity. The mail app shows 7,288 unread email. I would like to get rid of that red number, the problem is that the mail app does not load old email – and so I can't mark them as read. By the way, is there a way to mark ALL that 7,288 as read in one go?

A: Actually I found out that the problem was simply due to the fact that I had a lot of unread messages in the "social" and "promotion" folders on Gmail. Best way to get rid of all of those unread emails: do a search using the query is:unread on Gmail's web interface.

A: If using Gmail, there are no user-accesible parameters to limit how much email does iOS download to your device, but in my experience old email is downloaded "on-demand", while browsing mailboxes.
The easiest way to get rid of the unread sign is to go through http://gmail.com and delete, archive or mark as read all unread email.  That will sync sooner or later with your device if it is properly configured.
If by chance it is configured with the POP3 protocol (instead of IMAP), the easiest way would be to erase and add again. This may prove problematic because depending on the configuration and set-up, you may lose email by deleting the account on your device.
It may resolve on its own: if you haven't used it in a while and it's configured with IMAP, and those emails are marked as "read" on the server, it may be that the device it's just delayed in updating the information.


text:
Q: Svelte {#await}..{:then} block duplicating html with new data I'm trying to use Sveltes {#await}..{:then} block to show NASA's image of the day but I'm getting a strange intermittent outcome. On the first page load the image and data loads in just fine. When I change the date using the date-picker on the page, it's supposed to replace the current image and description with the image and description for the selected date that is retrieved asynchronously. However, what's happening is sometimes the html with the new data just get's appended to the bottom of the page so the image and description for the previously selected date is still there.
Can anyone tell me how I can make sure the previous data is removed? Or could this be some kind of race condition?

<svelte:head>
    <title>All About Space: Photo of the day</title>
</svelte:head>

Photo of the day on {formattedDate}

Choose a day to see the photo of the day for that date:
        <input type="date" bind:value="{selectedDate}" max="{todaysDate}" >

    {#if imageData===""}

error.. no data for the selected date

    {:else}
        {#await imageData}
            <Loader show="true"/>
        {:then image}

{image.title}

                    {image.explanation}

        {:catch error}

        {error.message}

        {/await}

    {/if}

A: There is an active bug for transitions in await blocks. It seems to be your issue: https://github.com/sveltejs/svelte/issues/1591


text:
Q: export model to PMML I have labeled data, couple categorical variables and two binary target variables.
header for example;
column_1,column_2,column_3,column_4,target_1,target_1

how do I export it to PMML ? the only example I've found is with unsupervised data
import pandas

iris_df = pandas.read_csv("Iris.csv")

from sklearn2pmml import PMMLPipeline
from sklearn2pmml.decoration import ContinuousDomain
from sklearn_pandas import DataFrameMapper
from sklearn.decomposition import PCA
from sklearn.feature_selection import SelectKBest
from sklearn.preprocessing import Imputer
from sklearn.linear_model import LogisticRegression

iris_pipeline = PMMLPipeline([
    ("mapper", DataFrameMapper([
        (["Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width"], [ContinuousDomain(), Imputer()])
    ])),
    ("pca", PCA(n_components = 3)),
    ("selector", SelectKBest(k = 2)),
    ("classifier", LogisticRegression())
])
iris_pipeline.fit(iris_df, iris_df["Species"])

from sklearn2pmml import sklearn2pmml

sklearn2pmml(iris_pipeline, "LogisticRegressionIris.pmml", with_repr = True)

A: The provided example is about supervised classificication - the y argument of the Pipeline#fit(X, y) method is the label.
Your case would look like this:
pipeline = PMMLPipeline(
  ("mapper", DataFrameMapper([
    (feature_column, LabelBinarizer()) for feature_column in ["column_1", "column_2", "column_3", "column_4"]
  ])),
  ("classifier", LogisticClassification())
)
pipeline.fit(df, df["target_1"])


text:
Q: Placeholder variable for table name in fetchAll function I have a function in PHP that uses a SELECT SQL query.
I using placeholder variable (?) in the query like this. (this placeholder is for table name in mysql database):
protected function _fetchPreviousShiftData($table, $report_time)
{

$query = "SELECT * FROM ? WHERE report_date=? and shift=?";
$previousShiftData = $this->_getDbConnection()->fetchAll($query,array($table, date("Y-m-d"), $this->_shiftValue($report_time, 8)));

return $previousShiftData;
}

but I have an error in $table variable, how should I use "?" for $table variable?
The error is like this:
PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''adsl_support' WHERE report_date='2013-04-06' and shift='18-2'' at line 1' in C:\php_shared_lib\Zend\Db\Statement\Pdo.php:228

A: You can't use this for table name or fields names...
Only for passed values...
You can make a list of the possibles table names,
check it and build query with
"SELECT FROM `$table`..."

if check passed


text:
Q: How to set i response status n Sprint cloud function for azurei I am new to Azure Functions, I would like to integrate Spring Cloud Function with Azure Function, I referred many articles but could not get any information regarding how to set HTTP response status and customize content produce from API using Spring cloud.
I am using the following Maven dependency:
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-function-adapter-azure</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-function-web</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </exclusion>
  </exclusions>
  <scope>provided</scope>
</dependency>

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <!--<version>5.0.10.RELEASE</version>-->
</dependency>

This is supposed to run on Azure Serverless platform.
1: Spring Function code:
public class AuthorizationFunction implements Function<String,ServicesOut> {

    @Autowired
    private someservice;

    @Override
    public DomainObject apply(String entitlement) {

    }
}

2: Spring Function Handler integrating Azure
public class EntitlementHandler extends AzureSpringBootRequestHandler<String, ServicesOut> {

    @FunctionName("functionname")
    public DomainObject execute(@HttpTrigger(name = "request", methods = {HttpMethod.GET}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage request,
             ExecutionContext context) {

     // Depending on Function.apply value set httpresponse status and details
     // set 201 when success
     // set 401 when failure
     // set 500 for other failures
   }
}

Any help will be much appreciated.

A: You can custom your response by return a HttpResponseMessage. For more details, you may refer to: HttpRequestMessage and HttpResponseMessage
Here is my test:
1. Download the Azure function with spring function sample
git clone https://github.com/Azure-Samples/hello-spring-function-azure.git

2. Modify the class as following
Class HelloHandler
public class HelloHandler extends AzureSpringBootRequestHandler<HttpRequestMessage<Optional<User>>, HttpResponseMessage> {

    @FunctionName("hello")
    public HttpResponseMessage execute(
            @HttpTrigger(name = "request", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<User>> request,
            ExecutionContext context) {

        context.getLogger().info("Greeting user name: " + request.getBody().get().getName());
        return handleRequest(request, context);
    }
}

Class hello() function bean
@SpringBootApplication
public class HelloFunction {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(HelloFunction.class, args);
    }

    @Bean
    public Function<HttpRequestMessage<Optional<User>>, HttpResponseMessage> hello() {
        return request -> request.createResponseBuilder(HttpStatus.ACCEPTED).body(request.getBody().get().getName()).build();
    }
}

3. Result
As I chenged the function, so I removed all the test class. Because it did not match any more. If you need the test, you should chage the test logic.
Then I just ran the function in terminal with: mvn clean package azure-functions:run
And then I made a http request, and got the following response:

you can see that the response http status is "Accepted", which is correct as I set in the function.

A: I have pushed a sample project to Github, Check it out.
This project has spring cloud functions in azure that can handle request and response effectively. I have added Firebase authentication to the sample API and also configured the database operations with JPA.


text:
Q: Python - Render a Slanted Font This question is inline with the answer in my previous question in Stackoverflow.
I am creating a program that converts a text to image. I want to render it in using the font OCR A. But since OCR A font, has no corresponding font file for italics, I have to do the slanting of the upright font manually.

Upright Font

Slanted Font

Below is my initial code :
 from PIL import Image
 from PIL import ImageDraw
 from PIL import ImageFont
 import numpy as np

 #Returns the text size in terms of width and height.
 def getSize(txt, font):
     testImg = Image.new('RGB', (1, 1))
     testDraw = ImageDraw.Draw(testImg)
     return testDraw.textsize(txt, font)

 text = 'CNN Font Recognition Model'
 font_size = 12
 font = ImageFont.truetype('ocra.ttf' , font_size)
 #ocra.ttf is a font file for OCR A Regular font (I have to render it slanted)

 width, height = getSize(text, font)

 #Creates an image with white background of constant size.
 img = Image.new('RGB',(width, height), 'white')
 d = ImageDraw.Draw(img)
 d.text((0,0), text, fill='black', font=font)
 img.save('slanted_ocr_a.png')

How do I manually slant the upright OCR A font? Thanks.
You can download a sample ocra.ttf file here.

A: This answer to a similar question is probably the easiest way, although it is not exactly what you want to do. Basically you render the upright font into an image then slant (shear) the entire image using PIL's Image.transform method.
To accomplish exactly what you are asking (slanting the font before imaging it) is possible, but would require a lot of work overriding PIL's truetype scheme to have the underlying font engine (FreeType) perform the slant transformation at the font level. PIL's truetype interface simply doesn't have a way to express a transform, so you'd have to override/patch it to pass that all the way down to FreeType where the font is set up.
Another option might be to skip PIL's truetype scheme and use a Python font-rendering library that allows you to set the font transform directly, then scrape the pixel data from that into your PIL Image. One such library is freetype-py.


text:
Q: Returning an anonymous function/lambda that is a curried function Just trying to get a handle on some FP patterns.
Can someone show and explain a function that returns an anonymous method/lambda which is also a curried function?

A: Here is an example:
val foo: Int => Int => Int = x => y => x + y

Function foo has a signature of Int => Int => Int which means that calling it for some argument (what is also called partial application), it returns another function of signature Int => Int:
val bar: Int => Int = foo(1)

That you can call following way:
val result = bar(2)
result == 3

A:
Can someone show and explain a function that returns an anonymous method/lambda which is also a curried function?

One of the easy ways to see it is to create a currried sum method:
def sum(x: Int): Int => Int = y => x + y

And call it:
val curried: Int => Int = sum(1)
println(curried(2)) // will yield 3

If you want to transform the method to a function, you can use eta expansion:
val sumFunc: Int => Int => Int = sum _
println(sumFunc(1)(2))


text:
Q: TS will not infer possible undefined when destructuring empty array When looking at the inferred type of destructured element, it will assume the array is never empty.
const x: number[] = [];
const [first] = x; // first inferred as number

console.log(first); // undefined

if (first !== undefined) {
    // ...
}

Playground Link
This leads to an interesting behavior with TSLint rule "strict-type-predicates" for example, that will mark the if statement as always true, while it's in fact isn't.
Am I missing something and it's normal behavior?

A: UPDATE for TypeScript 4.1
It is still the intended behavior that undefined is not included in the domain of index signature properties, for the reasons listed below.  However, since this is an oft-requested feature, the TypeScript team has (somewhat grudgingly?) relented and added the --noUncheckedIndexedAccess compiler flag.  If you enable that (and it is neither enabled by default, nor included in the --strict compiler flag, so you need to do it explicitly), you will start getting the behavior you presumably want.
Note that this is actually not exactly the same as adding undefined yourself.  Indexed access will add undefined:
// --noUncheckedIndexedAccess is enabled

const x: number[] = [];
const [first] = x; // number | undefined

console.log(first); // undefined

if (first !== undefined) {
    first.toFixed(); // okay
}

But for..of loops and array functional programming methods will still act as though undefined is not possible (that is: as if sparse arrays do not exist):
for (const n of x) {
    n.toFixed(); // no error, yay!
}

x.map(n => n.toFixed()); // no error, yay!

So possibly you want to enable that flag.  Keep in mind that some common array/dictionary manipulation techniques may still be "annoying", which is why it isn't part of the --strict family.
Playground link to code

ORIGINAL ANSWER
It's the intended behavior. See microsoft/TypeScript#13778 for more information.  This issue is a request to allow index signature property types to automatically include undefined in their domain, and while the issue is still open, it is fairly clear that it will not be implemented.  See this comment for example.
It is not a design goal of TypeScript (see #3 on the list) for the type system to be perfectly sound or correct (despite the heartache that people like me feel when we think about this too much; I've joked before about starting a TypeScript Unsoundness Support Group to help people deal with this).  Instead, there's a tradeoff between correctness and usability.
The language maintainers note that there's a lot of real-world code out there which indexes into arrays without checking for possible undefined values everywhere, and that enforcing this check would turn a simple for-loop into a tedious exercise of either performing checks or using type assertions.  The problem is (see this comment) that the compiler cannot easily tell the difference between safe and unsafe indexes into array types.  So either the compiler assume that the property won't be undefined and have false negatives from the compiler when that assumption is wrong, as happens now.... or, assume the property might be undefined and have false positives from the compiler when the indexing operation is actually safe.  The argument by the language maintainers is that such false positives would happen so often that developers would condition themselves to ignore the errors entirely, thus making it just as useless as the current situation while being more annoying.  So they will leave it as it is now.

If you want, you can always add undefined to the element type yourself, assuming such issues are more likely to show up for you in your use cases:
const x: (number | undefined)[] = [];
const [first] = x; // number | undefined

console.log(first); // undefined

if (first !== undefined) {
    first.toFixed(); // okay
}

but keep in mind that you'll run into the annoying situation if your use cases follow the normal patterns:
for (const n of x) {
    n.toFixed(); // error, annoying
    if (typeof n !== "undefined") n.toFixed(); // okay
    n!.toFixed(); // okay
}

x.map(n => n.toFixed()); // error, annoying
x.filter((n): n is number => typeof n !== "undefined").filter(n => n.toFixed()); // okay
x.map(n => n!.toFixed()); // okay

Okay, hope that helps; good luck!
Playground link to code


text:
Q: iOS Background Access Token Refresh I am looking to extend the expiry time of an access token by refreshing the token in the background. The expiry time is currently set to 30 minutes (server side) and this value is not to be changed, the idea is that every 29 minutes I will call a method that refreshes the access token to keep it alive for a further 1 and a half hours (meaning the access token stays alive for almost 2 hours). I have read that background tasks should take up to 5 second to complete then if more time is required to use UIKit, although this will only allow a further few minutes to complete the tasks needed.
Are there any special circumstances that will allow me to do this in background, or is there a better way to do this? Thank you for any help!

A: In AppDelegate.swift do this.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    Timer.scheduledTimer(timeInterval: (60.0 * 29.0), target: self, selector: #selector(self.doThisEvery29Min), userInfo: nil, repeats: true)
    return true
}

@objc func doThisEvery29Min () {
    if Constant.uToken != nil {
        ServiceManager.sharedInstance.RefreshTokens() {
            (result) in
            switch result {
            case .Success(let responce):
                // update token
            case .FailureDueToService(let error):
                print(error)
                break
            case .Failure(let error):
                print(error)
                break
            }
        }
    }
}


text:
Q: Goland - Unresolved dependency I want the goland to find the dependencies that I installed using go get
It was working but now when I open it marks as unresolved

I already tried go mod tidy but it didn't work

A: Did you try to sync dependencies as follow link

enter image description here

And make sure you specified the location of your Go installation in $GOROOT


text:
Q: Jquery filter function May be you can help me.
I need to filter
* tags using an array as follows:

My example textActor
         Group one

My example text 2 posted by Andrew

My example text 3

         Actor
         Group one

Actor
         Ten groupMy example text.

6 element. Actor

Group other

7 element.

First group

First group

My other group

My array:
var ids=["1","8","3","4","5"]
And I need to get this output (LI tags containing A tag with groupid in array):

         Actor
         Group one

6 element. Actor

Group other

First group

My other group

Thank you guys!

A: can you not just use :eq() Selector


text:
Q: Show image inside modal, Even if it's the same image I have a file input that allows me to upload an image, After selecting an image the modal is opened with the image inside the modal.
Here is a Fiddle Example:
Here is the code:

$("#input").on("change", function(e) {
  var _URL = window.URL || window.webkitURL,
      file = this.files[0],
      image = new Image();
  $('#image').attr('src',  _URL.createObjectURL(file));
  $(image).ready(function($) {
   $('#modal').modal('show');
  });
  window.URL.revokeObjectURL(image.src);
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">

<input type="file" id="input" name="image">

Image Upload

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

But if I close the modal and try to upload the same image it's not opened, As I'm using change.
I tried to use click:
$("#input").on("click", function(e) {});

But I get these errors and the modal is not shown:
Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.

I will then check the image dimensions and size.
So how to make it work that if I choose the same image again it will be opened?

A: You just need to reset your input's val attribute to an empty string in your change event handler.
Your trouble is that the input's change event doesn't get called when its val attribute doesn't change. Obvious on the face of it, but you're probably confusing your img and your input elements. Not only do you need to call revokeObjectURL to free up browser memory, you also need to reset the value of your input. Otherwise, if you open the same file, nothing changes in your input element so its change event doesn't get called. Revoking the URL in the img element is irrelevant to the input element.

$("#input").on("change", function(e) {
  var _URL = window.URL || window.webkitURL,
      file = this.files[0],
      image = new Image();
  $('#image').attr('src',  _URL.createObjectURL(file));
  $(image).ready(function($) {
   $('#modal').modal('show');
  });
  window.URL.revokeObjectURL(image.src);
  $(e.target.id).val(''); // <- ADD THIS
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">

<input type="file" id="input" name="image">

Image Upload

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

A: Reset your input value on click

$("#input").on("change", function(e) {
  var _URL = window.URL || window.webkitURL,
      file = this.files[0],
      image = new Image();
  $('#image').attr('src',  _URL.createObjectURL(file));
  $(image).ready(function($) {
   $('#modal').modal('show');
  });
  window.URL.revokeObjectURL(image.src);
});
$("#input").on("click", function(e) {
var value= $('#input').val();
  if(value){
    $('#input').val('');
  }
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">

<input type="file" id="input" name="image">

Image Upload

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


text:
Q: Pandas cx_Oracle - Insert failing I have this code to use cx_oracle to insert data to a table, but getting some error.
My data looks like this:
[['BOB', 20190619, 118.16, 118.38, 116.05, 117.8, 'No', 117.8, 117.8, 117.8, 0.0, 0.0, 0.0, nan, nan, nan, nan]

My attempts at the code is this:
sql='INSERT INTO stockstats VALUES(:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13,:14,:15,:16)'

n = 0
for i in df.iterrows():
  cursor_1.execute(sql,df_list[n])
  n += 1

cursor_1.execute(sql,df_list[n])
cx_Oracle.DatabaseError: ORA-01036: illegal variable name/number

I also tried this, and get the same issue:
sql = 'INSERT INTO stockstats VALUES(:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13,:14,:15,:16)'
cursor_1.executemany(sql, df.values.tolist())

cursor_1.executemany(sql, df.values.tolist())
cx_Oracle.DatabaseError: ORA-01036: illegal variable name/number

Was wondering what I was doing wrong.
Any hep would be great.

A: A couple of possibilities for you to investigate:

*

*make sure that all of the rows have the same number of columns (by printing the length prior to calling execute())

*check the list of bind names that cx_Oracle thinks exist by calling cursor.prepare(sql) followed by cursor.bindnames()
Both of these checks should help discover the source of the issue -- whether a typo or "bad" input data.

A: It's not clear what you have within the dataframe df whether they're columns or rows. Even if you consider them as columns, the number of comma-seperated elements(17) does not conform to the number of bind variables(16) within the VALUES list of the sql string.
Considering as a regular insertion from a dataframe along with those comma-seperated elements as columns, fixing the number of columns depending on the number of column of the table, prefer using df.to_sql with connection through use of sqlalchemy.create_engine during the insertion such as
import pandas as pd
import sqlalchemy as db

engine = db.create_engine('oracle+cx_oracle://un:pwd@dbhost:port/dbname')
conn = engine.connect()

try:
    df.to_sql('stockstats', con=engine, if_exists='append', index=False )
    engine.execute("SELECT * FROM stockstats").fetchall()

against issues due to NaN values


text:
Q: How to set JPA Eclipse Link connection timeout? I'm using jpa with eclipse link and my application throw exception when the net work connection is poor i want to increase time out or another solution to this problem

A: use this in a query
 query.setHint(QueryHints.JDBC_TIMEOUT, x);

Edit: you can set or override javax.persistence.query.timeout by query.setHint("javax.persistence.query.timeout", x); but the hint can be not considered in the case of different databases or different persistence providers


text:
Q: how to pass jwt token into the header I make web application using react js, node, express
when I login the error message appear says "No token attached"
now I need to put a jwt token into header how can I do that
this is my code:
import { webToken } from "../crypto/web_token.js";
import { responses } from "../classes/responses.js";

export const verifyRequest = (req, res, nex) => {
  try {
    if (!req.headers.authorization) {
      throw Error("no token attached");
    }

    const token = req.headers.authorization.split(" ")[1];

    const payload = webToken.verify(token);

    req.user = payload;

    nex();
  } catch (error) {
    res.json(new responses.Error(error.message));
  }
};

another code: web_token.js
import jsonwebtoken from "jsonwebtoken";
import { errors } from "../classes/errors.js";

const secret = "#########";

export const webToken = Object.freeze({
  generate: (data, expiry = "1hr") => {
    try {
      return jsonwebtoken.sign(data, secret, { expiresIn: expiry });
    } catch (error) {
      throw new errors.Logic("Internal error from the bcrypt hashing", "jwt");
    }
  },

  verify: (token) => {
    try {
      const data = jsonwebtoken.verify(token, secret);

      return data;
    } catch (error) {
      throw new errors.Authentication(
        error.message.replace("jwt", "Token"),
        "jwt"
      );
    }
  },
});

A: here is the template, take a look
var axios = require('axios');
var data = JSON.stringify({
  "value1": "val1"
});

var config = {
  method: 'post',
  url: 'http://localhost:3000/GetText',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  },
  data : data
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});


text:
Q: Why strcpy() copies every string to first index of 2d array I have a problem with filling a 2d char array with strings from a text file. I am trying to fill 2d array with specific strings from my file, but when I try to print out the first string at position 0 I get all strings connected as if they were one string. I tried it on more simple code and it worked where the strings were declared manually and weren't taken from a file. I've read something about the function itself but couldn't find anything which could couse a problem.
'''
char mer_mod[20], input_mer[20], input_mer_vel[20], data[25];
char line[20], time_arr[57][4];
double val_arr[57];
int flag = 0, offsets[5], n=1, j = 0, dates_arr[57], min_date, k =0;

if(strcmp(mer_mod, input_mer_vel) == 0 && flag == 1)
{
    flag = 0;
    for(int i=0; i<3; i++)
    {
        memset(data,0,sizeof(data));
        fgets(data, sizeof data, *pp_file);

        switch (i)
        {
            case 0: val_arr[k] = strtod(data, NULL); break;
            case 1: strcpy(time_arr[k], data); break;
            case 2: dates_arr[k] = atoi(data); break;
        }
    }
    printf("%s\n", time_arr[0]);
    k++;
}

'''
When I print out string from the array at 0th index I get output from the first picture. In the second picture is output which I desire, but I get this output only if I'm printing the string right after it was added to the array.
time_arr is 2d char array, data is a character array where each line from the file gets stored.

A: This
 char time_arr[57][4];

Is an array of 57 elements of size 4
This
 data[25];

Is a string of 25 characters
So this
 strcpy(time_arr[k], data);

is wrong.  If data is longer than 3 characters (you have to leave space for the terminator) it will overrun the size of the array element.

Note, based on the results it looks like you just do not have space for the null terminator -- it looks like char time_arr[57][5]; would solve your problem


text: Q: FFT to compare two audio Files I am using the minim library in processing which is able to give me the FFT of an audio file. How can I use that data to compare it with another audio file and output the similarity of the two audio files ?


text:
Q: How to check if a nested member exists Rapidjson I have a JSON File like this
{
    "Person":[
        {
            "name":"Frank",
            "age":69,
            "amount_of_jobs":9,
            "years_worked":6,
            "unemployed":true,
            "job_seeking":false
        },
        {
            "name":"Tom",
            "age":23,
            "amount_of_jobs":2,
            "years_worked":6,
            "unemployed":false,
            "job_seeking":false
        },
        {
            "name":"Mike",
            "age":31,
            "amount_of_jobs":5,
            "years_worked":12,
            "unemployed":false,
            "job_seeking":false
        },
        {
            "name":"Herb",
            "age":45,
            "amount_of_jobs":7,
            "years_worked":29,
            "unemployed":false,
            "job_seeking":true
        }
    ],
    "Companies":[
        {
            "name":"Slave Inc"
        },
        {
            "name":"Some LLC"
        },
        {
            "name":"Other PTY LTD"
        },
        {
            "name":"A company"
        }
    ]
}

and I would like to check if the right keys are in the file.
What I have managed is to check if Person and Companies exists with this code snippet
if (!document.HasMember("Person") || (!document.HasMember("Companies")))
{
    std::cout << "KEY NOT FOUND" << std::endl;
    file.close();
    return false;
}
else
{
    std::cout << "ALL GOOD" << std::endl;
}

But when I try to check if name or years_worked (which are nested members) exists it does not work.
I've tried:
if (!document.HasMember("name") || (!document.HasMember("years_worked")))
{
    std::cout << "KEY NOT FOUND" << std::endl;
    file.close();
    return false;
}
else
{
    std::cout << "ALL GOOD" << std::endl;
}

and
if (!document["Person"].HasMember("name") || (!document["Person"].HasMember("years_worked")))
{
    std::cout << "KEY NOT FOUND" << std::endl;
    file.close();
    return false;
}
else
{
    std::cout << "ALL GOOD" << std::endl;
}

and all I get is:

Assertion failed: (IsObject())

How could I fix this issue?
Thanks in advance!

A: Person is an array so you should access it like an array i.e. by an index.
Example:
document["Person"][0].HasMember("name")

The same goes for Companies.


text:
Q: Download a login page and its subfolders I want to download a specific page and its subfolders/subpages, which could for instance be the primary page https://example.com/pageaboutlitterature/ and then something like subpages/subfolders that looks like this: https://example.com/pageaboutlitterature/writers...
The problem is that I use a login to acces the page. I tried downloading it with HTTRACK and filled out "Authentication", but it still only downloaded the site as it is when you are logged out.
You can see what I mean here:
enter image description here
Anybody who has suggestions?

A: Give this one a shot. It worked for me long back. I guess you are making some mistake while HTTrack authetication capture process. Be sure to follow the instruction and set correct proxy.


text:
Q: Cross Thread after 20 seconds running I receive data from a serial port and I show all the received data in the format they arrive in a multiline text box. This is my serial monitor "txtOutput".
After I have validated the data as complete messages and filtered out few characters (in a separate class), I need to show those data to additional text boxes (textBox7, 2 and 6).
For some reason that I am not able to understand, after 10 to 20 seconds of debugging, with messages coming in continuously (200-300 ms), I get a cross thread error, "Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on".
This is my code:
Serial port reading
 private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                SetText(serialPort1.ReadExisting());
            }
            catch (Exception ex)
            {
                SetText(ex.ToString());
            }
        }

Delegate SetText
delegate void SetTextCallback(string text);

Receive the serial port data and elaborate
  private void SetText(string text)
        {
            if (this.txtOutput.InvokeRequired)
            {
             SetTextCallback d = new SetTextCallback(SetText);
             this.BeginInvoke(d, new object[] { text });
            }
            else
            {
               txtOutput.AppendText(text);
            }
               string a="", b="", c="";
                    string invia = text.ToString();
                    Stripper strp = new Stripper();
                    strp.Distri(invia, out a, out b, out c);
                    textBox7.Text = a; // Current
                    textBox2.Text = b; //Temperature
                    textBox6.Text = c; //RPM
               }
           }

This is one of my first app.
What do I need to change to avoid the cross thread error and where is the mistake I made?

A: You've got some code that changes UI elements outside the part protected by the InvokeRequired. All the text boxes need to be protected too.
Try this:
private void SetText(string text)
{
    if (this.txtOutput.InvokeRequired)
    {
        SetTextCallback d = new SetTextCallback(SetText);
        this.BeginInvoke(d, new object[] { text });
    }
    else
    {
        txtOutput.AppendText(text);
        string a="", b="", c="";
        string invia = text.ToString();
        Stripper strp = new Stripper();
        strp.Distri(invia, out a, out b, out c);
        textBox7.Text = a; // Current
        textBox2.Text = b; //Temperature
        textBox6.Text = c; //RPM
    }
}


text:
Q: Spring data jedis connection pool configuration A quick impatient configuration for starter of Jedis in Spring is
<bean
        id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        p:host-name="${redis.hostname}"
        p:port="${redis.port}"
        p:use-pool="${redis.use.pool}"
/>

I understand that Jedis uses in backend the Apache common pool. However the pool configuration is something I can't figure out to configure by Spring DI in xml by looking at JedisConnectionFactory
============ Update ===================
For the completeness, defining the solution.
<!-- Jedis Connection Pool configuration -->
    <bean
        id="jedisPoolConfig"
        class="redis.clients.jedis.JedisPoolConfig"
        p:maxTotal="30"
        p:maxIdle="10"
    />
<!-- Redis Connection Factory -->
    <bean
        id="jedisConnFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        p:host-name="${redis.hostname}"
        p:port="${redis.port}"
        p:password="${redis.password}"
        p:use-pool="${redis.use.pool}"
        p:pool-config-ref="jedisPoolConfig"
    />

A: You can create another bean of class JedisPoolConfig (it extends apache GenericObjectPoolConfig) and set properties you need. Then set that bean into your jedisConnFactory with p:pool-config-ref.


text:
Q: Why it is not possible to use an initializer_list to initialize a vector of unique_ptr's? I'm wondering why initializer_list doesn't work with unique_ptr:
std::vector<std::unique_ptr<int>> vptr = {std::make_unique<int>(1), std::make_unique<int>(2)};

do not compile.
However:
std::vector<std::unique_ptr<int>> vptr(2);
vptr[0] =std::make_unique<int>(1);
vptr[1] =std::make_unique<int>(2);

compile.
and
std::vector<int*>vint={new int{1},new int{2}};

or
 std::vector<std::shared_ptr<int>> vptr= {std::make_shared<int>(1), std::make_shared<int>(2)};

compile.
The unique_ptr variant is giving this error message in clang:
In file included from main.cpp:2:
In file included from /usr/local/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.9.0/../../../../include/c++/4.9.0/vector:62:
/usr/local/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.9.0/../../../../include/c++/4.9.0/bits/stl_construct.h:75:38: error: call to deleted constructor of 'std::unique_ptr<int, std::default_delete<int> >'
    { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
                                     ^   ~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/local/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.9.0/../../../../include/c++/4.9.0/bits/stl_uninitialized.h:75:8: note: in instantiation of function template specialization 'std::_Construct<std::unique_ptr<int, std::default_delete<int> >, const std::unique_ptr<int, std::default_delete<int> > &>' requested here
                std::_Construct(std::__addressof(*__cur), *__first);
                     ^
/usr/local/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.9.0/../../../../include/c++/4.9.0/bits/stl_uninitialized.h:125:2: note: in instantiation of function template specialization 'std::__uninitialized_copy<false>::__uninit_copy<const std::unique_ptr<int, std::default_delete<int> > *, std::unique_ptr<int, std::default_delete<int> > *>' requested here
        __uninit_copy(__first, __last, __result);
        ^
/usr/local/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.9.0/../../../../include/c++/4.9.0/bits/stl_uninitialized.h:278:19: note: in instantiation of function template specialization 'std::uninitialized_copy<const std::unique_ptr<int, std::default_delete<int> > *, std::unique_ptr<int, std::default_delete<int> > *>' requested here
    { return std::uninitialized_copy(__first, __last, __result); }
                  ^
/usr/local/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.9.0/../../../../include/c++/4.9.0/bits/stl_vector.h:1284:11: note: in instantiation of function template specialization 'std::__uninitialized_copy_a<const std::unique_ptr<int, std::default_delete<int> > *, std::unique_ptr<int, std::default_delete<int> > *, std::unique_ptr<int, std::default_delete<int> > >' requested here
            std::__uninitialized_copy_a(__first, __last,
                 ^
/usr/local/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.9.0/../../../../include/c++/4.9.0/bits/stl_vector.h:377:2: note: in instantiation of function template specialization 'std::vector<std::unique_ptr<int, std::default_delete<int> >, std::allocator<std::unique_ptr<int, std::default_delete<int> > > >::_M_range_initialize<const std::unique_ptr<int, std::default_delete<int> > *>' requested here
        _M_range_initialize(__l.begin(), __l.end(),
        ^
main.cpp:10:42: note: in instantiation of member function 'std::vector<std::unique_ptr<int, std::default_delete<int> >, std::allocator<std::unique_ptr<int, std::default_delete<int> > > >::vector' requested here
std::vector<std::unique_ptr<int>> vptr = {std::make_unique<int>(1), std::make_unique<int>(2)};
                                         ^
/usr/local/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.9.0/../../../../include/c++/4.9.0/bits/unique_ptr.h:356:7: note: 'unique_ptr' has been explicitly marked deleted here
      unique_ptr(const unique_ptr&) = delete;
      ^
1 error generated.

A: The constructor for vector<T> taking an initializer_list<T> copies the elements from the initializer list into the vector. This does not work when you're dealing with an uncopyable type: the design of unique_ptr<T> prevents copies from being made. It does allow moving, which is why assignment works: make_unique returns an rvalue, for which the compiler knows it's safe to move.
You'd need some sort of constructor taking an initializer_list<T &&>, but C++ doesn't have such a constructor (nor indeed, as dyp pointed out, does the type initializer_list<T &&> even function).


text:
Q: Angular 12 in .NET Core project - Routing Not Working I'm following a tutorial on how to create a specific project in Angular 10 with .NET Core Web API and SQL Server functionality. I'm using Angular 12 on my setup.
The tutorial functions up to the routing portion.
-I've created the ./app/department and ./app/employee folders and the components them. So those files are there and they read:

department works!

and

employee works!

-In the ./app folder, I've modified app-routing.module.ts to include importing the those components and adding them to the routes. So the routing file knows about my component files and it knows that URL+'/employee' should bring up the employee component and URL+'/department' should bring up the department component. That is all I'm trying to do.
import { EmployeeComponent } from './employee/employee.component';
import { DepartmentComponent } from './department/department.component';

const routes: Routes = [
  {path: 'employee', component: EmployeeComponent},
  {path: 'department', compoennt: DepartmentComponent}
];

-In the ./app folder, I've modified shared.service.ts to include methods and observables related to the urls. I'm not sure how any of these provide me routing functionality I need, but the /api/employee, /api/department, and /api/GetAllDepartmentNames actually work.
export class SharedService {
readonly APIUrl = "http://localhost:5000/api";
readonly PhotoUrl = "http://localhost:5000/Photos";
  constructor(private http:HttpClient) { }

//department code is identical to employee code, so it's omitted for brevity

  getEmpList():Observable<any[]>{
    return this.http.get<any>(this.APIUrl+'/Employee');
  }

  addEmployee(val:any){
    return this.http.post(this.APIUrl+'/Employee',val);
  }

  updateEmployee(val:any){
    return this.http.put(this.APIUrl+'/Employee',val);
  }

  deleteEmployee(val:any){
    return this.http.delete(this.APIUrl+'/Employee/'+val);
  }

  UploadPhoto(val:any){
    return this.http.post(this.APIUrl+'/Employee/SaveFile',val);
  }

  getAllDepartmentNames():Observable<any[]>{
    return this.http.get<any[]>(this.APIUrl+'/Employee/GetAllDepartmentNames');
  }

-In ./app, I've modified app.module.ts to import the shared service, HttpClientModule, Forms Module, and Reactive Forms Module. This is in some way different to regular list of library imports at the top of these other files.

import { HttpClientModule } from '@angular/common/http';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    DepartmentComponent,
    ShowDepComponent,
    AddEditDepComponent,
    EmployeeComponent,
    ShowEmpComponent,
    AddEditEmpComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [SharedService],
  bootstrap: [AppComponent]
})
export class AppModule { }

-Finally, in app.component.html in the main project folder, I've added the call for router outlet.

some text

<router-outlet></router-outlet>

-I then switch from Visual Studio Code back to Visual Studio, run the project, and I cannot bring up the contents of ./app/department/department.component.html by navigating to the /department extension on the localhost:5000 location where the project displays, or to its employee.component.html counterpart (http://localhost:5000/employee).
The error I receive is a pretty basic, 'your webpage doesn't work' error:
This localhost page can't be found.
No webpage was found for the web address: http://localhost:5000/department
HTTP ERROR 404
I've combed over this thing for punctuation and spelling and all the little errors. Most of the posted questions about this issue use a different form of routing than what I'm using, which requires more knowledge of what these systems do than I have. The others are about more detailed creation of routes based on controllers and actions, which I'm working on yet.
I just don't understand why this routing isn't working. It seems like a simple setup.

A: are you running ng serve? That would start up the angular project that you could then go to http://localhost:4200. If that is not working for you, you might have to make changes to your proxy, something like:
{
  "/api/*": {
    "target": "http://localhost:5000",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}

My hope is that this gives you some information to lead you in the right direction based on what I know the problem to be for you.


text:
Q: TypeError: set_value(): incompatible function arguments This code should be simple enough. But I can't get it right. And, I don't find answer from previous similar questions. Is it a pydrake issue or just I don't use it in the right way?
TypeError: set_value(): incompatible function arguments. The following argument types are supported:
    1. (self: pydrake.common.value.Value[QueryObject_[float]], arg0: pydrake.geometry.QueryObject_[float]) -> None
Invoked with: <pydrake.common.value.Value[QueryObject_[float]] object at 0x1298c2c30>, (0, 0)

from pydrake.all import *
from underactuated import ManipulatorDynamics

x= [1,2,3,4]
u= [1,1]

plant = MultibodyPlant(time_step=0)
parser = Parser(plant)
parser.AddModelFromFile(FindResource("models/double_pendulum.urdf"))
plant.Finalize()

context = plant.CreateDefaultContext()
context.SetContinuousState(x)
plant.get_actuation_input_port(0).FixValue(context,u)

A: Turns out there was a real bug here.  It's fixed in https://github.com/robotlocomotion/drake/pull/14343
You should be able to call plant.get_actuation_input_port(0).FixValue(context,u) without having to go through BasicVector.


text:
Q: DataGrid ComboBox has no selected item when clicked the first time Recently I asked similar questions here and here, but could not fix the issue properly.
I have a DataGrid with ComboBox that can contain either a selected item or not. But if it does then the ComboBox should select it when the dropdown is opening which is doesn't.

Currently I have this code which works except when opening the dropdown the first time. It is nothing selected.
 <DataGridTemplateColumn Header="Company">
     <DataGridTemplateColumn.CellEditingTemplate>
         <DataTemplate>
             <ComboBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=DataContext.Companies}"
                       SelectedItem="{Binding Company, Converter={StaticResource NullValueConverter}}"/>
         </DataTemplate>
     </DataGridTemplateColumn.CellEditingTemplate>
     <DataGridTemplateColumn.CellTemplate>
     <DataTemplate>
         <TextBlock Text="{Binding Company, Converter={StaticResource NullValueConverter}}" />
      </DataTemplate>
   </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

The NullValueConverter prevents exceptions if the Company is null.

A: *

*If your company was not a string as you mentioned in the comments then it can't display the Name unless you set
DisplayMemberPath="Name" or create an ItemTemplate.

*You should use SelectedItem="{Binding
Company,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" to update
the value as soon as it changes because if you don't it will only
raise ProperyChanged when you focus another cell or row.

*if your Property was immutable or a value type then you
should use SelectedValue="{Binding Path=Company,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"  SelectedValuePath="Content"
.


text:
Q: ThreeJS orthographic camera: Adjusting size of scene to window In ThreeJS, I'm using the OrthographicCamera because I have several objects which should be shown from the front, without any perspective distortion. This works fine with one issue: the bunch of objects I created should always roughly fill the screen, but not be much smaller or larger. Using e.g.
var factor = 4.5;
this.camera = new THREE.OrthographicCamera(-window.innerWidth / factor, window.innerWidth / factor, window.innerHeight / factor, -window.innerHeight / factor, 1, 1000);

... I can get it to run fine on 1920x1080 pixel resolution, but when I then resize the window to something smaller and reload the page, the objects will start to be too large, as they act as if they were fixed. (When using the CombinedCamera with perspective, the resizing is dynamic and works well.) How to fix this using the OrthographicCamera? Or is there a trick where I can turn off perspective in the CombinedCamera?
Thanks!

A: I am not sure if this will help with your particular issue or not. I am not sure if this is correct or not, or if there is a better or more standard way to handle this. But this is what I use in my orthographic code so far. It doesn't work perfect by any means, but you can try it out. Post back and let me know if you figure out anything better.
        $(window).on('resize', function () {
            // notify the renderer of the size change
            renderer.setSize(window.innerWidth, window.innerHeight);
            // update the camera
            camera.left = -window.innerWidth / camFactor;
            camera.right = window.innerWidth / camFactor;
            camera.top = window.innerHeight / camFactor;
            camera.bottom = -window.innerHeight / camFactor;
            camera.updateProjectionMatrix();
        });


text:
Q: The name '$exception' does not exist in the current context Today I was debugging an application in my work. I proceeded to set a breakpoint in one of my catch blocks in order to inspect an exception with more detail.
The View Detail modal window opens normally, but instead of showing me the details of the exception, it is throwing a strange error, one I never got, nor I know what it means:

The error says:

The name '$exception' does not exist in the current context

This is frustating because I am within the catch block scope, so I should be able to see my exception.
After restarting my application, I managed to debug it just fine. This was the only time (so far) I got this error.
Does anyone know what it means and how can I fix it (without having to restart application)?
NOTE: I am using Visual Studio 2012 Premium. Version 11.0.61030.00 Update 4

A: Try explicitly to tell the compiler how to import the dll. Ex:
using System;
using System.Runtime.InteropServices;

namespace BitmapProcessingCs
{
    public static class NativeMethods
    {
        [DllImport("BitmapProcessingCpp.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void GenerateBitmap(IntPtr src, int dimension);
    }
}

A: I solved the same problem in these steps:
step 1) If you program your custom DLL in C++ using Visual studio,then at the property page of your project set the Common Language Runtime Support (/clr)parameter to Common Language Runtime Support (/clr).
step 2) To function deceleration in .h file use __declspec(dllexport) keyword like below:
__declspec(dllexport) double Sub(int a,int b);

step 3) Build and export DLL file, then use the Dependency Walker software to get your function EntryPoint.
step4) Import DLL file In the C# project and set EntryPoint and CallingConvention variable like below:
[DllImport("custom.dll", EntryPoint = "?Sub@@Y234NN@Z", CallingConvention = CallingConvention.Cdecl)]

    public static extern double Sub(int a,int b);

A: Have a look at MSDN's library : https://msdn.microsoft.com/en-us/library/ms164891.aspx
According to them, you'll get an exception if you try to evaluate an exception object if no exception has occurred. But, since you're in the catch block, an excption has occurred... Without seeing your code it's hard to guess, but is it maybe possible that you have multiple threads running, and the exception was consumed by one thread before being handled by another? Doesn't really make sense but it's worth looking at.
A safe(r) option would be to ensure you check if the exception is null in your logger, before trying to get detail from it.
Also worth looking at: The HttpRequestException contains an inner exception, which might be the source of your null reference? Just speculating.

A: I agree with trapsuutjies, there is probably no exception. To suppress this error, press Ctrl+Alt+E, expand Managed Debugging Assistant, and uncheck LoadFromContext.

A: When I saw this error, I was also getting 'Could not evaluate expression' errors in the debugger. That lead me to this post by Rick Strahl that said it was a bug in the original version of Visual Studio 2013.
https://weblog.west-wind.com/posts/2013/Nov/21/Visual-Studio-2013-Could-not-evaluate-Expression-Debugger-Abnormality
When I checked the machine I was on, it in fact had VS2013 without any of the updates installed. Installing the updates fixed the issue.

A: I got this when in Configuration Manager the Configuration for the project was set to Release. Switching to debug solve this.


text:
Q: I am getting only december month expenses details not all month using XLOOKUP and Query formula created expenses track sheet in google sheet. but in dropdown list 2022 ALL MONTH EXPENSES (B2) result show only december month expense details. how to correct and show all month expenses details in 2022 ALL MONTH EXPENSES?
my code
=query(DATA!B2:D, "where month(B)+1="& month(xlookup(B2,DATA!H2:H,DATA!I2:I)),0)
my gogole sheet link u can correct
https://docs.google.com/spreadsheets/d/1rNB-ikqSPwgGJmA12mXD5aUq9tqsKlqpRMXQLyrVSts/edit?usp=sharing
pl dont add arrayformula,use xlookup formula

A: For all month expenses you should avoid then the conditions inside the query. And add a 0 in XLOOKUP to exact match. You can try this:
=query(DATA!B2:D, IF(B2="2022 ALL MONTH EXPENSES","","where month(B)+1="& MOIS(xlookup(B2,DATA!H2:H,DATA!I2:I,,0))),0)


text:
Q: TNS:listener does not currently know of service requested in connect descriptor I get ORA-12514:TNS:listener does not currently know of service requested in connect descriptor when running my application yet I can connect to the database via server explorer in visual studio. Where does the application look (when published) to get the information required to connect to the database? The connection string used by our application is correct.

A: It can change as the following and it is working in my environment.
Drive:\app\Administrator\product\11.2.0\dbhome_1\NETWORK\ADMIN
listener.ora

*

*Before
LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
  )

*After
LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
      (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.50.90)(PORT = 1521))
    )
  )
tnsnames.ora

*

*Before
LISTENER_ORCL =
  (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
ORCL =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl)
    )
  )

*After
LISTENER_ORCL =
  (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.50.90)(PORT = 1521))
ORCL =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.50.90)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl)
    )
  )
After that, restart the OracleOraDb11g_home1TNSListener service and OracleServiceORCL service.

A: look for tnsnames.ora
http://www.orafaq.com/wiki/Tnsnames.ora
and keep in mind service name vs. server name.

A: I faced the same exception when using sqldeveloper client. This may happen if the tnsnames.ora is not present in your machine or sqldeveloper is not properly installed.
To resolve this error, change the connection type to advanced and provide the JDBC connection URL in the format "jdbc:oracle:thin:@hostname:port:sid" as shown in the image below


text:
Q: Realtime multi_line graph updates at decent performance I'm currently using Bokeh to present a multi_line plot, that has several static lines and one line, that is live updated. This runs fine with only few lines but, depending on the resolution of the lines (usually 2000-4000 points per line), the refreshing rate drops significantly when having 50+ lines in the plot. The CPU usage of the browser is pretty high at that moment.
This is how the the plot is initialized and the live update is triggered:
    figure_opts = dict(plot_width=750,
                        plot_height=750,
                        x_range=(0, dset_size),
                        y_range=(0, np.iinfo(dtype).max),
                        tools='pan,wheel_zoom')

    line_opts = dict(
        line_width=5, line_color='color', line_alpha=0.6,
        hover_line_color='color', hover_line_alpha=1.0,
        source=profile_lines
    )

    profile_plot = figure(**figure_opts)
    profile_plot.toolbar.logo = None
    multi_line_plot = profile_plot.multi_line(xs='x', ys='y', **line_opts)
    profile_plot.xaxis.axis_label = "x"
    profile_plot.yaxis.axis_label = "y"

    ds = multi_line_plot.data_source

    def update_live_plot():
        random_arr = np.random.random_integers(65535 * (i % 100) / (100 + 100 / 4), 65535 * (i % 100 + 1) / 100, (2048))
        profile = random_arr.astype(np.uint16)
        if profile is not None:
            profile_lines["x"][i] = x
            profile_lines["y"][i] = profile
            profile_lines["color"][i] = Category20_20[0]
            ds.data = profile_lines

    doc.add_periodic_callback(update_live_plot, 100)

Is there any way to make this better performing?
Is it, for example, possible to only update the one line, that needs to get updated, instead of ds.data = profile_lines?
Edit: The one line that needs to be updated has to be updated in its full length. I.e. I'm not streaming data at one end, but instead I have a full new set of 2000-4000 values and want to show those, instead of the old live line.
Currently the live line is the element at i in the arrays in the profile_lines dictionary.

A: You are in luck, updating a single line with all new elements while keeping the same length is something that can be accomplished with the CDS patch method. (Streaming would not help here, since streaming to the end of a CDS for a multi_line means adding an entire new line, and the other case of streaming to the end of each sub-line does not have a good solution at all.)
There is a patch_app.py example in the repository that shows how to use patch to update one line of a multi_line. The example only updates a single point in the line, but it's possible to update the entire line at once using slices:
source.patch({ 'ys' : [([i, slice(None)], new_y)]})

That will update the ith line in source.data['ys'], as long as new_y has the same length as the old line.


text:
Q: Microsoft Cognitive Image Search API - filtering result to specific website we use Microsoft Cognitive services to create automated search requests to Bing.
Web Search works fine as we are able to filter results to a specific site:

https://api.cognitive.microsoft.com/bing/v5.0/search?q=Donald Duck
  site:etsy.com&count=10

What I'm not able to do is do the same with the image search api:

https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=
  site:artfire.com&count=10&modulesRequested=similarimages&imgUrl=https://img1.etsystatic.com/000/0/8236745/iusa_400x400.6291711.jpg

Can you assist? How do I search for similar images in a specific destination site?
Thanks in advance,
Dan

A: Bing Search doesn'tt support these for non-query based image-searches (i.e search by image-binary, search by image-url etc).
This is not an API specific limitation, it applies to www.Bing.com/images  as well. In general, what's not supported on www.bing.com/images  will not be supported in image-API either


text:
Q: What is the function of placing a "C" before the categorical variable when performing a one-way ANOVA in statsmodel in Python? I am performing a one-way ANOVA in the following code:
results = ols('price ~ C(make)', data=df_anova).fit()
print(results.summary())

What is the function of "C" before the categorical variable "make" (those are 22 car brands)?
I don't really see something is changing when leaving the C out. This webpage (https://pythonfordatascience.org/anova-python/) states that it automatically assigns a dummy variable to your categories, excludes one of the categories and captures it as the intercept in order to make proper comparison relative to the excluded brand. But as I stated earlier, when not including the C in front of the categorical variable, nothing seems to alter.

A: The formulas in statamodels are handled by patsy.
C(x) requires that x is treated as a categorical variable. If the values are strings, then patsy always treats the variable as a categorical variable and C is redundant in that case.
C forces numeric values like integers to be treated as categorical, which will then be replaced by a dummy or other categorical encoding.
C is also required to change options from their default values.
https://patsy.readthedocs.io/en/latest/builtins-reference.html#patsy.builtins.C