Q: Template administration Error after WP 4.8 update We are using UpStream template on our WP site. After the last WP 4.8 update, we are getting an error message on the administration panel, which does not allow us to use the slideshow. The error is the following:

Fatal error: Uncaught Error: Function name must be a string in
  /var/www/vhost/calamburteatro.com/home/html/wp-content/themes/UpStream/lib/Admin.php:248
  Stack trace: #0
  /var/www/vhost/calamburteatro.com/home/html/wp-content/themes/UpStream/lib/Admin.php(451):
  ThematerAdmin->form_callback('featuredposts_s...', Array) #1
  /var/www/vhost/calamburteatro.com/home/html/wp-content/themes/UpStream/lib/Admin.php(388):
  ThematerAdmin->optionsPageContentItems(Array) #2
  /var/www/vhost/calamburteatro.com/home/html/wp-content/themes/UpStream/lib/Admin.php(324):
  ThematerAdmin->optionsPageContent() #3
  /var/www/vhost/calamburteatro.com/home/html/wp-includes/class-wp-hook.php(298):
  ThematerAdmin->ThematerThemeOptions('') #4
  /var/www/vhost/calamburteatro.com/home/html/wp-includes/class-wp-hook.php(323):
  WP_Hook->apply_filters('', Array) #5
  /var/www/vhost/calamburteatro.com/home/html/wp-includes/plugin.php(453):
  WP_Hook->do_action(Array) #6
  /var/www/vhost/calamburteatro.com/home/html/wp-admin/admin.php(222):
  do_action('appearance_page...') #7 / in
  /var/www/vhost/calamburteatro.com/home/html/wp-content/themes/UpStream/lib/Admin.php
  on line 248

The line 248 on the admin.php is: $callback[0]->$callback[1]();
And the whole fuction code is:
function form_callback ($name, $attributes = array())
    {
        if(isset($attributes['callback']) && is_array(($attributes['callback']))) {
            $callback = $attributes['callback'];
            $callback[0]->$callback[1]();
        } else {
            if(function_exists($name)) {
                return $name($attributes);
            }
        }

    }

Would anybody help us with this, please? Thanks in advance!

A: This is a generic PHP question, but simple to answer. The problem is most likely caused by PHP 7.
Simply change the line:
$callback[0]->$callback[1]();

to
$callback[0]->{$callback[1]}();

This is because $callback[0]->$callback[1](); means $callback[0]->{$callback[1]}(); in PHP5, while it means ($callback[0]->$callback)[1](); in PHP7.
Take a look into this page to know the details about the change.


Q: Making Python Logging work async with Celery I have logging setup. In particular, I have SMTPHandler. I would like to have it happen async. I'd like to use celery to make that happen. Is that possible?
import logging
logger = logging.getLogger("logger")

mail_handler = STMPHandler(...)
mail_handler.setLevel(logging.ERROR)
...
logger.addHandler(mail_handler)


Q: Limit of singletons Let $a ∈\mathbb R$ and let ($x_n$ : $n ∈\mathbb N$) be a sequence of points in $\mathbb R$, all distinct from $a$, such that $\lim_{n→∞}x_n=a.$
Show that $\lim_{n→∞}\{x_n\}$ exists and is different from $\{a\}.$

*

*I suppose that "a" is a point, so the sequence xn goes to a when n goes to infinity and that's ok by def.

*How can the limit of singletons ( i suppose that {xn} means the single point of the sequence) exist and also be different from a?

*I was thinking about using cauchy convergence, but I don't know how to proceed.

A: Using the definition of the limit of a sequence of sets, let us prove that $\limsup_{n \to \infty}\{x_n\}=\varnothing$ (it will prove that $\lim_{n→∞}\{x_n\}=\varnothing$), i.e. let us prove (by contradiction) that no real number $x$ can belong to infinitely many $\{x_n\}$'s.
If $x$ was equal to $x_n$ for an infinity of indices $n$, the sequence $(x_n)$ would admit a constant subsequence $x_{n_k}=x$, so the limit $a=\lim_{n\to\infty}x_n$ would also be a limit of that subsequence, i.e. we would have $a=x$. But then, $a$ would be equal to $x_n$ for some $n$ (even many: all the $n_k$'s), contrarily to the hypothesis.


Q: Set ForkLift as default file viewer Is there a way to set ForkLift as the default file viewer, to a degree? PathFinder somehow does this, see http://cocoatech.com/faqs#3, but how does it do this and could that option be set to redirect to ForkLift instead of PathFinder?

A: Now as the ForkLift V3 came out, the new command should be:
defaults write -g NSFileViewer -string com.binarynights.ForkLift-3

At the same time, if you like to restore Finder to be the default file manager again, use:
defaults delete -g NSFileViewer

A: From Forklift official documentation:

If you are using ForkLift from Setapp, paste this command instead:
defaults write -g NSFileViewer -string com.binarynights.forklift-setapp;
defaults write com.apple.LaunchServices/com.apple.launchservices.secure LSHandlers -array-add '{LSHandlerContentType="public.folder";LSHandlerRoleAll="com.binarynights.ForkLift-3";}'

A: Path Finder looks like it's modifying the "NSFileViewer" preference. You can set this manually from Terminal to point to ForkLift (I tried this, and it seems to work):
defaults write -g NSFileViewer -string com.binarynights.ForkLift2

(The -g sets this preference globally for all applications.)
However, be warned that the Path Finder website lists some applications that don't respect this setting, such as the Dock and Firefox.

A: You can change default file manager like this, but ForkLift or Transmit not work as expected, only Path Finder are
#!/usr/bin/python2.6

from LaunchServices import LSSetDefaultRoleHandlerForContentType, kLSRolesViewer, LSSetDefaultHandlerForURLScheme
from CoreFoundation import CFPreferencesCopyApplicationList, kCFPreferencesCurrentUser, kCFPreferencesAnyHost, CFPreferencesSetAppValue, CFPreferencesAppSynchronize

applicationBundleIdentifier = "com.cocoatech.PathFinder" #"com.panic.Transmit" #"com.binarynights.forklift2"

LSSetDefaultRoleHandlerForContentType("public.folder", kLSRolesViewer, applicationBundleIdentifier)
LSSetDefaultHandlerForURLScheme("file:///", applicationBundleIdentifier)

applicationIDs = CFPreferencesCopyApplicationList(kCFPreferencesCurrentUser, kCFPreferencesAnyHost)
for app_id in applicationIDs:
    CFPreferencesSetAppValue("NSFileViewer", applicationBundleIdentifier, app_id);
    CFPreferencesAppSynchronize(app_id);


Q: Nonlinear regression: Confidence intervals on transformed or untransformed parameters? Suppose I am using a standard inhibition model to find biochemical parameters that fit my data. The equation is:
$y = \frac{A}{{1 + \exp \left( {\ln \left[ S \right] - \ln IC_{50}} \right)}} $
where $\left[ S \right]$ is the concentration of my inhibitor and $IC_{50}$ is the concentration of my inhibitor at which the measurement (with a maximum $A$) is reduced by half. Which of these approaches should I take?

*

*enter the equation into the NLR procedure as-is (FYI: I am using SPSS) and let it fit the values of $A$ and $IC_{50}$ in the same manner, i.e. with all of the assumptions of OLS regression parameters. Or...

*enter the equation as
$y = \frac{A}{{1 + \exp \left( {\ln \left[ S \right]- \ IC_{50}^* } \right)}} $
where $ IC_{50}^* = \ln IC_{50}$. This of course would require a transform on the output parameter and confidence limits of $ IC_{50}^*$ giving me asymmetric error bars.
Which of these strategies is most rigorous? My instincts suggest the 2nd option, as $ IC_{50}$ is actually bound by 0 and is thus more likely to be log-normal rather than normal. Any help (direct answers, references, etc) is appreciated.

A: I assume that the log(S) vs. Y curve is symmetrical, so the uncertainty of the log(IC50) is symmetrical and the uncertainty of the IC50 is not. Accordingly, you are much better off using your second model. You'll get the same the best-fit curve, the same best-fit value for the IC50 (after transforming), and the same  sum-of-squares and R2. But the two methods will give you different confidence intervals of the IC50 (even after transforming) and the second method will give you a more useful (more accurate) confidence interval.


Q: Record Screen's Happenings(Audio+Video) i am new baby in WebRTC and want to implement system like video conferencing , live streaming or you can skype using WebRTC and NodeJS.
i am confused with one thing , as its our one of client's requirement , suppose on page whatever is happening it may be video conferencing say one moderator answering to many audiences one by one , so there should be one video created , which continuously recording all this stuff together and sending live stream to server to save in our database.
is this kind of stuff implementable or not?
any help please.

A: You can capture video through grabbing Jpeg images from a canvas element. You could also capture the entire page(if numerous videos in the same page) through grabbing the page itself through chrome.
For audio, recording remote audio with the Audio API is still an issue but locally grabbed audio is not an issue.

*

*RecordRTC and my Modified Version for recording streams either to file or through websockets respectively.

*Capture a page to a stream on how to record or screenShare an entire page of Chrome.

If you have multiple different videos not all in the same page but want to combine them all, I would suggest recording them as above and then combining and syncing them up server side(not in javascript but probably in C or C++).
If you MUST record remote audio, then I would suggest that you have those particular pages send their audio data over websockets themselves so that you can sync them up with their video and with the other sessions.


Q: Problem with CKEditor inside a ColorBox modal popup Please can anyone help me out. I have an html page in which I have added a modal popup from ColorBox. In the ColorBox popup, I have added a CKEditor. The problem is as follows:
In IE, the CKEditor works fine, but in FF & Chrome, I get the CKEditor like in readonly mode (I can't type anything in it).
If i put the CKEditor directly into the page (and not in the modal popup), it works fine in all browsers.
I think this might be a problem with the z-index on one of the elements generated by CKEditor. But I don't know which one exactly?
I would really appreciate some help plz, thanks in advance!

A: We got around our problem by switching lightboxes, rather than use ColorBox, use Simple Modal.  I have a funny feeling it will work for you.  Good luck!

A: <script>
  $(document).ready(function() {
    initCKEditor(); //function ckeditor.
    $("#id_textarea").val(CKEDITOR.instances.id_textarea.getData());
  });
</script>

A: Render/create ckeditor on colorbox "onComplete" callback.
See callbacks here : http://www.jacklmoore.com/colorbox

A: After some debugging I found that it is because of a CSS rule.
In the skin named kama you need to change the following CSS rule in mainui.css from:
.cke_skin_kama .cke_browser_ie.cke_browser_quirks .cke_contents iframe
{
    position: absolute;
    top: 0;
}

To:
.cke_skin_kama .cke_browser_ie.cke_browser_quirks .cke_contents iframe
{
    top: 0;
}

Depending on your setup, you might need to change it in skins/kama/editor.css
I however recommend upgrading to a newer version of ckeditor.  I found this issue on version 3.6.2.


Q: JPA: relation manyToMany on the same entity I have an Entity that has two relation manyToMany with itself and I don't want to use Cascade.MERGE because I need to do some data checks to validate the data:
@Entity("device")
public class Device {
...
@ManyToMany(mappedBy = "parents", targetEntity = Device.class, fetch = FetchType.LAZY)
    public Set<Device> getChildren() {
        return this.children;
    }

    @Override
    @ManyToMany(targetEntity = Device.class, fetch = FetchType.LAZY)
    @JoinTable(name = "dem_hierarchy", joinColumns = {
        @JoinColumn(name = "CHILDREN_UUID", referencedColumnName = "UUID")},
            inverseJoinColumns = {
                @JoinColumn(name = "DEM_DEVICE_UUID", referencedColumnName = "UUID")})
    public Set<Device> getParents() {
        return parents;
    }

...
}

When I save a tree like this:
Device grandGrandPa = new Device();
grandGrandPa.setName("TEST" + counter + "_grandGrandPa");

Device grandPa = new Device();
grandPa.setName("TEST" + counter + "_grandPa");

grandGrandPa.addChild(grandPa);

Device daddy = new Device();
daddy.setName("TEST" + counter + "_daddy");

grandPa.addChild(daddy);

Device son = new Device();
son.setName("TEST" + counter + "_son");

daddy.addChild(son);
grandGrandPa = deviceService.register(grandGrandPa);

The register method is recursive and it descends the tree using the children column. When its the turn of the "grandPa" to be saved the weblogic return an exception:

Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

I cannot understand why this happens. It gives me this error when in code there are some queries on parent Device: first turn it is empty, second turn it has one value.
I'm using weblogic 12.1.3 and hibernate 4.0.0, as database Oracle 11g.

A:
It gives me this error when in code there are some queries on parent Device

By default, Hibernate will flush pending changes to the database before attempting to execute a query. At that stage, all entities referenced in all relationships should have been persisted, or else an exception will be thrown.
Also, since mappedBy is declared on the children end, the parents is the owning side of the relationship. Because of that, Hibernate will ignore children completely at persist time and look for transient entities in parents instead. Your persisting logic should therefore be reversed - save parents first, children last (alternatively, you could simply declare children the owning side).


Q: Get Google.GoogleApiException 'File not found: [404]' when trying to list files in a non-root Google Drive folder I'm trying to access files in Google Drive. I picked up code to create a Google Drive service from the Google docs...
private static DriveService GetDriveService() {
  UserCredential credential;
  using (FileStream stream = new("credentials_desktop.json", FileMode.Open, FileAccess.Read)) {
    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
      GoogleClientSecrets.Load(stream).Secrets,
      Scopes,
      "user",
      CancellationToken.None,
      new FileDataStore("token.json", true)).Result;
  }
  DriveService service = new(new BaseClientService.Initializer {
    HttpClientInitializer = credential,
    ApplicationName = ApplicationName,
  });
  return service;
}

Using code found in this blog post, I can make a call to the Google Drive API and see all the files in the root folder...
private static void ListFiles() {
  DriveService service = GetDriveService();
  FilesResource.ListRequest fileList = service.Files.List();
  fileList.Q = "mimeType != 'application/vnd.google-apps.folder' and 'root' in parents";
  fileList.Fields = "nextPageToken, files(id, name, size, mimeType)";
  List<File> files = new();
  string pageToken = null;
  do {
    fileList.PageToken = pageToken;
    FileList filesResult = fileList.Execute();
    IList<File> pageFiles = filesResult.Files;
    pageToken = filesResult.NextPageToken;
    files.AddRange(pageFiles);
  } while (pageToken != null);
  // dump files to console...
}

That works fine, but if I try to list the files in a folder...
fileList.Q = "mimeType != 'application/vnd.google-apps.folder' and 'Admin' in parents";

...then when it tries to make the call to fileList.Execute() I get the following exception...
Google.GoogleApiException
  HResult=0x80131500
  Message=Google.Apis.Requests.RequestError
File not found: . [404]
Errors [
    Message[File not found: .] Location[fileId - parameter] Reason[notFound] Domain[global]
]

  Source=Google.Apis
  StackTrace:
   at Google.Apis.Requests.ClientServiceRequest`1.<ParseResponse>d__35.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Google.Apis.Requests.ClientServiceRequest`1.Execute()
   at GoogleDrivePlay.Program.ListFiles2() in d:\GoogleDrivePlay\GoogleDrivePlay\Program.cs:line 59
   at GoogleDrivePlay.Program.Main(String[] args) in d:\GoogleDrivePlay\GoogleDrivePlay\Program.cs:line 23

As you can see, the Admin folder does exist...

Anyone any idea how I can list the contents of other folders? Thanks

A: fileList.Q = "mimeType != 'application/vnd.google-apps.folder' and 'Admin' in parents";

The issue you are having is that you are using the name of the directory 'Admin' you need to use the file id of the Admin directory.
Do a file.list and search for the admin directory get its file id then pass it to that instead.
fileList.Q = "name ='Admin' and mimeType != 'application/vnd.google-apps.folder'";


Q: Get values from NSDictionaries I have the following code:
NSDictionary *dict = @[@{@"Country" : @"Afghanistan", @"Capital" : @"Kabul"},
                     @{@"Country" : @"Albania", @"Capital" : @"Tirana"}];

I want to list many countries and capitals, and then randomize i.e a country and put it on the screen, then the user should be able to pick the correct capital..

*

*How to I put the Country? Like dict.Country[0] or something like that?

*What is wrong with the code? I get the error "Initializer element is not a compile-time constant" and the warning "Incompatible pointer types initializing 'NSDictionary *_strong' with an expression of type 'NSArray *'.

*Can I make a third String in the Dictionary, containing a flag file.. for example
@"Flagfile" : @"Albania.png"
and later put it in a image view?
I want like a loop with a random number I (for example) and put like (I know this is not right, but I hope you get the point)
loop..
....

text= dict.Country[I];

button.text= dict.Capital[I];

Imageview=dict.Flagfile[I];
.....
....

A: Your top level element is an NSArray (@[], with square brackets, makes an array) of two NSDictionary's.  To access an attribute in one of the dictionaries, you would do array[index][key], e.g. array[0][@"Country"] would give you @"Afghanistan".  If you did NSArray *array = ... instead of NSDictionary *dict = ...
If you want to pick a country at random, you can get a random number, get it mod 2 (someInteger % 2) and use that as your index, e.g. array[randomNumber % 2][@"Country"] will give you a random country name from your array of dictionaries.
If you store an image name in the dictionaries, you can load an image of that name using UIImage's +imageNamed: method.

A: Here's more complete instruction on mbuc91's correct idea.
1) create a country
// Country.h

