text:
Q: Discord.py Error Handling Bot missing permission I am working a discord bot using discord.py. I was handling errors and I found this

discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

This is my error handling code:
@client.event
async def  on_command_error(ctx, error):
  if isinstance(error, commands.MissingPermissions):
    await ctx.send("You can't do that ;-;")
    await ctx.message.delete()
  elif isinstance(error, commands.MissingRequiredArgument):
     await ctx.send("Please enter all the required arguments")
     await ctx.message.delete()
  elif isinstance(error, commands.MemberNotFound):
    await ctx.send("Member not found, Please mention a valid user!")
    await ctx.message.delete()
  elif isinstance(error, commands.BotMissingPermissions):
    await ctx.send("I don't have the permissions to do that!")
    await ctx.message.delete()
  elif isinstance(error, Forbidden.MissingPermissions):
    await ctx.send("I don't have the permissions to do that!")
    await ctx.message.delete()

  else:
    raise error

I also have a mute command and when the bot is placed under the role that has been commanded to mute it says, "I can't do that. Place my role above the specified role" or something like that


text:
Q: Concerning the sequence of gradients in Nesterov's Accelerated Descent Suppose we apply Nesterov's accelerated gradient descent to a $L$-smooth convex function $f \colon \mathbb R^n \to \mathbb R \cup \{\infty\}$,
\begin{align*}
 & x_k = y_k - \frac{1} {L} \nabla f(y_k) \\
 & y_{k+1}= x_k + \frac{k+1} {k+3} (x_k - x_{k-1}).
\end{align*}
We know the function values $\{f(x_k)\}$ might not monotonically decrease.
What about the sequence of $\{\|\nabla f(x_k)\|_2\}$? Are they monotonic? More specifically, I am interested to know if we assume the minimum $x^*$ exists, will the seqence of gradients $\{\|\nabla f(x_k)\|_2^2\}$ generated be bounded?

redpajama_set_name: RedPajamaStackExchange


text:
Q: C2DM do not receive any of sent messages I have one question about C2DM, I registered yesterday and I got email that my mail and app are approved. From app I get registration_id, I have broadcast_receiver like
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    android.util.Log.d("REG_1","onReceive");

    if ("com.google.android.c2dm.intent.REGISTRATION".equals(action)) {
        final String registrationId = intent
                .getStringExtra("registration_id");
        String error = intent.getStringExtra("error");

        android.util.Log.d("REG_1",registrationId);

        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(context);
        String token = prefs.getString("token", null);
        String userId;
        try {
            userId = RestClient.getUserIdByToken(token).getString(
                    "user_id");

            Intent i = new Intent(context, RegService.class);
            i.putExtra("c2dm_registration_id",registrationId);
            i.putExtra("token", token);
            i.putExtra("user_id", userId);
            i.putExtra("device_id", "bla");
            i.setAction(android.content.Intent.ACTION_VIEW);
            context.startService(i);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        saveRegistrationId(context, registrationId);
    }

and I enter in this function during registration and I send messages from command line like
curl https://www.google.com/accounts/ClientLogin -d Email=MYGOOGLEACCOUNT@gmail.com -d "Passwd=MY_PASSWORD" -d accountType=GOOGLE -d source=Google-cURL-Example -d service=ac2dm

and
curl --header "Authorization: GoogleLogin auth=DQAAAMMAAAC58D4X-5zjQFdYuGz7D9DhnuN4OUiz_gCtOJRSNwNLN0-wxveAEVL985hNKJXyQ_7U4sTfsUGh_3OXMLKpB5PNN1eaI4AfT19LaJ1vGJCZ_sSE0NDqGsC0mZVdMsYbE2Sz1r1WE_p5WNokfGMRdmxIHl0QCWb43lTD3iCvr51ujmnHnvpn2mDLWr6j9DtyDxADRw1to2iGgpJNelXmIA8tOzjyqF3szN-N2IYnihJ8H2t3G5wotOWy1EahB43Lv2NPdlV-A4yVSbdsYGM_AVdd" "https://android.apis.google.com/c2dm/send" -d registration_id=APA91bHhbsPedDVnYCaSJQMhWjfjK3W9jOaMgVITUHqw97w4fF_8fermSG22CzFvpPuTyRKnJFyJ_iwfgJEJ4uidURxuHZCCBuPtGAsv6NeVipmOd53Fkru_A3NW3cpIMo9gvuVxIB0QqxOvl1SmVfqRzD4qQfSNaw -d "data.test_result=This data will be send to your application as payload" -d collapse_key=2
id=0:1322216144957968%b3c4048a00000032

but it never enter in onHandle function of broadcatreceiver.
    <receiver
        android:name="com.surveyce.android.c2dm.C2DMRegistrationReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter >
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="com.surveyce.android" />
        </intent-filter>
        <!-- Receive the registration id -->
        <intent-filter >
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="com.surveyce.android" />
        </intent-filter>
    </receiver>

...
    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!--<uses-permission android:name="android.permission.WAKE_LOCK" />-->
    <uses-permission android:name="com.surveyce.android.permission.C2D_MESSAGE" />
    <permission
        android:name="com.surveyce.android.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
        <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

Did anybody have similar strange problems  that get registrationId and send messages but do not receive message on phone ? What can be problem, maybe because I registered yesterday ( but how than I get rigistrationId and auth for that account) ? Package names and gmail are account are 100% ok.

A: Add a service tag [write your receiver name in below service tag which is sub class of C2DMBaseReceiver]
<service android:name=".C2DMReceiver" />

Use C2DMBroadcastReceiver Instead of C2DMRegistrationReceiver
<receiver android:name="com.google.android.c2dm.C2DMBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND">

A: You can refer following Link for proper implementation of C2DM Google C2DM service


text:
Q: распределения контента по странам Здравствуйте, нужно отделить ленту новостей для стран СНГ от общей. То есть, если пользователь зашел на сайт из СНГ, выводим одну ленту, если из Европы/Америки - другую (англоязычную). Для этого всё готово, осталось только создать масссив языков (первые 2 символа $_SERVER['HTTP_ACCEPT_LANGUAGE']), которые входят в эти страны, пока что есть только ru и ua. Подскажите все остальные заголовки языков стран СНГ?

A: На языки нельзя ориентироваться, во многих браузерах в СНГ стоит язык EN. Относительно достоверно можно определить только по ip для этого используйте базу geoip. Но такой вариант не учтёт тех, кто заходит через VPN например
Список сокращений стран https://www.artlebedev.ru/country-list/


text:
Q: Pop-up bootstrap + angular I am trying use bootstrap's pop up in my web page. I have included all necessary files to my app but I get this exception in firebug console:
Error: $modal is not a function $scope.addBook@http://localhost:8080/engineering-project-web/resources/angular-app/navigation_bar/naviBarCtrl.js:7:18 $parseFunctionCall@http://localhost:8080/engineering-project-web/resources/libs/angular.js:12332:15 ngEventHandler/</callback@http://localhost:8080/engineering-project-web/resources/libs/angular.js:21389:17 $RootScopeProvider/this.$get</Scope.prototype.$eval@http://localhost:8080/engineering-project-web/resources/libs/angular.js:14384:16 $RootScopeProvider/this.$get</Scope.prototype.$apply@http://localhost:8080/engineering-project-web/resources/libs/angular.js:14483:18 ngEventHandler/<@http://localhost:8080/engineering-project-web/resources/libs/angular.js:21394:17 n.event.dispatch@http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js:3:6392 n.event.add/r.handle@http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js:3:3202

There are my all included scripts:
<script src="<c:url value="/resources/libs/jquery.js" />"></script>

        <!-- Angular Scripts -->
        <script src="<c:url value="/resources/libs/angular.js" />"></script>
        <script src="<c:url value="/resources/libs/angular-animate.min.js" />"></script>
        <script src="<c:url value="/resources/libs/angular-route.js" />"></script>
        <script src="<c:url value="/resources/libs/angular-resource.js" />"></script>

        <!-- Bootstrap -->
        <script src="<c:url value="/resources/libs/jquery-ui.custom.min.js" />"></script>
        <script src="<c:url value="/resources/libs/bootstrap.js"/>"></script>
        <script src="<c:url value="/resources/libs/ui-bootstrap.js"/>"></script>

        <!-- Controlers -->
        <script src="<c:url value="/resources/angular-app/main/AppCtrl.js" />"></script>
        <script src="<c:url value="/resources/angular-app/home/homeCtrl.js" />"></script>
        <script src="<c:url value="/resources/angular-app/navigation_bar/naviBarCtrl.js" />"></script>

        <!-- Services -->
        <script src="<c:url value="/resources/angular-app/home/homeSrvc.js" />"></script>

        <!-- Directives -->
        <script src="<c:url value="/resources/angular-app/main/directives.js" />"></script>

        <!-- CSS -->
        <link type="text/css" rel="stylesheet" href="<c:url value="/resources/css/main.css" />" />
        <link type="text/css" rel="stylesheet" href="<c:url value="/resources/angular-app/home/home.css" />" />
        <link type="text/css" rel="stylesheet" href="<c:url value="/resources/css/bootstrap.css"/>">
        <link type="text/css" rel="stylesheet" href="<c:url value="/resources/css/bootstrap-theme.css"/>">

        <!-- IE -->
        <script src="<c:url value="/resources/libs/html5.js" />"></script>
        <script src="<c:url value="/resources/libs/respond.js" />"></script>
        <script src="<c:url value="/resources/libs/css3-mediaqueries.js" />"></script>

This is my main angular's module:
var appModule = angular.module('frontendApp', ['ngRoute', 'ui.bootstrap']);

appModule.controller('AppCtrl' , ['$scope', function($scope) {
    $scope.init = function() {
        $scope.baseUrl = "/engineering-project-web/resources/angular-app";
    };
}]);

And this is controller wherein I am trying turn on pop up.
appModule.controller('NaviBarCtrl', ['$scope', '$modal',  function ($scope, $modal) {

    $scope.addBook = function(){
        $scope.popup = $modal({
            scope : $scope,
            template : 'resources/angular-app/popups/AddTrainingUser.html',
            show : true
        });
    }

  }]);

A: It looks like your $modal service is imported correctly; be sure you are calling the function to open it.
Try this:
    $scope.popup = $modal.open({
        scope : $scope,
        template : 'resources/angular-app/popups/AddTrainingUser.html',
        show : true
    });


text:
Q: Large Objects and .NET (x64): The Meaning? I've been reading about the ~2GB size limit of objects in .NET, and sadly feel that I must be missing something. I believe I have created Lists that are larger than 2GBs, and in so far as a List is an object...I am confused. Could someone explain to me what they mean by this limitation?

A: The total space taken by all of your dereferenced objects may have exceeded that. But the space requirement for the list and its internal pointers to each object it contains were less than 2 GB.
To expound upon this general concept - the pointers themselves are relatively small in terms of storage requirement.  The objects to which they point can individually be very large (or very numerous).


text:
Q: How to determine file equivalency between app sessions prior to OS X 10.10? I'm making an app that monitors changes to a "hot" folder and uploading new files to a remote server (think one-way Dropbox). The app needs to remember which files were previously uploaded and not re-upload them, even if the user moves them to a different child folder. If I had access to the 10.10 API, I'd just use the NSURLDocumentIdentifierKey property of NSURL and call it a day... but I need to support back to 10.7 (Lion). Here are the approaches I've thought of so far, which all seem somewhat deficient:

*

*There is the NSURLFileResourceIdentifierKey but it is not maintained across system boots, so it is ineffective for more than same-session usage.

*I could compute an MD5/SHA1 hash for each file, but this app is targeted at pro photo users, so the prospect of hashing hundreds of multi-megabyte image files is not appealing.

*The Alias framework and FSRefs all got deprecated in 10.8, so I'm reluctant to build a solution based on them.

What other approaches am I overlooking?

A: The solution I eventually settled upon was to assign each file my app touched a UUID that was stored in the file's extended attributes under a key unique to my app. Extended attributes follow a file when it is moved or copied. When reading in a directory structure, I check each file for a UUID and assign one if it is not present. In the event of a UUID collision due to a copy of a file being encountered (I'm keeping a lookup table of encountered UUIDs), I assign a new UUID to the later-encountered file.
NSHipster's writeup on Extended Attributes
I encapsulated the messy C interactions with setxattr(), getxattr() and listxattr() in a category on NSURL which lets me easily query/get/set arbitrary text attributes on the file system document pointed to by the URL.


