text:
Q: I can't get value of this class

class Progress {
    constructor(Max, Min) {
        this.Max = Max;
        this.Min = Min;
        this.current;
    }

    static get get() {
        //((input - min) * 100) / (max - min)
        return this.current;
    }

    static set Progress(number) {
        this.current = number;
    }
}

var prog = new Progress(0, 200);
prog.Progress = 22;
console.log(prog.get);
// console return 'undefined'

Any can help me with this.
I try to get the percent, of "Max" and "Min", but i can't get nothing

A:
Static
The static keyword defines a static method for a class. Static methods aren't called on instances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects.

You have a problem because of the modifier static, basically, you're not calling the method/attribute get because you're trying to access an attribute which doesn't exist.
For example, to access the static method get, you have to execute the following:
Progress.get

Removing the modifier static everthing work well.

class Progress {
  constructor(Max, Min) {
    this.Max = Max;
    this.Min = Min;
  }

  get get() {
    return this.current;
  }

  set Progress(number) {
    this.current = number;
  }
}

var prog = new Progress(0, 200);
prog.Progress = 22;
console.log(prog.get);

A: Remove the static from get and set as static methods cannot access local variables
class Progress {
  constructor(Max, Min) {
    this.Max = Max;
    this.Min = Min;
    this.current;
  }

  get get() {
    //((input - min) * 100) / (max - min)
    return this.current;
  }

  set Progress(number) {
    this.current = number;
  }
}

var prog = new Progress(0, 200);
prog.Progress = 22;
console.log(prog.get);


text:
Q: Why do invres and invresz give me identical results, but freqs and freqz give completely different results? I'm using scipy.signal.invresz() to generate a digital filter from a pole/residue specification. I notice that using the invres() function gives me the same result. However, using freqz vs. freqs to generate the plotting data give me drastically different plots; why?
%matplotlib inline

import random
import numpy        as np
import scipy.signal as sig

from matplotlib import pyplot as plt

# Simulation configuration
n_bits        = 128
samps_per_bit = 32
symbols       = [1, -1]
peaking_mag   = 12         # (dB)

# Generate the oversampled random symbol stream.
u = np.array([random.choice(symbols) for i in xrange(n_bits)]).repeat(samps_per_bit)

# Generate the peaking filter (i.e. - CTLE).
p1 = -1. / samps_per_bit
p2 = -2. / samps_per_bit
z  = p1 / pow(10., peaking_mag / 20.)
r1 = (z - p1) / (p2 - p1)
r2 = 1. - r1

# I get the same values for 'b' and 'a', whether I use invres, or invresz.
b, a = sig.invresz([r1, r2], [p1, p2], [])
print b, a
b, a = sig.invres([r1, r2], [p1, p2], [])
print b, a

# But, I get drastically different plots, depending upon my use of freqz vs. freqs.
# I was expecting to get similar plots, as long as I was consistent in my choice of S vs. Z domain.
# That is: use invresz/freqz, or invres/freqs.
w, h = sig.freqz(b, a)
plt.plot(w, abs(h))
plt.figure()
w, h = sig.freqs(b, a)
plt.plot(w, abs(h))

[ 1.          0.00784965] [ 1.          0.09375     0.00195312]
[ 1.          0.00784965] [ 1.          0.09375     0.00195312]
Out[16]:

redpajama_set_name: RedPajamaStackExchange


text:
Q: webpack dev server not serving (but compiles) I'm trying to setup a basic webpack config for react and serve it in dev mode using webpack dev server. Webpack compiles everything just fine, but the files aren't served when using webpack dev server... I am hosting the project on a VPS and tested whether the server is reachable using a boilerplate create-react-app dev server - it is. I can see the project just fine going to 'http://serverIPv4:3000'. Webpack dev server project is configured to serve on port 9000 - and that does not work, even though the files are being compiled. It also doesn't work on default port 8080 or 3000. What am I missing?
webpack.config.js:
const webpack = require('webpack');
const path = require('path');

const config = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                use: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            }
        ]
    },
    resolve: {
        extensions: [
            '.js',
            '.jsx'
        ]
    },
    devServer: {
        contentBase: path.resolve(__dirname, 'dist'),
        compress: true,
        port: 9000
    },

};

module.exports = config;

devDependencies:
"webpack": "^5.11.1",
"webpack-cli": "^4.3.1",
"webpack-dev-server": "^3.11.1"

project structure:
dist
 |-index.html
src
 |-App.js
 |-index.js
 |-styles.css