@interface Country : NSObject

@property(strong,nonatomic) NSString *name;
@property(strong,nonatomic) NSString *capital;
@property(strong,nonatomic) NSString *flagUrl;
@property(strong,nonatomic) UIImage *flag;

// this is the only interesting part of this class, so try it out...
// asynchronously fetch the flag from a web url.  the url must point to an image
- (void)flagWithCompletion:(void (^)(UIImage *))completion;

@end

// Country.m

#import "Country.h"

@implementation Country

- (id)initWithName:(NSString *)name capital:(NSString *)capital flagUrl:(NSString *)flagUrl {

    self = [self init];
    if (self) {
        _name = name;
        _capital = capital;
        _flagUrl = flagUrl;
    }
    return self;
}

- (void)flagWithCompletion:(void (^)(UIImage *))completion {

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.flagUrl]];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               if (data) {
                                   UIImage *image = [UIImage imageWithData:data];
                                   completion(image);
                               } else {
                                   completion(nil);
                               }
                           }];
}

@end

2) Now, in some other class, use the Country
#import "Country.h"

- (NSArray *)countries {

    NSMutableArray *answer = [NSMutableArray array];

    [answer addObject:[[Country alloc]
                       initWithName:@"Afghanistan" capital:@"Kabul" flagUrl:@"http://www.flags.com/afgan.jpg"]];

    [answer addObject:[[Country alloc]
                       initWithName:@"Albania" capital:@"Tirana" flagUrl:@"http://www.flags.com/albania.jpg"]];

    return [NSArray arrayWithArray:answer];
}

- (id)randomElementIn:(NSArray *)array {

    NSUInteger index = arc4random() % array.count;
    return [array objectAtIndex:index];
}

-(void)someMethod {

    NSArray *countries = [self countries];
    Country *randomCountry = [self randomElementIn:countries];
    [randomCountry flagWithCompletion:^(UIImage *flagImage) {
        // update UI, like this ...
        // self.flagImageView.image = flagImage;
    }];
}

A: You cannot initialize an NSDictionary in that way.  An NSDictionary is an unsorted set of key-object pairs - its order is not static, and so you cannot address it as you would an array.  In your case, you probably want an NSMutableDictionary since you will be modifying its contents (see Apple's NSMutableDictionary Class Reference for more info).
You could implement your code in a few ways.  Using NSDictionaries you would do something similar to the following:
NSMutableDictionary *dict = [[NSMutableDictionary alloc]
    initWithObjectsAndKeys:@"Afghanistan", @"Country",
    @"Kabul", @"Capital", nil];

You would then have an array of dictionaries, with each dictionary holding the details of one country.
Another option would be to create a simple model class for each country and have an array of those.  For example, you could create a Class named Country, with Country.h as:
#import <Foundation/Foundation.h>
@interface Country : NSObject

@property (nonatomic, retain) NSString *Name;
@property (nonatomic, retain) NSString *Capital;
//etc...

@end


Q: Encontrar valor de atributo com regex Recebo uma string por um feed RSS, cuja parte que interessa é a seguinte:
&lt;table feedtag="divinegoblin" ...
Cada pedaço do feed sempre vai ter esse atributo feedtag="...". Gostaria de pegar o valor desse atributo (no caso divinegoblin) com Regex. Não sei quase nada de Regex, estava tentando pegar usando (feedtag), mas não sei como pegar o que está adiante (no caso o que está dentro das aspas). Como posso fazer?

A: O jeito mais simples que você pode utilizar é assim:
feedtag="([^"]*)"

Desta forma ele pega tudo o que tem dentro das aspas depois de um feedtag=
Veja funcionando: https://regex101.com/r/BwibaW/2

A: Seguem outras alternativas de encontrar o valor, no snippet abaixo tem um exemplo usando .substring(sei que na pergunta pede por regex) mas achei interessante colocar, e um exemplo utilizando regex, retornando somente o valor dentro das aspas através da captura de grupo.

var a = '&lt;table feedtxag="wesas" feedtag="divinegoblin"';
var conteudo;
conteudo = a.substring(a.indexOf('feedtag="') + 'feedtag="'.length, a.indexOf('"', a.indexOf('feedtag="') + 'feedtag="'.length));
console.log("SUBSTRING: " + conteudo);

var regexResultado = a.match(/feedtag="\s*([^"]*)\s*"/)[1];
console.log("REGEX: " + regexResultado);


Q: shim-signed breaks dkms I'm trying to install the dkms package on Ubuntu 16.04.
I cannot have access to Internet because Ubuntu does not detect the ethernet adapter (Realtek)
Googling the problem, it seems I have to install the r8168 driver and I downloaded with another PC the r8168-dkms_8.041.00-1_all.deb file and I tried to install it. Unfortunately it depends on dkms which is not installed.
Thus, I manually downloaded the dkms_2.2.0.3-2ubuntu11_all.deb and I run the following command:
sudo dpkg -i dkms_2.2.0.3-2ubuntu11_all.deb