text:
Q: Is it possible using a declared Javascript function in an event listener? I've got a simple question, when adding an event listener in Javascript, can you call an existing declared function using its name (without storing it in a variable)? I know defining a new function within the event listener arguments (Ex. #1) works, as well as inserting a declared function into a variable and using it (Ex. #2), but when I'm trying to call a declared function without a variable by using its name it just executes the function once (Ex. #3)

var my_button = document.querySelector("my_button")

/* Ex. 1 - works */
my_button.addEventListener("click", function() {
console.log("Click Occured");
});

/* Ex. 2 - works */
var func_a = function My_Click()
{
  console.log("Click Occured");
}

my_button.addEventListener("click", func_a);

/* Ex. 3 - won't work */
function func_a()
{
  console.log("Click Occured");
}

my_button.addEventListener("click", func_a())

I'd also really appreciate an explanation about why it works that way, thanks a lot in advance!


text:
Q: Opencv 1080p record but show 720p I am recording 1080p video to file, but I need to show to user 1280*720 size. how can I do this ?  When it's 1080p, it doesn't fit on the screen, so I want to show 720p to the user and get the recording in 1080p.
This is my source code:
cap = cv2.VideoCapture('rtsp://secret:secret@192.168.1.64/1')

    filename = user_id +'.mp4' #.avi .mp4
    frames_per_seconds = 25 #this is the standard for the movie or films
    config = CFEVideoConf(cap, filepath = filename, res='1080p')
    out = cv2.VideoWriter(filename, config.video_type, frames_per_seconds,config.dims)
    print(config.dims)
    img_path = 'ap_logo.png'
    logo = cv2.imread(img_path,-1)
    watermark = image_resize(logo, height=50)
    watermark = cv2.cvtColor(watermark, cv2.COLOR_BGR2BGRA)

    while(True):
        ret, frame = cap.read()
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA)

        frame = cv2.flip(frame, 1)
        frame = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE)

        frame_h, frame_w, frame_c = frame.shape
        # # overlay with 4 channel BGR and Alpha
        overlay = np.zeros((frame_h, frame_w, 4), dtype='uint8')

        watermark_h, watermark_w, watermark_c = watermark.shape
        for i in range(0, watermark_h):
            for j in range(0, watermark_w):
                if watermark[i, j][3] != 0:
                    h_offset = frame_h - watermark_h
                    w_offset = frame_w - watermark_w
                    overlay[h_offset + i, w_offset + j] = watermark[i, j]

        cv2.addWeighted(overlay, 0.25, frame, 1.0, 0, frame)

        # Display the resulting frame
        frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
        if ret:
            # cv2.resize(1280, 720)
            cv2.imshow('Frame', frame)
            # cv2.resize(frame, 720,1280, interpolation=cv2.INTER_AREA)

            # cv2.namedWindow('Frame', cv2.WINDOW_KEEPRATIO)

            # cv2.resizeWindow('Frame', 720, 1280)

            out.write(frame)  # file a ilgili frame yazılıyor

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

    #When everything done, relase the capture
    cap.release()
    out.release() # saved
    cv2.destroyAllWindows()


text:
Q: To Find factorial of large number(number of digits >20) I wrote some c++ code to find the factorial of int n. As factorial can be a very large number, so I decided to store the number in a vector. But My Code is not working as expected. Some please point out the bug and guide me. I lowkey feel like I messed with pointers.
And Please suggest if there is a more optimal approach for this.
Thanks Community.
The Code:
    #include <iostream>
    #include <vector>
    #include <algorithm>
    using std::cout;
    using std::endl;
    using Digits = std::vector<int>;

    //define the length of the array, should be the maximum number of digits in the factorial(n)
    #define MAX 20

    void multiply(int x,Digits res,int res_size){
      int carry=0;
      for(int i=0;i<res_size;i++){
          int prod=carry+ x*res[i];
          res[i] = prod%10;
          carry = prod/10;
      }

      while(carry){
          res[res_size] = carry%10;
          carry/=10;
          (res_size)++;
      }
    }

    Digits factorial(int n){
      Digits res(MAX);
      res[0] = 1;
      int res_size=1;
      for(int i=2;i<=n;i++){
          multiply(i,res,res_size);
      }
      reverse(res.begin(),res.end());
      return res;
    }

    int main(){
      for(auto i: factorial(20)){
        cout << i;
      }cout << endl;
      return 0;
    }

The Output:
10000000000000000000

[Done] exited with code=0 in 3.204 seconds

A: Fixed version:
#include <vector>
#include <iostream>
using namespace std;

//define the length of the array, should be the maximum number of digits in the factorial(n)
#define MAX 20

void multiply(int x, vector<int>& res, int* res_size) {
    int carry = 0;
    for (int i = 0; i < *res_size; i++) {
        int prod = carry + x * res[i];
        res[i] = prod % 10;
        carry = prod / 10;
    }

    while (carry) {
        res[*res_size] = carry % 10;
        carry /= 10;
        (*res_size)++;
    }
}

vector<int> factorial(int n) {
    vector<int> res(MAX);
    res[0] = 1;
    int res_size = 1;
    for (int i = 2; i <= n; i++) {
        multiply(i, res, &res_size);
    }
    return res;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    for (auto i : factorial(20)) {
        cout << i;
    }cout << endl;
    return 0;
}

To pass by reference, simply add an & after the type of a parameter.
Also, see Why should I not #include <bits/stdc++.h>? and Why is "using namespace std;" considered bad practice?.
For more info on pass-by-value and pass-by-reference, you can look here: https://www.educative.io/edpresso/pass-by-value-vs-pass-by-reference.
Basically, passing by value creates a copy of the original type, wheras passing by reference passes a reference to the original copy, so modifying the reference is modifying the original value.
Also, pointers and references are very similar, although I would use references when you want to modify a variable you are passing to a function. More on this: https://www.tutorialspoint.com/pointers-vs-references-in-cplusplus#:~:text=References%20are%20used%20to%20refer,to%20store%20address%20of%20variable.&text=A%20reference%20shares%20the%20same,and%20size%20on%20the%20stack.

A: i see some errors:
#define MAX 20

    void multiply(int x,vector<int> res,int* res_size){ // should be .. void multiply(int x,vector<int> res,int &res_size)
      int carry=0;
      for(int i=0;i<*res_size;i++){
          int prod=carry+ x*res[i];
          res[i] = prod%10;
          carry = prod/10;
      }

      while(carry){
          res[*res_size] = carry%10;
          carry/=10;
          (*res_size)++;
      }
    }

    vector<int> factorial(int n){
      vector<int> res(MAX);
      res[0] = 1;
      int res_size=1;
      for(int i=2;i<=n;i++){
          multiply(i,res,&res_size); // should be ... multiply(i,res,res_size)
      }
      return res;
    }

total:
void multiply(int x,vector<int> res,int &res_size){
cout << &res_size<< endl; // print address of "res_size"
  int carry=0;
  for(int i=0;i<res_size;i++){
      int prod=carry+ x*res[i];
      res[i] = prod%10;
      carry = prod/10;
  }

  while(carry){
      res[res_size] = carry%10;
      carry/=10;
      (res_size)++;
  }
}

vector<int> factorial(int n){
  vector<int> res(MAX);
  res[0] = 1;
  int res_size=1;
  for(int i=2;i<=n;i++){
      multiply(i,res,res_size);
  }
  return res;
}

cout << &res_size<< endl; // prints out the address where the value is stored.

int* res_size // stores the reference ( adddress )

Pointers
#include <iostream>
using namespace std;

    int main ()
    {
      int firstvalue, secondvalue;
      int * mypointer;

      mypointer = &firstvalue;
      *mypointer = 10;
      mypointer = &secondvalue;
      *mypointer = 20;
      cout << "firstvalue is " << firstvalue << '\n';
      cout << "secondvalue is " << secondvalue << '\n';
      return 0;
    }

pointers provide a remote control to the original value where it's stored in the ram.
instead of making copies everywhere in your code.
check out this video, it's very good
Introduction to pointers in C/C++
Pointers and dynamic memory - stack vs heap
mycodeschool


text:
Q: Can't render variables in ion-card inside an ng-repeat - Ionic 4 Angular I made a project using Ionic 4.5.0 within Angular, it worked properly until I tried to update Ionic to 4.11.9.
The problem is that the variables present inside the ion-cards inside an ng-repeat have stopped being rendered, giving the console this error:
Cannot set property 'nodeValue' of undefined
The problem is only about ion-cards, the other Ionic components work properly, and it seems to be related to the use of ui-router.
I made an example on Codepen https://codepen.io/andreavalzasina/pen/BaNLNqR
Has there been a particular change on this specific component in the latest ionic releases?
Is there any way to solve this problem, without having to stay at version 4.5.0 or having to change all the ion-cards of the project with other custom components?


text:
Q: ImportError: cannot import name 'async contextmanager' I am using
windows 10,
python 3.6
I am running a selenium project
my code is
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.clear()
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.close()