Console output:
ℹ 「wds」: Project is running at http://localhost:9000/
ℹ 「wds」: webpack output is served from /
ℹ 「wds」: Content not from webpack is served from /home/ubuntu/rcw-webpack/dist
ℹ 「wdm」: asset bundle.js 1.36 MiB [emitted] (name: main)
runtime modules 1.25 KiB 6 modules
modules by path ./node_modules/ 1.29 MiB 32 modules
modules by path ./src/ 4.32 KiB
  modules by path ./src/*.js 3.65 KiB
    ./src/index.js 244 bytes [built] [code generated]
    ./src/App.js 3.41 KiB [built] [code generated]
  modules by path ./src/*.css 681 bytes
    ./src/styles.css 327 bytes [built] [code generated]
    ./node_modules/css-loader/dist/cjs.js!./src/styles.css 354 bytes [built] [code generated]
webpack 5.11.1 compiled successfully in 2535 ms
ℹ 「wdm」: Compiled successfully.

UPDATE: package.json:
{
  "name": "rcw-webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "clean": "rm dist/bundle.js",
    "dev": "webpack --mode development",
    "start": "webpack serve --mode development --env development",
    "build-prod": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.12.10",
    "@babel/preset-env": "^7.12.11",
    "@babel/preset-react": "^7.12.10",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "babel-loader": "^8.2.2",
    "css-loader": "^5.0.1",
    "style-loader": "^2.0.0",
    "ts-loader": "^8.0.14",
    "typescript": "^4.1.3",
    "webpack": "^5.11.1",
    "webpack-cli": "^4.3.1",
    "webpack-dev-server": "^3.11.1"
  },
  "dependencies": {
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "socket.io-client": "^3.0.5"
  }
}


text:
Q: Sink kafka topics in strict order I have generated new topics with Kafka Streams. I want to sink them to Postgres DB in correct way. In Postgres DB I have tables with foreign keys. Is it possible to set priority for topics because I don't know how to solve the problem with foreign keys (which I must have in Postgres if I add some new data) ?

A: I think the only way we can guarantee ordering events in Kafka is by the concept of keys into a single partition. So if your case is like you have data in two separate topics at the same time and need to start consuming the other only after events in one is consumed, am afraid this kind of orchestration is not built into Kafka. And it is hard to achieve it without some additional logic/tool outside of Kafka.


text:
Q: Getting "TypeError: cis.createLoader is not a function" unit testing BsDatepickerDirective The following is a piece of code of my unit testing.
let BsDatepickerConfigStub = {};

beforeEach(() => {
    TestBed.configureTestingModule({
        ...
        providers: [
            { provide: BsDatepickerConfig, useValue: BsDatepickerConfigStub }
        ]
    }).compileComponents();
    fixture = TestBed.createComponent(GoalDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});

Whenever I run the test
it('should create', () => {
    expect(component).toBeTruthy();
});

I get this error:
TypeError: cis.createLoader is not a function at new BsDatepickerDirective
What is right way to mock all Bootstrap items in unit testing?


text:
Q: Lightroom 5, photo order is wrong in Develop mode When in Develop mode, my opened Catalog or simply imported photos, are not displayed in order.
I am trying to find a "Sort by Name" or similar like I have in Windows, but I cant find it.
This problem is frustrating because I am an event photographer, and I want the beginning of the night to be the first photos I edit. Also, imagine shooting a city for a full weekend. You will end up with many shots of one building, so you want them nicely in a row so you can easily go through all of them. Instead of having to scroll back and forth trying to find all of them.
My question is, how do I sort the order? It should be so easy. What have I missed?

A: Go back to the Grid Mode, then use the View > Sort menu to set your sorting option.


text:
Q: Why using a dot (.) separator in folder structure in .NET/C# I'm new to c# & .NET development and I was wondering what is the use of the . in folder structure.
Example:
Folder -> Project.Api
Folder -> Project.Api.Tests
Folder -> Project.Database.Models
I think I'm probably missing something here, so thank you for any explanations on this!


text:
Q: Como identificar fim da linha em JavaScript / jQuery? Tenho o seguinte código:
var cont1 = $('.stat_col:contains("Total de páginas impressas")').next();
var cont2 = $('.stat_col:contains("Total de páginas impressas em preto e branco")').next();
var cont3 = $('.stat_col:contains("Total de páginas coloridas impressas")').next();
var cont4 = $('.stat_col:contains("Total de páginas impressas de um só lado")').next();
var cont5 = $('.stat_col:contains("Total de páginas impressas de ambos os lados")').next();
var cont6 = $('.stat_col:contains("Total de atolamentos")').next();
var cont7 = $('.stat_col:contains("Total de separações perdidas")').next();
var cont8 = $('.stat_col:contains("Total de páginas digitalizadas do ADF")').next();
var cont9 = $('.stat_col:contains("Total de páginas digitalizadas de ambos os lados")').next();
var cont10 = $('.stat_col:contains("Total de páginas do vidro do scanner")').next();
var cont11 = $('.stat_col:contains("Total de atolamentos")').next();
var cont12 = $('.stat_col:contains("Total de separações perdidas")').next();
var cont13 = $('.stat_col:contains("Total de cópias")').next();
var cont14 = $('.stat_col:contains("Total de cópias em preto e branco")').next();
$(cont1).append($(" - " + cont1).html());

A exemplo o conteúdo do HTML da linha que cont1 procura é:

Total de páginas impressas	5382

O problema que por exemplo o tudo que tem no 'cont1', tem também no 'cont2', 4 e 5.
Preciso além de capturar cada 'contador', poder injetar uma informação (dinâmica) em cada um deles com base no valor correspondente de cada linha.

A: Talvez você nem precise de regex. Basta buscar por elementos cuja classe é stat_col, e usar filter para filtrar esses elementos pelo texto exato:

let cont1 = $('.stat_col').filter(function() {
    return $(this).text() === "Total de páginas impressas";
}).next();
let cont2 = $('.stat_col').filter(function() {
    return $(this).text() === "Total de páginas impressas em preto e branco";
}).next();
console.log(cont1.text()); // 5382
console.log(cont2.text()); // 123

Total de páginas impressas em preto e branco	123

Total de páginas impressas	5382

Ao fazer a comparação com ===, estou buscando pelo texto exato. Se você está buscando sempre por textos fixos, usar regex é um exagero.

Também é possível fazer as mesmas buscas sem jQuery:

function filtrar(texto) {
    return Array.prototype.filter.call(
        document.querySelectorAll('.stat_col'),
        function(node) {
            return node.innerText === texto;
        }
    );
}

let cont1 = filtrar("Total de páginas impressas")[0].nextSibling;
let cont2 = filtrar("Total de páginas impressas em preto e branco")[0].nextSibling;
console.log(cont1.innerText); // 5382
console.log(cont2.innerText); // 123

Total de páginas impressas em preto e branco	123

Total de páginas impressas	5382

No caso, filter retorna um array (não é o mesmo filter do jQuery), então estou pegando somente o primeiro elemento ([0]), mas caso possa haver mais de um, basta fazer um for neste array e tratar os elementos da maneira que precisar.


text:
Q: UserDefault property wrapper not saving values iOS versions below iOS 13 I am using a property wrapper to save my User Default values. On iOS 13 devices, this solution works great. However on iOS 11 and iOS 12, the values are not being saved into User Defaults. I read that property wrappers are backwards compatible so I don't know why this would not work on older iOS versions.
This is the property wrapper:
@propertyWrapper
struct UserDefaultWrapper<T: Codable> {
    private let key: String
    private let defaultValue: T

    init(key: String, defaultValue: T) {
        self.key = key
        self.defaultValue = defaultValue
    }

    var wrappedValue: T {
        get {
            guard let data = UserDefaults.standard.object(forKey: key) as? Data else {
                // Return defaultValue when no data in UserDefaults
                return defaultValue
            }

            // Convert data to the desire data type
            let value = try? JSONDecoder().decode(T.self, from: data)
            return value ?? defaultValue
        }
        set {
            // Convert newValue to data
            let data = try? JSONEncoder().encode(newValue)

            UserDefaults.standard.set(data, forKey: key)
            UserDefaults.standard.synchronize()
        }
    }
}

struct UserDefault {
    @UserDefaultWrapper(key: "userIsSignedIn", defaultValue: false)
    static var isSignedIn: Bool
}

I can then set the value like this:
UserDefault.isSignedIn = true

Am I using the property wrapper wrong? Is anyone else running into issues with property wrappers on older iOS versions?

A: Nothing to do with property wrappers! The problem is that in iOS 12 and before, a simple value like a Bool (or String, etc.), though Codable as a property of a Codable struct (for example), cannot itself be JSON encoded. The error (which you are throwing away) is quite clear about this:

Top-level Bool encoded as number JSON fragment.

To see this, just run this code:
    do {
        _ = try JSONEncoder().encode(false)
        print("succeeded")
    } catch {
        print(error)
    }

On iOS 12, we get the error. On iOS 13, we get "succeeded".
But if we wrap our Bool (or String, etc.) in a Codable struct, all is well:
    struct S : Codable { let prop : Bool }
    do {
        _ = try JSONEncoder().encode(S(prop:false))
        print("succeeded")
    } catch {
        print(error)
    }

That works fine on both iOS 12 and iOS 13.
And that fact suggests a solution! Redefine your property wrapper so that it wraps its value in a generic Wrapper struct:
struct UserDefaultWrapper<T: Codable> {

    struct Wrapper<T> : Codable where T : Codable {
        let wrapped : T
    }

    private let key: String
    private let defaultValue: T

    init(key: String, defaultValue: T) {
        self.key = key
        self.defaultValue = defaultValue
    }

    var wrappedValue: T {
        get {
            guard let data = UserDefaults.standard.object(forKey: key) as? Data
                else { return defaultValue }
            let value = try? JSONDecoder().decode(Wrapper<T>.self, from: data)
            return value?.wrapped ?? defaultValue
        }
        set {
            do {
                let data = try JSONEncoder().encode(Wrapper(wrapped:newValue))
                UserDefaults.standard.set(data, forKey: key)
            } catch {
                print(error)
            }
        }
    }
}

Now it works on iOS 12 and iOS 13.

By the way, I actually think you would do better to save as a property list rather than JSON. But that makes no difference to the question generally. You can't encode a bare Bool as a property list either. You'd still need the Wrapper approach.


text:
Q: How do I prevent text selection on my website? I am working on an internal website for a company and they requested that I disable text selection as well as right click. They want text selection disabled mainly to prevent people from using Control+C to copy since right click is disabled.
I have been requested to allow text selection in textboxes as well as textfields. I managed to get this working except for the fact that in Internet Explorer, users can't select in text boxes. Chrome allows text selection in textboxes.
<script type="text/JavaScript">
                var msgpopup="This action is disabled.";
                function killCopy(e){
                    return false
                }
                function reEnable(){
                    return true
                }
                document.onselectstart=new Function ("return false")

                if (window.sidebar){
                    document.onmousedown=killCopy
                    document.onclick=reEnable
                }
                function handle(){
                      if(toShowMessage== "1") alert(message);
                      if(closeSelf== "1") self.close();
                      return false;
                }
                function mouseDown() {
                     if (event.button == "2" || event.button == "3"){handle();}
                }
                function mouseUp(e) {
                     if (e.which == "2" || e.which == "3"){ handle();}
                }
                document.onmousedown=mouseDown;
                document.onmouseup=mouseUp;
                document.oncontextmenu=new Function("alert(msgpopup);return false")
            </script>
            <script type="text/javascript">
                function right(e) {
                    if (navigator.appName == 'Netscape' && (e.which == 3 || e.which == 2))
                        return false;
                    else if (navigator.appName == 'Microsoft Internet Explorer' && (event.button == 2 || event.button == 3)) {
                        return false;
                    }
                    return true;
                    }
                    document.onmousedown=right;
                    if (document.layers) window.captureEvents(Event.MOUSEDOWN); window.onmousedown=right;
            </script>

Thanks.


text:
Q: Why converting java.util.Date to java.sql.Date results in a wrong date? I am converting java.util.Date to java.sql.date to insert date of birth in mysql database.
But entering 2001-04-03 always results in a java.sql.Date of 2000-12-31
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter dob(YYYY-MM-DD) :");
String date = br.readLine();

SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD");

java.util.Date util_dob = dateFormat.parse(date);

java.sql.Date dob = new java.sql.Date(util_dob.getTime());

input: 2001-04-03
output: 2000-12-31
expecting: 2001-04-03

A: Your format-string is not correct.
Take a look at the documentation of SimpleDateFormat: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/SimpleDateFormat.html

*

*Uppercase Y: pattern letter for Week year

*Uppercase M: pattern letter for Month in year (correct)

*Uppercase D: pattern letter for Day in year
You should use lowercase y and lowercase d.

*

*Lowercase y: pattern letter for Year

*Lowercase d: pattern letter for Day in Month
I think your converting should work with this pattern:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");


text:
Q: Flash flash message appended to text area I am trying to retrieve flash messages and append them in a text area on a webpage. The function works without the flask/flash provided code but trying to mix flash code with javascript is not working. I am calling this function with a onclick="get_flash();"  The onclick does work without the flash code embedded.
head>
<script type="text/javascript">
function get_flash(){
{% with messages = get_flashed_messages() %}
    {{% if messages %}
         {% for message in messages() %}
             document.getElementById('msg_box').innerHTML+={{message}};
         {% endfor %}
    {% endif %}
{% endwith %}
}

A: Your code leads to an Unexpected identifier error. Put quotations around your {{message}} variable.
{% with messages = get_flashed_messages() %}
    {% if messages %}
        {% for message in messages %}
          document.getElementById('msg_box').innerHTML += "{{message}}";
        {% endfor %}
    {% endif %}
{% endwith %}


text:
Q: How do you test a new email filtering system? What method do you use to test or evaluate potential new email filtering systems before you set it up on your production network?
I am particularly interested in methods that are appropriate for small/medium sized organizations with a single mail server without the resources to build a duplicate of their email system.

A: Our company fits your criteria very well. For about a month before testing the new spam filter I gathered up all the spam our system was receiving by asking the users to forward it to a special account instead of just deleting it. Spam detected by our third party filter service was also forwarded to the spam account. That spam was then resent through the new filter to a temporary dummy account to see how it performed. As it was all sent in one big batch this also tested the load handling capacity of the filter.
Some adjustments were made as a result of the test and the same spam was also fed into the learning system. Users still send me any spam that gets through but over time the quantity has lessened to the point where users complain if they get just one or two spams a week.

A: You can test by sending a mail with a GTUBE (Generic Test for Unsolicited Bulk Email).
Simply create a mail containing this :
XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X

This is working fine with spamassassin for example. You may find other GTUBE for specific antispams

A: Testing a email filtering product seems to be a lot harder that it sounds on the surface. As I thought about it, I outlined my ideas and broke them down into specific problem-domains.
Delivery
The first part of testing is associated with mocking-up delivery of email to the filtering system. Potentially, a filtering system can take any of the following (and probably more things I'm forgetting) into account:

*

*Specific details of the SMTP protocol (did the sender do an HELO, EHLO, and what with name or IP, etc)

*Attributes of the sending domain's DNS (does it resolve, SPF records, domain-keys records)

*Reachability of the sender's MX (for reverse-path verification)

*Source IP address of the server delivering the message

*Content of the message

*An "opinion" that third-party databases or "signatures" give about any of the above (DNSBLs, proprietary "reputation" databases, etc)

Mocking up delivery of messages to a filtering tool becomes less representative of reality if any of these factors aren't the same as what would occur during "real" delivery. Sending captured incoming email to a filtering rig in a manner that doesn't simulate the source IP address of the sending server, for example, impedes that filtering product's ability to act on that factor (running it by a DNSBL, etc). Likewise, sending delayed messages to a filtering (say you have a "canned" corpus of messages to test with) will give a false impression of behavior because the attributes of the sender's DNS and of any third-party databases or signatures may have changed since the time the message was originally sent (sender altered their SPF records to prevent false positives, a third-party service "blacklisted" the sender, etc).
I'd argue that it's impossible to completely mock-up reality, as it comes to delivery. Getting close going to be fairly difficult if you intend to simulate the sending server's IP address (and I'm not aware of any "off the shelf" solution that does that... and having gotten fairly good results from DNSBLs, I'd be concerned about not simulating the sending server's IP address.)  Ultimately, you'll just have to get as close as you can afford.
Storage
You've got to stored the filtered email somewhere if you intend to analyze the results. Without storage of some kind there's no good way to actually view the results. Sure, the filtering software generates statistics, but it would certainly improve my comfort-level if I could see the filtered messages.
Some filtering products have a storage capability built-in (like MailMarshal, for example). Other products expect to have an email system to deliver into and don't have any storage capability. To test those products, and so as not to disrupt your production email system, you'll have to create up some kind of secondary email infrastructure to store the test filtering results.
If licensing expense is a concern, you can use free and open source tools to prevent incurring licensing expense. That may present a learning curve for the testing personnel.
More convoluted "groupware"-type email systems may present a challenge in mocking-up because of their dependencies on other services. Exchange Server will require you to mock-up an Active Directory infrastructure to host the mailboxes. Other "groupware"-type email systems (Notes, Groupwise, etc) will have their own associated degrees of difficulty in creating parallel infrastructures.
Analysis
On top of mocking-up delivery and storing the results you also need to have human analysis of the accuracy of filtering (flagging as spam, deleting, filing to a "Junk E-mail" folder, etc). It probably goes w/o saying, but a human needs to verify the results of filtering since the whole point of this exercise is to test the computer's ability to filter results. (I know, that went w/o saying... but I can just hear somebody saying "But wait! We'll write a script to test the accuracy...")
The filtering analysis is problematic foremost, to my mind, as a matter of scale. For any large group of end-users, filtering analysis is going to be beyond the abilities of an individual or small group of testers (or, more likely, they'll just "spot check" and hope for the best). Moreover, the tester may have a different idea of what should be considered "spam" than the real receiving user (who really does want to receive those stupid promotional emails from their car rental company, or the "vocabulary word of the day"). Identifying obviously failed messages is probably pretty easy (poronographic emails in the "Inbox", messages from known Customers in the "Junk E-mail" folder, etc), but there's certainly the potential for subtlety.
I don't think there's a 100% substitute for reality-- you're just going to have to get close and hope that your testing setup reflects reality closely enough to give you an accurate assessment of the filter's performance.

A: Test for relaying first to make sure you will not open a new spambox to the internet.
You can do so by using online tools like those provided here: http://spamlinks.net/prevent-secure-relay-test.htm or some tools of the non-free http://www.dnsstuff.com/.


text:
Q: Run C++ application with a custom script in Eclipse I have a custom shell that I can run C++ applications in. I start the shell from a bash prompt and then run my C++ code. I want to emulate this behavior with Eclipse, particularly for debugging. I can't seem to figure this out.
I could write a simple bash script that kicks off the custom shell and runs my application but Eclipse does not let me debug when I do this.
Is there a way to achieve this functionality?

A: Please keep in mind eclipse can set environment variables for running/debugging job.
If your shell is more complicated than that, please provide more details about your shell.
But I'm not optimistic about it.
Btw, you can always attach an existing process for debugging.


text:
Q: How can I warn about function usage in `perl -c`? Our codebase includes various debugging hooks that should only be used for testing. As an illustrative example:
sub example {
   my ($arg) = @_;
   my $result = do_something_with($arg);
   debug_dump_values($arg); # debugging code
   return $result;
}

Of course, such debugging code should not be committed (or even deployed). Is there a way to generate a warning when running this code through perl -c? Something along the lines of
Debug function debug_dump_values() called at example.pl line 4.

This would be trivial to implement as a runtime warning:
sub debug_dump_values {
    carp "Debug function debug_dump_values() called";
    ...
}

But I want a warning that shows up in my text editor through its syntax check plugin, so it needs to be a "compile-time" warning.

A: I think this isn't an easy thing to accomplish - it's not going to be possible without some significant rejigging of coding style.
Approaches I can think of:
Put your 'debug' code into a separate module.
Embed a warning in the module that indicates it's enabled - embed within a 'BEGIN' block. (This won't necessarily tell you which sub is being called though, nor where)
E.g.
BEGIN {
    carp "Debugging module is imported"
}

Advantages of this might be - you can have a 'debug' and 'not debug' module, and have the same subs in both. The 'not debug' would put in dummy subs.
You can then use B::Lint to validate your module and check if subs are all defined:
perl -MO=Lint[,OPTIONS] foo.pl
undefined-subs
This option warns whenever an undefined subroutine is invoked. This option will only catch explicitly invoked subroutines such as foo() and not indirect invocations such as &$subref() or $obj->meth() . Note that some programs or modules delay definition of subs until runtime by means of the AUTOLOAD mechanism
Assign your sub via a reference.
Edit: Doesn't work as well as I thought - had a notion of declaring anonymous subs and creating references within 'BEGIN' blocks - that doesn't work as well as I thought - it only errors at runtime, because you get errors of scope.
Best I can offer is:
use strict;
use warnings;

my $debug = 1;

##debug code bit.
#Comment out if not needed
my $debug_sub = gimme_debug();

sub gimme_debug {
    if ( $debug ) {
        warn "Debugging enabled\n";
        return sub { print "Got values of :", @_, "\n"; };
    }
    else { warn "Debug subroutine defined with debug disabled!" };
}

#... way down code ...

&$debug_sub ( "Some input" );

If you remove the declaration of then you'll get a compile time warning because $debug_sub is undeclared. This might combine with the above, e.g. bundling it in a module or object.
Automated testing
It doesn't do specifically what you asked about, however you may want to consider it anyway. Automated testing for your code/modules. For example, using TAP::Harness. It's a bit more complicated and intensive than what you're asking, but having something that'll automatically trap debug code (and otherwise validate the various components of your code) is probably the 'right' way to do it.
I've also heard of (but not done much with) Class::Inspector which may be suitable for your needs.
But I think at a fairly fundamental level - what you're trying to do isn't checked at compile time, because it's very difficult to evaluate which bits of code are actually being called without actually running the code. So anything you do like this would be something you have to 'hand manage' in some fashion.
The Halting Problem
"In computability theory, the halting problem is the problem of determining, from a description of an arbitrary computer program and an input, whether the program will finish running or continue to run forever.
Alan Turing proved in 1936 that a general algorithm to solve the halting problem for all possible program-input pairs cannot exist. A key part of the proof was a mathematical definition of a computer and program, which became known as a Turing machine; the halting problem is undecidable over Turing machines. It is one of the first examples of a decision problem."
So if you do come up with a good solution to this - there's probably a usefully large prize on offer :).

A: In my development environment, I face a similar problem. My approach has been to surround debugging code with C-style #ifdef and #endif comments, like this:
sub example {
   my ($arg) = @_;
   my $result = do_something_with($arg);
#ifdef DEBUG
   debug_dump_values($arg); # debugging code
#endif
   return $result;
}

As part of building a release, the program ppp.pl (that I wrote) runs on each Perl source file and comments out (or removes) the debugging code. A simple ppp.pl is easy to write. If anyone is interested, I can post my version in a public place.

A: if you used Log::Log4perl  and create a logger called $logger, then you can check for debug mode via $logger->is_debug()  which will call the function only if debug level is enabled
your code could then just stay then, but only be called when debugging.
ie.

sub example {
   my ($arg) = @_;
   my $result = do_something_with($arg);
   debug_dump_values($arg) if $logger->is_debug(); # debugging code
   return $result;
}


text:
Q: Add a wms layer to OL for Drupal Just installed Openlayers 7.2 for Drupal 7. I have trouble figuring out how to make a wms layer that shows these info:
http://www.kulturstyrelsen.dk/fileadmin/_migrated/content_uploads/2_1_3_Beskrivelse_af_WMS_WFS_tjenester_01.pdf
I tried to create a standard wms layer, from the layer option and put : http://www.kulturarv.dk/ffpublic/wms/ows?service=wms&version=1.1.0&request=GetCapabilities In the Base url, but nothing shows.
I tried to play with this in qgis. Inserted the same link as a WMS layer in Qgis, and this worked very well. What am i missing ? Is this the wrong way to approach it in OL ?


text:
Q: How many rich people we Robin Hood at least see?
Every black tile is a house of a rich person and every white house is a house of a poor person if Robin Hood starts from black tile(not a constant one) and can move to the tiles next to it How many rich people we Rabin Hood at least see if he wants to pass from all white tiles.It is something bigger than $5$ because for passing the corner tiles we should go from a distinct black tile to go to them but then again we can't pass the center so we should pass at least $5$ black tiles
but I can't find the case that we pass from $5$ of them but I can find the case that we pass from $6$ of them.Is the answer $6$ or $5$.

A: I'm fairly sure it is six, I can test it with a program  but ill also try to prove it.
I'm assuming the first black square is counted as seen (included in the six).
If there is a path with only 5 black squares than necessarily all white squares need to be adjacent to that set. only paths that go trough this type of sets can be solutions. since we need for each corner at least one adjacent square we clearly need one square per corner. to connect all four corner-squares we need at least one square and we need at least one square from the middle to statisfy the middle square. lets drop the connection requirement and just look at sets that accomplish  the goal of covering all the white sets. clearly we need the five black squares to do this. More interestingly is that there is only a limited number of ways to do this. in essence only two.
first consider this picture with all the outer black squares being marked S or N (South and North) and all in black  squares with a number between 1 and 4.

*

*In the first solution the center square choice doesn't matter, in this we choose the corner square so that it covers the entire outer layer. This means that all outer squares thats are next to each other horizontally have different letters and squares that are next to each other vertically have to have the same letter.
Then we can add a random middle square to cover all white squares. However without the center square it is impossible to have a path between the chosen outer black squares. since the inner square can only connect two of them. it is impossible to construct a path in this cover set and so it is not applicable.

*In the second solution we still need to pick four outer squares and one inner square. but we do not cover the entire the entire outer layer. It is clear that all white squares outside the outer layer are covered when the corners are covered except for the very center. however we can choose to not cover some white squares that are not corners but are on the outside layer. since the center square can only cover one of these we need to cover the other three.
this means we can divert from the previous solution but only with one square. this means we still have three non adjacents sets and just one connection in the form of the center square so we can still not make a path.


text:
Q: How to set values of variable using postprocessor in Jmeter and use it in Preprocessor for same sampler? My scenario is to pass different time (15 mins gap) till the script runs for each sampler run.
I am using preprocessor and postprocessor in the same step and now i want to use the the variable changed in postprocessor step, in side post processor step.
Below is the screenshot of code and script.

A: *

*According to JMeter Test Elements Execution Order PreProcessor is executed before the PostProcessor therefore you cannot access the variables set in the PostProcessor in the PreProcessor

*There is __timeShift() function which can generate the date in the given format with the given offset, for example you can add 15 minutes to current time as simple as:
${__timeShift(yyyy-MM-dd'T'HH:mm:ss.SSS'Z',,PT15M,,)}

*There is no need to use these SimpleDateFormat/Calendar in Groovy, there is TimeCategory class which makes dates manipulation very easy. Moreover, Groovy's Date class provides format() function therefore you can add 15 minutes to the current date like:
use(groovy.time.TimeCategory) {
    15.minutes.from.now.format("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
}

Demo:

A: Just found out the solution. I don't need to add preprocessor here. instead just using jsr223 sampler will work fine with onceonly controller.
preprocessor was resetting the starttime and endtime value here.


text:
Q: Next.js SyntaxError "Unexpected token 'export'" I'm trying to import a functions from a dependency to my next/react functional component, but somehow I keep getting the following error:

SyntaxError: Unexpected token 'export'

That's the function I'm trying to import:
export function classes(...args) {
    const list = [];
    for (let i = 0; i < args.length; i++) {
        const entry = args[i];
        if (typeof entry === "string") {
            list.push(entry);
        }
        else {
            for (let key in entry) {
                if (entry[key]) {
                    list.push(key);
                }
            }
        }
    }
    return list.join(" ");

There additionally is a classes.d.ts next to the classes.js above:
export declare function classes(...args: Array<string | {
    [key: string]: any;
}>): string;

Exporting this code identically from within the project works fine, but not when I use an external library from node_modules. How so?
Read about next-transpile-module, but haven't been able to make it run with this one either.
The only way to make the import work is using relative paths ../../node_modules/thedependency/class - how can I make it work properly?

A: There's another way:
import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(
  () => import('package'),
  { ssr: false }
)

// ...

// use it in render like:
<DynamicComponentWithNoSSR />

Found in https://stackoverflow.com/a/60738624/3051080
Context:
I was getting the same error: Unexpected token 'export'; with a node_modules dependency made for the browser (client-side). I tried with @MarkoCen's answer with no luck, because I got a window is not defined error later.
The dynamic approach did the trick.

A: UPDATE: All features of next-transpile-modules are now natively built-in Next.js 13.1. you should be able to use Next's transpilePackages option to transpile external packages

Old Answer: So the dependency in node_modules folder exports a function using ES6 import/export module. The code will throw error when it running in browser since browser cannot recognize the ES6 module syntax.
The reason is that, by default, Next.js configs the babel-loader to only transpile the ES6 code in the src folder, any ES6 code imported from node_modules will directly go into final bundle without transpiling.
Try to modify the webpack config in next.config.js file to let the babel loader transpile the es6 dependency. You may want to use this package next-transpile-modules

A: Next.js 13 has an option called transpilePackages that is somewhat equivalent to next-transpile-modules, check the docs here: https://beta.nextjs.org/docs/api-reference/next.config.js#transpilepackages.
I use it for youtubei.js on 'next.config.js'
experimental: {
    transpilePackages: ['youtubei.js'],
}

A: As you said that it is a js file, I am pretty sure to pinpoint your problem to this line: export function classes(...args): string
You have a Typescript declaration behind the function declaration. So remove the : string part and you should be fine.


text:
Q: Create a binary variable based on a threshold in R The following dataset contains 7 columns (i.e., AI_1 until AI_7) that have 1440 observations per ID (in total 42 IDs). I want to create a dataset that makes a binary variable of each AI based on a threshold. For example if AI_1 > 0,1 it should get the value 1 in a new variable called ACTIVITY otherwise the value 0 in the same variable ACTIVITY. I tried this with the following code but when I try to find the mean value of the binary variable it indicates that the mean is above 1.. which is curious since it can only take the value of either 0 or 1. So does anyone know how to make 7 of these binary variables in the same dataset where the mean is between 0 and 1?
structure(list(X = 1:30, x1.time = c("00:00:00", "00:01:00",
"00:02:00", "00:03:00", "00:04:00", "00:05:00", "00:06:00", "00:07:00",
"00:08:00", "00:09:00", "00:10:00", "00:11:00", "00:12:00", "00:13:00",
"00:14:00", "00:15:00", "00:16:00", "00:17:00", "00:18:00", "00:19:00",
"00:20:00", "00:21:00", "00:22:00", "00:23:00", "00:24:00", "00:25:00",
"00:26:00", "00:27:00", "00:28:00", "00:29:00"), AI_1 = c(0.17532896077581,
0.174249939439765, 0.174170544792533, 0.172877357886967, 0.173679017353614,
0.174216799443538, 0.174514454250882, 0.174656389074666, 0.173377175454716,
0.173044040397703, 0.172476572884875, 0.174738790856458, 0.173833445732856,
0.174229265722835, 0.174392878820111, 0.174715890976243, 0.174241614289181,
0.173229751013599, 0.173579164085914, 0.173829069216696, 0.173499039975341,
0.174387946222767, 0.173802854581089, 0.174107580137568, 0.174113709936873,
0.173172609295233, 0.174509255493075, 0.173383120975257, 0.173398927511582,
0.173466516952908), AI_2 = c(0.173549588758752, 0, 0.85729795236214,
0.513925586220723, 0.140789239632585, 0.0989981552300843, 0.321625480480368,
0.62540390366724, 0.00714855410741877, 0, 0, 0, 0.212943798631015,
0, 0, 0.023650258664654, 0.00159158576982517, 0.0172670511608436,
0, 0, 0, 0.25653572767355, 0.41158598021939, 0.433889173147664,
0.442200975044019, 0.471931171507954, 0.415009919603445, 0.43364443321512,
0.449930874231746, 0.48397633182816), AI_3 = c(0.026069149474549,
0.0417747330978121, 0.276687600798659, 0.258591321128928, 0.208790296683244,
0.0300099278967508, 0.15234594700642, 0.26519848659315, 0.34220566727692,
0.352310255219813, 0.297621781376737, 0.292800000618149, 0.481566536382664,
0.337770306519177, 0.743182296874282, 0.256202127993172, 0.201340506649845,
0.200155318345632, 0.237126429055375, 0.234974163009848, 0.235808994849961,
0.302168675921402, 0.377936665388589, 0.416123299239618, 0.389279883023212,
0.357972848973051, 0.305268847437493, 0.290040891577408, 0.197384083463156,
0.258282654013295), AI_4 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00841646877382803,
0), AI_5 = c(0, 0, 0.0015062890214412, 0.00154798776365785, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0), AI_6 = c(0.190018331633492, 0.241159552783285, 0.231916111803065,
0.193196835220518, 0.240381778378367, 0.266125762332231, 0.339227319507121,
0.354841547583334, 0.277011867279295, 0.474462632995715, 0.516356521276347,
0.559477604383845, 0.374857636694405, 0.376675155204282, 0.516347133869462,
0.627633542885353, 0.565732682034457, 0.544148310829377, 0.545022418887296,
0.602327138107482, 0.529578366594453, 0.571672817412653, 0.51963881197827,
0.493590581088222, 0.487545798153711, 0.525272191616523, 0.586906227102549,
0.555446579214151, 0.578788883825157, 0.617822898150646), AI_7 = c(0.139608768263461,
0.165583663096789, 0.326959508587122, 0.221739297198209, 0.160657663051105,
0.107439748199699, 0.117594125364214, 0.133528520361788, 0.117950354159875,
0.131428192187155, 0.125355403562937, 0.119185646272255, 0.196285453922129,
0.167061057207379, 0.169855099745761, 0.141077126343563, 0.078433720675593,
0.0999303057993443, 0.0798045801131668, 0.0331137028671696, 0.0920945831761988,
0.0233052285173748, 0, 0, 0, 0.00876293044107867, 0, 0.109134564970416,
0.110323312017635, 0.117772975747077), ID = c("ID1", "ID1", "ID1",
"ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1",
"ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1",
"ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1"
), activity = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0), activity2 = c("0",
"1", "0", "0", "0", "1", "0", "0", "1", "1", "1", "1", "0", "1",
"1", "1", "1", "1", "1", "1", "1", "0", "0", "0", "0", "0", "0",
"0", "0", "0"), activity3 = c("1", "1", "0", "0", "0", "1", "0",
"0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
"0", "0", "0", "0", "0", "0", "0", "0", "0", "0"), activity4 = c("1",
"1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1",
"1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1",
"1", "1", "1"), activity5 = c("1", "1", "1", "1", "1", "1", "1",
"1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1",
"1", "1", "1", "1", "1", "1", "1", "1", "1", "1"), activity6 = c("0",
"0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
"0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
"0", "0", "0"), activity7 = c("0", "0", "0", "0", "0", "0", "0",
"0", "0", "0", "0", "0", "0", "0", "0", "0", "1", "1", "1", "1",
"1", "1", "1", "1", "1", "1", "1", "0", "0", "0")), row.names = c(NA,
30L), class = "data.frame")

This is the code I used
    Threshold <- Activity_index_1 %>%
                  mutate(activity = case_when(
                          AI_1 <= 0.1 ~ "1",
                          AI_1 > 0.1 ~ "0",

                  ))
Threshold2 <-  Threshold %>%
                  mutate(activity2 = case_when(
                          AI_2 <= 0.1 ~ "1",
                          AI_2 > 0.1 ~ "0",

                  ))
Threshold3 <- Threshold2 %>%
                  mutate(activity3 = case_when(
                          AI_3 <= 0.1 ~ "1",
                          AI_3 > 0.1 ~ "0",

                  ))
Threshold4 <- Threshold3 %>%
                  mutate(activity4 = case_when(
                          AI_4 <= 0.1 ~ "1",
                          AI_4 > 0.1 ~ "0",

                  ))
Threshold5 <- Threshold4 %>%
                  mutate(activity5 = case_when(
                          AI_5 <= 0.1 ~ "1",
                          AI_5 > 0.1 ~ "0",

                  ))
Threshold6 <- Threshold5 %>%
                  mutate(activity6 = case_when(
                          AI_6 <= 0.1 ~ "1",
                          AI_6 > 0.1 ~ "0",

                  ))
Threshold7 <- Threshold6 %>%
                  mutate(activity7 = case_when(
                          AI_7 <= 0.1 ~ "1",
                          AI_7 > 0.1 ~ "0",

                  ))

A: Here is a solution with mutate/across and a logical condition returning FALSE/TRUE then coerced to integers 0/1.
The posted data already has columns activity so I start by removing them from the data.
suppressPackageStartupMessages({
  library(dplyr)
  library(stringr)
})

Threshold <- Activity_index_1 %>%
  select(-starts_with("activity")) %>%
  mutate(across(starts_with("AI_"), ~ as.integer(.x <= 0.1), .names = "activity_{col}")) %>%
  rename_at(vars(starts_with("activity_AI")), ~ str_remove(., "_AI_"))

str(Threshold)
#> 'data.frame':    30 obs. of  17 variables:
#>  $ X        : int  1 2 3 4 5 6 7 8 9 10 ...
#>  $ x1.time  : chr  "00:00:00" "00:01:00" "00:02:00" "00:03:00" ...
#>  $ AI_1     : num  0.175 0.174 0.174 0.173 0.174 ...
#>  $ AI_2     : num  0.174 0 0.857 0.514 0.141 ...
#>  $ AI_3     : num  0.0261 0.0418 0.2767 0.2586 0.2088 ...
#>  $ AI_4     : num  0 0 0 0 0 0 0 0 0 0 ...
#>  $ AI_5     : num  0 0 0.00151 0.00155 0 ...
#>  $ AI_6     : num  0.19 0.241 0.232 0.193 0.24 ...
#>  $ AI_7     : num  0.14 0.166 0.327 0.222 0.161 ...
#>  $ ID       : chr  "ID1" "ID1" "ID1" "ID1" ...
#>  $ activity1: int  0 0 0 0 0 0 0 0 0 0 ...
#>  $ activity2: int  0 1 0 0 0 1 0 0 1 1 ...
#>  $ activity3: int  1 1 0 0 0 1 0 0 0 0 ...
#>  $ activity4: int  1 1 1 1 1 1 1 1 1 1 ...
#>  $ activity5: int  1 1 1 1 1 1 1 1 1 1 ...
#>  $ activity6: int  0 0 0 0 0 0 0 0 0 0 ...
#>  $ activity7: int  0 0 0 0 0 0 0 0 0 0 ...

Created on 2022-10-10 with reprex v2.0.2

A: Comparing just AI variables with .1, convert to numeric, set colnames and cbind.
res <- cbind(dat, ((dat[grep('^AI', names(dat))] <= .1)^1) |>
               {\(.) `colnames<-`(., gsub('AI', 'activity', colnames(.)))}())

str(res)
# 'data.frame': 30 obs. of  16 variables:
# $ x1.time   : chr  "00:00:00" "00:01:00" "00:02:00" "00:03:00" ...
# $ AI_1      : num  0.175 0.174 0.174 0.173 0.174 ...
# $ AI_2      : num  0.174 0 0.857 0.514 0.141 ...
# $ AI_3      : num  0.0261 0.0418 0.2767 0.2586 0.2088 ...
# $ AI_4      : num  0 0 0 0 0 0 0 0 0 0 ...
# $ AI_5      : num  0 0 0.00151 0.00155 0 ...
# $ AI_6      : num  0.19 0.241 0.232 0.193 0.24 ...
# $ AI_7      : num  0.14 0.166 0.327 0.222 0.161 ...
# $ ID        : chr  "ID1" "ID1" "ID1" "ID1" ...
# $ activity_1: num  0 0 0 0 0 0 0 0 0 0 ...
# $ activity_2: num  0 1 0 0 0 1 0 0 1 1 ...
# $ activity_3: num  1 1 0 0 0 1 0 0 0 0 ...
# $ activity_4: num  1 1 1 1 1 1 1 1 1 1 ...
# $ activity_5: num  1 1 1 1 1 1 1 1 1 1 ...
# $ activity_6: num  0 0 0 0 0 0 0 0 0 0 ...
# $ activity_7: num  0 0 0 0 0 0 0 0 0 0 ...

dat <- structure(list(x1.time = c("00:00:00", "00:01:00", "00:02:00",
"00:03:00", "00:04:00", "00:05:00", "00:06:00", "00:07:00", "00:08:00",
"00:09:00", "00:10:00", "00:11:00", "00:12:00", "00:13:00", "00:14:00",
"00:15:00", "00:16:00", "00:17:00", "00:18:00", "00:19:00", "00:20:00",
"00:21:00", "00:22:00", "00:23:00", "00:24:00", "00:25:00", "00:26:00",
"00:27:00", "00:28:00", "00:29:00"), AI_1 = c(0.17532896077581,
0.174249939439765, 0.174170544792533, 0.172877357886967, 0.173679017353614,
0.174216799443538, 0.174514454250882, 0.174656389074666, 0.173377175454716,
0.173044040397703, 0.172476572884875, 0.174738790856458, 0.173833445732856,
0.174229265722835, 0.174392878820111, 0.174715890976243, 0.174241614289181,
0.173229751013599, 0.173579164085914, 0.173829069216696, 0.173499039975341,
0.174387946222767, 0.173802854581089, 0.174107580137568, 0.174113709936873,
0.173172609295233, 0.174509255493075, 0.173383120975257, 0.173398927511582,
0.173466516952908), AI_2 = c(0.173549588758752, 0, 0.85729795236214,
0.513925586220723, 0.140789239632585, 0.0989981552300843, 0.321625480480368,
0.62540390366724, 0.00714855410741877, 0, 0, 0, 0.212943798631015,
0, 0, 0.023650258664654, 0.00159158576982517, 0.0172670511608436,
0, 0, 0, 0.25653572767355, 0.41158598021939, 0.433889173147664,
0.442200975044019, 0.471931171507954, 0.415009919603445, 0.43364443321512,
0.449930874231746, 0.48397633182816), AI_3 = c(0.026069149474549,
0.0417747330978121, 0.276687600798659, 0.258591321128928, 0.208790296683244,
0.0300099278967508, 0.15234594700642, 0.26519848659315, 0.34220566727692,
0.352310255219813, 0.297621781376737, 0.292800000618149, 0.481566536382664,
0.337770306519177, 0.743182296874282, 0.256202127993172, 0.201340506649845,
0.200155318345632, 0.237126429055375, 0.234974163009848, 0.235808994849961,
0.302168675921402, 0.377936665388589, 0.416123299239618, 0.389279883023212,
0.357972848973051, 0.305268847437493, 0.290040891577408, 0.197384083463156,
0.258282654013295), AI_4 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00841646877382803,
0), AI_5 = c(0, 0, 0.0015062890214412, 0.00154798776365785, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0), AI_6 = c(0.190018331633492, 0.241159552783285, 0.231916111803065,
0.193196835220518, 0.240381778378367, 0.266125762332231, 0.339227319507121,
0.354841547583334, 0.277011867279295, 0.474462632995715, 0.516356521276347,
0.559477604383845, 0.374857636694405, 0.376675155204282, 0.516347133869462,
0.627633542885353, 0.565732682034457, 0.544148310829377, 0.545022418887296,
0.602327138107482, 0.529578366594453, 0.571672817412653, 0.51963881197827,
0.493590581088222, 0.487545798153711, 0.525272191616523, 0.586906227102549,
0.555446579214151, 0.578788883825157, 0.617822898150646), AI_7 = c(0.139608768263461,
0.165583663096789, 0.326959508587122, 0.221739297198209, 0.160657663051105,
0.107439748199699, 0.117594125364214, 0.133528520361788, 0.117950354159875,
0.131428192187155, 0.125355403562937, 0.119185646272255, 0.196285453922129,
0.167061057207379, 0.169855099745761, 0.141077126343563, 0.078433720675593,
0.0999303057993443, 0.0798045801131668, 0.0331137028671696, 0.0920945831761988,
0.0233052285173748, 0, 0, 0, 0.00876293044107867, 0, 0.109134564970416,
0.110323312017635, 0.117772975747077), ID = c("ID1", "ID1", "ID1",
"ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1",
"ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1",
"ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1", "ID1"
)), row.names = c(NA, 30L), class = "data.frame")


text:
Q: Why does my Ubuntu virtual machine hosted in Hyper-V power on with a date in the future? I have several Ubuntu virtual machine running within a Hyper-V server.  The server is a Windows 2012r2 machine.  The Ubuntu VMs are either Ubuntu 14.04 or Ubuntu 16.04 (the current LTS releases).
It seems that when the virtual machines first power on they often have a timestamp of several days in the future.  This can be seen in the syslog.  The system time is corrected once the network connection comes up and NTP starts.
Why are virtual-machines running under Hyper-V starting with a date several days in the future?
The Hyper-V host server is connected to a UPS so has a very long uptime.  It has the correct date and time at present.  It is set to use a 0.uk.pool.ntp.org server as a time source.  The ADDC and DC on my network also act as time servers to most of the client machines.  Both of these have the correct time & date at present.  Both of these are also setup to use several .pool.ntp.org servers as a reference.  w32tm /query /peers confirms the settings on all three machines.
This time error on start up causes problems with my DNS entries for the VMs as well.  When the Ubuntu system comes up it acquires an IPv4 address with a DHCP reservation.  My network currently hands out 8 day reservations.  Sometimes the power on date error is so great that the reservations look as if the were requested in the future, after the current date.  When I look at the /var/lib/dhcp/dhclient.eth0.leases file modification date it is several days in the future.  This then seems to make the Ubuntu DHCP client think it has a reservation which runs until a date several days in the future.  The client then does not to reserve (or renew) a new IP Address over DHCP and its DNS entries expire on the server side.

A: Based on my experience: (Every) OS on physical machine fistly gets time from hardware clock on motherboard. After bootup ntp client kicks in and can correct time based on information from ntp server. So: Linux VMs should firstly retrieve time from HyperVM Host, and later ntp can change time.
Check the Settings in specific VM called "Integration Services". There is "Time synchronization" service. It controls whether Hardware Host shares the time to VM. Helps to keep time in sync.

A: Make sure you use the right timezone in Ubuntu. You can also install the HyperV integration for Linux. In Hyper-V manager under the settings of a VM, under Management > Integration Services you can validate "Time synchronization";
Good luck!!


text:
Q: Java&JFreeChart - How to set a JFreeChart's ChartPanel resize with it's container ( say JPanel )? I just found that when i add a ChartPanel to a JFrame, the ChartPanel will resize to fit the frame as the JFrame dragged larger or smaller. However, when i add the ChartPanel to a JPanel, the JPanel's size( width and height ) changes to fit the JFrame as the JFrame resized. But the ChartPanel just keeps it's dimensions, leaving the enlarged JPanel a lot of empty space. How to make ChartPanel resize with it's container in GUI?
Here is my sample codes :

*

*This case the chart resize with the JFrame

ChartPanel chartPanel = new ChartPanel(createWhateverChart());
JFrame frame = new JFrame();
frame.add(chartPanel);

*

*In the case, i add the ChartPanel to JPanel first, for ease of management and update the chart but the ChartPanel doesn't resize with the JPanel/JFrame.

ChartPanel chartPanel = new ChartPanel(createWhateverChart());
JPanel panel = new JPanel("Who cares");
panel.add(chartPanel, BorderLayout.CENTER);
JFrame frame = new JFrame();
frame.add(panel);

A: Try my code and it works fine.
Note that :
I have one frame which contains a panelMain, A panelMain contains a subPanel and a subPanel contains ChartPanel.
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
JPanel panelMain = new JPanel(new GridLayout(0,2));
ChartPanel chartPanel = createChart();
JPanel subPanel = new JPanel(new BorderLayout());
subPanel.setBorder(BorderFactory.createTitledBorder("Consommation"));
subPanel.setPreferredSize(new Dimension(400, 200));
subPanel.add(chartPanel);

panelMain.add(subPanel);
frame.add(panelMain);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

And now when you resize your window application. Your chartPanel will resized automatically. Hope this helps.


text:
Q: R / R Studio unable to load workspace/project I have been working with large objects and have received an error when trying to load my project in RStudio (or similarly, my workspace in the R console). I know it is a space issue. I can see from my task manager that the memory and disk are being maxxed out. The CPU is maxing out for a single core. I know I need to remove some objects and make some matrices sparse to free up space,
My specific questions are:

*

*Can I modify or remove objects when I do not have the project/workspace loaded?

*Can I set the memory to be higher using something like memory.limit for a project load?

*Can I use more than one core of my processor for the project load?

*Any other ideas?

Here are the errors:

WARNING: Failed to restore workspace from '~/D/. . .' Reason: cannot
  allocate vector of size 148 Kb

Here is the session info for Rstudio:
sessionInfo()

R version 3.3.2 (2016-10-31) Platform: x86_64-w64-mingw32/x64 (64-bit)
      Running under: Windows >= 8 x64 (build 9200)

And I also tried it in R; the resultant error is:

Error: cannot allocate vector of size 148 Kb

Here is the session info for the R console:
sessionInfo()

R version 3.3.2 (2016-10-31) Platform: x86_64-w64-mingw32/x64 (64-bit)
  Running under: Windows 10 x64 (build 14393)

What I have done so far:

*

*Updated Rstudio to latest version 1.0.44

*Updated R to 3.3.2

*gc() (both in R console and in Rstudio)

*Restarted programs and computer

*Tried to use remove() without being in the project

UPDATE: I was able to find a work around so that I could view my objects.

*

*I opened R. It pulled up the scripts from the previously opened project, and displayed the above error, leaving the environment box blank (no objects).

*I ran memory.limit(size = 50000).

*In the environment box of RStudio, I selected the open file icon, and chose my latest saved R workspace associated with this project, and it very slowly loaded the objects.

*I exported some objects, deleted some.

The project is still large and I am afraid to work in it, lest I not be able to open it up again. Still looking for answers.


text:
Q: "It had to have been..." vs. "it has to have been..." when drawing conclusios In the fifth episode of the TV show Chernobyle one of the characters said the following.

In order to sign the certificates, all safety tests had to have been completed.

I don't understand why he say had to have been, not has to have been For example:

In order to sign the certificates, all safety tests have to have been completed.

Do both sentences perfectly grammatical and natural If so, could you tell me what the difference is?

A: Both are natural-sounding and grammatical except for the subject agreement in the second sentence: ... all safety tests have to ...
You can clear up the confusion by inserting an adverb: ... had to have previously/already been completed in order to ...
It suggests the linkage between two events.
Besides, the sentence is a bit stuffy and overdone, so I recommend saying:

all safety tests had/needed to be completed.

Pragmatically speaking, both mean the same thing beside the tense. But if you changed the tense, it still wouldn't be in marked contrast to the tense used in the original sentence.
Both of the sentences lack the context, so that's why the tense wouldn't make any noticeable difference in meaning.
Compare these two:

In order to sign the certificates, all safety tests had to
be completed.

In order to sign the certificates, all safety tests have to
be completed.

A: Both sentences are perfectly natural and grammatical, but they have different meanings.
"... all safety tests had to have been..." means the certificates were signed in the past, so the condition of having to have been completed applies in the past, before the certificates were signed, not in the present.
Your suggested sentence means the current requirement is that all safety tests be completed before someone signs the certificate.
If the story is about certificates signed in the past, then the original sentence is correct. If the story is about certificates being signed now, then your sentence is correct.


text:
Q: Javascript create variable from its name In PHP we can do this:
$variable = "name_of_variable";
$this->{$variable} = "somevalue";

how to do this in javascript?
where use case should look like:
function Apple(){
    var name = "variable_name";
    this.(name) = "value";
}
console.log(new Apple());

to output
[Apple: {variable_name:"value"}]

A: You can use square bracket notation in Javascript:
variable = "name_of_variable";
window[variable] = "somevalue";

You can do this with any object in Javascript.

A: var name = "var_name";
var obj = {};
obj[name] = 'value';
alert(obj.var_name);

A: try:
this[name] = "value";

All objects can use dot and array notation for variable access.
Also note, this will allow you to create name value pairs that are inaccessible via dot notation:
var foo = {};
foo['bar-baz'] = 'fizzbuzz';
alert(foo.bar-baz); //this will not work because `-` is subtraction
alert(foo['bar-baz']); //this will work fine

If you are creating a new object literal, you can use string literals for the names for values with special characters:
var foo  = {'bar-baz':'fizzbuzz'};

But you will not be able to use variables as the key within an object literal because they are interpreted as the name to use:
var foo = 'fizz';
var bar = { foo:'buzz' }
alert( bar.fizz ); //this will not work because `foo` was the key provided
alert( bar.foo ); //alerts 'buzz'

Because other answerers are mentioning eval, I will explain a case where eval could be useful.
Warning! Code using eval is evil, proceed with caution.
If you need to use a variable with a dynamic name, and that variable does not exist on another object.
It's important to know that calling var foo in the global context attaches the new variable to the global object (typically window). In a closure, however, the variable created by var foo exists only within the context of the closure, and is not attached to any particular object.
If you need a dynamic variable name within a closure it is better to use a container object:
var container = {};
container[foo] = 'bar';

So with that all being said, if a dynamic variable name is required and a container object is not able to be used, eval can be used to create/access/modify a dynamic variable name.
var evalString = ['var', variableName, '=', String.quote(variableValue), ';'].join(' ')
eval( evalString );

A: window['name_of_variable'] = 'somevalue';

or
eval('var ' + variable_name + ' = ' + variable_name + ';');

Beyond that, don't do this. Variable variables are NEVER a good idea and make it nearly impossible to debug problems when (invariably) things break.

A: I suggest using associative arrays to do whatever you're trying to do as they are significantly cleaner and easier to debug.
However if you really insist, you can use eval() to accomplish this:
variable = "name_of_variable";
eval(variable + " = \"somevalue\""); // this will work, but please do not do it
alert(name_of_variable);

EDIT: It his just come to my attention that a significantly easier (and better) way of doing this is by simply accessing the window object:
window[variable] = "somevalue";

http://jsfiddle.net/WJCrB/


text:
Q: How do I set the cache size of FirebaseDatabase in the new FirebaseDatabase API for Android? How do I set the cache size of FirebaseDatabase in the new FirebaseDatabase API for Android?
I am just updating my legacy code to the new version, the old setup would be:
    Firebase.setAndroidContext(this);
    Config config = Firebase.getDefaultConfig();
    config.setPersistenceEnabled(true);
    config.setPersistenceCacheSizeBytes(50 * 1000 * 1000);
    Firebase.setDefaultConfig(config);

The new code as described in documentations is only
    FirebaseDatabase.getInstance().setPersistenceEnabled(true);

But class FirebaseDatabase does not have a method like setPersistenceCacheSizeBytes() as described in this reference: https://firebase.google.com/docs/reference/android/com/google/firebase/database/FirebaseDatabase
The new documentation states that the default size is 10Mb, but it does not tell me where to change this default value.

A: There is a setPersistenceCacheSizeBytes() method. I don't know when this was added, though.

A: This line works for me to set persistence cache size.
FirebaseDatabase.getInstance().setPersistenceCacheSizeBytes(50 * 1000 * 1000);

https://firebase.google.com/docs/reference/android/com/google/firebase/database/FirebaseDatabase#public-synchronized-void-setpersistencecachesizebytes-long-cachesizeinbytes
This documentation will help to set cache size of firebase database.


text:
Q: How come Chrome opens some PDFs directly while DL others? It would be nice to just view the pdf within chrome without saving it in the download folder (in Mac, I don't know how it is in other OS'). After a while you get tones of material in your download folder and you don't know which one is really worth keeping.
So how come some PDF's are open as a new tab while others download automatically to the mentioned folder?

A: The reason is pretty simple. The server actually makes the decision to either download, or render the PDF in the browser. So the server admin must set the server to do either option, or the web developer / webmaster can add code to force the PDF either way.
On your end, you can run a plugin called redirector, that changes the http-header that tells the browser to download the PDF, and actually make it do the opposite.
You create a rule that removes the  Content-Disposition header.


text:
Q: How do I return values in lua function after calling other lua function inside C function So i have something like this:
public static int Window(ILuaState lua)
{
    int id = lua.L_CheckInteger(1);
    Rect rect = RectLib.CheckRect(lua, 2);
    string title = lua.L_CheckString(3);
    int fRef = lua.L_Ref(LuaDef.LUA_REGISTRYINDEX); // a function was passed as a parameter

    Rect r = GUI.Window(id, rect, (i) => // this functions executes before RectLib.PushRect right here
    {
        lua.RawGetI(LuaDef.LUA_REGISTRYINDEX, fRef);
        lua.PushInteger(i);
        if (lua.PCall(1, 0, 0) != ThreadStatus.LUA_OK)
            Debug.LogError(lua.ToString(-1));
    }, title);

    RectLib.PushRect(lua, r); // basically pushes a table

    return 0;
}

The problem here that after calling function that was passed as a parameter something bad goes with the stack and return value becomes nil. I tried putting lua.Pop(1), lua.Pop(2), lua.Pop(3) after lua.PCall but i failed. What do i do?
The stack after looks like this:
5: none
4: table
3: string (string title)
2: table
1: number (int id)
0: number (4th element of a table that need to be returned)
-1: table
-2: string (string title)
-3: table
-4: number
-5: function

Help


text:
Q: Find delay time of socket message at receiver side I implement the CFNetwork framework for sending and receiving message in local network(All devices are connected with same network). I successfully implement this functionality but my problem is that If i connected more device like 8 to 10 at that time message will be delay and i want to get that delay time at receiver side. I tried a lot but no luck for getting a delay time. If anyone have any idea how to get this please help me.
Thanks in advance.

A: I'd start by grabbing a BSD-licensed ntpd implementation and use that to compute the clock offset between the various devices.  Declare one of those times arbitrarily to be "truth".
With this scheme, the sending device can add a time stamp (adjusted for its local clock offset relative to the "truth") into the outbound packets, and the receiving device can compare the time stamp on the other end to the current time (again adjusted for its local clock offset).
AFAIK, there's not an easier way that is accurate.  Normally, the delay doesn't matter, and when it does, it takes a lot of work to figure out the delay with any real precision.


text: Q: How does FlexBright control screen blue light levels without using private APIs? I just read an article on MacRumors about a new app that allows the user to reduce blue light levels (like flux for Mac). The app has been approved and the same article states that the app achieves the control without using private APIs... So how do they do it?


text:
Q: Principal and fiber bundles as defined by Husemoller In his book 'Fiber Bundles' Husemoller defines principal bundles and fiber bundles quite differently from how they are usually defined.
Specifically:
Definition: a right $G$-space $X$ is called effective if $G$ acts freely (or faithfully? It's ambiguous) on $X$ (that is, $xs = x$ implies $s = 1$).
Definition: Consider the space $X^* \subset X \times X$ given as $X^* = \{(x, xs) \mid x \in X, s \in G\}$. For all $(x, y) \in X^*$ there is a unique $\tau(x, y) \in G$ such that $x \tau(x, y) = y$. Thus we have the translation function $\tau: X^* \to G$. We call $X$ principal if $\tau$ is continuous.
Definition: A bundle $\xi: X \to B$ is called principal if $X$ is a principal $G$-space, and there exists a homeomorphism $f: X/G \to B$ inducing a bundle isomorphism $(1_X, f): \alpha(X) \to \xi$, where $\alpha$ is a functor from right $G$-spaces to bundles given by projection $X \to X/G$.
Definition: Consider a principal $G$-bundle $\xi: X \to B$, and let $F$ be a left $G$-space. The formula $(x, y)s = (xs, s^{-1}y)$ gives a structure of a right $G$-space on $X \times F$. Denote $X_F := (X \times F)/G$, and consider $\xi[F]: X_F \to B$ - a factorization of the composition $X \times F \to X \stackrel{\xi}{\to} B$ by the projection $X \times F \to X_F$, or, explicitly, $\xi[F] ((x,y)G) = \xi(x)$. Such a $\xi[F]$ is called the fiber bundle over $B$ with fiber $F$ and the associated principal bundle $\xi$. The group $G$ is called the structure group of the fiber bundle $\xi[F]$.
This is totally baffling to me, because the meaning of the terms is wildly different from the meaning in other sources I encountered so far, like Wikipedia; note that neither principal bundle nor fiber bundle is required to be locally trivial here! What are these things called in the mainstream literature? How do they arise, why are they interesting? I admit I have only started reading this section of Husemoller so I'll probably get the big picture if I continue reading, that's why I'm mostly interested in the terminology right now.

A: What Husemoller calls a principal bundle Richard S. Palais in his On the existence of slices for actions of non-compact Lie groups calls a Cartan principal bundle (introduced, to the best of my knowledge, by Jean-Pierre Serre in Seminar Cartan 1949-1950, perhaps incorrectly cited as 1948-1949), with the term principal bundle meaning any bundle induced by a free continuous group action.
Some facts about Cartan principal bundles:
1) Any locally trivial principal bundle is Cartan.
2) Any quotient space of a topological group by a closed subgroup is Cartan.
3) A Cartan principal bundle is trivial iff it has a section, so a Cartan principal bundle is locally trivial iff it has a local section. Thus Cartan principal bundles generalize the question of existence of local sections of subgroups.
Palais also generalizes Cartan principal bundles further by defining the notions of Cartan G-space and proper G-space, which do away with the action being free. He then proceeds to use these notions to give new proofs to several interesting theorems. See also this question on MO: https://mathoverflow.net/questions/57015/which-principlal-bundles-are-locally-trivial
What Husemoller calls a fiber bundle is the bundle associated to the Cartan principal bundle. I haven't read Husemoller that far, but I believe that such a bundle is not necessarily locally trivial.


text:
Q: How to set the background color on p-button using external css or tailwind css I'm designing a popup element with a p-button. I've tried background colour using styleClass="p-button-secondary", but it seems it's not like dark black. I also tried external css, but I could not set the background colour I expected.
My HTML Code :

          <mat-icon class="bg-white text-black rounded-full mr-4" [icIcon]="icAdd"></mat-icon>
          Create System Type

My external Css :
.p-button .prime-button-black {
  background-color:#161b2900  !important;
}

A: Change the css selector to p-button and provide a valid and visible color hex. You have provided eight value hex color i.e. 161b2900 where last two digits are alpha component, indicating its transparency. 0 represents a fully transparent color and ff is for complete opaque. In your case 00 is making the background color completely transparent.

p-button{
  background-color: #161b2944 !important;
}

  <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet" />

    <mat-icon class="bg-white text-black rounded-full mr-4" [icIcon]="icAdd"></mat-icon>
    Create System Type


text:
Q: Infinite multidimensional limits I cannot find the definition of limit of a function of several variables involving infinity such as $(x,y) \rightarrow (0,-\infty)$

A: There's a reason for that. In one dimension you have a clear definition of $+\infty$ and $-\infty$. However the is not so clear in higher dimensions. Consider for instance the plane. You could consider an infinite family of infinities $\infty_\theta$ in the direction $\theta$, where $\theta$ is an angle, $0\le\theta<2\,\pi$:you would be approaching infinity alogn the semi-infinite straight line $\{r\,(\cos\theta,\sin\theta):r\ge0\}$. However, this does not cover all the ways of approaching infinity: you could do it through an spiral, for instance. So, usually, only one infinity is considered in higher dimensions.
In the case you indicate, this could be a possible definition:
For all $\epsilon>0$ there is $\delta>0$ and $M>0$ such that if $|x|<\delta$ and $y<-M$, then $|f(x,y)-\ell|<\epsilon$, where $\ell$ is the limit.

A: There is no generic such definition since it depends on a number of issues, including the relative speeds of convergence.  For instance, consider the function
$$f(x,y)=xy.$$
Should the limit be zero, $-\infty$, $\infty$ (if $x$ is negative), or is there no limit?
So try to express both $x$ and $y$ as a function of a single index $t$ and take the limit as $t\to \infty$ (or $0$).


text:
Q: Getting Error in Apache error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch I have just downloaded SSL certificate from cheapsslsecurity, but apache is giving above errors.
[Sun Jul 17 15:30:01.256726 2022] [ssl:emerg] [pid 3640] SSL Library Error: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch
[Sun Jul 17 15:30:01.256729 2022] [ssl:emerg] [pid 3640] AH02312: Fatal error initialising mod_ssl, exiting.
[Sun Jul 17 16:00:01.434769 2022] [suexec:notice] [pid 3698] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[Sun Jul 17 16:00:01.439767 2022] [ssl:emerg] [pid 3698] AH02238: Unable to configure RSA server private key
[Sun Jul 17 16:00:01.439859 2022] [ssl:emerg] [pid 3698] SSL Library Error: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch
[Sun Jul 17 16:00:01.439862 2022] [ssl:emerg] [pid 3698] AH02312: Fatal error initialising mod_ssl, exiting.
Things I tried

*

*Checked private key and certificate key and they are matching

*In SSL certificate entered the path for crt file. Private key entered the private key file. In  SSLCACertificateFile entered the bundle path provided by the site.

*Removed spaces from private key

*Encoding of private key file is UTF-8 and also tried changing .txt to .key

*Checked validity of certificae and it is of next year


text:
Q: Color and formatting of Rstudio console output How can I get console output like this:

Currently my console looks like this:

I have tried installing cli, crayon packages but it does not work.

A: Using R version 4.2.2 it now works after installing the crayon-package from CRAN.
install.packages("crayon")

Console is nicely formatted:


text:
Q: Error Python TypeError Hola estoy haciendo un programa que lo que hace a grandes rasgos es permitirte registrar y despues iniciar sesion y a la hora de terminar de colocar la contrasenia en iniciar sesion me da el error TypeError pero no encuentro el codigo que da el error pero sospecho que es que no esta "procesando" la contrasenia anteriormente pasada a hashlib(creo que asi se diria).
Aqui el codigo que teorizo que da error en la aprte de 'descifrado' de contrasenias:
usuario.py
from usuarios import conexion
import datetime
import hashlib

connect = conexion.conectar()
database = connect[0]
cursor = connect[1]

class Usuario:

    def __init__(self, nombre, apellidos, email, password):
        self.nombre = nombre
        self.apellidos = apellidos
        self.email = email
        self.email = email
        self.password = password

    def registrar(self):
        fecha = datetime.datetime.now()

        # Cifrar contrasenia
        cifrado = hashlib.sha256()
        cifrado.update(self.password.encode('utf8'))

        sql = "INSERT INTO usuarios VALUES(null, %s, %s, %s, %s, %s)"
        usuario = (self.nombre, self.apellidos, self.email, cifrado.hexdigest(), fecha)

        try:
            cursor.execute(sql, usuario)
            database.commit()
            result = [cursor.rowcount, self]
        except:
            result = [0, self]

        return result
    def identificar(self):

        sql = "SELECT * FROM usuarios WHERE email = %s and password = %s"

        # Cifrar contrasenia
        cifrado = hashlib.sha256()
        cifrado.update(self.password.encode('utf8'))

        # Datos para la consulta
        usuario = (self.email, cifrado.hexdigest())
        cursor.execute(sql, usuario)
        result = cursor.fetchone()

        return result

y aqui el resto del codigo junto al orden en que va:

conexion.py
import mysql.connector

def conectar():
    database = mysql.connector.connect(
        host="localhost",
        user="root",
        password="",
        database="master_python",
        port=3306
    )

    cursor = database.cursor(buffered=True)

    return [database, cursor]

acciones.py(usuarios)
import usuarios.usuario as modelo
class Acciones:

    def registro(self):
        print("\nVamos aregistrarte...")

        nombre = input("Ingrese su nombre: ")
        apellidos = input("Ingrese su apellido: ")
        password = input("Introduzca sus contrasenia: ")
        email = input('Intruduzca su email: ')
        usuario = modelo.Usuario(nombre, apellidos, email, password)
        registro = usuario.registrar()

        if registro[0] >= 1:
            """
            print(f"Perfecto {registro[1].nombre} te has registrado con el email {registro[1].email}")
            """
        else:
            print("Error al registrar...")

    def login(self):
        print("\nIniciemos sesion...")

        try:
            email = input("Ingresa tu email: ")
            password = input("Introduce tu contrasenia: ")

            usuario = modelo.Usuario('', '', email, password)
            login = modelo.Usuario.identificar()

            if email == login[3]:
                print(f"\nBienvenido {login[1]}, te has registrado en el sistema el {login[5]}")
                self.proximasAcciones(login)
        except Exception as e:
            print(type(e))
            print(type(e).__name__)
            print(f"Login incorrecto, intentalo mas tarde.")

    def proximasAcciones(self, usuario):
        print("""
        Acciones disponibles:
        - Crear nota (crear)
        - Mostrar tus notas (mostrar)
        - Eliminar nota (eliminar)
        - Salir (salir)
        """)

        accion = input("Introduzca la accion a realizar: ")

        if accion == "crear":
            print("\nProcedamos a crear.")
            self.proximasAcciones(usuario)

        elif accion == "mostrar":
            print("\nProcedamos a mostrar.")
            self.proximasAcciones(usuario)

nota.py
import usuarios.conexion as conexion

connect = conexion.conectar()
database = connect[0]
cursor = connect[1]

class Nota:

    def __init__(self, usuario_id, titulo, descripcion):
        self.usuario_id = usuario_id
        self.titulo = titulo
        self.descripcion = descripcion

    def guardar(self):
        sql = "INSERT INTO notas VALUES(null, %s, %s, %s, NOW())"
        nota = (self.usuario_id, self.titulo, self.descripcion)

        cursor.execute(sql, nota)
        database.commit()
        return [cursor.rowcount, self]

acciones.py(notas)
from notas import nota as modelo

class Acciones:

    def crear(self, usuario):
        print(f"De acuerdo{usuario}, creando una nueva nota...")
        titulo = input("Introduce el titulo de tu nota: ")
        descripcion = input("Introduce la descripcion de tu nota: ")

        nota = modelo.Nota(usuario[0], titulo, descripcion)
        guardar = nota.guardar()

        if guardar[0] >= 1:
            print("Se ha guardado correctamente la nota: ")
        else:
            print("\nHan habido problemas al intentar guardar la nota...")


text:
Q: Accessing data file on Android 9 Internal Memoy I had developed a small application on Android 4.5, 5 years ago.
This application is for searching on .csv files (text files) if a certain item was on the file.
The data .csv files were on a smartcard (external memory)
This was working.
Today I changed of mobile and run on Android 9.0.
I changed my application only to run on internal memory in "/storage/emulated/0/Download/".
But I get the following message:
either in  several internal directories
java.io.FileNotFoundException: /storage/emulated/0/Download/books.csv (Permission denied)
or
java.io.FileNotFoundException: /storage/emulated/0/Movies/books.csv (Permission denied)
The file is present, I can open it on the mobile with a simple text editor.
I have searched how to read in internal storage, but not found a solution.
Can you help.
Thank you

A: you have to check for runtime permission
private static final int WRITE_EXTERNAL_STORAGE = 0;
private static final int REQUEST_PERMISSION = 0;

int permissionCheckStorage = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheckStorage != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions( MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
        && ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            REQUEST_PERMISSION);

    return;
}

and add permission in your manifest file
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

A: I suspect you are running Android 6.0 Marshmallow (API 23) or later. If this is the case, you must implement runtime permissions before you try to read/write external storage.


text:
Q: Spring XD Dynamic Module ClassLoader Issue According to the documentation we can load jars dynamically at module creation time by exploiting the attribute module.classloader in the .properties file :
http://docs.spring.io/spring-xd/docs/1.3.1.RELEASE/reference/html/#module-class-loading
I spent two days trying to test this feature. It does not work. The option module.classloader seems to be simply ignored
I did not find any string named module.classloader in the XD code. But I found another one called module.classpath in this class:
https://github.com/spring-projects/spring-xd/blob/master/spring-xd-module/src/main/java/org/springframework/xd/module/options/ModuleUtils.java
The code in the above class seems to match the documentation. But unfortunalletely it does not work too. My classes are not found and I get java.lang.ClassNotFoundException
I have module option named dir4jars where I put the jars to load at creation time (when I issue job create --name xx --defintion ..). It's a directory, and I have tested the following possibilities, with both module.classpath and module.classloader :
module.classpath=${dir4jars}/*.jar
module.classloader=${dir4jars}/*.jar
.
.
job create --name jobName --definition "myJobModuleName --dir4jars=C:/ELS/Flash/libxd" --deploy

and

job create --name jobName --definition "myJobModuleName --dir4jars=file:C:/ELS/Flash/libxd" --deploy

I need the dir4jars to be absolute and outside XD home.
So my questions:

*

*What's the right option to use for this dynamic load? module.classpath or module.classloader ?

*How can I set an absolute directory as I mentioned above?

Many thanks.

A: I think it has to be module.classpath and module.classloader looks like a mistake in the documentation. Does this work when you explicitly use module.classpath=file:C:/ELS/Flash/libxd?
As a side note: Please consider using Spring Cloud Data Flow which is the successor of Spring XD.


text:
Q: What's the more elegant way to declare a const in C#
Possible Duplicate:
C# naming convention for constants?

I'm refactoring a library in C# and I found a lot of upper case constants:
INTERVAL, TIME, SECONDS.

I think this a kind of unnecessary, and personally I prefer declare everything with camel case. Exist some exactly definition about the better way?

A: Ultimately the case isn't going to make any difference (unless it collides with a type/keyword/etc). So really consistency is the main thing.
The Capitalization Conventions don't distinguish between constants and other members - but these are guidelines only. So it would be pascal-case.

A: All-caps constants are a common convention…
…but a convention is just that, and is arbitrary. If you are writing code for yourself, there is no compelling reason not to choose your own. If you work with other developers, you must all agree on a naming convention.
If you are writing something that will be consumed by others outside your team, you might do well to stick to the most common and recognizable naming conventions to avoid confusion.
In the end, consistency is what counts.

A: It's all up to the standards that your group/team chose when they defined their coding guidelines.
If everybody else uses ALL_UPPER_CASE, then you should fall in line.
Personally, I prefer to use upper case for constants just so I know what they are simply by looking at them.

A: The MSDN page on constants suggests that constants should be treat like static field members.  In this case, the Captialization Conventions would suggest that PascalCasing is appropriate.
If your constant is part of a public API, I would recommend following this convention.
If the constant is just a private member, however, you can use any convention you wish.  MSDN, in this case, actually has lower case constant members in the Constant help page, for example.

A: Microsoft's recommendations make no mention of all-uppercase names. They do not explicitly specify a casing convention for constants, but they have one for enum values (PascalCase) and read-only static fields (also PascalCase). So according to Microsoft's guidelines, PascalCase is probably your best option.

A: I generally use PascalCase for public constants and camelCase for private ones. The exception is when the constants are imported from an older C/C++ library or similar (such as those use alongside P/Invoke). - I keep them as they were written in the original library.

A: This is all preference, but the upper case is I believe a throw back to #define because a const isn't a far cry from it as I understand.
More specifically, I believe the upper case const is just another delineation method where you see in a method something in all caps and you know it's a const, if it's camel case it's local, camel case with _ is member private, and pascal case is member public.
Though this is just one standard of consistencies which some prefer, it really is preferential, though I think the reason is as I said, just to make it obvious when you see all caps you know it's a const.


text:
Q: PHP - Pass mysql @variable in SQL query I have the following SQL that I'd like to run on MySQL DB via PHP.
ERROR
syntax error  check the
 manual that corresponds to your MySQL server version for the right syntax to use near '@rn := if(@prevDate=eve_date

SQL
SELECT eve_date,
       cust_name,
       item_id,
       Sum(item_bundle_size) sumsize
FROM   (SELECT eve_date,
               cust_name,
               item_id,
               item_bundle_size,
               @rn := IF(@prevdate = eve_date, IF (@previtem = item_id, @rn,
                      IF (@previtem := item_id, @rn + 1
                      , @rn +
                      1)),
                      IF
                             (@prevdate := eve_date,
                      IF (@previtem := item_id, 1, 1), 1
                      )
                      ) rn
        FROM   cust_sales_hist
               CROSS JOIN (SELECT @rn := 0,
                                  @prevdate := NULL,
                                  @previtem := NULL) t
        WHERE  cust_name = 'Cust1'
               AND eve_date BETWEEN '2015-08-01' AND '2015-08-05'
        ORDER  BY eve_date,
                  item_bundle_size DESC) t
WHERE  rn <= 4
GROUP  BY eve_date,
          cust_name,
          item_id
ORDER  BY eve_date,
          cust_name,
          sumsize DESC

I looked up SO for examples that advised about splitting the query into several parts. However, in my case, it looks like I gotta run this as one due to the requirement of the output. The SQL fiddle for this query is here in case needed - http://sqlfiddle.com/#!9/3a5d08/5
I'd truly appreciate any help to get me moving here please.

A: As suggested by Barmer above, the code had a special character that not visible strangely that was splitting the query into 2 parts & hence the problem. Worked around this. Thanks to Barmer


text:
Q: Multi Select Listbox is not working I want to be able to select multiple items from the list box and create record for each item in a SQL table. But I get the following error:
Uncaught TypeError: $(...).multiselect is not a function
    at HTMLDocument.<anonymous> (EVENROL.aspx:334)
    at j (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at Function.ready (jquery.min.js:2)
    at HTMLDocument.I (jquery.min.js:2)

The dropdown list appears but the multiple selection option doesn't work.

A: This means that the multiselect plugin is not being referenced properly. Make sure that it is referenced before your code and that you are implementing it the way you want it to.


text:
Q: How can i escape "? if (richTextBox1.Lines[i].StartsWith(@"<a href=""") ||
     richTextBox1.Lines[i].EndsWith(@""""))

The StartsWith should be <a href="
The EndsWith should be one single "
But the way it is now i'm getting no results.
Input for example:
Screen-reader users, click here to turn off ggg Instant.

I need to get this part:
/setprefs?suggon=2&prev=https://www.test.com/search?q%3D%2Band%2B%26espv%3D2%26biw%3D960%26bih%3D489%26source%3Dlnms%26tbm%3Disch%26sa%3DX%26ei%3DYrxxVb-hJqac7gba0YOgDQ%26ved%3D0CAYQ_AUoAQ&sig=0_seDQVVTDQQx1hvN3BRktZNFc9Ew%3D

The part between the

I also tried to use htmlagilitypack:
HtmlAgilityPack.HtmlWeb hw = new HtmlAgilityPack.HtmlWeb();

                        HtmlAgilityPack.HtmlDocument doc = hw.Load("https://www.test.com");

                        foreach (HtmlAgilityPack.HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
                        {
                            string hrefValue = link.GetAttributeValue("href", string.Empty);

                                if (!newHtmls.Contains(hrefValue) && hrefValue.Contains("images"))
                                    newHtmls.Add(hrefValue);
                        }

But this gave me only 1 link.
When i browse and see the page view-source and i make search and filter with the word image or images im getting over 350 results.
I tried also this solution:
var document = new HtmlWeb().Load(url);
var urls = document.DocumentNode.Descendants("img")
                                .Select(e => e.GetAttributeValue("src", null))
                                .Where(s => !String.IsNullOrEmpty(s));

But it didnt give me the results i needed.
Forgot to mention that the view-source of the page content i copied it to richTextBox1 window and then i'm reading line by line the text from the richTextBox1 so maybe that's why i'm not getting the results as i need ?
for (int i = 0; i < richTextBox1.Lines.Length; i++)
                {
                    if (richTextBox1.Lines[i].StartsWith("<a href=\"") &&
                        richTextBox1.Lines[i].EndsWith("\""))
                    {
                        listBox1.Items.Add(richTextBox1.Lines[i]);
                    }
                }

Maybe the view-source content as it's in the browser(chrome) is not the same as in the richTextbox1. And maybe i should not read it line by line from the richTextBox1 maybe to read the whole text from the richTextBox1 first ?

A: Based on your input, EndsWith isn't doing to help (as your input actually ends with . Your next-best option would be to store the location (position) of href=", then look for the next occurrence of a " beginning at your stored location. e.g.
var input = @"Screen-reader users, click here to turn off ggg Instant.";

var needle = @"href=""";
var start = input.IndexOf(needle);
if (start != -1)
{
    start += needle.Length;
    var end = input.IndexOf(@"""", start);

    // final result:
    var href = input.Substring(start, end - start).Dump();
}

Better than that would be to use an actual HTML parser (might I recommend HtmlAgilityPack?).


text:
Q: Oracle SQL efficiently find not matching rows I have the below tables t1 and t2 in respective order:

CA
CAC

CA1
CA1C1

CA1
CA1C2

CA2
CA2C1

CA2
CA2C2

CA3
CA3C1

CA3
CA3C2

CA
CAC
MO

CA1
CA1C1
A99

CA1
CA1C2
A99

CA1
CA1C3
A00

CA2
CA2C1
A99

CA2
CA2C2
A99

CA2
CA2C3
A00

CA3
CA3C1
A99

CA3
CA3C2
A99

CA3
CA3C3
A99

CA4
CA4C1
A99

CA4
CA4C2
A00

CA4
CA4C3
A00

I would like to find the entries from t2 whose CA is in t1 but have a CAC with a MO equal to 'A99' which is not present in t1.
The expected result should look like this:

CA
CAC

CA3
CA3C3

Please find the code to generate the data below:
with t1(ca, cac) as(
    select 'ca1', 'ca1c1' from dual union all
    select 'ca1', 'ca1c2' from dual union all
    select 'ca2', 'ca2c1' from dual union all
    select 'ca2', 'ca2c2' from dual union all
    select 'ca3', 'ca3c1' from dual union all
    select 'ca3', 'ca3c2' from dual
    )
,
t2(ca, cac, mo) as(
    select 'ca1', 'ca1c1', 'a99' from dual union all
    select 'ca1', 'ca1c2', 'a99' from dual union all
    select 'ca1', 'ca1c3', 'a00' from dual union all
    select 'ca1', 'ca1c1', 'a99' from dual union all
    select 'ca2', 'ca1c2', 'a99' from dual union all
    select 'ca2', 'ca1c3', 'a00' from dual union all
    select 'ca3', 'ca1c1', 'a99' from dual union all
    select 'ca3', 'ca1c2', 'a99' from dual union all
    select 'ca3', 'ca1c3', 'a99' from dual union all
    select 'ca4', 'ca1c1', 'a99' from dual union all
    select 'ca4', 'ca1c2', 'a00' from dual union all
    select 'ca4', 'ca1c3', 'a00' from dual
    )
select * from t1

A: Hmmm . . . If I follow correctly, this is filtering:
select t2.*
from t2
where t2.mo = 'a99' and
      exists (select 1 from t1 where t1.ca = t2.ca) and
      not exists (select 1 from t1 where t1.cac = t2.cac);

Here is a db<>fiddle.