but I have a problem with shim-signed, which I am not familiar with.
shim-signed (1.33.1~16.04.5+15+1533136590.3beb971-0ubuntu1) breaks dkms (<< 2.2.0.3-2ubuntu11.6) and is installed

I followed Method 2 of this link https://wiki.ubuntu.com/UEFI/SecureBoot/DKMS to disable Secure Boot in shim-signed, but honestly I don't even know if it makes sense (and it did not solve the problem)...
Does anyone know how to install dkms without internet connection?
Update 1
I deleted the 16.04 and I succesfully installed Ubuntu 20.04.
However, it only detects the wi-fi adapter, not the ethernet one.
The ethernet adapter should be: Realtek Semiconductor Co., Ltd. RTS5260 PCI Express Card Reader (rev 01)
lspci -v:
Unassigned class [ff00]: Realtek Semiconductor Co., Ltd. RTS5260 PCI Express Card Reader (rev 01)
    Subsystem: CLEVO/KAPOK Computer RTS5260 PCI Express Card Reader
    Flags: bus master, fast devsel, latency 0, IRQ 151
    Memory at a2100000 (32-bit, non-prefetchable) [size=4K]
    Capabilities: <access denied>
    Kernel driver in use: rtsx_pci
    Kernel modules: rtsx_pci

lspci -knn | grep Eth -A2; ifconfig
Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. Device [10ec:3000] (rev 06)
    Subsystem: CLEVO/KAPOK Computer Device [1558:7714]
    Kernel modules: r8169

lshw -c network
*-network UNCLAIMED
       description: Ethernet controller
       product: Realtek Semiconductor Co., Ltd.
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:48:00.0
       version: 06
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix vpd cap_list
       configuration: latency=0
       resources: ioport:3000(size=256) memory:a2200000-a220ffff memory:a2210000-a2213fff

uname -r
5.8.0-44-generic

cat: /etc/network/interfaces: No such file or directory

Update 2
I added to the blacklist the r8169 driver. I added the following parameters to the "kernel command" during the booting (see https://wiki.archlinux.org/index.php/Kernel_module#Blacklisting):
module_blacklist=r8169

Then, I manually uploaded the r8168 with:
modprobe r8168

However, it seems it does not work:
dmesg

[  288.556472] r8168: module verification failed: signature and/or required key missing - tainting kernel

Update 3
Following the first answer of @heynnema, I run
sudo apt install dkms r8168-dkms

but I got these errors:
ERROR: Cannot create report: [Errno 17] File exists: '/var/crash/r8168-dkms.0.crash'
Error! Bad return status for module build on kernel: 5.8.0-44-generic (x86_64)
Consult /var/lib/dkms/r8168/8.048.00/build/make.log for more information.
dpkg: error processing package r8168-dkms (--configure):
 installed r8168-dkms package post-installation script subprocess returned error exit status 10
Processing triggers for man-db (2.9.1-1) ...
Errors were encountered while processing:
 r8168-dkms
E: Sub-process /usr/bin/dpkg returned an error code (1)

the make.log file:
less /var/lib/dkms/r8168/8.048.00/build/make.log

DKMS make.log for r8168-8.048.00 for kernel 5.8.0-44-generic (x86_64)
dom 7 mar 2021, 17:58:28, CET
make: Entering directory '/usr/src/linux-headers-5.8.0-44-generic'

  ERROR: Kernel configuration is invalid.
         include/generated/autoconf.h or include/config/auto.conf are missing.
         Run 'make oldconfig && make prepare' on kernel src to fix it.

make: *** [Makefile:746: include/config/auto.conf] Error 1
make: Leaving directory '/usr/src/linux-headers-5.8.0-44-generic'

Update 4
From v5.9.16 I installed the following packages running
sudo dpkg -i *.deb

*

*linux-headers-5.9.16-050916_5.9.16-050916.202012211331_all.deb

*linux-headers-5.9.16-050916-generic_5.9.16-050916.202012211331_amd64.deb

*linux-image-unsigned-5.9.16-050916-generic_5.9.16-050916.202012211331_amd64.deb

*linux-modules-5.9.16-050916-generic_5.9.16-050916.202012211331_amd64.deb

but I got the following error:
Setting up linux-headers-5.9.16-050916-generic (5.9.16-050916.202012211331) ...
/etc/kernel/header_postinst.d/dkms:
 * dkms: running auto installation service for kernel 5.9.16-050916-generic

Kernel preparation unnecessary for this kernel.  Skipping...

Building module:
cleaning build area...
make -j20 KERNELRELEASE=5.9.16-050916-generic -C /lib/modules/5.9.16-050916-generic/build M=/var/lib/dkms/r8168/8.048.00/build.....
Signing module:
 - /var/lib/dkms/r8168/8.048.00/5.9.16-050916-generic/x86_64/module/r8168.ko
Secure Boot not enabled on this system.
cleaning build area...

DKMS: build completed.

r8168.ko:
Running module version sanity check.
 - Original module
   - No original module exists within this kernel
 - Installation
   - Installing to /lib/modules/5.9.16-050916-generic/updates/dkms/

depmod...

Warning: Unable to find an initial ram disk that I know how to handle.
Will not try to make an initrd.

DKMS: install completed.

Kernel preparation unnecessary for this kernel.  Skipping...

Building module:
cleaning build area...
make -j20 KERNELRELEASE=5.9.16-050916-generic KVERSION=5.9.16-050916-generic...(bad exit status: 2)
ERROR (dkms apport): binary package for rts_pstor: 1.11 not found
Error! Bad return status for module build on kernel: 5.9.16-050916-generic (x86_64)
Consult /var/lib/dkms/rts_pstor/1.11/build/make.log for more information.
   ...done.

The installation is however completed but when I try to boot the new kernel, it prints some errors without completing the booting process (black screen).
Update 5
dkms status

r8168, 8.048.00, 5.8.0-44-generic, x86_64: installed
r8168, 8.048.00, 5.8.0-45-generic, x86_64: installed (WARNING! Diff between built and installed module!)
r8168, 8.048.00, 5.9.16-050916-generic, x86_64: installed
rts_pstor, 1.11: added

cat /var/lib/dkms/rts_pstor/1.11/build/make.log

DKMS make.log for rts_pstor-1.11 for kernel 5.9.16-050916-generic (x86_64)
sab 20 mar 2021, 11:35:44, CET
sed "s/RTSX_MK_TIME/`date +%y.%m.%d.%H.%M`/" timestamp.in > timestamp.h
cp -f ./define.release ./define.h
make -C /lib/modules/5.9.16-050916-generic/build/ SUBDIRS=/var/lib/dkms/rts_pstor/1.11/build modules
make[1]: warning: jobserver unavailable: using -j1.  Add '+' to parent make rule.
make[1]: Entering directory '/usr/src/linux-headers-5.9.16-050916-generic'
  LEX     scripts/kconfig/lexer.lex.c
/bin/sh: 1: flex: not found
make[3]: *** [scripts/Makefile.host:9: scripts/kconfig/lexer.lex.c] Error 127
make[2]: *** [Makefile:606: syncconfig] Error 2
make[1]: *** [Makefile:711: include/config/auto.conf.cmd] Error 2
make[1]: Leaving directory '/usr/src/linux-headers-5.9.16-050916-generic'
make: *** [Makefile:39: default] Error 2

Update 6
sudo lshw -C network

  *-network
       description: Wireless interface
       product: Wi-Fi 6 AX200
       vendor: Intel Corporation
       physical id: 0
       bus info: pci@0000:47:00.0
       logical name: wlp71s0
       version: 1a
       serial: 5c:80:b6:8f:c3:4d
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix bus_master cap_list ethernet physical wireless
       configuration: broadcast=yes driver=iwlwifi driverversion=5.8.0-48-generic firmware=55.d9698065.0 cc-a0-55.ucode ip=192.168.178.66 latency=0 link=yes multicast=yes wireless=IEEE 802.11
       resources: irq:16 memory:a2300000-a2303fff
  *-network UNCLAIMED
       description: Ethernet controller
       product: Realtek Semiconductor Co., Ltd.
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:48:00.0
       version: 06
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix vpd cap_list
       configuration: latency=0
       resources: ioport:3000(size=256) memory:a2200000-a220ffff memory:a2210000-a2213fff

A: Remove module_blacklist=r8169 from /etc/default/grub, and then sudo update-grub. If the r8168-dkms module is installed, the proper place to blacklist the r8169, if required, would be in /etc/modprobe.d/r8168-dkms.conf. But don't do that yet.
The r8169 kernel module is required to drive your ethernet card...
Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. Device [10ec:3000] (rev 06)

Assuming that you have wireless connectivity, do this...
dkms status
If only r8168-dkms shows up, then do this...
sudo rm -i /var/crash/r8168-dkms.0.crash
sudo apt purge r8168-dkms dkms
sudo apt install --reinstall linux-headers-5.8.0-44-generic
sudo apt install build-essential dkms r8168-dkms
reboot
Update #1:
For kernel 5.9.16... https://kernel.ubuntu.com/~kernel-ppa/mainline/v5.9.16/. Download the 4 files, but skip the low-latency files, install, and report back.
Update #2:
Boot to the 5.8.0-45-generic kernel.
sudo apt purge  the 5.9.16-050916-generic kernel... (easiest to install gdebi and use that to uninstall the following .deb files...)
linux-headers-5.9.16-050916_5.9.16-050916.202012211331_all.deb
linux-headers-5.9.16-050916-generic_5.9.16-050916.202012211331_amd64.deb
linux-image-unsigned-5.9.16-050916-generic_5.9.16-050916.202012211331_amd64.deb
linux-modules-5.9.16-050916-generic_5.9.16-050916.202012211331_amd64.deb

sudo dkms remove r8168/8.048.00 --all # remove r8168 from all kernels
sudo apt purge r8168-dkms # remove the r8168 driver
Remove module_blacklist=r8169 from /etc/default/grub (if it's still there)
sudo update-grub
reboot # reboot the computer
If required for card reader...

*

*sudo dkms build rts_pstor/1.11 # build the card reader kernel module

*sudo dkms install rts_pstor/1.11 # install the card reader kernel module

*dkms status # confirm the card reader module shows as installed
Otherwise...

*

*sudo dkms remove rts_pstor/1.11 --all


Q: Where did the Millennium Falcon learn to communicate? From the script:

THREEPIO: Sir, I don't know where your ship learned to communicate,
  but it has the most peculiar dialect. I believe, sir, it says that the
  power coupling on the negative axis has been polarized. I'm afraid
  you'll have to replace it.

Is it ever explained what dialect the Millennium Falcon's computer had, or why it was so "peculiar"?

A: Within the film canon, there's no specific indication of the reason why the ship has a peculiar dialect other than its generally "cobbled-together" nature. On top of that, whenever we see the ship at rest it's invariably in a constant state of repair using a mix of parts sourced from wherever Han can get them cheapest.
The ultimate implication is, of course that because the ship has been owned by a series of rough-and-ready smuggler types (Lando and Han that we know of), that the ship's brain is much the same, built using a mixture of official and unofficial parts and periodically using vulgar language which we know C3PO finds offensive.

In the excellent (but not especially canonical) "Millennium Falcon Owner's Manual" we can see the problem more clearly;

A: It is L3-37, Lando’s droid co-pilot.

 She was damaged in the escape from Kessel (in Solo) and died. Han, Lando, and co. uploaded her core processor into the Falcon so they could use her navigational database to plot a shorter course for their escape.

A: In the radio drama version of The Empire Strikes Back, Han states that the Millennium Falcon's particularly rude communications is a product of being crewed by himself and Chewbacca.
Beginning at 1:38:00 in the recording linked above:

THREEPIO:  Oh dear, oh dear.  Where is Artoo when I need him?  What an incredible mess!
HAN:  How's it going on the hyperdrive Threepio?  Fixed yet?
THREEPIO:  Captain, I don't know where the Falcon learned to communicate, but she has the most peculiar dialect.
HAN:  Don't knock her.
THREEPIO:  No, no, she's very intelligent, but she can be so rude at times.
HAN:  Well, it comes from hanging around with me and Chewie.  You're liable to start doing it yourself.  What'd she say?


Q: asp.net Razor v3 jquery ajax post returns 404 not found I recently started a Asp.net Razor v3 project. It's the first time I use this (before I only used MVC and Web Forms)
I am struggling to get a code behind that gets called by a jquery ajax function to work. When debugging on Chrome I see that the script returns POST 404 (Not Found)
$.ajax({
  type: "POST",
  url: "../App_Code/GlobalSitesController/GetSiteTable",
  data: "{'siteName': 'Some Site' , 'daysDiff': '0'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (response) {
  document.getElementById("siteTable").innerHTML = response.responseText;
  },
  failure: function (response) {
  document.getElementById("siteTable").innerHTML = "ERROR" + response.responseText;
  },
  error: function (response) {
  document.getElementById("siteTable").innerHTML = "ERROR" + response.responseText;
  }
});

public class GlobalSitesController : Controller
{
 [HttpPost]
 public string GetSiteTable(string siteName, int daysDiff)
 {
  return "some string";
 }
}

First I noticed that my project didn't include System.Web.Mvc so I added Microsoft.AspNet.Mvc via Nugget
The full Chrome error is jquery-1.10.2.min.js:23 POST http://localhost:9997/App_Code/GlobalSitesController/GetSiteTable 404 (Not Found). This is the correct URL and should be working

A: It turns out the url bit needs to be in the following form
url: '@url.Action("GetSiteTable", "GlobalSitesController")',

(url needs to be initialised as in below)
System.Web.Mvc.UrlHelper url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);