I get this error:
  from contextlib import (contextmanager, asyncio contextmanager) ImportError: cannot import name 'async contextmanager' Process finished with exit code 1

Error photo

A: Use Python New Version.
python 3.9 will be working in this case.
for more details you can read:
https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager


text:
Q: error when inserted props in getJSON I'll be very grateful who can help me with this line I've this:
i need a props when i load whit json
$.getJSON({this.props.archivo}, function(data){

and this is the fixed
SyntaxError: C:/xampp/htdocs/mip/App.js: Unexpected token (193:17)
  191 |     },
  192 |     componentWillMount: function(){
> 193 |         $.getJSON({this.props.archivo}, function(data){
      |                  ^

thanks for you colaboration

A: this.props.archivo is already a JavaScript object. You only need to wrap it in { } when binding it for rendering.
$.getJSON(this.props.archivo, function(data){});


text:
Q: Import Table (IT) vs Import Address Table (IAT) I've been trying to parse/display the information in the Import Address Table (IAT) of a process after it is loaded and running. I understand API calls in programs jump to the relevant point in the IAT, which then jumps to the actual function in the loaded DLL's.
Is it correct that the IAT can be found by reading the PE header and following the OptionalHeader.DataDirectory[1] pointer, to the array of IMAGE_IMPORT_DESCRIPTORs. Then following the FirstThunk pointers. Whereas the  OriginalFirstThunk pointers here, will give you the original Import Table (IT)?
I have also tried following the OptionalHeader.DataDirectory[12] pointer in the PE header, but this was even less successful.
I've been testing this by trying to parse this structure for notepad.exe (32bit), using ReadProcessMemory from another process.
Here's the rough C-psuedocode for what I'm doing:
char buf[128];

// get first import descriptor
readMemory(&import, procImgBase + DataDirectory[1].VirtualAddress, sizeof(IMAGE_IMPORT_DESCRIPTOR));

// get dll name
readMemory(buf, import.Name + procImgBase, 127);
printf("libname: %s\n", buf);

// get first function name
DWORD iltAddress = 0;
readMemory(&iltAddress, import.FirstThunk + procImgBase, 4);
readMemory(buf, iltAddress + procImgBase, 127);
printf("fname: %s\n", libName + 2); // <-- the +2 for the 2byte 'hint' of import lookup table entries

If, on the 3rd to last line, i replace it with import.OriginalFirstThunk instead of FirstThunk, it will print everything as expected. I must be missing something conceptually, and so I was wondering if anyone could clarify what this is, for me?
Many thanks!

A: It looks like you're heading the right direction. Some notes:

*

*The DataDirectory gives you an offset
to an array of
IMAGE_IMPORT_DESCRIPTOR which is
terminated by an entry of all zeros.
There will be one
IMAGE_IMPORT_DESCRIPTOR for each DLL
that is imported

*The
IMAGE_IMPORT_DESCRIPTOR has offsets
to 2 arrays of IMAGE_THUNK_DATA, one
that maintains offsets to the names
of the imported functions
(OriginalFirstThunk) and another that
now has the actual addresses of the
functions (FirstThunk)

Since your executable is running, the IAT should contain the actual address of the function rather than an RVA to a name entry.
You could do something like this instead:
DWORD rva_to_name_of_function = 0;
DWORD address_of_function = 0;

// get the RVA of the IMAGE_IMPORT_BY_NAME entry
readMemory(&rva_to_name, import.OriginalFirstThunk + procImgBase, 4);

// copy the name of the import
readMemory(buf, rva_to_name + procImgBase + 2, 127);

// get the actual address that was filled in by the loader
readMemory(&address_of_function, import.FirstThunk + procImgBase, 4);

printf("fname: %s address: %X", buf, address_of_function);

Take a look at this article for some helpful details:
http://msdn.microsoft.com/en-us/magazine/cc301808.aspx

A: Eric gave a good answer, here are some additional clarifications:

I understand API calls in programs jump to the relevant point in the IAT, which then jumps to the actual function in the loaded DLL's.

The program uses a CALL PTR DS:[IAT-ADDRESS] that reads from an address in the IAT to determine where the program is at runtime.

Whereas the OriginalFirstThunk pointers here, will give you the original Import Table (IT)?

The OriginalFirstThunk pointers point you at the Import Lookup table (ILT).  If you open up the binary on disk, the ILT and the IAT are identical; both contain RVA's to function name strings.  Once the program has been loaded, the IAT's entries (in memory) are overwritten with the addresses of the imported functions.
In my experience, the best source of information on the import table and all of its attendant data structures is the PE specification itself.  If you read patiently through the section on imports, all will be made clear.
http://msdn.microsoft.com/en-us/windows/hardware/gg463125


text:
Q: Static storage objects optimization on thread context Can a compiler optimize a static storage object in multithread program context? I'm asking it to know if a variable declared as static, for instance, generates a side effect when used in a function called in a thread.
bool flag = false; // static storage duration object

void f(){ //function called in a thread
  flag = false;
  // do some work...
  flag = true;
}

//a possible representation of the code above after optimization
void f(){
  flag = true;
  // do some work...
} // is this possible to happen?

I read some answers from here, but I didn't find anything that could help.

A: Static storage duration has no affect on thread safety.  In your example the second code block would be legal as long as the reordering doesn't break anything inside f.
You still need synchronization on all shared objects that any thread writes to.  In this case you could get that by using a std::atomic<bool> for flag like
std::atomic<bool> flag = false;

The rule for thread safety is that if you have an object shared between multiple threads, and at least one of them is a writer, then you need synchronization.  If you do not then you have a data race which is undefined behavior.


text:
Q: Python Pandas GroupBy Max Date I have a very simple dataframe with columns: Index, Person, Item, Date. There are only 4 people and 3 items and random dates. All person/item/date combinations are unique. I am trying to get a simple pivot-table like df to print using:
import pandas as pd

mydf = pd.read_csv("Test_Data.csv",index_col=[0])
mydf = mydf.sort_values(by=['Date','Item','Person'], ascending=False)

print(mydf.groupby(['Person','Item'])['Date'].max())

however, I noticed that while the structure is what I want, the data is not. It is not returning the max date for the Person/Item combination. I thought sorting things first would help, but it did not. Do I need to create a temp df first and then join to do what I'm trying to do?
Also to be clear, there are 28 rows of data (all test data) with some People/Items being repeated but with different dates. Index is just 0 through 27.

A: Figured it out! Should have made sure the Date field was actually recognized as a date:
mydf['Date'] = pd.to_datetime(mydf['Date'])


text:
Q: understanding the the benefit of generics over typecasting? I have a couple of ways to get a value from a config file, that contains various types.
I'm trying to understand the benefits of using a generic vs typecasting.
on the caller side I could do a simple cast:
const botToken = AppConfig.getenv('botToken') as string
vs
const botToken = AppConfig.getenv<string>('botToken')
On the API provider side the basic yolo any way
export class AppConfig {
    static getenv(key: configKey): any {
 ...

vs
export class AppConfig {
    static getenv<T extends any>(key: string, env?: string): T {

The question is:
Does the generic method do any extra checking for example to test that given a key of X the return type is the same as the requested type in ?
Or is it effectively just typecasting the results to what I asked for in  in order to pass the compile checks?
Perhaps this isn't a good use case because there are so many different types and data structures this API could return... so i'm still using T extends any for the definition.
I'm also type checking the key param that is passed, given I have some knowledge of the shape of the Config env data:
export interface ConfigVars {
    prefixes?: string[];
    port?: number;
    network?: string;
    alchemyApi?: AlchemyConfig;
}
export type configKey = keyof ConfigVars

ref:
https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-types

A: I think in your use case it will not have direct benefits.
The indirect one I can think of: You can disallow type assertions generally (e.g. via linter) and still happily use the generic version.
As this looks like a config value, it is likely impossible to have this 100% type checked at compile time.


text:
Q: how to edit value at the child widget i try to edit the value of the child widget, i can do it with StatefulWidget parent but i want to do it with StatelessWidget parent and without using global value
    class Homepage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: <Widget>[
          FlatButton(child: Text('addFile'), onPressed: () {}),
          FlatButton(child: Text('deleteFile'), onPressed: () {})
        ],
      ),
      body: Child(),
    );
  }
}

class Child extends StatefulWidget {
  @override
  _ChildState createState() => _ChildState();
}

class _ChildState extends State<Child> {
  var hasFile = true;
  @override
  Widget build(BuildContext context) {
    return hasFile ? Text('has a file') : Text("no File");
  }
}

A: You can use BLoC pattern to implement this kind of functionality,
Here is the BLoC class which will handle state of bool
import 'dart:async';

class Bloc {
  final _fileController = StreamController<bool>();

  changeState(bool val) {
    _fileController.sink.add(val);
  }

  get hasFile => _fileController.stream;

  dispose() {
    _fileController.close();
  }
}

final bloc = Bloc();

Then you can add stream builder in your Stateful Widget, in which you will provide stream of BLoC class.
StreamBuilder updates it's UI according to Stream.
class Child extends StatefulWidget {
  @override
  _ChildState createState() => _ChildState();
}

class _ChildState extends State<Child> {
  var hasFile = true;

  @override
  void dispose() {
    bloc.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: bloc.hasFile,
      initialData: false,
      builder: (context, snapshot) {
        return snapshot.data ? Text('has a file') : Text("no File");
      },
    );
  }
}

At last you can access BLoC class with your stateless widget as follows
class Homepage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: <Widget>[
          FlatButton(
              child: Text('addFile'),
              onPressed: () {
                bloc.changeState(true);
              }),
          FlatButton(
              child: Text('deleteFile'),
              onPressed: () {
                bloc.changeState(false);
              })
        ],
      ),
      body: Child(),
    );
  }
}

Full example is as below
import 'package:flutter/material.dart';
import 'dart:async';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Homepage(),
    );
  }
}

class Homepage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: <Widget>[
          FlatButton(
              child: Text('addFile'),
              onPressed: () {
                bloc.changeState(true);
              }),
          FlatButton(
              child: Text('deleteFile'),
              onPressed: () {
                bloc.changeState(false);
              })
        ],
      ),
      body: Child(),
    );
  }
}

class Child extends StatefulWidget {
  @override
  _ChildState createState() => _ChildState();
}

class _ChildState extends State<Child> {
  var hasFile = true;

  @override
  void dispose() {
    bloc.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: bloc.hasFile,
      initialData: false,
      builder: (context, snapshot) {
        return snapshot.data ? Text('has a file') : Text("no File");
      },
    );
  }
}

class Bloc {
  final _fileController = StreamController<bool>();

  changeState(bool val) {
    _fileController.sink.add(val);
  }

  get hasFile => _fileController.stream;

  dispose() {
    _fileController.close();
  }
}

final bloc = Bloc();

A: You are thinking the wrong way. Child aka Text() should get its value from a model which is managed by the application or at least managed by the widget above. I would go with the provider package https://pub.dev/packages/provider and do this:
import 'package:provider/provider.dart';
import 'package:flutter/material.dart';

class MyState with ChangeNotifier {
  String _myText;

  MyState(this._myText);

  getMyText() => _myText;

  void changeText(String newText) {
    _myText = newText;
    notifyListeners();
  }
}

class Homepage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
          ChangeNotifierProvider(builder: (_) => MyState("initial Text")),
        ],
        child: Scaffold(
          appBar: AppBar(
            actions: <Widget>[
              FlatButton(
                  child: Text('addFile'),
                  onPressed: () {
                    Provider.of<MyState>(context).changeText("addFile");
                  }),
              FlatButton(
                  child: Text('deleteFile'),
                  onPressed: () {
                    Provider.of<MyState>(context).changeText("deleteFile");
                  })
            ],
          ),
          body: Child(),
        ));
  }
}

class Child extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    MyState myState = Provider.of<MyState>(context);
    return Text(myState.getMyText());
  }
}

This is coded without IDE support or even compiling and running. But it should get you to the right direction.


text:
Q: File globbing in Ruby and Unix I have the following directory structure on my desktop:
sample/
  a.rb
  b.rb
  c.rb
  sub_sample/
    blah.rb
  whatever/
    meow.rb

Unix globbing behaves as expected in bash:
Desktop $ ls sample/*.rb
sample/a.rb sample/b.rb sample/c.rb

Desktop $ ls sample/*/*.rb
sample/sub_sample/blah.rb   sample/whatever/meow.rb

Desktop $ ls sample/**/*.rb
sample/sub_sample/blah.rb   sample/whatever/meow.rb

Apparently, the last example will recursively glob, similar to Ruby, if globstar is enabled.
Here is how the globbing works in Ruby (last example produces the different output):
>> Dir[Dir.home + "/Desktop/sample/*.rb"]
=> ["/Users/powers/Desktop/sample/a.rb", "/Users/powers/Desktop/sample/b.rb", "/Users/powers/Desktop/sample/c.rb"]

>> Dir[Dir.home + "/Desktop/sample/*/*.rb"]
=> ["/Users/powers/Desktop/sample/sub_sample/blah.rb", "/Users/powers/Desktop/sample/whatever/meow.rb"]

# This is the recursive output that I don't understand
>> Dir[Dir.home + "/Desktop/sample/**/*.rb"]
=> ["/Users/powers/Desktop/sample/a.rb", "/Users/powers/Desktop/sample/b.rb", "/Users/powers/Desktop/sample/c.rb", "/Users/powers/Desktop/sample/sub_sample/blah.rb", "/Users/powers/Desktop/sample/whatever/meow.rb"]

When more than one star is used, it behaves the same as the single star:
>> Dir[Dir.home + "/Desktop/sample/***************/*.rb"]
=> ["/Users/powers/Desktop/sample/sub_sample/blah.rb", "/Users/powers/Desktop/sample/whatever/meow.rb"]

Here are my questions:

*

*How does ** recursively search through all the folders?  I think of * as something that matches anything of any length.  Is ** interpreted as something entirely different (like a method)?

*Are there any other ways to recursively glob in Ruby?  It seems like /**/* is the 'standard' way to glob in Ruby, but the syntax is a bit confusing for me.  Hopefully I can get more comfortable with it when I figure out what ** is doing.
Thanks.

A: Saying Dir['path/**/*.rb'] is, more or less, like saying:
find path -name '*.rb'

from the shell. So with Ruby's Dir, a ** glob searches the specified path and all directories under path. Apparently bash's ** only looks at directories under path without looking at the files in path at all.


text:
Q: Overflow and Underflow BigIntegers in C# I have the following piece of code which i'm trying to comprehend.
The Big Integer class (custom, not the standard class) has the following members:
    private const int maxLength = 2000;
    private uint[] data = null;             // stores bytes from the Big Integer
    public int dataLength;                 // number of actual chars used