Q: python 3 hex conversion I'm trying to convert some code from 2 to 3.  I have
val = str(''.join(map(chr, list(range(0, 256, 8)))))

and I need to translate
x = str(val).encode('hex')

and
x.decode('hex')

Thanks

A: In python2, your code produces:
In [4]: val = str(''.join(map(chr, list(range(0, 256, 8))))) ;  val
Out[4]: '\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'
In [5]: x = str(val).encode('hex') ; x
Out[5]: '0008101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f0f8'
In [6]: x.decode('hex')
Out[6]: '\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'

To get the similar output in python3:
In [19]: import codecs
In [20]: val = ''.join(map(chr, range(0, 256, 8))) ; val
Out[20]: '\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0¨°¸ÀÈÐØàèðø'
In [21]: x = codecs.encode(val.encode('latin-1'), 'hex_codec') ; x
Out[21]: b'0008101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f0f8'
In [22]: codecs.decode(x, 'hex_codec')
Out[22]: b'\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'

Notes:

*

*The python3 version of x above is a byte-string.  Since it is entirely ASCII, it can be converted to unicode simply via x.decode().

*The display of val toward the end of the string in the python3 code above does not match the python2 version.  For a method of creating val which does match, see the next section.

Alternatives
Use bytes to create the string.  Use binascii.hexlify to convert it to hex:
In [15]: val = bytes(range(0, 256, 8))
In [16]: val
Out[16]: b'\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'
In [17]: binascii.hexlify(val)
Out[17]: b'0008101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f0f8'

More on unicode and character 0xf8
You wanted ø to be 0xf8.  Here is how to make that work:
>>> s = chr( int('f8', 16) )
>>> s
'ø'

And, to convert s back to a hex number:
>>> hex(ord(s))
'0xf8'

Note that 0xf8' is the unicode code point of 'ø' and that that is not the same as the byte string representing the unicode character 'ø' which is:
>>> s.encode('utf8')
b'\xc3\xb8'

So, 'ø' is the 248th (0xf8) character in the unicode set and its byte-string representation is b'\xc3\xb8'.

A: Your Python 2 code:
val = str(''.join(map(chr, list(range(0, 256, 8)))))
x = str(val).encode('hex')
x.decode('hex')

Let's make version that works on both Python 2 and 3:
import binascii

val = bytearray(range(0, 0x100, 8))
x = binascii.hexlify(val)
binascii.unhexlify(x)


Q: MonoDevelop and XCode I'm using MonoDevelop 2.8.5 and XCode 4.2.1.
Every time I'm switching to monodevelop window from anything else, it starts to update XCode project file and pops XCode window.
More over, when I switch from XCode back to monotouch, it updates the project and switches back to XCode.
Thats's really annoying. How do I disable this "feature"?

A: Problem was fixed by downloading new Monodevelop: 2.8.6 beta

A: This behavior cannot be disabled, since there is no other way that MonoDevelop can use to communicate with xcode 4. This is because MonoDevelop creates an Xcode project on the fly (when you dbl clic any xib file within MD) and then MD launches xcode with the generated xcode project.
when you do all necessary changes in xcode and you switch back to MD the OnFocus event of MD (i don't really know if thats the event's name btw) process the changes you have done on the xcode project and modifies it in order to maintain both projects (xcode and MD) on sync
My suggestion is just make all necessary changes on xcode save them and then close it, then work on MD as usual and if you need to reopen xcode again work on it, Xcode won't bother you as long as you don't focus the MD window
I hope this helps.
Alex


Q: I cannot seem to run this properly... It stucks and does not display an output Here's my script:
while [[ $startTime -le $endTime ]]
do

thisfile=$(find * -type f | xargs grep -l $startDate | xargs grep -l $startTime)
fordestination=`cut -d$ -f2 $thisfile | xargs cut -d ~ -f4`

echo $fordestination

startTime=$(( $startTime + 1 ))

done

A: I think your cut and grep commands could get stuck. You probably should make sure that their parameters aren't empty, by using the [ -n "$string" ] command to see if $string isn't empty. In your case, if it were empty, it wouldn't add any files to the command that would use it afterwards, meaning that the command would probably wait for input from the command line (ex: if $string is empty and you do grep regex $string, grep wouldn't receive input files from $string and would instead wait for input from the command line). Here's a "complex" version that tries to show where things could go wrong:
while [[ $startTime -le $endTime ]]
do

thisfile=$(find * -type f)
if [ -n "$thisfile" ]; then
    thisfile=$(grep -l $startDate $thisfile)
    if [ -n "$thisfile" ]; then
        thisfile=$(grep -l $startTime $thisfile)
        if [ -n "$thisfile" ]; then
            thisfile=`cut -d$ -f2 $thisfile`

            if [ -n "$thisfile" ]; then
                forDestination=`cut -d ~ -f4 $thisfile`
                echo $fordestination
            fi
        fi
    fi
fi

startTime=$(( $startTime + 1 ))

done

And here's a simpler version:
while [[ $startTime -le $endTime ]]
do

thisfile=$(grep -Rl $startDate *)
[ -n "$thisfile" ] && thisfile=$(grep -l $startTime $thisfile)

[ -n "$thisfile" ] && thisfile=`cut -d$ -f2 $thisfile`
[ -n "$thisfile" ] && cut -d ~ -f4 $thisfile

startTime=$(( $startTime + 1 ))

done

The "-R" tells grep to search files recursively, and the && tells bash to only execute the command that follows it if the command before it succeeded, and the command before the && is the test command (used in ifs).
Hope this helps =)


Q: How to set a threshold value from signal to be processed in wavelet thresholding in python I'm trying to denoise my signal using discrete wavelet transform in python using pywt package. But i cannot define what is threshold value that i should set in pywt.threshold() function
I have no idea what the best threshold value that should be set in order to reconstruct a signal with minimal noise
I used ordinary code:
pywt.threshold(mysignal, threshold, 'soft')
yes i am intended to do soft thresholding
I want to know if the threshold value could be determined by looking to my signal or from the other way

A: There are some helpful graphics on pywt webpage that help visualize what these thresholds are and what they do.
The threshold applies to the coefficients as opposed to your raw signal.  So for denoising, this will typically be the last couple of entries returned by pywt.wavedec that will need to be zeroed/thresholded.
I could initial guess is the 0.5*np.std of each coefficeint level you want to threshold.


Q: Convert c# date to Javascript This is how I convert .Net Datetime to Javascript. I found the code somewhere a long time ago and use it for Highcharts. Now the chart sometimes looks strange with the lines messed up. I suspect it has to do with the date.
Datetime curDate = "11/14/2013";
string jsDate = "Date.UTC(" + curDate.Year + "," + (curDate.Month - 1) + "," +     curDate.Day;
if (curDate.Millisecond > 0)
        {
            jsDate += "," + curDate.Hour + "," + curDate.Minute + "," + curDate.Second + "," + curDate.Millisecond;
            return jsDate += ")";
        }
        if (curDate.Second > 0)
        {
            jsDate += "," + curDate.Hour + "," + curDate.Minute + "," + curDate.Second;
            return jsDate += ")";
        }
        if (curDate.Minute > 0)
        {
            jsDate += "," + curDate.Hour + "," + curDate.Minute;
            return jsDate += ")";
        }
        if (curDate.Hour > 0)
        {
            jsDate += "," + curDate.Hour;
            return jsDate += ")";
        }

        jsDate += ")";

Is this a correct way to convert .Net date to javascript?
Thank you!

A: The easiest way to convert between the two is to convert the .NET time to a timespan in milliseconds from the UNIX epoch time:
public static long ToEpochDate(this DateTime dt)
{
    var epoch = new DateTime(1970, 1, 1);
    return dt.Subtract(epoch).Ticks;
}

You can then use that to generate your JS string:
DateTime current = DateTime.Now;
var jsDate = string.Format("Date.UTC({0})", current.ToEpochDate());


Q: two forms conflict with each other I have placed two forms on one page. Bothe forms work fine separately but when they are placed on one page at the same time they conflict with each other. Here are both forms:
Contact Form:
<form name="contactform" id="contactform" method="post" action="#targetAnchorPage2">

<?php
if (isset($_POST["name"])){
?>

 <?php
 require_once("contact_send.php");
 ?>

<?php
}
?>

<label for="name" class="<?=$name_class?>">name:	<input  type="text" name="name" maxlength="50" value="<?=$name?>">

<label for="email" class="<?=$emailaddress_class?>">email:	<input  type="text" name="email" maxlength="80" value="<?=$emailaddress?>">

<label id="tworows" for="message" class="<?=$message_class?>">your message:

<textarea  name="message" cols="22" rows="6" value="<?=$message_class?>"></textarea>

<input class="button" type="submit" value="">

</form>

Subscribe Form:
<form name="subscribeform" id="subscribeform" method="post" action="#targetAnchorPage3">