The constructor is as follows:
public BigInteger(long value)
    {
            data = new uint[maxLength];
            long tempVal = value;

            // copy bytes from long to BigInteger without any assumption of
            // the length of the long datatype

            dataLength = 0;
            while(value != 0 && dataLength < maxLength)
            {
                    data[dataLength] = (uint)(value & 0xFFFFFFFF);
                    value >>= 32;
                    dataLength++;
            }

            if(tempVal > 0)         // overflow check for +ve value
            {
                    if(value != 0 || (data[maxLength-1] & 0x80000000) != 0)
                            throw(new ArithmeticException("Positive overflow in constructor."));
            }
            else if(tempVal < 0)    // underflow check for -ve value
            {
                    if(value != -1 || (data[dataLength-1] & 0x80000000) == 0)
                            throw(new ArithmeticException("Negative underflow in constructor."));
            }

Essentially, the BigInteger class aids in manipulating large integers. The constructor is used to assign a long value to a Big Integer object. I understand that the variable named value is copied to the uint[] data array (the maximum number of digits allowed being maxLength).
I'm not able to completely understand how the check for underflow and overflow has been made. I understand the conditions if(tempVal > 0) and else if(tempVal < 0) but why is the highest array index of data anded with 0x80000000 in case of both underflow and overflow? (why not 0xFFFFFFFF in the case of overflow/underflow? If the number is even 1 more/less than the maximum number allowed, it will result in an overflow/underflow)
Also, doesn't passing a long value to the constructor limit the overall size of the BigInteger (whose maximum value can then be the same as the maximum value of a long variable)?

A: For an int in C#, the bit at 0x80000000 (ie. the most significant bit) is the sign bit. In other words if it contains 1, then the number is negative.   An int that contained bits 0xffffffff would be interpreted as containing -1.  During integer arithmetic, a number carrying over into this bit would represent an overflow condition, which is presumably what the check is based on.
Similarly, the sign bit contains 0 for any positive number, so if you're expecting the number to be negative, but this bit contains 0, then you know that some overflow must have occurred into this bit. In fact, the way negative numbers are represented, every bit to the left of the actual number is set to 1.  For example, 3 is represented as 0x00000003 (everything to the left is 0) while -3 is represented as 0xfffffffd (everything to the left is 1).
The code will basically populate the entire array with the same convention. Store a positive number in it, and it'll fill the first couple of elements, leaving everything else zero'd out. Pass a negative number in, and it'll put the number in the first couple of elements, then fill up almost the entire array with 0xffffffff, thus preserving the convention that the very leftmost bit (ie. the leftmost bit of the last element of the array) is the sign bit.   The filling the entire array, after the number, with -0xffffffff, happens because the right-shift operator in C# preserves the sign bit: If it's right-shifting a negative number, it fills everything to the left with 1's not 0's.
So the way to think of those tests is that they are checking that the sign bit of the array (the leftmost bit of the last element) is correct.
By the way, I don't believe there's any way either exception condition would be triggered, so I suspect those tests may have been put in for debugging purposes while the code was being written, and then got left in.
My reading of the code is that you are correct when you suggest that passing the long value to the constructor limits the overall size of the value stored in the BigInteger. However, you've only shown the code for the constructor. I'd surmise that the class contains other methods (eg. to do arithmetic) that could cause larger values to be placed into the BigInteger. For example, does it allow two BigIntegers to be multiplied?


text:
Q: Whether the limit on representable functors be non-representable? I'm looking for examples of the following situation:
Let $A$ be a complete and cocomplete category, $B$ is a small category and $T\colon B\to\mathbf{Set}^{A^{op}}$ be a functor, such that for any $b\in B$ functor $T(b)$ is representable. Could it be that the functor $\varprojlim T$ is not representable?

A: By the Yoneda-Lemma, $T$ lifts to a diagram $X : B \to A$, which has a limit $\{L \to X_b\}$. Then one easily checks that $\{\hom(-,L) \to T_b\}$ is a limit (in fact the Yoneda embedding preserves all limits).


text:
Q: Calculating distance between point and selected pixel in R? I would like to obtain the distance between a point and a selection of pixel on raster image. Here the process:
I read my JPEG image and extract colors I want:
 img.raster<-stack(***)

 names(img.raster) <- c('r','g','b')

img.a<-img.raster[[1]]

img.a[] =0

img.a[img.raster$r<70 & img.raster$g<70 & img.raster$b<255] <- 255

img.c<-img.raster[[1]]

img.c[] =0

img.c[img.raster$r>70 & img.raster$g>82 & img.raster$b>65] <- 255

img.b<-img.raster[[1]]

img.b[] =0

img.b[img.raster$r>65 & img.raster$r<160

       & img.raster$g>70 & img.raster$g<255

       & img.raster$b>0 & img.raster$b<65] <- 255

Then I recreate my final image and thus img.c is red, img.b is green and img.a is blue:
      final_image = stack(img.c, img.b, img.a)

I am trying to calculate the distance between a point of coord (x,y) and all the pixels I extracted of the img.a. (in green in the following picture):

But if I calculate the distance between the point (xy) and img.a by using:
xy <- c(590,61)
d <- distanceFromPoints(img.a, xy)
I obtain the distance between all pixels (means the green and white).
Do you know how to select only the pixel I extracted on img.a ?

A: You can define a function to select pixel values and then transform that raster into points in order to use pointDistance() function.
Here is a piece of the code I have used: my raster is a dem and my selected point proceed from a shp (you can make it easily from a point like your xy <- c(590,61)). Then I select just get raster cells above 450m. Finally, I use that pointDistance function to add the value of distance to the SpatialPointsDataFrame created by subseting raster.
library(rgdal)

r <- raster("./DEM/DEM.tif") #read raster
shpA <- readOGR("./PA", "PA")[1,] #read shapefile of and get one point

#raster to points (>450)
rpoints <- rasterToPoints(r, fun=function(x){x>450}, spatial=TRUE)

rpoints$pdist <- pointDistance(shpA, rpoints)
rpoints

> > rpoints
>     class       : SpatialPointsDataFrame
>     features    : 33615
>     extent      : 511046.5, 513250.5, 4648854, 4651485  (xmin, xmax, ymin, ymax)
>     coord. ref. : +proj=utm +zone=29 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
>     variables   : 2
>     names       :              DEM,            pdist
>     min values  : 450.001007080078, 1289.01733845496
>     max values  : 548.039978027344, 3042.91320760357

#plots
plot(r)
plot(rpoints, add = TRUE)
plot(shpA, add=TRUE)


text:
Q: Strptime open source code not implementing I am trying to convert a string into time format. As I read here on stackoverflow, the discussion of converting a string into time format. The function strptime() has been used for the same. I am also using the strptime() in my program in C, in windows. I tried to copy the open source strptime code from the following link in my program, but there are too many headerfiles missing. I created those headerfiles too, but still the code is not working and giving many warnings.
Please help.
http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/time/strptime.c?rev=HEAD
Thanks much.

A: From the (Linux) manual page for strptime():

Conforming To
SUSv2, POSIX.1-2001.

Those are Unix specifications; Windows doesn't implement them in general.

A: The following is an open source implementation of strptime. You can use that if the license fits your legal status.
Shamelessly stolen from here.
/*  $NetBSD: strptime.c,v 1.28 2008/04/28 20:23:01 martin Exp $ */

/*-
 * Copyright (c) 1997, 1998, 2005, 2008 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code was contributed to The NetBSD Foundation by Klaus Klein.
 * Heavily optimised by David Laight
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: strptime.c,v 1.28 2008/04/28 20:23:01 martin Exp $");
#endif
#include "namespace.h"
#include <sys/localedef.h>
#include <ctype.h>
#include <locale.h>
#include <string.h>
#include <time.h>
#include <tzfile.h>
#ifdef __weak_alias
__weak_alias(strptime,_strptime)
#endif
#define _ctloc(x)       (_CurrentTimeLocale->x)

/*
 * We do not implement alternate representations. However, we always
 * check whether a given modifier is allowed for a certain conversion.
 */
#define ALT_E           0x01
#define ALT_O           0x02
#define LEGAL_ALT(x)        { if (alt_format & ~(x)) return NULL; }

static const char gmt[4] = { "GMT" };

static const u_char *conv_num(const unsigned char *, int *, uint, uint);
static const u_char *find_string(const u_char *, int *, const char * const *,
    const char * const *, int);

char *
strptime(const char *buf, const char *fmt, struct tm *tm)
{
    unsigned char c;
    const unsigned char *bp;
    int alt_format, i, split_year = 0;
    const char *new_fmt;

    bp = (const u_char *)buf;

    while (bp != NULL && (c = *fmt++) != '\0') {
        /* Clear `alternate' modifier prior to new conversion. */
        alt_format = 0;
        i = 0;

        /* Eat up white-space. */
        if (isspace(c)) {
            while (isspace(*bp))
                bp++;
            continue;
        }

        if (c != '%')
            goto literal;

again:      switch (c = *fmt++) {
        case '%':   /* "%%" is converted to "%". */
literal:
            if (c != *bp++)
                return NULL;
            LEGAL_ALT(0);
            continue;

        /*
         * "Alternative" modifiers. Just set the appropriate flag
         * and start over again.
         */
        case 'E':   /* "%E?" alternative conversion modifier. */
            LEGAL_ALT(0);
            alt_format |= ALT_E;
            goto again;

        case 'O':   /* "%O?" alternative conversion modifier. */
            LEGAL_ALT(0);
            alt_format |= ALT_O;
            goto again;

        /*
         * "Complex" conversion rules, implemented through recursion.
         */
        case 'c':   /* Date and time, using the locale's format. */
            new_fmt = _ctloc(d_t_fmt);
            goto recurse;

        case 'D':   /* The date as "%m/%d/%y". */
            new_fmt = "%m/%d/%y";
            LEGAL_ALT(0);
            goto recurse;

        case 'F':   /* The date as "%Y-%m-%d". */
            new_fmt = "%Y-%m-%d";
            LEGAL_ALT(0);
            goto recurse;

        case 'R':   /* The time as "%H:%M". */
            new_fmt = "%H:%M";
            LEGAL_ALT(0);
            goto recurse;

        case 'r':   /* The time in 12-hour clock representation. */
            new_fmt =_ctloc(t_fmt_ampm);
            LEGAL_ALT(0);
            goto recurse;

        case 'T':   /* The time as "%H:%M:%S". */
            new_fmt = "%H:%M:%S";
            LEGAL_ALT(0);
            goto recurse;

        case 'X':   /* The time, using the locale's format. */
            new_fmt =_ctloc(t_fmt);
            goto recurse;

        case 'x':   /* The date, using the locale's format. */
            new_fmt =_ctloc(d_fmt);
            recurse:
            bp = (const u_char *)strptime((const char *)bp,
                                new_fmt, tm);
            LEGAL_ALT(ALT_E);
            continue;

        /*
         * "Elementary" conversion rules.
         */
        case 'A':   /* The day of week, using the locale's form. */
        case 'a':
            bp = find_string(bp, &tm->tm_wday, _ctloc(day),
                    _ctloc(abday), 7);
            LEGAL_ALT(0);
            continue;

        case 'B':   /* The month, using the locale's form. */
        case 'b':
        case 'h':
            bp = find_string(bp, &tm->tm_mon, _ctloc(mon),
                    _ctloc(abmon), 12);
            LEGAL_ALT(0);
            continue;

        case 'C':   /* The century number. */
            i = 20;
            bp = conv_num(bp, &i, 0, 99);

            i = i * 100 - TM_YEAR_BASE;
            if (split_year)
                i += tm->tm_year % 100;
            split_year = 1;
            tm->tm_year = i;
            LEGAL_ALT(ALT_E);
            continue;

        case 'd':   /* The day of month. */
        case 'e':
            bp = conv_num(bp, &tm->tm_mday, 1, 31);
            LEGAL_ALT(ALT_O);
            continue;

        case 'k':   /* The hour (24-hour clock representation). */
            LEGAL_ALT(0);
            /* FALLTHROUGH */
        case 'H':
            bp = conv_num(bp, &tm->tm_hour, 0, 23);
            LEGAL_ALT(ALT_O);
            continue;

        case 'l':   /* The hour (12-hour clock representation). */
            LEGAL_ALT(0);
            /* FALLTHROUGH */
        case 'I':
            bp = conv_num(bp, &tm->tm_hour, 1, 12);
            if (tm->tm_hour == 12)
                tm->tm_hour = 0;
            LEGAL_ALT(ALT_O);
            continue;

        case 'j':   /* The day of year. */
            i = 1;
            bp = conv_num(bp, &i, 1, 366);
            tm->tm_yday = i - 1;
            LEGAL_ALT(0);
            continue;

        case 'M':   /* The minute. */
            bp = conv_num(bp, &tm->tm_min, 0, 59);
            LEGAL_ALT(ALT_O);
            continue;

        case 'm':   /* The month. */
            i = 1;
            bp = conv_num(bp, &i, 1, 12);
            tm->tm_mon = i - 1;
            LEGAL_ALT(ALT_O);
            continue;

        case 'p':   /* The locale's equivalent of AM/PM. */
            bp = find_string(bp, &i, _ctloc(am_pm), NULL, 2);
            if (tm->tm_hour > 11)
                return NULL;
            tm->tm_hour += i * 12;
            LEGAL_ALT(0);
            continue;

        case 'S':   /* The seconds. */
            bp = conv_num(bp, &tm->tm_sec, 0, 61);
            LEGAL_ALT(ALT_O);
            continue;

        case 'U':   /* The week of year, beginning on sunday. */
        case 'W':   /* The week of year, beginning on monday. */
            /*
             * XXX This is bogus, as we can not assume any valid
             * information present in the tm structure at this
             * point to calculate a real value, so just check the
             * range for now.
             */
             bp = conv_num(bp, &i, 0, 53);
             LEGAL_ALT(ALT_O);
             continue;

        case 'w':   /* The day of week, beginning on sunday. */
            bp = conv_num(bp, &tm->tm_wday, 0, 6);
            LEGAL_ALT(ALT_O);
            continue;

        case 'Y':   /* The year. */
            i = TM_YEAR_BASE;   /* just for data sanity... */
            bp = conv_num(bp, &i, 0, 9999);
            tm->tm_year = i - TM_YEAR_BASE;
            LEGAL_ALT(ALT_E);
            continue;

        case 'y':   /* The year within 100 years of the epoch. */
            /* LEGAL_ALT(ALT_E | ALT_O); */
            bp = conv_num(bp, &i, 0, 99);

            if (split_year)
                /* preserve century */
                i += (tm->tm_year / 100) * 100;
            else {
                split_year = 1;
                if (i <= 68)
                    i = i + 2000 - TM_YEAR_BASE;
                else
                    i = i + 1900 - TM_YEAR_BASE;
            }
            tm->tm_year = i;
            continue;

        case 'Z':
            tzset();
            if (strncmp((const char *)bp, gmt, 3) == 0) {
                tm->tm_isdst = 0;
#ifdef TM_GMTOFF
                tm->TM_GMTOFF = 0;
#endif
#ifdef TM_ZONE
                tm->TM_ZONE = gmt;
#endif
                bp += 3;
            } else {
                const unsigned char *ep;

                ep = find_string(bp, &i,
                             (const char * const *)tzname,
                              NULL, 2);
                if (ep != NULL) {
                    tm->tm_isdst = i;
#ifdef TM_GMTOFF
                    tm->TM_GMTOFF = -(timezone);
#endif
#ifdef TM_ZONE
                    tm->TM_ZONE = tzname[i];
#endif
                }
                bp = ep;
            }
            continue;

        /*
         * Miscellaneous conversions.
         */
        case 'n':   /* Any kind of white-space. */
        case 't':
            while (isspace(*bp))
                bp++;
            LEGAL_ALT(0);
            continue;

        default:    /* Unknown/unsupported conversion. */
            return NULL;
        }
    }

    return __UNCONST(bp);
}

static const u_char *
conv_num(const unsigned char *buf, int *dest, uint llim, uint ulim)
{
    uint result = 0;
    unsigned char ch;

    /* The limit also determines the number of valid digits. */
    uint rulim = ulim;

    ch = *buf;
    if (ch < '0' || ch > '9')
        return NULL;

    do {
        result *= 10;
        result += ch - '0';
        rulim /= 10;
        ch = *++buf;
    } while ((result * 10 <= ulim) && rulim && ch >= '0' && ch <= '9');

    if (result < llim || result > ulim)
        return NULL;

    *dest = result;
    return buf;
}

static const u_char *
find_string(const u_char *bp, int *tgt, const char * const *n1,
        const char * const *n2, int c)
{
    int i;
    unsigned int len;

    /* check full name - then abbreviated ones */
    for (; n1 != NULL; n1 = n2, n2 = NULL) {
        for (i = 0; i < c; i++, n1++) {
            len = strlen(*n1);
            if (strncasecmp(*n1, (const char *)bp, len) == 0) {
                *tgt = i;
                return bp + len;
            }
        }
    }

    /* Nothing matched */
    return NULL;
}


text:
Q: Работа с библиотекой geocoder Исходная задача. Есть широта и долгота. Надо получить адрес, страна, город, область и пр.
Использую библиотеку geocoder.
в режиме дебага посмотрел, куда обращается geocoder при выполнении. он дает запрос в гугл. Возможно, тут причина.
API key гугл я сделал. Карты две подключил. Для всех карт один API key.
import geocoder

api_key = 'api_key'
g = geocoder.google([45.15, -75.14], method='reverse', key=api_key)

print(str(g.ok)) #False возвращает.

Посмотрел, что вызывает при создании g

В чем может быть причина?

A: <[REQUEST_DENIED] Google - Geocode [empty]> - некорректный api_key, с действительныи ключом работает:
import geocoder

api_key = 'my_api_key'
g = geocoder.google([45.15, -75.14], method='reverse', key=api_key)

в g:
>>> g
<[OK] Google - Reverse #9 results>
>>> g.status
'OK'

результаты:

for r in g:
    print(r)

[14634 Concession Rd 4, Berwick, ON K0C 1G0, Canada]
[14634 Concession Rd 4, Berwick, ON K0C 1G0, Canada]
[Berwick, ON K0C 1G0, Canada]
[North Stormont, ON, Canada]
[Ontario K0C, Canada]
[Stormont, Dundas and Glengarry United Counties, ON, Canada]
[Ontario, Canada]
[Canada]
[5V25+2X North Stormont, ON, Canada]


text:
Q: How to add hover effect to button using Revolution slider in word press Am using Revolution slider in wordpress how to give hover effect to button please any one help me.
 Am created class for that am written css but its not taking.

A: It's actually quite easy.
Once you add a button layer, you can choose an idle and hover state color. If you have already added a button layer you can right-click on the button itself, choose "Style" > "Advanced Layer CSS" and you will have two tabs - one is for idle and one for hover.
In both tabs you can enter background-color and choose what color should be displayed for idle button and hovered button.

A: In Slider Revolution 6, it is in "Layer options -> Hover"
There you can set it all for hover state


text:
Q: deny IPs from wp-login using .htaccess i am trying to ban a spam bot IP from my wordpress, since the "limit login attempts" extension mails me multiple times every day, that the same IP is trying to login. so i added the following to the .htaccess file in the wordpress root:
order allow,deny
allow from all
deny from x.x.x.x

with x.x.x.x being the IP of the bot. still the bot is trying to login. so i tried my own IP and found out, that the htaccess order does only block the css of the login page. mywordpress.com/wp-login.php still shows the login form, though without any styling, but the bot can still try to gain access.
so how can i really block the entire site including the backend from certain IPs?

A: I think you've got it backwards. Try
order allow,deny
deny from x.x.x.x
allow from all

That should block all URLs from that IP.
And Limit Login Attempts  http://wordpress.org/extend/plugins/limit-login-attempts/ can be set to not email you with each lockout. Set the lockout timeouts to 9999 hours, too, which is the maximum setting.
If things still don't work, deactivate other plugins that might be intercepting calls to or reads of .htaccess.

A: You should also consider blocking entire ranges of IP addresses if they come from countries that aren't a part of your normal reader base.  Russia, China, and some countries in Euorpe are notorious for turining a blind eye to spammers and other bots that can wreak havock on your system.  Just locate the offending IP in your log file and look it up in whois.  The whois record should list the ip range it's a part of and then block it.
Edit - If you look at your log files you can easily tell who the offenders are.  I had to ban hundreds of IP ranges because it severely effected the performance of my server (over 500K unique non spam/bot users a month).


text:
Q: Do I need a decoupling cap for ICs that do not switch very fast? I am designing a space and cost constrained layout. On it I have two analog muxes (ADG719 (datasheet) or similar.) Both switch states a maximum of two times a second. They do carry video signals with a bandwidth of around 10 MHz, but they aren't amplifying those signals, just passing them. So I figure I can omit the 100n capacitor which is normally installed next to all the ICs on my board. Am I okay in doing so?

A: You do need decoupling for all IC's that switch or carry analog BUT where the decoupling is located and how many there are is a matter of design. Noise happens and decoupling is essential to ensure that it does not 'happen too much" - but part of the designers role is to avoid blind and pointless use of excess decoupling. Placing a capacitor adjacent to each IC is traditional and safe enough but what matters is what is being achieved by the decoupling, not where the capacitors are located.
The object is three fold

*

*Reduce switching spikes and noise originating from an IC to such an extent that they do not interfere unacceptably with the operation of the system as a whole.

*Reduce power supply noise to such an extent that it does not interfere unacceptably with the operation of the IC.

*Providing a reservoir to handle current demand by the IC. This can largely be interpreted in terms of the other two requirements - but an IC that cares not about system noise and for which noise generated is unimportant may still misoperate if supply impedance is not low enough to handle very large demand peaks. Generally overall power supply impedance should be mostly adequate to this demand with the local cap "stiffening up" the supply somewhat
The first two aims are complementary. At a board level, if you achieved either one wholly then you would not need to achieve the other. In practice they work together. Meeting the 3rd helps the other two.
In your case, if space is constrained then moving the capacitor somewhere else or using one capacitor in the place of two or more others is entirely acceptable provided that the object that was originally aimed at** is still met. ie this places more effort on you as a system designer to properly identify and quantify your noise sources, to properly understand the  effect of noise on a given IC etc and to design a decoupling system that meets your needs.
Note that a 0.1 uF capacitor is almost certainly not the ideal size per IC - not so these days and possibly never so. Certainly 0.1 uF is often a fine compromise, but if you are trying to fine tune the result you may want a larger of smaller capacitor or possibly even several in parallel or several of different sizes in different locations. Also, as capacitor technology has improved things like ESR and lead inductance are smaller, surface mount packages give better electro mechanical environments (eg lead length minimal from an eg 0402 cap) and you may be able to use smaller or larger caps than in previous eras. Some suggest that a 1 uF ceramic cap is now a better general decoupling element than a 0.1 uF "monolithic ceramic" cap used to be, and others argue that a 0.01 uF cap is better able to handle the faster switching edges and clock speeds of modern systems.
For demanding situations it actually helps to look at specific data sheets and look at impedance/frequency curves. Capacitors of the same capacitance made with slightly different technologies (even amongst eg ceramics cap family) and/or from different manufacturers can and do have different enough frequency/impedance curves to be worth being aware of.
In the case of your multiplexers you should be able to estimate "within reason" the noise spikes originated by your ICs and the effect of system noise on them. Then by orientation of ICs, location of capacitors at sensible and critical locations etc you will be able to reduce capacitor count to under 1 capacitor for every IC.
Cost You say " ... and cost constrained..." on this point you are far less "safe". An ADG719 costs about $US1 in 10000s, falling to maybe $US0.80 in 100,000s. Maybe somewhat less in Asia. A decoupling capacitor costs around 1 cent for a 0.01uF or 0.1 uF in production volumes.  Board space and mounting and inventory and ... costs more, but the IC also has additional costs. While every cent matters, a saving of perhaps 1% to 5% on a critical component should be a secondary issue. By all means eliminate the per IC capacitor if you can - but do not let cost be the deciding factor.

In response to query

*

*What kind of trouble would be caused by the fast switching? The mux switches between two channels of a video source, so it doesn't really matter if it bounces in between the two sources as long as it settles in about 10 ms

What's acceptable deep-ends largely on what you are happy with.
If you have no other circuitry to react to noise spikes, or don't care about worst case outcomes, whatever they may be, then you may not care about generated spikes.
If noise from elsewhere does not occur, or is sure to be at a level where the effect on the video or IC is unimportant to you then you may not care about incoming noise. Extreme worst case response to noise may be IC "SCR" latchup or even destruction - but this would be "less likely" with low as opposed to no decoupling.
SCR latchup and death is a real world effect in some ICs. Less common in modern ones, by design.

Latchup
The following references cover latchup in a range of devices. Only some of the following is specifically relevant but all may be of general educational value wrt the possible effect of out of range input transients on ICs.

*

*Wikipedia

*Analog Devices CMOS analog switches

*

*NB - this application note specifically lists "Analog Devices" brand analog multiplexer and switch products which are designed to eliminate parasitic SCR latchup problems. The ADG 719 is NOT on the list of latchup exempt devices.

*This article will briefly describe the causes, mechanism, and consequences of latchup and discuss available prevention methods. Although our aim is to give an understanding of latchup as it occurs in CMOS switches, similar principles apply to many other CMOS devices. Latchup may be defined as the creation of a low-impedance path between power supply rails as a result of triggering a parasitic device. In this condition, excessive current flow is possible, and a potentially destructive situation exists. After even a very short period of time in this condition, the device in which it occurs can be destroyed or weakened; and potential damage can occur to other components in the system. Latchup may be caused by a number of triggering factors, to be discussed below—including overvoltage spikes or transients, exceeding maximum ratings, and incorrect power sequencing.

*Youtube CMOS latchup

*Siliconfareast.com

*Fairchild - CMOS 74HC - how we stopped it - 1987!

*Microchip MOSFET drivers

*Zarlink - CMOS

A: You didn't supply a link to the datasheet, so we don't know particulars.  However, any IC that contains digital signals at all should have a decoupling cap at first and even second approximation.  The signals passing thru a anlog mux aren't the issue, it's the digital signals it uses to switch those signals and switch the FETs that will be passing or not passing the analog signals.
The frequency of switching has nothing to do with it since the problem occurs at the switching edges.  If you ever switch at all, then there are probably short term current spikes.  Each spike is a separate event and it doesn't matter whether the next spike is 20ns or 2 seconds away.
Besides, decoupling caps are small and usually not much burden on a layout.  Surely there are other ways you can economize on space.  You really really don't have room for a few 0402, or 0603 or even 0805 parts?  I find that hard to believe.  What about the bottom of the board?
To paraphrase Dirty Harry: Do you feel lucky, punk?  Well, do you?  Go ahead, leave off the decoupling caps.  Make my day.

A: If you really want to save cost, then add the capacitor now and leave it unpopulated if you are 100% sure that everything will be ok in every thinkable scenario. While it will still requires the boardspace, you might save the placement and part cost in the end.
Saving costs might be tempting, but in the end you risk having to do a redesign of the board together with a sample rerun. Also, completely verifying that the design will (always) work without the decoupling capacitor will cost a LOT of ressources and money, so maybe you should start saving at some other point in your design.

A: When deciding whether to use a coupling cap, I think the normal question should be whether anything in the circuit would be affected if, every time there is a change on an input which should cause something in the device to switch, the internal state of the device was randomized, and the state of all outputs would be randomized for a new nanoseconds.  Note that analog inputs which are amplified count as "causing something to switch", but pass-gate analog connections generally don't.  From a functional standpoint, I don't see wouldn't need for bypass caps in your device.  On the other hand, if there is any noise on the supply rails from some other source, it could get capacitively-coupled onto your video signal.  In such a case, if there's more noise on the VDD reaching the device than on its VSS, adding a bypass cap might help.


text:
Q: Saving Record To Database Takes Too Long I am trying to save a record to Oracle DB in Spring Boot project. I am taking an input from rest services, running a logic and saving result into DB. While I search my logs, I saw that some of records are been saved in 10 to 20 ms but some of them saved in thousand milliseconds. I suspect of data source pooling but i am not sure. Is there any mistake in here?
JPA Configuration
@Configuration
@PropertySource({"classpath:application.properties"})
@EnableJpaRepositories(
        basePackages = "com.ykb.frd.fraudbase.repository.hibernate.fraud",
        entityManagerFactoryRef = "fraudEntityManager",
        transactionManagerRef = "fraudTransactionManager")
public class FraudConfiguration {
    @Autowired
    private DataSourceProperties dataSourceProperties;

    @Autowired
    private Environment env;

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean fraudEntityManager() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(fraudDataSource());
        em.setPackagesToScan("com.ykb.frd.fraudbase.entity.fraud");

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);

        return em;
    }

    @Primary
    @Bean
    public DataSource fraudDataSource() {
        DataSourceBuilder factory = DataSourceBuilder
                .create(this.dataSourceProperties.getClassLoader())
                .driverClassName(env.getProperty("driver-class-name"))
                .url(env.getProperty("fraud.url"))
                .username(env.getProperty("fraud.username"))
                .password(env.getProperty("fraud.password"));
        return factory.build();
    }

    @Primary
    @Bean
    public PlatformTransactionManager fraudTransactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(fraudEntityManager().getObject());
        return transactionManager;
    }
}

Repository
@Repository
public interface FraudRequestTransactionsRepository extends CrudRepository<FraudRequestTransactionsEntity, Long> {
}

Saving To Database
long start = System.currentTimeMillis();
        BaseService service = baseServices.length > 0 ? baseServices[0] : null;
        FraudRequestTransactionsEntity fraudRequestTransactionsEntity = new FraudRequestTransactionsEntity();
        fraudRequestTransactionsEntity.setLuc(0);
        fraudRequestTransactionsEntity.setTransactionId(fraudActionsRestRequest.getTransactionId());
        if (fraudActionsRestRequest.getSenderClientNo() != null)
            fraudRequestTransactionsEntity.setClientNo(Integer.parseInt(fraudActionsRestRequest.getSenderClientNo()));
        fraudRequestTransactionsEntity.setTransactionId(fraudActionsRestRequest.getTransactionId());
        fraudRequestTransactionsEntity.setUserId(fraudActionsRestRequest.getUserId());
        fraudRequestTransactionsEntity.setChannelName(fraudActionsRestRequest.getChannel());
        fraudRequestTransactionsEntity.setProcessCode(fraudActionsRestRequest.getProcessCode());
        fraudRequestTransactionsEntity.setProcessName(fraudActionsRestRequest.getProcessName());
        fraudRequestTransactionsEntity.setRequest(requestMessage);
        fraudRequestTransactionsEntity.setTransactionStatus("FINISHED");
        fraudRequestTransactionsEntity.setSessionId(fraudActionsRestRequest.getSessionId());
        Calendar date = Calendar.getInstance();
        fraudRequestTransactionsEntity.setTransactionDate(date.getTime());
        fraudRequestTransactionsEntity.setTransactionMillisecond(date.get(Calendar.MILLISECOND));
        fraudRequestTransactionsEntity.setAmount(fraudActionsRestRequest.getTlAmount());
        fraudRequestTransactionsEntity.setCurrency(fraudActionsRestRequest.getSenderCurrencyCode());
        fraudRequestTransactionsEntity.setDeviceId(fraudActionsRestRequest.getDeviceId());
        fraudRequestTransactionsEntity.setReceiverAccountNo(fraudActionsRestRequest.getReceiverAccountNo());
        fraudRequestTransactionsEntity.setTransactionType(fraudActionsRestRequest.getFraudTransactionsMapEntity().getTransactionType());
        fraudRequestTransactionsEntity.setSenderCardNo(fraudActionsRestRequest.getSenderCreditCardNumber());
        fraudRequestTransactionsEntity.setTransactionSequenceNo(Long.toString(fraudActionsRestRequest.getTransactionSequenceNo()));
        //TODO zeynep & berkin : bu alanları almamız gereken yerlere bakılacak
        /*fraudRequestTransactionsEntity.setSubScriberNo(fraudActionsRestRequest.get);
        if(fraudActionsRestRequest.getFraudTransactionsMapEntity().getTransactionType().equalsIgnoreCase(FalconUtil.RBTRAN)){
            fraudRequestTransactionsEntity.setReceiverClientNo(((RbtranServiceInputModel)service).);
            fraudRequestTransactionsEntity.setReceiverCardNo(((RbtranServiceInputModel)service).);
            fraudRequestTransactionsEntity.setReceiverPhoneNo(((RbtranServiceInputModel)service).);
        }*/

        fraudRequestTransactionsRepository.save(fraudRequestTransactionsEntity);
        log.info("[{}] REQ DB Yazma Süresi {}", fraudActionsRestRequest.getTransactionId(), System.currentTimeMillis() - start);