<?php
if (isset($_POST["name"])){
?>

 <?php
 require_once("subscribe_send.php");
 ?>

<?php
}
?>

<label for="name" class="<?=$name_class?>">name:	<input type="text" name="name" maxlength="50" value="<?=$name?>">

<label for="email" class="<?=$emailaddress_class?>">email:	<input type="text" name="email" maxlength="80" value="<?=$emailaddress?>">

<input class="button" type="submit" value="">

</form>

How can this be solved? Is it caused by the "required_once" command?

A: I am guessing that since you are showing the required files based on the same criteria isset($_POST['name']) and since both forms have the name field you end up showing the code in both requires regardless of which form is submitted.  You should simply change the form field names on on of the forms such that they are different.

A: Both forms have the same action attribute, they both point back to the same page (note that the hash is not sent to the server). As they both have a field called name and you are checking for that, both actions get executed regardless of which form was sent in.
You can do either:

*

*use different scripts / form processors (don't post back to the same page)

*use a different check for each form, for example by adding a hidden input that will allow you to distinguish between the forms.

A: Add
  formaction="Your_URL"

Attribut  in Button


Q: Loading a whole mySQL table into a PHP array I have a table with 4 columns and 23 rows. I need all 92 values in the the table as PHP variables (whether that be one array, 4 arrays, 92 individual variables, or whatever).
The rows are:
ID
Category
Summary
Text
I need to build a series of select boxes where the items are grouped by the category, the options available are the summaries, and the resulting text is passed on for processing.
I've been searching, but all the examples I can find are about printing the table out, and I need to continue working with the variables.
I really appreciate any help!
Billy

A: Just a SELECT * FROM table_name will select all the columns and rows.
$query = "SELECT * FROM table_name";
$result = mysql_query($query);

$num = mysql_num_rows($results);
if ($num > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        // You have $row['ID'], $row['Category'], $row['Summary'], $row['Text']
    }
}

A: OK, I found my answer with better search terms.  I'm still new here, so let me know if this is not a fair way to handle the situation.  I upvoted @Indranil since he or she spent so much time trying to help me.
Anyway...
    $content = array();
    while($row = mysql_fetch_assoc($result)) {
      $content[$row['id']] = $row;
    }

Puts my whole entire table into one huge, multidimensional array so that I can use it throughout my code.  And it even names the first level of the array by the ID (which is the unique identifier).
Thank you to those that tried to help me!
Billy

A: $pdo = new PDO(
    'mysql:host=hostname;dbname=database;charset=utf-8',
    'username',
    'password'
);
$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );

$stmt = $pdo->query('SELECT ID, Category, Summary, Text FROM Table');
if ( $stmt !== false )
{
   $data = $stmt->fetchAll( PDO::FETCH_ASSOC );
}

In the case if the SQL query has no conditions, use query() , otherwise, you should be using prepare() ans bind the parameters.
Oh .. and please stop using the ancient mysql_* functions, they are in the process of being deprecated and no new code should written with them.


Q: trouble scraping data from an html table I'm trying to scrape data, in the form of a table, and the hrefs from within that table from a town assessor website using the R package rvest. Despite having luck scraping tables from other websites (e.g. wikipedia), I'm unable to get anything from the town assessor.
I am using RStudio v1.1.442 and R v3.5.0.
sessioninfo()
R version 3.5.0 (2018-04-23)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.6

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] rvest_0.3.3 xml2_1.2.0  V8_2.2

loaded via a namespace (and not attached):
 [1] httr_1.4.0     compiler_3.5.0 selectr_0.4-1  magrittr_1.5   R6_2.4.0       tools_3.5.0    yaml_2.2.0
 [8] curl_3.3       Rcpp_1.0.1     stringi_1.4.3  stringr_1.4.0  jsonlite_1.6

I have tried to follow a few examples. First, the wikipedia state population example, which works fine.
url <- "https://en.wikipedia.org/wiki/List_of_states_and_territories_of_the_United_States_by_population"
population <- url %>%
  read_html() %>%
  html_nodes("#mw-content-text > div > table:nth-child(11)") %>%
  html_table()
population <- population[[1]]

I've also been able to scrape data from yelp without issue. This, for example, gives me the names of the restaurants.
url <- "https://www.yelp.com/search?find_loc=New+York,+NY,+USA"
heading <- url %>%
  read_html() %>%
  html_nodes(".alternate__373c0__1uacp .link-size--inherit__373c0__2JXk5") %>%
  html_text()

The website I'm having trouble with is like this one, which is the output of a search for properties on a specific street.
url <- "https://imo.ulstercountyny.gov/viewlist.aspx?sort=printkey&swis=all&streetname=Lake+Shore+Dr"
helpme <- url %>%
  read_html() %>%
  html_nodes("#tblList > tbody") %>%
  html_table()

I would also like to be able to pull out the hrefs using something like this
helpme <- url %>%
  read_html() %>%
  html_nodes("#tblList > tbody") %>%
  html_attr('href') %>%
  html_text()

Unfortunately, my attempts to scrape the table and the href are empty.
Is there something strange about this website. I've used the chrome browser inspector and SelectorGadget to help find the right copy selectors. I've also tried it with the xpath. The result is the same either way.


Q: Hibernate EntityManager is getting closed, in wildfly 10 I use container managed JPA where  inject the EntityManager instance. With the injected entitymanager instance, when I use find() method it says entity manager is closed.
I use wildfly 10.
How can I overcome this issue? What I do wrong here?
I create entity manager like this;
        @PersistenceContext
        protected EntityManager em;

    @Stateless
    public class CustomerService  CrudService<Customer> {

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void update(Customer entity) {

    Customer item = em.find(Customer.class,entity.getId()); //ISSUE
    if (entity.getParentId()!=null) {
        item.setParent(em.find(CRMEntity.class , entity.getParentId()));
    item.setParentId(entity.getParentId());
    }
....

super.update(item);
}

public abstract class CrudService<T extends BaseEntity>  {
public void update(T entity) {
        Session session = null;

        try {
            session = getSession();
            session.update(entity);
            session.flush();

        } catch (HibernateException ex) {
            log.error("Error when update." + entity.getCode(), ex);
            if (session != null) {
                session.cancelQuery();
            }
        } finally {
            if (session != null && session.isOpen()) {
                session.clear();
                session.close();
            }
        }
    }
public Session getSession() {
        if (session == null || !session.isOpen()) {
            session = getEntityManager().unwrap(Session.class);
        }
        return session;
    }

}

I get issue at this line;
Customer item = em.find(Customer.class,entity.getId());

Error
Caused by: java.lang.IllegalStateException: Session/EntityManager is closed
    at org.hibernate.internal.AbstractSharedSessionContract.checkOpen(AbstractSharedSessionContract.java:326)
    at org.hibernate.engine.spi.SharedSessionContractImplementor.checkOpen(SharedSessionContractImplementor.java:126)
    at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3312)
    at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3297)
    at org.jboss.as.jpa.container.AbstractEntityManager.find(AbstractEntityManager.java:213)
    at com.leightonobrien.lob2.service.autogen.CustomerService.update(CustomerService.java:412)
    at sun.reflect.GeneratedMethodAccessor249.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptor.java:52)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:437)

A: Issue here is I closed the session. After removing it, everything works fine


Q: Allow only numeric value in textbox using Javascript I want to allow only numeric values to be entered into the text and if user enters alphabetic character it should warn the user.
Any suggestion for optimized and short javascript code?

A: function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

from here

A: use following code
function numericFilter(txb) {
   txb.value = txb.value.replace(/[^\0-9]/ig, "");
}

call it in on key up
<input type="text" onKeyUp="numericFilter(this);" />

A: Here is a solution which blocks all non numeric input from being entered into the text-field.
html
<input type="text" id="numbersOnly" />

javascript
var input = document.getElementById('numbersOnly');
input.onkeydown = function(e) {
    var k = e.which;
    /* numeric inputs can come from the keypad or the numeric row at the top */
    if ( (k < 48 || k > 57) && (k < 96 || k > 105)) {
        e.preventDefault();
        return false;
    }
};

A: Please note that, you should allow "system" key as well
    $(element).keydown(function (e) {
    var code = (e.keyCode ? e.keyCode : e.which), value;
    if (isSysKey(code) || code === 8 || code === 46) {
        return true;
    }

    if (e.shiftKey || e.altKey || e.ctrlKey) {
        return ;
    }

    if (code >= 48 && code <= 57) {
        return true;
    }

    if (code >= 96 && code <= 105) {
        return true;
    }

    return false;
});

function isSysKey(code) {
    if (code === 40 || code === 38 ||
            code === 13 || code === 39 || code === 27 ||
            code === 35 ||
            code === 36 || code === 37 || code === 38 ||
            code === 16 || code === 17 || code === 18 ||
            code === 20 || code === 37 || code === 9 ||
            (code >= 112 && code <= 123)) {
        return true;
    }

    return false;
}

A: // Solution to enter only numeric value in text box
$('#num_of_emp').keyup(function () {
    this.value = this.value.replace(/[^0-9.]/g,'');
});

for an input box such as :
<input type='text' name='number_of_employee' id='num_of_emp' />