Logs
> 2019-02-01 09:31:03,671 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-3] [1550097604112] REQ DB Yazma Süresi 33
> 2019-02-01 09:32:04,338 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-8] [1548428179551] REQ DB Yazma Süresi 23
> 2019-02-01 09:32:38,260 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-8] [1549819439559] REQ DB Yazma Süresi 39
> 2019-02-01 09:33:41,725 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-3] [1548871854756] REQ DB Yazma Süresi 654
> 2019-02-01 09:34:04,093 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-9] [1551123829603] REQ DB Yazma Süresi 7841
> 2019-02-01 09:34:04,104 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-4] [1548256231753] REQ DB Yazma Süresi 18835
> 2019-02-01 09:34:50,452 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-1] [1550169566966] REQ DB Yazma Süresi 100
> 2019-02-01 09:35:52,729 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-8] [1548634610667] REQ DB Yazma Süresi 17
> 2019-02-01 09:36:48,676 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-9] [1548513532722] REQ DB Yazma Süresi 26
> 2019-02-01 09:37:29,116 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-10] [1547445362906] REQ DB Yazma Süresi 17
> 2019-02-01 09:39:09,091 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-4] [1548339052481] REQ DB Yazma Süresi 19
> 2019-02-01 09:39:53,977 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-2] [1547701783551] REQ DB Yazma Süresi 51
> 2019-02-01 09:40:31,429 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-2] [1550619321669] REQ DB Yazma Süresi 20
> 2019-02-01 09:41:12,516 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-2] [1549734992552] REQ DB Yazma Süresi 31
> 2019-02-01 09:42:42,585 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-2] [1550174884815] REQ DB Yazma Süresi 38
> 2019-02-01 09:44:10,962 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-2] [1547618724242] REQ DB Yazma Süresi 40
> 2019-02-01 09:47:26,009 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-5] [1548172574161] REQ DB Yazma Süresi 53
> 2019-02-01 09:47:57,171 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-1] [1548842916526] REQ DB Yazma Süresi 33
> 2019-02-01 09:47:58,080 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-5] [1547521859756] REQ DB Yazma Süresi 27
> 2019-02-01 09:49:13,696 INFO com.ykb.frd.fraudcommon.CommonApplication [http-nio-8080-exec-1] [1550270365545] REQ DB Yazma Süresi 974

Thanks.


text:
Q: How to get a gtkDialog's default response to trigger of the space bar as well I have a messageDialog set up so that its default response is gtk.RESPONSE_OK so the okay button is clicked when the user hits enter even if the okay button does not have focus. I would like to also have the space bar trigget the default_response. What is the best way to do this?
This is with python 2.4 in a linux environment. Unfortunately I don't have permission to upgrade python.

A: Connect to the key-press-event signal on the message dialog:
def on_dialog_key_press(dialog, event):
    if event.string == ' ':
        dialog.response(gtk.RESPONSE_OK)
        return True
    return False

dialog = gtk.MessageDialog(message_format='Some message', buttons=gtk.BUTTONS_OK_CANCEL)
dialog.add_events(gtk.gdk.KEY_PRESS_MASK)
dialog.connect('key-press-event', on_dialog_key_press)
dialog.run()

Bear in mind, though, that changing users' expectations of the user interface is generally considered Not Cool.

A: I'm a total noob at pygtk, but I could not get @ptomato's example + "hello world" boilerplate to work unless I responded to space and return plus added a call to dialog.destroy(). Take it for what it is worth.
#!/usr/bin/env python

# example helloworld.py

import pygtk
pygtk.require('2.0')
import gtk

def md_event(dialog, event):
    if event.keyval in (gtk.keysyms.Return, gtk.keysyms.space):
        dialog.response(gtk.RESPONSE_OK)
        dialog.destroy()
        return True
    elif event.keyval == gtk.keysyms.Escape:
        dialog.response(gtk.RESPONSE_CANCEL)
        dialog.destroy()
        return True
    return False

class HelloWorld:
    # This is a callback function. The data arguments are ignored
    # in this example. More on callbacks below.
    def hello(self, widget, data=None):
        print "Hello World"

    # Another callback
    def destroy(self, widget, data=None):
        gtk.main_quit()

    def create_message_dialog(self, x, y):
        md = gtk.MessageDialog(buttons=gtk.BUTTONS_OK_CANCEL, message_format="wawawawaaaaa")
        md.add_events(gtk.gdk.KEY_PRESS_MASK)
        md.connect("key-press-event", md_event)
        result = md.run()
        print result

    def __init__(self):
        # create a new window
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)

        # Here we connect the "destroy" event to a signal handler.
        # This event occurs when we call gtk_widget_destroy() on the window,
        # or if we return FALSE in the "delete_event" callback.
        self.window.connect("destroy", self.destroy)

        # Sets the border width of the window.
        self.window.set_border_width(10)

        self.button2 = gtk.Button("Message Dialog")
        self.button2.connect("clicked", self.create_message_dialog, None)
        self.window.add(self.button2)
        self.button2.show()

        # and the window
        self.window.show()

    def main(self):
        # All PyGTK applications must have a gtk.main(). Control ends here
        # and waits for an event to occur (like a key press or mouse event).
        gtk.main()

def run_hello():
    hello = HelloWorld()
    hello.main()

# If the program is run directly or passed as an argument to the python
# interpreter then create a HelloWorld instance and show it
if __name__ == "__main__":
    run_hello()


text:
Q: Mathematical definition of congruent sets I cant really find a proper definition for this. If two sets are congruent, then what does that mean.
I heard that it can be defined in terms of isometries...
This is with respect to the banach tarski paradox/hausdorff paradox

A: Two sets $X$ and $Y$ are congruent it they can be each partititioned in $X=\coprod X_i$ and $Y=\coprod Y_i$ (finite partitions in the definition I know, I guess this may depend on the author), such that $X_i$ is isometric to $Y_i$.
I should probably add that "congruent" is kind of a buzzword in math, so it surely has a huuuge number of different definitions depending on the context, but I think this is what you're looking for.


text:
Q: Delete branches which are not in the local repository using git There's a bunch of branches on one of my git repo's that I got when I forked it on GitHub. I don't want my GitHub fork to have these branches.
Is there any way that I can delete all the branches on my GitHub repo that are not in my local repo?

A: git push --mirror <origin> will make the refs on the remote match those in the local repository, including deleting branches that you don't have locally.
From git help push:
--mirror
    Instead of naming each ref to push, specifies that all refs under
    refs/ (which includes but is not limited to refs/heads/,
    refs/remotes/, and refs/tags/) be mirrored to the remote
    repository. Newly created local refs will be pushed to the remote
    end, locally updated refs will be force updated on the remote end,
    and deleted refs will be removed from the remote end. This is the
    default if the configuration option remote.<remote>.mirror is set.

A: You can delete remote branches my pushing an empty branch:
$ git push origin :branch-to-delete


text:
Q: Global variable declaration from class module I have a workbook with multiple modules and multiple subs. There are some variables though that are usesd constantly in most subs such as given worksheest.
eg
dim cr as worksheet
set cr=sheets("combined_report")

I have this written in way too many subs. Can I write this once in say a class module and use "cr" from any sub in any module without having to reassign it?

A: You can do this with a function in a standard module and cache the reference using the Static keyword:
Function CR() As Worksheet
    Static CRSheet As Worksheet
    If CRSheet Is Nothing Then Set CRSheet = Sheets("combined_report")
    Set CR = CRSheet
End Function

A: Yes, you can!
Generally, you can define a global variable in any module before the declaration of your subs/functions using the Global keyword, e.g.
Option Explicit

Global cr as Worksheet

Public Sub mySub...

The global variable will keep it's scope - but of course you have to initialize is first, i.e. assign a value/object to it.
It is best practice to prefix global variable with a g, e.g. gWSMain, so you'll always know you're dealing with a global variable.
In case you only want a global variable for one or more specific worksheets in your workbook, you don't need a global variable at all! Instead, you can access them directly with their code names. Those are usually Sheet1, Sheet2, etc. - but you can change the name in the properties window.
These worksheets are available globally in your application, the same way as ThisWorkbook is.


text:
Q: Windows "Print" process verb ignores my default printer argument I have adobe installed and it opens a PDF fine. I am trying to get a PDF to print to a specific printer (not my default printer) from my vb.net program - and it isn't working.
Dim p As New System.Diagnostics.ProcessStartInfo
p.Verb = "print"
p.Arguments = "Brother HL-2270DW series"
p.FileName = xfile
p.UseShellExecute = True
p.CreateNoWindow = True
p.WindowStyle = ProcessWindowStyle.Hidden

Using xp As System.Diagnostics.Process = System.Diagnostics.Process.Start(p)

      xp.WaitForExit(10000)
      xp.Close()
end using

Instead, it opens adobe with the document and wants to print to my default printer (which is the XPS document writer).

A: I found a workaround that might help others.
It was happening to us in Windows 10 with an old VB 6.0 program: regardless which printer was selected it was always coming out from the default one.
To solve this we had to uncheck the "let windows manage my default printer" on the "Printers and Scanners" dialog.
After that, VB6.0 program worked correctly.
https://support.microsoft.com/en-us/windows/set-a-default-printer-in-windows-e10cf8b8-e596-b102-bf84-c41022b5036f

A: I have found my solution that was quite easy and took about 10 minutes.
NuGet package PDFium Viewer (v2.13.0) and the 32bit PDFium.Viewer.Native.x86 (v2018.4.8.256). Works perfectly.


text:
Q: Only put random number in list if doesn't exist in a different list I have another list named lRVars
I am trying to generate another list with a hashSet generated from a loop as follows, however, I need to make sure that the number doesn't already exist in the above list:
List<int> lCVars = new List<int>();
HashSet<int> hCVars = new HashSet<int>();

        while (hCVars.Count < randCVarsCount)
        {
            hCVars.Add(rnd.Next(1, 11));

        }

        lColVars = hsColVars.ToList();

So in the above loop, I need to check if the rnd.Next already exists in the list being compared and can't figure out the syntax.
An extra eye would be great.

A: You just need a temporary variable for the random number and use that to check it already exists.
You could add an else clause and only add it to the HashSet if it isn't already in there, but the Add method does that (i.e. hs.Add(8); hs.Add(8); //hs will only have count of 1)
List<int> lCVars = new List<int>();
HashSet<int> hCVars = new HashSet<int>();
var rnd = new Random();
var randCVarsCount = 5;
while (hCVars.Count < randCVarsCount)
{
    var num = rnd.Next(1, 11);
    if (hCVars.Contains(num))
        Console.WriteLine("already in there");
    hCVars.Add(num);
}

lColVars = hsColVars.ToList();

A: Since the HashSet.ToList() method returns a new List, converting the HashSet into a List should guarantee the uniqueness of the values within your List object.
The source code for the ToList method showing this is below:
public static List<TSource> ToList<TSource> (this IEnumerable<TSource> source)
{
    Check.Source (source);
    return new List<TSource> (source);
}

In your app, you just need your own temporary variable to store the random number you wish to check. The sample program below shows the two ways of doing it.
#define UNCONDITIONAL

using System;
using System.Collections.Generic;
using System.Linq;

namespace StackOverflow
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            HashSet<int> hash = new HashSet<int>();
            Random rnd = new Random();

#if(UNCONDITIONAL)
            Console.WriteLine("Adding unconditionally...");
#else
            Console.WriteLine("Adding after checks...");
#endif

            while(hash.Count < 5)
            {
                int rv = rnd.Next (1, 11);
#if(UNCONDITIONAL)
                hash.Add (rv);
#else
                if(hash.Contains(rv))
                {
                    Console.WriteLine ("Duplicate skipped");
                }
                else
                {
                    hash.Add (rv);
                }
#endif
            }

            List<int> list = hash.ToList ();  // ToList() gives back a new instance
            foreach(var e in list)
            {
                Console.WriteLine (e);
            }
        }
    }
}

NOTE: The UNCONDITIONAL symbol is simply to let you play around with an example more easily. You can comment it out to see both behaviors.
Sample output with symbol defined:
Adding unconditionally...
5
10
2
6
3

Sample output with symbol commented out:
Adding after checks...
Duplicate skipped
7
3
4
2
10


text:
Q: Value inside loop doesn't change Can someone please explain me how to change template.portNumber value ?
var template = {
  portNumber: null,
  stuff: ""
}

myfunc(template, 3);

function myfunc(template, count) {
  var ports = {}
  for (var i = 0; i < count; i++) {
    var portNumber = i + 1;
    ports[portNumber.toString()] = template;
    ports[portNumber.toString()].portNumber = portNumber;
  }
  console.debug(JSON.stringify(ports, null, 4));
  return ports;
}

Result:
"{
    "1": {
        "portNumber": 3,
        "stuff": ""
    },
    "2": {
        "portNumber": 3,
        "stuff": ""
    },
    "3": {
        "portNumber": 3,
        "stuff": ""
    }
}"

Expected:
"{
    "1": {
        "portNumber": 1,
        "stuff": ""
    },
    "2": {
        "portNumber": 2,
        "stuff": ""
    },
    "3": {
        "portNumber": 3,
        "stuff": ""
    }
}"

Sorry for the stupid question but i really stuck with it. Same code works well in python.
Thanks.

A: Your array ends up having three references to the same object so each time you mutate it the change is visible in all array elements.
Writing ports[0].port = "99" will in other words change also ports[1].port because ports[0] and ports[1] are the very same object.
You need to create a copy of the object instead...

A: The reason all array object are reference type so point to only one instance.
Try using constructor function like this.
var template = function(portno, stf){
  this.portNumber = portno;
  this.stuff = stf;
}

myfunc(template, 3);

function myfunc(template, count) {
  var ports = {}
  for (var i = 0; i < count; i++) {
    var portNumber = i + 1;
    ports[portNumber.toString()] = new template(portNumber , template.stuff);
  }
  console.debug(JSON.stringify(ports, null, 4));
  return ports;
}

A: The template object is passed by reference, so all the items refer to the same object. It ends up looking a little like this:
template = {portNumber: 3, stuff: ""};
return {ports: {1:template, 2: template, 3: template}}

You need to clone the object, and then set it.
var template = {
  portNumber: null,
  stuff: ""
}

myfunc(template, 3);

function myfunc(template, count) {
  var ports = {}
  for (var i = 0; i < count; i++) {
    var portNumber = i + 1;
    ports[portNumber] = JSON.parse(JSON.stringify(template));
    ports[portNumber].portNumber = portNumber;
  }
  console.debug(JSON.stringify(ports, null, 4));
  return ports;
}

Also, you don't need to manually stringify a numerical key, it's done automatically.

A: This is a reference problem.

console.log(myFunc(template, 3));

function myFunc(template, count) {
  var ports = {}
  for (var i = 0; i < count; i++) {
    var portNumber = i + 1;
    ports[portNumber.toString()] = {portNumber:null, stuff:""};
    ports[portNumber.toString()].portNumber = portNumber;
  }
  // console.debug(JSON.stringify(ports, null, 4));
  return ports;
}

A: It's because template variable in your function holds the reference of the template object outside your function.
Try this:
 function myFunc (template, count) {
var ports = {};
for(var i = 0; i < count; i++) {
    var portNumber = i + 1;
    var tmplt = JSON.parse(JSON.stringify(template));
    tmplt.portNumber = portNumber;
    ports[portNumber + ''] = tmplt;
}
return ports;
    }


text:
Q: delete values from dataset i have an dataset with 3 tables in it they have a masterchild relationship,
lets  say the dataset is  like this
department table
deptID  departmentname
 1      IT
 2      CS
 3      EC

employee  table
empID  Empname DeptID
1      kiran    1
2      manu     2
3      kumar    3
4      ajay     3

now i have to delete value deptID =3 from  department table
then all the  employee who have DeptID ='3'  have  to  be  deleted from Employee table
how  do we do in dataset , is there any  builtin  function
thanks
Prince5

A: You have to define a ForeignKeyConstraint and set the rule to cascade:
 ForeignKeyConstraint fk = new ForeignKeyConstraint(dtDepartment.Columns["deptID"], dtEmployee.Columns["DeptID"]);
 fk.DeleteRule = Rule.Cascade;

Now when you delete records in the parent it will delete them in the children as well.

A: You can add a constraint to you dataset and enable cascade deleting
http://msdn.microsoft.com/en-us/library/st1t2c35.aspx