A: @Shane, you could code break anytime, any user could press and hold any text key like (hhhhhhhhh) and your could should allow to leave that value intact.
For safer side, use this:
$("#testInput").keypress(function(event){

instead of:
$("#testInput").keyup(function(event){

I hope this will help for someone.

A: or
function isNumber(n){
  return (parseFloat(n) == n);
}

http://jsfiddle.net/Vj2Kk/2/

A: This code uses the event object's .keyCode property to check the characters typed into a given field. If the key pressed is a number, do nothing; otherwise, if it's a letter, alert "Error". If it is neither of these things, it returns false.
HTML:
<form>
    <input type="text" id="txt" />
</form>

JS:
(function(a) {
    a.onkeypress = function(e) {
        if (e.keyCode >= 49 && e.keyCode <= 57) {}
        else {
            if (e.keyCode >= 97 && e.keyCode <= 122) {
                alert('Error');
                // return false;
            } else return false;
        }
    };
})($('txt'));

function $(id) {
    return document.getElementById(id);
}

For a result: http://jsfiddle.net/uUc22/
Mind you that the .keyCode result for .onkeypress, .onkeydown, and .onkeyup differ from each other.

A: Javascript For only numeric value in textbox ::
<input type="text" id="textBox" runat="server" class="form-control" onkeydown="return onlyNos(event)" tabindex="0" />

    <!--Only Numeric value in Textbox Script -->
        <script type="text/javascript">
            function onlyNos(e, t) {
                try {
                    if (window.event) {
                        var charCode = window.event.keyCode;
                    }
                    else if (e) {
                        var charCode = e.which;
                    }
                    else { return true; }
                    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                        return false;
                    }
                    return true;
                }
                catch (err) {
                    alert(err.Description);
                }
            }
        </script>
        <!--Only Numeric value in Textbox Script -->


Q: Ordenar uma matriz segundo coluna Como ordenar a seguinte matriz segundo a coluna das coordenadas x? Eu quero que nao ordene apenas as coordenadas, mas que me troque as linhas de maneira a que as coordenadas das cidades estejam corretas.
O que tenho até agora, funciona para as 3 primeiras cidades mas a ultima é simplesmente uma cópia de uma linha anterior.
matriz_ficheiro=[['Nome' 'Coordenada X' 'Coordenada Y' 'Peso']
 ['Lisboa' '36.752' '204.319' '3']
 ['Copenhaga' '1971.323' '2086.417' '5']
 ['Berlin' '2046.659' '1735.743' '4']
 ['Madrid' '520.862' '392.972' '2']]

lista_x=[]
for i in range(1,matriz_ficheiro[:,0].size):
    lista_x.append(float(matriz_ficheiro[i][1]))
matriz_ordenada_x=matriz_ficheiro

 for i in range (1,matriz_ficheiro[:,0].size):
    minimo_x=min(lista_x)
    for j in range (1,matriz_ficheiro[:,0].size):
        if minimo_x==eval(matriz_ficheiro[j][1]):

            matriz_ordenada_x[i][0]=matriz_ficheiro[j][0]
            matriz_ordenada_x[i][1]=minimo_x
            matriz_ordenada_x[i][2]=matriz_ficheiro[j][2]
            matriz_ordenada_x[i][3]=matriz_ficheiro[j][3]
    lista_x.remove(minimo_x)

O resultado é o seguinte:
--------------------------------------------------------------------------------
|     Nome           |     Coordenada X   |     Coordenada Y   |     Peso      |
--------------------------------------------------------------------------------
|     Lisboa         |     36.752         |     204.319        |     3         |
--------------------------------------------------------------------------------
|     Madrid         |     520.862        |     392.972        |     2         |
--------------------------------------------------------------------------------
|     Berlin         |     2046.659       |     1735.743       |     4         |
--------------------------------------------------------------------------------
|     Berlin         |     2046.659       |     1735.743       |     4         |
--------------------------------------------------------------------------------

A: Você pode utilizar o itemgetter do módulo operator e simplificar bastante seu código:
from operator import itemgetter

matrix_ficheiro = [['Nome', 'Coordenada X', 'Coordenada Y', 'Peso'],
 ['Lisboa', 36.752, 204.319, 3],
 ['Copenhaga', 1971.323, 2086.417, 5],
 ['Berlin', 2046.659, 1735.743, 4],
 ['Madrid', 520.862, 392.972, 2]]

# Recebendo a primeira linha da matriz (Nome, Coordenada X, Coordenada Y, Peso)
# Salvando em uma nova matriz que estará ordenada
matrix_ordenada = matrix_ficheiro[0]

# Ordenando pela segunda coluna da matrix (desconsiderando a primeira linha)
sub_matrix_ordenada = sorted(matrix_ficheiro[1:], key=itemgetter(1))

# Percorrendo a sub matriz e adicionando cada elemento na nova matriz ordenada
for elem in sub_matrix_ordenada:
    matrix_ordenada.append(elem)

# Opcional
# Matriz original recebe a nova matriz ordenada
# É opcional, pois você pode simplesmente usar a matriz ordenada
matrix_ficheiro = matrix_ordenada


Q: Spring Data JPA Self Join with Nullable foreign key I have problem with Spring Data JPA. I want to create a category that have parent category with the same table. Some categories don't need to have parent category, so parent category can be null. but when I do that, and save it, it shown error as below:
org.hibernate.TransientPropertyValueException: object references an unsaved
transient instance - save the transient instance before flushing :
com.ltech.solutions.ecom.models.category.Category.parent ->
com.ltech.solutions.ecom.models.category.Category

Here is my model:
@Entity
@Table(name = "tb_category")
public class Category extends BaseEntity {

    @Column(name = "name", nullable = false)
    private String name;

    @JsonIgnore
    @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id", referencedColumnName = "id")
    private Category parent;

    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
    @JsonProperty(value = "sub_categories")
    private Set<Category> subCategories;

    @Column(name = "is_visible", insertable = false, columnDefinition =
    "BOOLEAN DEFAULT TRUE")
    @JsonProperty(value = "is_visible")
    private Boolean isVisible;

    @Column(name = "is_enable", insertable = false, columnDefinition = "BOOLEAN
    DEFAULT TRUE")
    @JsonProperty(value = "is_enable")
    private Boolean isEnable;

    @Column(name = "desc_attribute")
    private String descAttribute;
 }

*

*When saving object, I use save method of CRUDRepsoitory.

Here is my view:
<form th:object="${createCategoryForm}" th:action="@{/category/save}"
method="post">
        <fieldset>
            <legend>Create Category</legend>

                Name
                <input class="form-control" th:field="*{name}" />

                Code
                <input class="form-control" th:field="*{code}" />

                Description (English)
                <input class="form-control" th:field="*{descEn}" />

                Description (Khmer)
                <input class="form-control" th:field="*{descKh}" />

                Attributecs
                <input class="form-control" th:field="*{descAttribute}" />

                Parent of
                <select class="form-control" th:field="*{parent.id}">
                    <option value="">None</option>
                    <option th:each="parent : ${parentCategories}" th:value="${parent.id}" th:text="${parent.name}"></option>
                </select>

            <input type="submit" />
        </fieldset>
    </form>


Q: Equivalency of Probabilistic statements: can one do algebra within $\Pr [ \cdots ] = x$? This question is motivated by the following example:
For some non-negative RV $X$ and real number $v$ the Markov inequality can be stated:
$$ \Pr [X \geq v] \leq \frac{E(X)}{v} $$
or equivalently,
$$ \Pr [X \geq v \cdot E(X)] \leq \frac{1}{v} $$
I cannot understand how these can be logically equivalent? And as a more general question, are there any rules pertaining to one's ability to pull terms out of the $\Pr[\cdots]$ area or put them into it?

A: I will assume that $\mathbb{E}[X]>0$, as otherwise $X=0$ almost surely (in this case the first inequality is true for all $v>0$, but the second is false for $v>1$).
Setting $t=\frac{v}{\mathbb{E}[X]}>0$ and using the first form of Markov's inequality in your question yields
$$ \mathbb{P}(X\geq t\mathbb{E}[X])\leq \frac{\mathbb{E}[X]}{t\mathbb{E}[X]}=\frac{1}{t} $$
which is the second form of Markov's inequality in your question.
Similarly, one may go in the opposite direction by writing $v=t\mathbb{E}[X]$.


Q: How to import one column to a new worksheet? I have a workbook which has individual worksheets detailing client stock trading data, and a master worksheet which has month to date and week to date totals for the clients.
I would like to set up a new worksheet titled week to date which will import the week to date column from the master worksheet and save it.
Additionally, I would like it to update every time I run the macro so it has an up to date record of the week to date figures.
My current code provides sum totals for specified columns on each worksheet, and embeds the contents of the active worksheet into the body of an outlook email.
Sub AutoSum()

    Dim wscount As Long
    wscount = ActiveWorkbook.Worksheets.Count

    Dim i As Long
    For i = 1 To wscount
        Sheets(i).Select
        Range("K3").Select
        Selection.End(xlDown).Select
        ActiveCell.Offset(2, 0).Select
        Dim cel1 As String, cel2 As String
        cel1 = ActiveCell.Offset(-2, 0).End(xlUp).Address
        cel2 = ActiveCell.Offset(-1).Address
        ActiveCell.Value = "=sum(" & (cel1) & ":" & (cel2) & ")"
    Next i

    'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
    'Don't forget to copy the function RangetoHTML in the module.
    'Working in Excel 2000-2016
    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object

    Set rng = Nothing
    On Error Resume Next
    'Only the visible cells in the selection
    Set rng = Selection.SpecialCells(xlCellTypeVisible)
    'You can also use a fixed range if you want
    'Set rng = Sheets("YourSheet").Range("D4:D12").SpecialCells(xlCellTypeVisible)
    On Error GoTo 0

    If rng Is Nothing Then
        MsgBox "The selection is not a range or the sheet is protected" & _
               vbNewLine & "please correct and try again.", vbOKOnly
        Exit Sub
    End If

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = "nabil.hure@dnb.no"
        .CC = ""
        .BCC = ""
        .Subject = "Today's Trades" & Date
        .HTMLBody = RangetoHTML(rng)
        .Send                                    'or use .Display
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Function RangetoHTML(rng As Range)
    ' Changed by Ron de Bruin 28-Oct-2006
    ' Working in Office 2000-2016

    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing

End Function

A: It sounds like you're just asking how to cut a column across into another worksheet. This will move everything in the K column in the master sheet and copy it to the A column in wtd. Obviously this can be changed to any column you want.
Sheets("wtd").Range("A:A").Value = Sheets("master").Range("K:K").Value


Q: ActionSupport not calling my function in controller What I'm trying to do is rerender my form once a row in the table is clicked. Initially, I have just put a system debug line in the function in the controller and I have not been able to see it in the debug log since the action support is not going there. Not sure why honestly...
VF Page :
<apex:column width="50px;">
  <apex:facet name="header">Name</apex:facet>
     <apex:outputpanel>
         <apex:actionSupport event="onRowClick" action="{!setSource}" reRender="form">
           <apex:param name="temp.name" value="{!temp.Name}"/>
           <apex:param name="temp.id" value="{!temp.ID}"/>
          </apex:actionSupport>
     {!temp.Name}
     </apex:outputpanel>
</apex:column>

Btw, this column is part of an apex page block table :
<apex:pageBlockTable rows="5" rendered="{!selectedObject=='ACCOUNT' && foundResults==true}"
value="{!searchResultsAcc}" var="temp">

Function in controller :
public void setSource() {
   System.debug('Inside setSource()');
}

A: onRowClick is only when you're using apex:dataTable or apex:pageBlockTable. You can't use it with apex:actionSupport. You'll probably want to just use "onclick" as the event.

Working demo of passing a value back to the row-click:
<apex:page standardController="Account" recordSetVar="Accounts">
    <apex:form>
        <apex:pageBlock>
        <apex:pageBlockTable value="{!accounts}" var="accountRecord" onrowclick="alert(this.firstChild.dataset.id)">
            <apex:column html-data-id="{!accountRecord.Id}" value="{!accountRecord.Name}" />
        </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

You can call an actionFunction (not shown here) to pass parameters to the controller.

Demo calling actionFunction:
Controller:
public class highlightRowController {
    public Id selectedId { get; set; }
    public Integer selectCount { get; set; }
    public highlightRowController() {
        selectCount = 0;
    }
    public Account[] getAccounts() {
        return [SELECT Id, Name FROM Account ORDER BY Name ASC LIMIT 100];
    }
    public void incrementCounter() {
        selectCount++;
    }
}

Page:
<apex:page controller="highlightRowController">
    <apex:form id="form">
        <apex:actionFunction name="highlightRow" reRender="form" action="{!incrementCounter}">
            <apex:param name="selectedId" assignTo="{!selectedId}" value="" />
        </apex:actionFunction>
        <apex:pageBlock title="Times function called: {!selectCount}">
            <apex:pageBlockTable value="{!accounts}" var="account" onrowclick="highlightRow(this.firstChild.dataset.id)">
                <apex:column value="{!account.Name}{!if(selectedId=account.Id,' (Selected)','')}" html-data-id="{!account.Id}" />
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>


Q: Overloading functions not compiling I am following the book C++ Cookbook from O'Reilly and I try one of the examples, here is the code:
#include <string>
#include <iostream>
#include <cctype>
#include <cwctype>

using namespace std;

template<typename T, typename F>
void rtrimws(basic_string<T>& s, F f){
    if(s.empty())
        return;

    typename basic_string<T>::iterator p;
    for(p = s.end(); p != s.begin() && f(*--p););

    if(!f(*p))
        p++;

    s.erase(p, s.end());
}

void rtrimws(string& ws){
    rtrimws(ws, isspace);
}

void rtrimws(wstring& ws){
    rtrimws(ws, iswspace);
}

int main(){
    string s = "zing            ";
    wstring ws = L"zonh     ";

    rtrimws(s);
    rtrimws(ws);

    cout << s << "|\n";
    wcout << ws << "|\n";
}

When I try to compile it, I get the following error
trim.cpp: In function ‘void rtrimws(std::string&)’:
trim.cpp:22: error: too many arguments to function ‘void rtrimws(std::string&)’
trim.cpp:23: error: at this point in file

and I don't understand what's wrong. If I don't use the char version (string) but the wchar_t version only, everything runs smooth.
By the way, I am using g++ 4.4.3 in an ubuntu machine 64 bits

A: isspace is also a template in C++ which accepts a templated character and also a locale with which it uses the facet std::ctype<T> to classify the given character (so it can't make up its mind what version to take, and as such ignores the template).
Try specifying that you mean the C compatibility version: static_cast<int(*)(int)>(isspace). The differences between the compilers could come from the inconsistent handling of deduction from an overloaded function name among the compilers - see this clang PR. See the second case in Faisal's first set of testcases for an analogous case.

Someone pointed out on IRC that this code would call isspace using a char - but isspace takes int and requires the value given to be in the range of unsigned char values or EOF. Now in case that char is signed on your PC and stores a negative non-EOF value, this will yield to undefined behavior.
I recommend to do it like @Kirill says in a comment and just use the templated std::isspace - then you can get rid of the function object argument too.

A: Try rtrimws(ws, ::isspace);.
Also, just as a note, you should be using the reverse iterator.

A: That's because isspace is a template function in c++. It cannot deduce F. If you want to use C variant of isspace you could fully qualify its name as follows:
void rtrimws(string& ws){
    rtrimws(ws, ::isspace); // this will use isspace from global namespace
                            // C++ version belongs to the namespace `std`
}

This is one more good sample why you shouldn't use using namespace std.


Q: Browser plugin to resize window for brower testing When im making a website i work on my 22" external display, which is fine, but to get a better idea of what the site will look like on smaller screens i have to resize my browser window.
At the moment i use http://resizemybrowser.com/ (which also has a safari extension) but i was wandering if theres a firefox or chrome browser plugin that dose somthing similar, ive searched but so far been unable to find anything.

A: This is actually a built-in feature in Chrome.

*

*Open the DevTools (F12)

*Open the Settings

*Set the size you want for your window in the Overrides panel.

Note: When selecting a User Agent in that panel, Chrome will automatically try to pick the correct device metrics for the selected agent.

A: For Chrome you can use Window Resizer. Fore Firefox, you can use Firesizer.

A: Was just digging around in firefox and found that it also has a "Responsive design" mode. Go to Web Developer → Responsive Design View.

You'll get a dropdown with preset resolutions afterwards:


Q: how to remove child(html elements) of div Id using jQuery I have

aa

hellow

So how to remove all content of Id "myId" Using jQuery?
The result must be this:

A: *

*Use .empty()

Description: Remove all child nodes of the set of matched elements from the DOM.

$("#myId").empty()

console.log($("#myId").get(0).outerHTML)

aa

hellow

A: You could use different ways:
// ref: https://api.jquery.com/empty/
$("#myId").empty()

// ref: https://api.jquery.com/html/
$("#myId").html('')

A: you can use remove() method. .empty()
$( "#myId" ).empty()

A: In order to remove or empty all the elements of a container div in this case, you can:
$("#myId").empty();

OR
$("#myId").html('');

Reference link to empty()


Q: jQuery status indication by file on web server I have a web server. On the web server there is a process running that is doing something. While the process (or program) is running it will post updates on the status of the task it is doing that should indicate more or less when it will be finished. (Like a status bar indicator for example with percentage number)
The process (or program) will write to a file called busy.html - Inside busy.html the following will be written by the process: Processing: 50%
busy.html is located at: http://www.somewhere.com/temp/busy.html for example.
The process on the web server will intermittently write to busy.html while it is working until 100% is reached. When 100% is reached busy.html will be removed.
On a web page I would like to have jQuery code that displays the contents of  busy.html to indicate the status or progress of the process the web server is busy with.
So in other words, Jquery should poll and display the contents of busy.html inside an existing web page until busy.html does not exist anymore.
How would the Jquery code for this look like? Perhaps there is a much easier way of passing on the progress status to jQuery instead of using a file to indicate the existing status like explained here.
Update to my question:
Also, would this be the proper way (using jQuery) to indicate the status of a process running on the server? I would like to enter a URL that is password protected and the web page that loads should tell me the status of the process running on the server. The tech that is running the process is a Perl script or program that is busy indexing the contents of files into a database.

A: You can use this code:
var place = $('#foo');
var delay = 3 * 1000; // 3 seconds
var url = 'http://www.somewhere.com/temp/busy.html';
(function recur() {
   $.ajax({url: url, success: function(page) {
      place.html(page);
      setTimeout(function() {
          recur();
      }, delay);
   }, error: function() {
     place.hide();
   }});
})();

A: Here are the steps you need.

*

*Read JQuery post or get method and see simple example.

*Inside document ready call a post or get request (get would do with your scenario) and url will point to busy.html

*In response you will get data that is your html or text written inside busy.html

*You can then use the last three letters of that text to fetch percentage and show a chart, guage or simple text as you wish.

Its not complicated.


Q: Use Regular Expressions to find a date in a String I am trying to use regular Expressions to extract the dates from a string using VBA in Excel.
The string is:
Previous Month: 9/1/2015 - 9/30/2015

Or it can be :
Custom: 9/1/2015 - 9/30/2015

Do you have any idea how can I achieve that? I have never used Regular Expressions before.

A: RegEx is a poor choice for dates. You could look for : and examine the remaining tokens:
Sub Foo()
    Dim result() As Variant

    result = GetDates("Previous Month: 9/1/2015 - 9/30/2015")

    If UBound(result) Then
        Debug.Print result(0)
        Debug.Print result(1)
    End If
End Sub

Function GetDates(str As String) As Variant()
    Dim tokens() As String
    tokens = Split(Mid$(str, InStr(str & ": ", ":")), " ")

    If (UBound(tokens) = 3) Then
        If IsDate(tokens(1)) And IsDate(tokens(3)) Then
            GetDates = Array(CDate(tokens(1)), CDate(tokens(3)))
            Exit Function
        End If
    End If

    ReDim GetDates(0)
End Function

A: Try this:
([1-9]|1[012])[/]([1-9]|[1-2][0-9]|3[01])[/](19|20)[0-9]{2}

A: search a commandtext string for dates and then replace them with a new date
dim regex as object
 Set regex = CreateObject("VBScript.RegExp")
 regex.Pattern = "\d{1,2}[-/]\d{1,2}[-/]\d{2,4}"
 regex.Global = True
 Set regexMatches = regex.Execute(CommandText)
 for i=0 to regexMatches.Count()
        date1 = regexMatches(i)
 next


Q: Image create using gd I am creating image using GD library all the functions are working fine. But the main problem where i stucked that i want to merge png image over an other image but after overlapping it cannot merge properly and looking like jpg or other instead of png. I cannot upload my image here due to low reputation so click on these links below to see the image.
The image which i want to merge is this
Png image

The image where i merge above image is:

My code is here:
<?php
$im = imagecreate(288,288);
$background_color = imagecolorallocate($im, 230, 248, 248);
$file = 'images/smiley/smile'.$_POST['smiley'].'.png';
$bg = imagecreatefrompng($file);
imagealphablending($im, true);
imagesavealpha($bg, true);
imagecopyresampled($im, $bg, 80, 80, 0, 0, 50, 50, 185, 185);

                           header("Content-Type: image/png");
            $filename = $_SESSION['rand'].'.png';
            imagepng($im,$filename);
            echo '<img src="'.$filename.'" alt="" />';
?>

A: Your background image doesn't have an alpha channel. This makes the PHP GD library do all of it's copying operations without using an alpha channel, instead just setting each pixel to be fully opaque or transparent, which is not what you want.
The simplest solution to this is to create a new image of the same size as the background that has an alpha channel, and then copy both the background and face into that one.
$baseImage = imagecreatefrompng("../../var/tmp/background.png");
$topImage = imagecreatefrompng("../../var/tmp/face.png");

// Get image dimensions
$baseWidth  = imagesx($baseImage);
$baseHeight = imagesy($baseImage);
$topWidth   = imagesx($topImage);
$topHeight  = imagesy($topImage);

//Create a new image
$imageOut = imagecreatetruecolor($baseWidth, $baseHeight);
//Make the new image definitely have an alpha channel
$backgroundColor = imagecolorallocatealpha($imageOut, 0, 0, 0, 127);
imagefill($imageOut, 0, 0, $backgroundColor);

imagecopy($imageOut, $baseImage, 0, 0, 0, 0, $baseWidth, $baseHeight); //have to play with these
imagecopy($imageOut, $topImage, 0, 0, 0, 0, $topWidth, $topHeight); //have to play with these

//header('Content-Type: image/png');
imagePng($imageOut, "../../var/tmp/output.png");

That code produces this image:


Q: 404 Response with Retrofit POST request with Headers parameters I am new to Retrofit Library. When I sending post request with headers parameters using hashMap using @HeaderMap annotation.
Below is my code
 @POST(Constants.UrlPath.POST_CLOSE_EVENT)
Call<ResponseBody> callDeleteEventRequest(@HeaderMap Map <String, String>id);

I am sending the headers using HashMap here like this.
 HashMap<String, String> headers = new HashMap<>();
                 headers.put("eventId", String.valueOf(1));

I am getting 404 error response. Please some one help me.
I have reviewed some Stack Overflow links, but again I am getting this error.

A: Try this:
@FormUrlEncoded
@POST(Constants.UrlPath.POST_CLOSE_EVENT)
Call<ResponseBody> callDeleteEventRequest(@FieldMap Map <String, String>id);

A: add headers in your interface class:
 @Headers({"Content-Type: application/json",
        "eventId: 1"})
@POST(Constants.UrlPath.POST_CLOSE_EVENT)
Call<ResponseBody> callDeleteEventRequest();

A: check your path Constants.UrlPath.POST_CLOSE_EVENT is right or not.
try to call using postman if it is working fine in that or not.


Q: Harmonic Average Yields incorrect Result As a homework assignment we are required to calculate the harmonic mean using an assembly program being driven by a C program.
We are using 64-bit linux machines and are required to use 64-bit floating point numbers.
I am new to Assembly. I apologize for any bad coding practices or if my code is just flat out wrong.

The problem with the code is the result returns only the last number entered in floating-point format. I do not know where the error occurs, although I believe it to lie in the addDen function.
As an example: If you were to enter the numbers 5, 6, 7, 8 the result would return 8.0000.
Here is my code for the assembly program:
;Assembly function that computs the harmonic mean
;of an array of 64-bit floating-point numbers.
;Retrieves input using a C program.
;
;Harmonic mean is defined as Sum(n/((1/x1) + (1/x2) + ... + (1/xn)))
;
;   expects:
;       RDI - address of array
;       RSI - length of the array
;   returns
;       XMMO - the harmonic average of array's values

global harmonicMean

section .data
    Zero dd 0.0
    One dd 1.0

section .text
    harmonicMean:
        push rbp
        mov rbp, rsp                    ;C prologue

        movss xmm10, [Zero]     ;Holds tally of denominator
        cvtsi2ss xmm0, rsi      ;Take length and put it into xmm0 register

        .whileLoop:
            cmp rsi, 0                  ;Is the length of array 0?
            je .endwhile
            call addDen                 ;Compute a denominator value and add it to sum
            add rdi, 4                  ;Add size of float to address
            dec rsi                         ;Decrease the length
            jmp .whileLoop
        .endwhile:

        divss xmm0, xmm10

        leave
        ret

    ;Calculates a number in the denominator
    addDen:
        push rdi
        movss xmm8, [One]
        movss xmm9, [rdi]
        divss xmm8, xmm9
        addss xmm10, xmm8
        pop rdi
        ret

In order to recreate the logic error, i will also include my driver program:
/*
* Harmonic Mean Driver
* Tyler Weaver
* 03-12-2014
*/
#include<stdio.h>

#define ARRAYSIZE 4

double harmonicMean(double *, unsigned);

int main(int argc, char **argv) {
    int i;
    double ary[ARRAYSIZE];
    double hm;

    printf("Enter %d f.p. values: ", ARRAYSIZE);

    for (i = 0; i < ARRAYSIZE; i++) {
        scanf(" %lf", &ary[i]);
    }

    hm = harmonicMean(ary, ARRAYSIZE);
    printf("asm: harmonic mean is %lf\n", hm);

    return 0;
}

Any help will be much appreciated!

A: Yes there seems to be float vs double confusion. You pass in a double array, but pretty much all of the asm code expects floats: you use the ss instructions and you assume size 4 and you return a float too.
                    – Jester
There was an issue with floats and doubles! I really appreciate both of your responses. I was confused because the instructor had told us to use floats in our assembly program he had used doubles in an example driver. I spoke with the instructor and he had fixed his instructions. I thank you again! – Tyler Weaver

A: here is the algorithm, is a mix between C and pseudo code
My suggestion is to write this program in C.
Then have the compiler output the related asm language
then use that asm output as a guide in writing your own program

! ----------------------------------------------------------
! This program reads a series of input data values and
! computes their arithmetic, geometric and harmonic means.
! Since geometric mean requires taking n-th root, all input
! data item must be all positive (a special requirement of
! this program , although it is not absolutely necessary).
! If an input item is not positive, it should be ignored.
! Since some data items may be ignored, this program also
! checks to see if no data items remain!
! ----------------------------------------------------------

PROGRAM   ComputingMeans
   IMPLICIT  NONE

   REAL    :: X
   REAL    :: Sum, Product, InverseSum
   REAL    :: Arithmetic, Geometric, Harmonic
   INTEGER :: Count, TotalNumber, TotalValid

   Sum        = 0.0                     ! for the sum
   Product    = 1.0                     ! for the product
   InverseSum = 0.0                     ! for the sum of 1/x
   TotalValid = 0                       ! # of valid items

   READ(*,*)  TotalNumber               ! read in # of items
   DO Count = 1, TotalNumber            ! for each item ...
      READ(*,*)  X                      ! read it in
      WRITE(*,*) 'Input item ', Count, ' --> ', X
      IF (X <= 0.0) THEN                ! if it is non-positive
         WRITE(*,*) 'Input <= 0.  Ignored'   ! ignore it
      ELSE                              ! otherwise,
         TotalValid = TotalValid + 1    ! count it in
         Sum        = Sum + X           ! compute the sum,
         Product    = Product * X       ! the product
         InverseSum = InverseSum + 1.0/X     ! and the sum of 1/x
      END IF
   END DO

   IF (TotalValid > 0) THEN             ! are there valid items?
      Arithmetic = Sum / TotalValid     ! yes, compute means
      Geometric  = Product**(1.0/TotalValid)
      Harmonic   = TotalValid / InverseSum

      WRITE(*,*)  'No. of valid items --> ', TotalValid
      WRITE(*,*)  'Arithmetic mean    --> ', Arithmetic
      WRITE(*,*)  'Geometric mean     --> ', Geometric
      WRITE(*,*)  'Harmonic mean      --> ', Harmonic
   ELSE                                 ! no, display a message
      WRITE(*,*)  'ERROR: none of the input is positive'
   END IF

END PROGRAM  ComputingMeans


Q: How to generate 1 second clock using verilog for Artix 7 that has internal frequency of 100 MHz I am working on Xilinx ISE, I have tried following code to get 1 second clock with 50% duty cycle.
module hhclock(seconds,clk,reset);

output seconds;

input clk,reset;
reg [26:0] count;
reg temp ;

always @(posedge(clk) or posedge (reset))
begin
    if(reset)
        count<=0;
    else
        count<=count + 1'b1;

end
assign seconds = (count ==27'b010111110101111000010000000)?1:0;
endmodule

The output is not toggling and running infinitely. Kindly share what I am doing wrong.
I don't have testbench for this. I am directly simulating.

A: You should see the seconds signal go high, but for only one clock cycle.  Perhaps there is a problem with your simulation setup.
There are 2 problems with your code.  You only want the output to toggle when your count reaches the value you specified, and you need to reset your count value when that happens.  You should declare seconds as a reg and drive it in the always block as follows:
module hhclock (seconds,clk,reset);

output reg seconds;
input clk, reset;
reg [26:0] count;

always @(posedge clk or posedge reset)
begin
    if(reset) begin
        count   <= 0;
        seconds <= 0;
    end else if (count == 27'd50_000_000) begin
        count   <= 0;
        seconds <= ~seconds;
    end else begin
        count   <= count + 1'b1;
    end
end

endmodule

Note: I use the decimal value (50_000_000) instead of your long string of 1's and 0's since it is more meaningful in this case.


Q: How to call d3 pie chart on button click in angularjs? I am trying to display pie chart using d3.js charts in angularjs . As far as the examples i have seen so far implements pie chart on load . But here i want to display pie chart based on the response from service which is called on a button click . Need some guidance to start
my user.html

Group by users

<select name="users" id="search" ng-model="searchItem">
<option value="">Search By</option>
<option value="admin">admin</option>
<option value="superAdmin">superAdmin</option>

</select>

<button ng-click="search()">Search</button>

my user.js
'use strict';

 angular.module('myApp.employee',['ngRoute'])

 .config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/employee', {
  templateUrl: 'employee/employee.html',
  controller: 'EmployeeCtrl'
  });
    }])

   .controller('EmployeeCtrl', ['$scope','$http',function($scope,$http) {
    $scope.search = function(){

    var   search=angular.element(document.getElementById("search"));
    //var data ;

    $scope.searchItem =search.val();
    console.log($scope.searchItem);

    $http.get("/assets/empDetails.json").then(function(response){

     // $scope.empDetail=response.data
      console.log(response.data);
      console.log();
    //   function groupBy(arr, prop) {
    //     const map = new Map(Array.from(arr, obj => [obj[prop], []]));
    //     arr.forEach(obj => map.get(obj[prop]).push(obj));
    //     return Array.from(map.values());
    // }

   // console.log(groupBy(response.data,$scope.searchItem ));

    var rows = response.data;
    var keyName =$scope.searchItem;
    groupBy(keyName);

    function groupBy(keyName) {
      console.log("Group By :: ", keyName)

      var occurences = rows.reduce(function (r, row) {
          r[row[keyName]] = ++r[row[keyName]] || 1;
          return r;
      }, {});

      var result = Object.keys(occurences).map(function (key)       {
          return { key: key, value: occurences[key] };
      });

      console.log(result);
      //data = result ;
      $scope.data = [
        {
          name : "Blue",
          value : 10,
          color : "#4a87ee"
        },
        {
          name : "Green",
          value : 40,
          color : "#66cc33"
        },
        {
          name : "Orange",
          value : 70,
          color : "#f0b840"
        },
        {
          name : "Red",
          value : 2,
          color : "#ef4e3a"
        }
      ];
  }

    })

    }

   }])

   .directive ("pieChart", function () {
     return {
    restrict : "A",
    scope : {
        data : "="
    },
    link : function (scope, element) {
        var width,
            height,
            radius,
            pie,
            arc,
            svg,
            path;

        width = element[0].clientWidth;
        height = element[0].clientHeight;
        radius = Math.min (width, height) / 2;

        pie = d3.layout.pie ()
                .value (function (d) {return d.value;})
                .sort (null);

        arc = d3.svg.arc ()
                .outerRadius (radius - 20)
                .innerRadius (radius - 80);

        svg = d3.select (element[0])
                .append ("svg")
                .attr ({width : width, height : height})
                .append ("g")
                .attr ("transform", "translate(" + width * 0.5 + "," + height * 0.5 + ")");

        path = svg.datum (scope.data)
                .selectAll ("path")
                .data (pie)
                .enter ()
                .append ("path")
                .attr ({
                    fill : function (d, i) {return scope.data [i].color;},
                    d : arc
                });

        scope.$watch (
            "data",
            function () {
                pie.value (function (d) {return d.value;});
                path = path.data(pie);
                path.attr("d", arc);
            },
            true
        );
    }
};

})
i have used this https://embed.plnkr.co/plunk/jDvdSh as reference . All i want to implement is on search i want perform the service call and then manipulate the response and render it as a pie chart.or someone please explain how the pie chart directive is called in the above plnkr reference that would be more helpful


Q: For $ \frac{n(n-1)}{2}I was doing Problem 67 of Project Euler, which involves number triangle which has similar structure to Pascal's triangle (the nth row contains n numbers). While thinking of a way to represent the triangle as a single list, I realized that the number of elements in a triangle of height n was $1+2+3+...+n = n(n+1)/2$, which must mean that the last number of any row n must be the $(n(n+1)/2)^{th}$ number in the triangle. More generally, we have that for any index $i$ starting at 1, $\frac{n(n-1)}{2} < i \leq  \frac{n(n+1)}{2}$ where $n$ is the row that contains the $i^{th}$ number of the triangle. From here, I figured that taking the square root of $2i$ and rounding it would give something close to $n$, and indeed rounding the square root of $2i$ results in the pattern $1,2,2,3,3,3,4,4,4,4,5,5,5,5,5$, etc. So far, I have not been able to prove this result to myself, so any help would be appreciated, thanks!

A: $$\frac{(n-1)^2}2<\frac{n(n-1)}2<\frac{n^2}2<\frac{n(n+1)}2<\frac{(n+1)^2}2$$
We also know that
$$\frac{n(n-1)}2<i<\frac{n(n+1)}2$$
On finding differences, we realise that $i$ will always be closer to $\frac{n^2}2$ than $\frac{(n-1)^2}2$ or $\frac{(n+1)^2}2$
Hence $i=round(\sqrt{2i})$