text:
Q: Java:: process builder: bash script: returned fileName is correct but fileReader throws a FileNotFoundException Can anyone please explain why this FileNotFoundException happens?
I am trying to get a last modified file_name from remote linux and this way works and returns a file name:
ProcessBuilder pb = new ProcessBuilder();
ProcessBuilder pbSetPermissions = new ProcessBuilder();
pb.command("/bin/bash", "-c", "ls -t " + System.getProperty("user.dir") + " | head -n 1");
String fileName = IOUtils.toString(pb.start().getInputStream(), StandardCharsets.UTF_8);
System.out.println(fileName);
File folder = new File(System.getProperty("user.dir"));
String filePath = folder + "/" + DOWNLOADS_DIR + "/" + fileName;
pbSetPermissions.command("/bin/bash", "-c", "chmod 777 " + filePath);
pbSetPermissions.start();
System.out.println(filePath);

Also, it set the correct permissions to file and I can read this file e.g. using 'nano'
But then, when I try to read and parse this file from Java fileReader:
FileReader filereader = new FileReader(filePath);

I always get:
java.io.FileNotFoundException: (No such file or directory)

See screens:

==================
I have resolved this problem and got last Modified File Name another way:
File file = findLastModified(System.getProperty("user.dir") + File.separator + DOWNLOADS_DIR);
System.out.println(System.getProperty("user.dir") + File.separator + DOWNLOADS_DIR);

public static File findLastModified (String sdir) {
    File dir = new File(sdir);
    if (dir.isDirectory()) {
        Optional<File> opFile = Arrays.stream(dir.listFiles(File::isFile))
                .max(Comparator.comparingLong(File::lastModified));
        if (opFile.isPresent()){
            return opFile.get();
        }
    }
    return null;
}

====================
But I am still confused why the first way with bash script is not working. It seems like there are some hidden symbols in file name? Or something with encoding? Because from what I see the file path is correct.


text:
Q: Select upper and lower values and create a new column with random values I have a data set with 30 rows and 2 columns. For example:
value <- c(305.19, 30.19, 126.97, 178.89, 640.01, 189.28, 15.92,
           219.79, 178.89, 911.61, 178.89, 18.28, 305.19, 322.90,
           126.97, 12.97, 178.89, 12.97, 322.90, 158.92, 322.90,
           219.79, 911.61, 219.79, 911.61, 325.90, 322.90, 911.61,
           158.92, 322.78)

Date <- c("1997-05-01","1997-05-02","1997-05-03","1997-05-04","1997-05-05",
          "1997-05-06","1997-05-07","1997-05-08","1997-05-09","1997-05-10",
          "1997-05-11","1997-05-12","1997-05-13","1997-05-14","1997-05-15",
          "1997-05-16","1997-05-17","1997-05-18","1997-05-19","1997-05-20",
          "1997-05-21","1997-05-22","1997-05-23","1997-05-24","1997-05-25",
          "1997-05-26","1997-05-27","1997-05-28","1997-05-29","1997-05-30")

data <- data.frame(value, Date)

Using the quantile function, I can select values between the percentages 25%, 50%, 75%.
For example:
data$value <- data$value[data$value>=quantile(data$value)[4]]
newvalue <- data$value[data$value>=quantile(data$value)[4]]
data$value <- sample(newvalue, dim(data)[1], replace=T)

I would like to create a new column with random values only - lower 12.5% and upper 87.5%.
how can I do that?

A: A dplyr solution
library(dplyr)
data %>% filter(ntile(value,n=8) %in% 2:7 == TRUE) %>%
  do(sample_n(.,30, replace = TRUE))

A: We can do
q1 <- quantile(data$value, probs = c(0.125, 0.875))
data$newValue <- sample(data$value[data$value > q1[1] & data$value < q1[2]],
                             nrow(data), replace = TRUE)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Push notification is queued on iphone Hi I am using EasyAPNs with PHP script. Before I use to get notification on my iOS device but very recently I am not getting the notification. All i have been getting this message stored in database:
message:- {"aps":{"alert":"This is tset for push not.."},"acme2":["bang","whiz"]}
status:- queued


text:
Q: How to change string with sed in Bash script I have file with parameters:
key1: 'testValue'

And I want to change the value of the key1 (testValue) according to parameter.
This one is working with hard-coded value:
sed -i "s/\(key1:\).*/\1 'newValue'/"  ./myFile

I tried with dynamic value:
MY_NEW_VALUE= testNewValue
sed -i "s/\(key1:\).*/\1 ${MY_NEW_VALUE}/" ./myFile

And I got am error:
sed: -e expression #1, char 32: unknown option to `s'

A: Working here:
root@foo:~# cat /tmp/c
key1: 'testValue'

root@foo:~# MY_NEW_VALUE="testNewValue"; cat /tmp/c | sed -s "s/\(key1:\).*/\1 '${MY_NEW_VALUE}'/"
key1: 'testNewValue'

Edit: Change your line:
MY_NEW_VALUE= testNewValue

to
MY_NEW_VALUE="testNewValue"


text:
Q: How to create podspec file for pods with right path to Localizable assets in iOS In my project I have three Pods and each have their own localizable assets under Resources/Pod/Assets folder. However the localizations for my main project files work but localization for pods didn't work.If I place all my pods localization assets into my main project folder , then everything works, but it is not the case I'm looking for.I need to have my pods store their own localizable assets.
Here is my podspec for my pods:
Pod::Spec.new do |s|
  s.name             = "MyPod"
  s.version          = "0.1"
  s.summary          = "A short description of MyLib."
 s.platform     = :ios, '8.0'
  s.requires_arc = true

  s.source_files = 'Pod/**/*.{h,m}'
  s.resource_bundles = {
    'MyPod' => ['Pod/**/*.{caf,xib,mp4,mp3,m4a,wav,plist,atlas}',
                             'Pod/Assets/pngs/**/*.{png,jpg}',
                             'Pod/Assets/fr-CA.lproj/*.strings',
                             ]
  }

  s.prefix_header_file = 'MyPodPrefixHeader.pch'

  s.dependency 'MyOtherPod'

end

I also tried
      'Pod/Assets/*.{lproj}'

and
      'Pod/Assets/*.{lproj}/*.strings'

Everytime I change the podspec I do pod install
But none of them worked. Pod localizable assets are not loading in my project.
ANy ideas where I could have gone wrong ?


text:
Q: Always the same size of image on all screens I need that square image always be the same size on any screen (including mobile, tablet...). So if I take the ruler and measure image on any screen it have to be 5mm for example. It must be in JavaScript.
I wonder if the size of that image depends only of screen's DPI or it depends of screen resolution also? If in JavaScript I detect screen's DPI (and resolution if needed) is there any formula (or some JavaScript function) to calculate image size to get always the same result?
In the end, can I define image size in some unit which will ensure image to be always the same?
I asked the question here because it is connected to JavaScript, if you think that it is more suitable for some other forum please let me know.
Thanks...

A: If I understand correctly you want an image always to have a fixed absolute physical size. There is no way to achieve that. You can define a width with absolute units like inch, centimeter or millimeter, but the rendered result differs from one screen to another.
Every browser has set internally 1 inch = 96px, and with that base all other units are calculated. So only if a screen has a physical pixel-size of exactly 25.4 / 96 = 0.26458 mm
an element having width set to 5mm is really 5mm.
But the absolute physical size of a pixel differs widely on different screens and is not detectable by javascript.
EDIT According to your comment: Yes it is possible with your own screen. You can display an element with a width set to 200mm and measure the real width on screen in mm with a ruler. The quotient 200 / your_measurement gives you a conversion factor.
If you now want to set a width to a fixed value you have to multiply that value with the factor.
Display following file and measure the width of the red quadrat:
<!doctype html>

The conversion factor is valid for all absolute units you want to use.
With some interaction of a user you can calibrate a users screen as they did on the ZEISS page you linked to. The user has to compare the element on screen against a fixed width (e.g. width of a credit card = 54mm). Since here the user is fixed and the code does the measurement, calculation of the factor is contrariwise: conversion factor f = code_result / 54.
I have made a FIDDLE here with 0.5mm-steps to get more accuracy.


text:
Q: Birthday paradox derivation: different approach I usually use randomization in algorithms so I am familiar with basics of probability but nothing much advanced. I have gone through the derivation for Birthday Paradox (Cormen et al) and decided to do the same thing in a slightly different way.
(Lets talk in terms of balls and bins. Let there be m balls and n bins).
Let E_ij be the event that two balls i and j end up in same bin. Clearly, $ Pr(E_{ij}) = \frac{1}{n} $.
I claim: probability that there exists at least 2 balls which end up in same bin <= $\sum Pr(E_{ij})$; by union bound. Firstly, is this claim correct? I guess it is not since I don't get the same answer by this formulation. Just for the sake of completeness, $\sum Pr(E_{ij}) = {m \choose 2} * \frac{1}{n}$
I want to get my understanding right and thats why I want to know why this is wrong. I am almost sure that I am messing this up in some very fundamental concept. I am just not able to find which one!

A: What you are counting with $\sum_{1\leq i < j \leq m} \Pr[E_{i,j}]$ is the expected number of collisions, i.e. the expectation of $X$, defined as the number of (pairs of balls that fall in the same bin). What you want is the probability to have at least one of these pairs: an loose upperbound is indeed be given by Markov's Inequality, which states that $$\Pr[X \geq 1] \leq \frac{\mathbb{E}[X]}{1}$$ (since $X$ is a non-negative r.v.).
But what do you mean by "I don't get the same answer by this formulation"? (depending on what you mean, it may come from the fact that Markov's inquality is usually not tight, and so the analysis does not result in the optimal conclusion).


text:
Q: Black screen after installing drivers using Intel Linux driver installer - 14.04 I am new to Ubuntu. Recently I installed Ubuntu 14.04 on my Dell Inspiron 3537 laptop having Intel HD 4400 graphics and AMD Radeon 8760m Graphics card. After installing intel drivers using the Intel Linux driver installer and rebooting I cannot get past the Ubuntu loading screen. I have tried every various solutions but no luck. I tried logging in with the recovery mode too. But no chance! I have tried the procedure mentioned in this question too.

My computer boots to a black screen what options do i have to fix it?

Is there a way for me to get back the default driver or reset the driver using the LiveCD? How can I fix this issue?

A: I had similar prolems with Dell& Ubuntu hybrid graphics (intel integrated&ATI discrete).
Try: https://askubuntu.com/a/483223/293492 (this is what I did, also you can check if you have similar symptoms)

A: The same procedure works for both the AMD and ATI drivers.  You might need to run this in recovery mode if you cannot open a tty.  How do I remove the proprietary ATI drivers?


text:
Q: I'm comparing a couple of GNSS front-end modules. Is a lower In-band IIP3 point better or worse than a higher one? I would typically compare the small signal gain and noise figure first. One of the FEMs requires an external matching component but other that they are very similar in terms of cost and foot-print size.
I reviewed this website tutorial on the differences between -1dB compression and 3rd order points but still not sure how the point (-9dBm or -7.3dBm) will ultimately affect the performance or linearity of the amplifier.
[

A: The higher the better (other things equal), because more input power will be needed for the same amount of degradation in linearity. So you will have better dynamic range.
Also, intermodulation noise can reduce your effective \$E_b/N_0\$, thus increasing your bit error rate (BER). The sensitivity of your receiver will decrease.


text:
Q: How to show embeded osm map in one language(german)? I'm new to OSM and got a world map enabled in a web page. I saw a possibility to switch languages for the map on a osm page. But can't find a tutorial how to set the wished langugage in a embeded map? Any ideas?

A: Try changing the domain name accordingly. For example, openstreetmap.org displays English, while openstreetmap.de displays German. Make use of this possibility.


text:
Q: Writing a java server for queueing incoming HTTP Request and processing them a little while later? I want to write an Java Server may be using Netty or anything else suggested.
The whole purpose is that I want to queue incoming HTTP Request for a while because the systems I'm targeting are doing Super Memory and Compute intensive tasks so if they are burdened with heavy load they eventually tend to get crashed.
I want to have a queue in place that will actually allow only max upto 5 requests passed to destination at any given time and hold the rest of the requests in queue.
Can this be achieved using Netty in Java, I'm equally open for an implementation in Scala, Python or clojure.

A: I did something similar with Scala Akka actors. Instead of HTTP Request I had unlimited number of job requests come in and get added to a queue (regular Queue). Worker Manager would manage that queue and dispatch work to worker actors whenever they are done processing previous tasks. Workers would notify Worker Manager that task is complete and it would send them a new one from the queue. So in this case there is no busy waiting or looping, everything happens on message reception. You can do the same with your HTTP Requests. Akka can be used from Scala or Java and a process I described is easier to implement than it sounds.
As a web server you could use anything really. It can be Jetty, or some Servlet Container like Tomcat, or even Spray-can. All it needs to do is to receive a request and send a message to Worker Manager. The whole system would be asynchronous and non-blocking.


text:
Q: Selecting one random data from a column from multiple rows in oracle I am creating a view that needs to select only one random row for each customer. Something like:
select c.name, p.number
from customers c, phone_numbers p
where p.customer_id = c.id

If this query returns:
NAME      NUMBER
--------- ------
Customer1 1
Customer1 2
Customer1 3
Customer2 4
Customer2 5
Customer3 6

I need it to be something like:
NAME      NUMBER
--------- ------
Customer1 1
Customer2 4
Customer3 6

Rownum wont work because it will select only the first from all 6 records, and i need the first from each customer. I need solution that won't affect performance much, because the query that selects the data is pretty complex, this is just an example to explain what I need. Thanks in advance.

A: Use the ROW_NUMBER() analytic function:
SELECT name,
       number
FROM   (
  SELECT c.name,
         p.number,
         ROW_NUMBER() OVER ( PARTITION BY c.id ORDER BY DBMS_RANDOM.VALUE ) AS rn
  FROM   customers c
         INNER JOIN phone_numbers p
         ON ( p.customer_id = c.id )
)
WHERE  rn = 1

A: You can use group by clause to return only one phone number:
select c.name, MAX(p.number) as phone
from customers c, phone_numbers p
where p.customer_id = c.id
group by c.name

A: You can also use the min or max aggregate function with the keep dense_rank syntax:
select c.name,
  min(p.number) keep (dense_rank last order by dbms_random.value) as number
from customers c
join phone_numbers p on p.customer_id = c.id
group by c.id, c.name
order by c.name;

(number isn't a valid column or alias name as it's a reserved word, so use your own real name of course).
If the phone number needs to be arbitrary rather than actually random, you can order by something else:
select c.name,
  min(p.number) keep (dense_rank last order by null) as number
from customers c
join phone_numbers p on p.customer_id = c.id
group by c.id, c.name
order by c.name;

You'll probably get the same number back for each customer each time, but not always, and data/stats/plan changes will affect which you see. It seems like you don't care though. But then, using a plain aggregate might work just as well for you, as in @under's answer.
If you're getting lots of columns from that random row, rather than just the phone number, MTO's subquery might be simpler; for one or two values I find this a bit clearer though.


text:
Q: Replace MDL icon font hamburgeur icon with svg Partly so I don't have to wait for the entire font file to load before icon displays, and because I've been reading a bit of discussion (pro and con) about using svg's instead of icon-fonts I am experimenting with using an svg instead of MDLs native icon font for the Material Design Lite mdl-navigation drawer.
On compatible browsers, they add the icon using the following script, which I don't want to modify, in case of upgrades.
if (this.drawer_) {
    var drawerButton = this.element_.querySelector('.' + this.CssClasses_.DRAWER_BTN);
    if (!drawerButton) {
        drawerButton = document.createElement('div');
        drawerButton.setAttribute('aria-expanded', 'false');
        drawerButton.setAttribute('role', 'button');
        drawerButton.setAttribute('tabindex', '0');
        drawerButton.classList.add(this.CssClasses_.DRAWER_BTN);
        var drawerButtonIcon = document.createElement('i');
        drawerButtonIcon.classList.add(this.CssClasses_.ICON);
        drawerButtonIcon.innerHTML = this.Constant_.MENU_ICON;
        drawerButton.appendChild(drawerButtonIcon);
    } # etc...
}

I came up with this:
var mdl_drawer_button = document.querySelector('.mdl-layout__drawer-button');
mdl_drawer_button.innerHTML = '<svg viewBox="0 0 100 100" class="icon nav-icon"><use xlink:href="#nav-icon"></use></svg>';

However, '.mdl-layout__drawer-button' doesn't exist until the MDL script has run, so am adding a 500ms timeout as seen in this fiddle.
Does my approach make sense? It there a more dependable way to run my function once the MDL code has run?
UPDATE:
Trying a slightly different method now using a recursive function with a test for .mdl-layout__drawer-button not being null:
//Replace MDL icon with our sprite
function mdl_drawer_btn() {
    var mdl_drawer_button = document.querySelector('.mdl-layout__drawer-button');
    if (mdl_drawer_button != null) {
        mdl_drawer_button.innerHTML = '<svg viewBox="0 0 100 100" class="icon nav-icon"><use xlink:href="#nav-icon"></use></svg>';
      } else {
        setTimeout(mdl_drawer_btn, 100);
      }
  }

setTimeout(mdl_drawer_btn, 100);

A: It's hard to advise without knowing how your whole site is implemented, but I would have thought it should be enough to put your script as the last script on the page.  Then to make sure all DOM changes, that previous scripts have made, are complete, wrap it in a 0ms timeout.
setTimeout(mdl_drawer_btn, 0);


text:
Q: using DidSet or WillSet on decodable object I currently have a Codable object which I am initializing using:
let decoder = JSONDecoder()
let objTest: TestOBJClass = try! decoder.decode(TestOBJClass.self, from: data)

TestOBJClass:

public class TestOBJClass: Codable {
    var name: String
    var lastname: String?
    var age: Int? {
        DidSet {
            //Do Something
        }
    }
}

The object gets initialized with no issues. However, the DidSet function on the age variable is not getting called. Are we able to use these functions when working with Decodable or Encodable objects? Thank you for your help!

A: As @Larme pointed out in comments, property observers like didSet aren't called in initializers, including the one for Codable conformance.  If you want that behavior, refactor the code from your didSet into a separate named function, and then at the end of your initializer call that function.
struct MyStruct: Codable
{
    ...
    var isEnabled: Bool {
        didSet { didSetIsEnabled() }
    }

    func didSetIsEnabled() {
        // Whatever you used to do in `didSet`
    }

    init(from decoder: Decoder) throws
    {
        defer { didSetIsEnabled() }
        ...
    }
}

Of course, that does mean you'll need to explicitly implement Codable conformance rather than relying on the compiler to synthesize it.


text:
Q: How to dump list of file's from subfolders with its full path in Linux I am not able to get the command (or group of commands)to do the following operation in Linux:
I am having a main project_folder with some 10 sub_folder containing all different extensions of files (for example *.cpp /*.txt/*.y / *.py etc ). But I want to just make a list of all REQUIRE_*.txt files from all SUB-FOLDERS with its complete path and dump into the text file .
For example :
result_dump.txt should include :
user/project_folder/sub_folder0/a0.txt
user/project_folder/sub_folder0/a6.txt
user/project_folder/sub_folder0/a11.txt
user/project_folder/sub_folder0/a12.txt
user/project_folder/sub_folder1/a1.txt
user/project_folder/sub_folder1/a13.txt
user/project_folder/sub_folder2/a14.txt
user/project_folder/sub_folder2/a15.txt
user/project_folder/sub_folder2/a2.txt
user/project_folder/sub_folder3/a3.txt
user/project_folder/sub_folder4/a4.txt
user/project_folder/sub_folder5/a5.txt
--
--
--

If I use below command ,then I am getting all files information which is not my intention:
find $(pwd) -maxdepth 1 -type f -not -path '*/\.*' | sort

Note: Please let me know how I can dump that result in text file !

A: Run the below command from the user's home directory
find project_folder/ -maxdepth 3 -type f -name REQUIRE_*.txt

Edit
You can then redirect the o/p using to a file adding > result_dump.txt after the command


text:
Q: Не работает авторизация через pycurl Есть скрипт вида:
import pycurl
from StringIO import StringIO

c = pycurl.Curl()
url = 'https://site.ru/index.php'
url1 = 'https://site.ru/index.php?_m=tickets&_a=manage&departmentid=17&ticketstatusid=1'

c.setopt(pycurl.URL, url)
c.setopt(pycurl.POSTFIELDS, 'username=user&password=pass&_ca=login')
c.setopt(pycurl.COOKIEJAR, "/tmp/cookie.txt")
c.setopt(pycurl.COOKIEFILE, "/tmp/cookie.txt")

def __list(url) :
 c = pycurl.Curl()
 c.setopt(pycurl.URL, url)
 c.setopt(pycurl.COOKIEJAR, "/tmp/cookie.txt")
 c.setopt(pycurl.COOKIEFILE, "/tmp/cookie.txt")
 c.bodyio = StringIO()
 c.setopt(pycurl.WRITEFUNCTION, c.bodyio.write)
 c.get_body = c.bodyio.getvalue
 c.perform()
 return c.get_body()

print __list(url1)

Ранее скрипт работал и, в принципе, выдавал ту страницу, что нужно.
Сейчас же, после обработки скрипта просто отдает страницу с авторизацией, а именно "https://site.ru/index.php" , не создает даже файлы в /tmp с cookie. В скрипте ничего не менял. Сколько не пытался понять - не могу выяснить причину, почему так происходит.

A: Благодаря подсказкам jfs код был приведен к виду:
import pycurl
from StringIO import StringIO

url = 'https://site.ru/index.php'
url1 = 'https://site.ru/index.php?_m=tickets&_a=manage&departmentid=17&ticketstatusid=1'

def __logging(url) :
 c = pycurl.Curl()
 c.setopt(pycurl.URL, url)
 c.setopt(pycurl.POSTFIELDS, 'username=user&password=pass&_ca=login')
 c.setopt(pycurl.COOKIEJAR, "/tmp/cookie.txt")
 c.setopt(pycurl.COOKIEFILE, "/tmp/cookie.txt")
 c.perform()

def __list(url) :
 c = pycurl.Curl()
 c.setopt(pycurl.URL, url)
 c.setopt(pycurl.COOKIEJAR, "/tmp/cookie.txt")
 c.setopt(pycurl.COOKIEFILE, "/tmp/cookie.txt")
 c.bodyio = StringIO()
 c.setopt(pycurl.WRITEFUNCTION, c.bodyio.write)
 c.get_body = c.bodyio.getvalue
 c.perform()
 return c.get_body()

__logging(url)
print __list(url1)


text:
Q: Actionscript mobile library project I'm developing an ActionScript 3.0 project for Blackberry Playbook, Android and iOS.
I have some custom UI classes, like buttons, that I want to use it in another projects.
How can I make an actionscript mobile library project?
I'm using Flash Builder 4.5, and I'm not using Flex in my code.

A: Using Flash Builder 4.5:

*

*choose File > Project > New

*choose "library project"

*check the "include AIR features" box.
This will compile a .swc, a binary file you can distribute easily.
Including AIR in this .swc ensures that all the mobile-oriented features will be compiled as well, i.e. TouchEvent.
Flex classes, that you're not using, won't be included.

A: You can create ActionScript project, then add it to your mobile project's references (as a source.) Or create Flex library and link it with mobile project.


text:
Q: How to construct JPA entites and JSON models? My spring application consuming JSON API then saves it in database using JPA. I'm facing problem with properly designed entites and models.
My model JSON looks like:
@Data
@Setter(AccessLevel.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
public class TvShowRemote implements TvShowEntity {
    @JsonProperty("id")
    public Integer id;
    @JsonProperty("url")
    public String url;
    @JsonProperty("name")
    public String name;
    @JsonProperty("summary")
    public String summary;
    @JsonProperty("updated")
    public Integer updated;
    @JsonProperty("_embedded")
    public Embedded embedded;

    public List<SeasonEntity> getSeasons() {
        return new ArrayList<SeasonEntity>(embedded.getSeasons());
    }

    public List<EpisodeEntity> getEpisodes() {
        return new ArrayList<EpisodeEntity>(embedded.getEpisodes());
    }
}

My JPA entites looks like:
@Data
@Setter(AccessLevel.NONE)
@Entity
@Table(name = "TvShows")
public class TvShowLocal implements TvShowEntity {

    @Id
    @GeneratedValue
    public Integer id;

    public Integer tvShowId;

    public String name;

    public Integer runtime;

    public String summary;

    @Column(name = "seasons")
    @OneToMany
    @ElementCollection(targetClass = SeasonLocal.class)
    public List<SeasonLocal> seasons;

    @Column(name = "episodes")
    @OneToMany
    @ElementCollection(targetClass = EpisodeLocal.class)
    public List<EpisodeLocal> episodes;

    @Override
    public List<SeasonEntity> getSeasons() {
        return new ArrayList<SeasonEntity>(seasons);
    }

    @Override
    public List<EpisodeEntity> getEpisodes() {
        return new ArrayList<EpisodeEntity>(episodes);
    }
}

Lombok annotation @Data automatically implements getter/setters.
I tried to implement to both classes interface:
public interface TvShowEntity {

    Integer getId();

    String getName();

    List getSeasons();

    List getEpisodes();
}

There's also two interface SeasonEntity, EpisodeEntity which I implemented in SeasonRemote, SeasonLocal, EpisodeRemote, EpisodeLocal. They looks like in example above.
Now I trying to assign TvShowRemote to TvShowLocal;
TvShowEntity tvshowEntity = new TvShowRemote();
TvShowLocal tvShowLocal = (TvShowLocal) tvShowEntity;

But I cannot cast this object like this.
Is there better way to achieve this?

A: TvShowEntity tvshowEntity = new TvShowRemote();
TvShowLocal tvShowLocal = (TvShowLocal) tvShowEntity;

You're trying to achieve an impossible cast which can't be done.
TvShowRemote is a TvShowEntity
and
TvShowLocal is a TvShowEntity
It doesn't mean that TvShowRemote is a TvShowLocal and vice versa.
You can use the Adapter design pattern.

A: I see that both TvShowEntity and TvShowLocal extends TvShowEntity.
But you can't cast a TvShowEntity that was instantiated as a TvShowRemote to a TvShowLocal.
From Wideskills:

The cast can be to its own class type or to one of its subclass or    superclass types or interfaces.

You should copy properties from TvShowRemote to TvShowLocal manually or just use the supertype TvShowEntity if you declare all needed method interfaces.


text:
Q: Why does my colon character disappear when I go from char[] to string? In an old Windows application I'm working on I need to get a path from an environment variable and then append onto it to build a path to a file. So the code looks something like this:
static std::string PathRoot; // Private variable stored in class' header file

char EnvVarValue[1024];
if (! GetEnvironmentVariable(L"ENV_ROOT", (LPWSTR) EnvVarValue, 1024))
{
    cout << "Could not retrieve the ROOT env variable" << endl;
    return;
}
else
{
    PathRoot = EnvVarValue;
}

// Added just for testing purposes - Returning -1
int foundAt = PathRoot.find_first_of(':');

std::string FullFilePath = PathRoot;
FullFilePath.append("\\data\\Config.xml");

The environment value for ENV_ROOT is set to "c:\RootDir" in the Windows System Control Panel. But when I run the program I keep ending up with a string in FullFilePath that is missing the colon char and anything that followed in the root folder. It looks like this: "c\data\Config.xml".
Using the Visual Studio debugger I looked at EnvVarValue after passing the GetEnvironmentVariable line and it shows me an array that seems to have all the characters I'd expect, including the colon. But after it gets assigned to PathRoot, mousing over PathRoot only shows the C and drilling down it says something about a bad ptr. As I noted the find_first_of() call doesn't find the colon char. And when the append is done it only keeps the initial C and drops the rest of the RootDir value.
So there seems to be something about the colon character that is confusing the string constructor. Yes, there are a number of ways I could work around this by leaving the colon out of the env variable and adding it later in the code. But I'd prefer to find a way to have it read and used properly from the environment variable as it is.

A: You cannot simply cast a char* to a wchar_t* (by casting to LPWSTR) and expect things to work. The two are fundamentally distinct types, and in Windows, they signify different encoding.
You obviously have WinAPI defines set such that GetEnvironmentVariable resolves to GetEnvironmentVariableW, which uses UTF-16 to encode the string. In practice, this means a 0 byte follows every ASCII character in memory.
You then construct a std::string out of this, so it takes the first 0 byte (at char index 1) as the string terminator, so you get just "c".
You have several options:

*

*Use std::wstring and wchar_t EnvVarValue[1024];

*Call GetEnvironmentVariableA() (which uses char and ASCII)

*Use wchar_t EnvVarValue[1024]; and convert the returned value to a std::string using something like wcstombs.

A: It seems you are building with wide-character functions (as indicated by your cast to LPWSTR). This means that the string in EnvVarValue is a wide-character string, and you you should be using wchar_t and std::wstring instead.
I would guess that the contents in the array array after the GetEnvironmentVariable call is actually the ASCII values 0x43 0x00 0x3a 0x00 0x5c 0x00 etc. (that is the wide-char representation of "C:\"). The first zero acts as the string terminator for a narrow-character string, which is why the narrow-character string PathRoot only contains the 'C'.

A: The problem might be that EnvVarValue is not a wchar. Try using wchar_t and std::wstrîng.


text:
Q: ksh get quarter start end dates I am writing a shell script, and need to calculate the first and last days of a quarter from the current date.  This is for use in Ingres 10 SQL statements triggered from within the script. The Ingres runs on a Solaris server with ksh.
So, if today is 31/01/17, I would want to calculate the following

*

*the first date of the current quarter (01/01/17)

*the last date of the current quarter (31/03/17). It would be OK here to return an exclusive to date if necessary (i.e. 01/04/17)

*the first date of the previous quarter (01/10/16)

*the last date of the previous quarter (31/12/16). An exclusive-to result of 01/01/17 would also be OK.

Can anyone please help? I've seen questions related to getting the quarter number but that's not really helping.
I've tried the following but its not working as the variables are not being populated in the case statement
CURR_MONTH=`date +%m`
echo "Current month num = $CURR_MONTH"

CURR_YEAR=`date +%Y`
echo "Current year = $CURR_YEAR"

let "LAST_YEAR = $CURR_YEAR - 1"
echo "Last year = $LAST_YEAR"

case $CURR_MONTH in
05) CURR_Q_FROM = 01.04.${CURR_YEAR}
CURR_Q_TO = "30.06.${CURR_YEAR}"
PREV_Q_FROM = "01.01.${CURR_YEAR}"
PREV_Q_TO = "31.03.${CURR_YEAR}" ;;
esac

echo "Current Q From = $CURR_Q_FROM"
echo "Current Q To = $CURR_Q_TO"
echo "Prev Q From = $PREV_Q_FROM"
echo "Prev Q To = $PREV_Q_TO"

I get the following output
Current month num = 05
Current year = 2017
Last year = 2016
Month to be extracted = April 2017
./stats_report_monthly.sh[85]: CURR_Q_FROM:  not found
./stats_report_monthly.sh[86]: CURR_Q_TO:  not found
./stats_report_monthly.sh[87]: PREV_Q_FROM:  not found
./stats_report_monthly.sh[88]: PREV_Q_TO:  not found
Current Q From =
Current Q To =
Prev Q From =
Prev Q To =

A: With ksh93 (also /bin/sh on Solaris 11):
#! /usr/bin/ksh -
eval "$(printf '%(y=%Y m=%-m)T')"
first=$(printf '%(%F)T' "$y-$(((m-1)/3*3+1))-1")
last=$(printf '%(%F)T' "$first next 2 months last day")
echo "$first $last"

first2=$(printf '%(%F)T' "$first last 3 months")
last2=$(printf '%(%F)T' "$first2 next 2 months last day")
echo "$first2 $last2"

Example:
$ ./quarter
2017-04-01 2017-06-30
2017-01-01 2017-03-31
$ faketime 2017-01-31 ./quarter
2017-01-01 2017-03-31
2016-10-01 2016-12-31

Using your approach, that would be:
eval "$(date +'y=%Y m=%m')"
case $m in
  (0[1-3])
     echo "$y-01-01 $y-03-31"
     echo "$((y-1))-10-01 $((y-1))-12-31";;
  (0[4-6])
     echo "$y-04-01 $y-06-30"
     echo "$y-01-01 $y-03-31";;
  (0[7-9])
     echo "$y-07-01 $y-09-30"
     echo "$y-04-01 $y-06-30";;
  (*)
     echo "$y-10-01 $y-12-31"
     echo "$y-07-01 $y-09-30"
esac

In any case, note that the syntax of variable assignments in Bourne-like shells is:
var=value

No space on either side of =.


text:
Q: Capacitor Size for a DC motor. Do I even need one? A couple months ago the AC motor on my wood lathe went out so, following a number of YouTube tutorials, I swapped it with a DC treadmill motor.  On the surface everything seems fine and it works.  The project got me interested in electronics again, so I've started taking online classes and trying to learn more.  I've recently started learning about capacitors and inductors and it got me thinking about my lathe circuit.  The circuit is very simple, it's basically a cheap SCR voltage controller ran into a bridge rectifier.  The more I learn though, I'm thinking I might need to add a capacitor after the bridge rectifier to smooth the voltage to the motor.  So my question is 2-fold.  Do I need a capacitor and how would I calculate what size I need?  The specs I have available for the motor are 2.25hp, 130V, 12.9A.  The max I ever need to use it is maybe 80%, after that it's almost too fast to be useable.  I've attached a rudimentary schematic of what I did below.

A: If it's running OK then I wouldn't mess with it.

Figure 1. Phase-angle AC control. Image source: LEDnique.com.
Your SCR control is most likely controlling voltage by changing the phase angle as shown in Figure 1. Adding any capacitance will tend to raise the DC after the bridge rectifier on longer than intended and would actually mess up the control depending on the amount of capacitance you add. In addition the SCR on turn-on would have to charge the capacitor on each half-cycle so it and the diodes would be stressed more.
Remember that the inertia of the motor is high enough that it doesn't respond in the < 10 ms half-wave (50 Hz) and it effectively smooths out the pulses of energy it receives giving a smooth rotation of the shaft.

A: The capacitor has nothing to do here, rather a large choke (inductor).if you want to smooth run. If you use a SCR, then also an EMI filter on the input side is needed.
Beside this, I would warn you about using cheap SCR rectifier, since it won't work for the DC motor. You need a controlled SCR rectifier made for controlling the DC motor and not a cheap lamp dimmer. Further the 4Q SCR control has everything, so you don't need an extra diode bridge and turnover switch as depicted.
EDIT:
A SCR rectifier has to be combined with a inductance, which you already have as motor inductance. The voltage can be smoothed with a capacitor only after the inductance - in your case impossible. The motor can exhibit torque ripple due to the current ripple and not due voltage ripple, so the capacitor is never needed. Right the opposite, if you want a very smooth current then you need to add yet another big choke.


text:
Q: C++ Array of Pointers from Array of strings I am new to c++ programming and I am currently working on my school project that involves manipulating data stored as a const string array that contains five strings.
Part of the requirements of this project is that I need to create an array of pointers that hold the data stored in the const string array and then create a student object for each of the "students" stored in that array to populate the array of pointers.
I have so far been experimenting with vectors to create the array of pointers, but have consistently hit a brick wall with trying to piece it all together. If someone could give some insight, I would really appreciate it. Thank you.

A: So, basically you want to create an Array of pointers, where each pointer points to the first char of a string.
The solution to these kind of problems can be dealt with using the code below:
#include<stdio.h>
#include<string.h>

int main()
{

    char *fruits[] = {
                         "apple",
                         "mango",
                         "orange",
                         "bananas",
                         "grapes"
                     };

    for(i = 0; i < 5; i++)
    {
        printf("String = %10s", fruits[i] );
        printf("Address of string's first char = %u\n", fruits[i]);
    }

    return 0;
}


text:
Q: SettingWithCopyWarning - How do I fix this warning? I am getting the SettingWithCopyWarning on the following code:
combined_updated['institute_service'] = combined_updated['institute_service'].copy().astype('float')

Could someone in the community help me out in understanding why I keep getting that warning?

A: There's no need to use copy() to change the column to float; maybe the .copy() is giving you the warning.  You can also try resetting the index before you do the operation, that usually works for me when I get that warning.
combined_updated = combined_updated.reset_index(drop=True)
combined_updated['institute_service'] = combined_updated['institute_service'].astype(float)


text:
Q: Deploying Vue.js application consuming REST API I'm trying to deploy my first Vue.js application on Heroku, but I need some clarification.
My app is a very simple client consuming REST service API.
I deployed the REST service on a Heroku dyno and now I need to also deploy my front-end application.
Is it possible to install client app on the same dyno? Is it a good practice, or should I deploy the client as a separate application?
What is the "real-world" production approach?
NOTE REST APIs are based on Java/Spring MVC.

A: It is certainly possible, and can keep your dyno costs down.
I answered a similar question here. That specific answer may or may not be suitable to your needs depending on what server technology you are using etc., however, the general idea is that you can certainly maintain multiple parts of your app within a single git repo that gets deployed to a single Heroku app.
Such a single Heroku app may or may not consist of multiple Process Types which may each run on one or more dynos.


text:
Q: How to make a website resolution same in all browsers i have built a site,but the thing i noticed when testing was, it appears in different resolutions in other system.i want to make the webpage appear perfectly fit to any resolution..how to do this can anyone help me? thanks in advance...

A: Create your site under 1000px or by using a 960 grid layout.
It will fit into all versions.
For Mobile - use CSS media queries or create your site by using percentages (target/context=result) and use ems for fonts and margins.

A: To make your website responsive you can use css media queries.
Refer to this link


text:
Q: How to click on a element which is not visible before mouse hovering on it? I use python3.6 and selenium3.6 to test charts from www.tradingview.com under Safari 11.When I want to zoom out the chart by clicking an invisible element before hovering the mouse on it.
driver.get('https://www.tradingview.com/chart/f8my3Ybg/')
zoom_out_button = driver.find_elements_by_class_name('zoom-out-right-button-control-bar')
Time.sleep(500)
ActionChains(driver).move_to_element(zoom_out_button).click().perform()

It comes out an error message
an element command could not be completed because the element is not visible on the page

I search the web and cannot find a way to correct it.The following is the code I analyzed.How would I realize such action on an invisible element?
the HTML code I analyzed
1

A: Instead of :
ActionChains(driver).move_to_element(zoom_out_button).click().perform()

First try to hover as follows :
ActionChains(driver).move_to_element(zoom_out_button).click("xpath_css_hidden_element").perform()


text:
Q: how to fix eclipse close automatically when starting in debug mode I use eclipse LUNA in that when I start debug mode the eclipse IDE will be closed. if any one can tell me why it happens and give the suggestion to solve it. And also tell me to start the template proposal because it won't start while entering ctrl+space,

A: you can probably raise a issue in Eclipse forum. If you dont have any specific requirements, you can probably go with Kepler as its more stable now.


text:
Q: Copy non-null properties from one object to another using BeanUtils or similar my aim is to copy fields of one object into another, but only those that aren't null. I don't want to assign it explicitly. A more generic solution would be very useful and easier to maintain i.e. for implementing PATCH in REST API where you allow providing only specific fields.
I saw this similar thread and I'm trying to implement some of the ideas from here: Helper in order to copy non null properties from object to another ? (Java)
But the objects aren't altered in any way after the program execution.
So here are my example classes created for example:
class Person {
    String name;
    int age;
    Pet friend;

    public Person() {
    }

    public Person(String name, int age, Pet friend) {
        this.name = name;
        this.age = age;
        this.friend = friend;
    }

    // getters and setters here
}

class Pet {
    String name;
    int age;

    public Pet(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // getters and setters here
}

Here is my overridden copyProperty method:
import org.apache.commons.beanutils.BeanUtilsBean;
import java.lang.reflect.InvocationTargetException;

public class MyBeansUtil extends BeanUtilsBean {

@Override
public void copyProperty(Object dest, String name, Object value)
        throws IllegalAccessException, InvocationTargetException {
    if(value == null) return;
    super.copyProperty(dest, name, value);
}
}

... and here is the place I'm trying to test it on some examples:
public class SandBox {
    public static void main(String[] args) {
        Person db = new Person("John", 36, new Pet("Lucy", 3));
        Person db2 = new Person("John", 36, new Pet("Lucy", 2));
        Person db3 = new Person("John", 36, new Pet("Lucy", 4));

        Person in = new Person();
        in.age = 17;
        in.name = "Paul";
        in.friend = new Pet(null, 35);

        Person in2 = new Person();
        in2.name = "Damian";

        Person in3 = new Person();
        in3.friend = new Pet("Lup", 25);

        try {
            BeanUtilsBean notNull  =new MyBeansUtil();
            notNull.copyProperties(db, in);
            notNull.copyProperties(db2, in2);
            notNull.copyProperties(db3, in3);

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

Unfortunately, the original objects db, db1, db2 stay the same as they were. Am I doing something wrong here?

A: I ended up using Spring BeanUtils library. Here is my working method:
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.lang.reflect.Field;
import java.util.Collection;

public class MyBeansUtil<T> {
    public T copyNonNullProperties(T target, T in) {
        if (in == null || target == null || target.getClass() != in.getClass()) return null;

        final BeanWrapper src = new BeanWrapperImpl(in);
        final BeanWrapper trg = new BeanWrapperImpl(target);

        for (final Field property : target.getClass().getDeclaredFields()) {
            Object providedObject = src.getPropertyValue(property.getName());
            if (providedObject != null && !(providedObject instanceof Collection<?>)) {
                trg.setPropertyValue(
                        property.getName(),
                        providedObject);
            }
        }
        return target;
    }
}

It works fine, but notice that it ignores fields that are collections. That's on purpose, I handle them separately.

A: You can create your own method to copy properties while ignoring null values.
public static String[] getNullPropertyNames (Object source) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

    Set<String> emptyNames = new HashSet<String>();
    for(java.beans.PropertyDescriptor pd : pds) {
        Object srcValue = src.getPropertyValue(pd.getName());
        if (srcValue == null) emptyNames.add(pd.getName());
    }
    String[] result = new String[emptyNames.size()];
    return emptyNames.toArray(result);
}

// then use Spring BeanUtils to copy and ignore null
public static void myCopyProperties(Object src, Object target) {
    BeanUtils.copyProperties(src, target, getNullPropertyNames(src))
}

A: Using BeanUtils and java8 we can achieve this:
BeanUtils.copyProperties(Object_source, Object_target, getNullPropertyNames(Object_source));

private String[] getNullPropertyNames(Object source) {
        final BeanWrapper wrappedSource = new BeanWrapperImpl(source);
        return Stream.of(wrappedSource.getPropertyDescriptors()).map(FeatureDescriptor::getName)
                .filter(propertyName -> wrappedSource.getPropertyValue(propertyName) == null).toArray(String[]::new);
    }

A: Using ProprtyUtils, we can achieve this using:
    private void copyNonNullProperties(Object destination,
            Object source) {
        try {
            PropertyUtils.describe(source).entrySet().stream()
                    .filter(source -> source.getValue() != null)
                    .filter(source -> !source.getKey().equals("class"))
                    .forEach(source -> {
                        try {
                            PropertyUtils.setProperty(destination, source.getKey(), source.getValue());
                        } catch (Exception e22) {
                            log.error("Error setting properties : {}", e22.getMessage());
                        }
                    });

        } catch (Exception e1) {
            log.error("Error setting properties : {}", e1.getMessage());
        }

    }

A: I have faced a similar problem recently. I was asked to implement a generic solution for implementing PATCH in REST API where you allow providing only specific field.
The project is a Java one with MongoDB.
In the beginning I thought would be possible to solve using the Mongo java driver and the operation $set passing the document with only the fields that should be modified. After extensive researching I realized that it doesn't work this way. If you have nested classes it won't update selectively the inner class but instead replace it. I have tried several options using directly the Mongo java driver and SpringMongoDB java API.
Then I went to the BeanUtils solution as described by the author @kiedysktos.
    public class MyBeansUtil extends BeanUtilsBean {

    @Override
    public void copyProperty(Object dest, String name, Object value)
        throws IllegalAccessException, InvocationTargetException {
        if(value == null) return;
        super.copyProperty(dest, name, value);
    }
    }

It turns out that doing only this it won't work properly as well. Imagine you call your PATCH in the following way

{ "name": "John Doe",
"friend": {
"age":2
}
}

The intent of this call is to update the age of the single pet of John Doe to 2. However the overridden code above will replace the entire Pet structure to

{ "name": null,
"age" : 2
}
erasing the name information.

My final solutions was to call recursively where I found a nested inner class. This way each one will be copied maintaining the previous information. To do that each class involved should implement a marking interface.
    Person implements NonNullCopy
    Pet implements NonNullCopy

Finally, the code:
class NullAwareBeanUtils extends BeanUtilsBean {

    @Override
    public void copyProperty(Object dest, String name, Object value)
            throws IllegalAccessException, InvocationTargetException {
        if (value == null)
            return;
        else if(value instanceof NonNullCopy) {
            Class<?> destClazz = value.getClass();
                Class<?> origClazz = dest.getClass();
                String className = destClazz.getSimpleName();

                //Recursively invokes copyProperties
                for(Method m : origClazz.getDeclaredMethods()) {
                    if(m.getReturnType().equals(destClazz)) {
                        copyProperties(m.invoke(dest, Collections.EMPTY_LIST.toArray()),value);
                    }
                }
                return;
        }

        super.copyProperty(dest, name, value);
    }

}

Notice that this solution is generic if the class implements the marking interface.


text:
Q: VSCode remote debugging on NextCloudPi not working because SSH connection failed Not really a question but already the answer. Just to save others from spending days on this task.
What I want to do
I want to extend the basic NextCloudPi image with some custom websites including PHP. For ease use of remote debugging I am using VSCode and Xdebug.
The Problem was
I can't get a SSH connection to my raspi from VSCode and therefore also PHP debugging didn't work. SSH connection to the raspi worked well with other tools (putty, PowerShell etc.). Also Xdebug was set properly on the raspi (according to phpinfo();). In the log of the ssh-plugin of VSCode the following error appeared:
Failed to set up socket for dynamic port forward to remote port 37399: Socket closed. Is the remote port correct?

Relevant Versions
NextCloudPi 1.36.3
Xdebug 3.0.4
VSCode 1.60.2 (RemoteSSH 0.65.8, PhpDebug 1.19.0)

A: The Solution is
After spending evenings of googling I found out that the TCP port forwarding of the raspi's SSH service has to be enabled which is not in the basic nextcloudpi-image. This thread gave me the final clue: VSCode Remote SSH Connection Failed
So just set in /etc/ssh/sshd_config AllowTcpForwarding to yes and everything should work as easy as described in all the manuals.


text:
Q: Trouble selecting an item in a SELECT box with jQuery with a quot I am having a hidden form with a list which I need to select an option from when a user wants to view this form.
I was using
var assignee = 'persons name';
jQuery('#edit-form' option[value='+option+']:first').attr("selected", "selected");
I tried doing this, but this is not working as the value in the option tag is not specified with the \ as well, so it won't find a match
jQuery('#edit-form option[value='+option.replace(/\'/,'\\\'')+']:first').attr("selected", "selected");

So is doing it this way the following my only option ?
jQuery('#edit-form option').each(function(){
  if(jQuery(this).val() == option) {
   jQuery(this).attr("selected", "selected");
   return false;
     }
});

a Test page
<html>
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>

  <script>
  //test vars
  var option1 = "option two";
  var option2 = "option '";
  var option = option2;

  $(document).ready(function(){
    $('#edit-form [name=select1] option').each(function(){
      if($(this).val() == option) {
    $(this).attr("selected", "selected");
    return false;
       }
    });

    $('#edit-form [name=select2] option[value='+option+']:first').attr("selected", "selected");
    option = option.replace(/\'/,'\\\'');
    $('#edit-form [name=select3] option[value='+option+']:first').attr("selected", "selected");
  });
  </script>
</head>
<body>
  <form id="edit-form">
  <select name=select1>
  <option value="option one">option one</option>
  <option value="option two">option two</option>
  <option value="option two">option two</option>
  <option value="option \'">option \'</option>
  <option value="option '">option '</option>
  </select>
  <select name=select2>
  <option value="option one">option one</option>
  <option value="option two">option two</option>
  <option value="option two">option two</option>
  <option value="option \'">option \'</option>
  <option value="option '">option '</option>
  </select>
  <select name=select3>
  <option value="option one">option one</option>
  <option value="option two">option two</option>
  <option value="option two">option two</option>
  <option value="option \'">option \'</option>
  <option value="option '">option '</option>
  </select>
</body>
</html>

A: What about:
jQuery('#edit-form option[value="'+option+'"]:first').attr("selected", "selected");

Note the use of the " and ' characters.
E.g. These are all valid strings:
"Valid 'string'"
'valid "string"'
// also valid with escape chars
"valid \"string"
'valid \'string'

but not these
"not valid "string""
'not valid 'string''

You can also see this with the syntax highlighter.
Edit:
Works for me if I use this:
$('#edit-form select[name="select3"] option[value="'+option+'"]').first().attr("selected", "selected");

Note: I use .first() instead of :first and proper select[name="select3"]. Make sure that you use proper jQuery selectors.


text:
Q: Turn a number into star rating display using jQuery and CSS I have been looking at jquery plugin and was wondering how to adapt that plugin to turn a number (like 4.8618164) into a 4.8618164 stars filled out of 5. Basically interpreting a number <5 into stars filled in a 5-star rating system using jQuery/JS/CSS.
Note that this would only display/show the stars rating from an already available number and not accept new ratings submissions.

A: Why not just have five separate images of a star (empty, quarter-full, half-full, three-quarter-full and full) then just inject the images into your DOM depending on the truncated or rouded value of rating multiplied by 4 (to get a whole numner for the quarters)?
For example, 4.8618164 multiplied by 4 and rounded is 19 which would be four and three quarter stars.
Alternatively (if you're lazy like me), just have one image selected from 21 (0 stars through 5 stars in one-quarter increments) and select the single image based on the aforementioned value. Then it's just one calculation followed by an image change in the DOM (rather than trying to change five different images).

A: I ended up going totally JS-free to avoid client-side render lag.  To accomplish that, I generate HTML like this:

To help with accessibility, I even add the raw rating value in the title attribute.

A: Anno 2022 there's more new methods available for modern browsers that require less runtime code if you can generate the rating/percentage in the right location.
Have your framework generate this html with e.g. 33.333% in the right style spots and you're good to go:

.star-rating::before {
  /* What also works: "⭐⭐⭐⭐⭐" or "" or other characters. */
  content: "⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐";
}

.star-rating {
    display: inline-block;
    background-clip: text;
    -webkit-background-clip: text;
    color: rgba(0, 0, 0, 0.1);
}

body {
  font-size: 32px; /* for demo purpose */
}

The original answer that accrued the first 40 upvotes then too:
If you only have to support modern browsers, you can get away with:

*

*No images;

*Mostly static css;

*Nearly no jQuery or Javascript;

You only need to convert the number to a class, e.g. class='stars-score-50'.
First a demo of "rendered" markup:

body { font-size: 18px; }

.stars-container {
  position: relative;
  display: inline-block;
  color: transparent;
}

.stars-container:before {
  position: absolute;
  top: 0;
  left: 0;
  content: '★★★★★';
  color: lightgray;
}

.stars-container:after {
  position: absolute;
  top: 0;
  left: 0;
  content: '★★★★★';
  color: gold;
  overflow: hidden;
}

.stars-0:after { width: 0%; }
.stars-10:after { width: 10%; }
.stars-20:after { width: 20%; }
.stars-30:after { width: 30%; }
.stars-40:after { width: 40%; }
.stars-50:after { width: 50%; }
.stars-60:after { width: 60%; }
.stars-70:after { width: 70%; }
.stars-80:after { width: 80%; }
.stars-90:after { width: 90%; }
.stars-100:after { width: 100; }
Within block level elements:

★★★★★

★★★★★

★★★★★

★★★★★

★★★★★

★★★★★

★★★★★

★★★★★

★★★★★

★★★★★

★★★★★

Or use it in a sentence: ★★★★★ (cool, huh?).

Then a demo that uses a wee bit of code:

$(function() {
  function addScore(score, $domElement) {
    $("")
      .addClass("stars-" + score.toString())
      .text("★★★★★")
      .appendTo($domElement);
  }

  addScore(70, $("#fixture"));
});
body { font-size: 18px; }

.stars-container {
  position: relative;
  display: inline-block;
  color: transparent;
}

.stars-container:before {
  position: absolute;
  top: 0;
  left: 0;
  content: '★★★★★';
  color: lightgray;
}

.stars-container:after {
  position: absolute;
  top: 0;
  left: 0;
  content: '★★★★★';
  color: gold;
  overflow: hidden;
}

.stars-0:after { width: 0%; }
.stars-10:after { width: 10%; }
.stars-20:after { width: 20%; }
.stars-30:after { width: 30%; }
.stars-40:after { width: 40%; }
.stars-50:after { width: 50%; }
.stars-60:after { width: 60%; }
.stars-70:after { width: 70%; }
.stars-80:after { width: 80%; }
.stars-90:after { width: 90%; }
.stars-100:after { width: 100; }

Generated:

The biggest downsides of this solution are:

*

*You need the stars inside the element to generate correct width;

*There's no semantic markup, e.g. you'd prefer the score as text inside the element;

*It only allows for as many scores as you'll have classes (because we can't use Javascript to set a precise width on a pseudo-element).

To fix this the solution above can be easily tweaked. The :before and :after bits need to become actual elements in the DOM (so we need some JS for that).
The latter is left as an excercise for the reader.

A: using jquery without prototype, update the js code to
$( ".stars" ).each(function() {
    // Get the value
    var val = $(this).data("rating");
    // Make sure that the value is in 0 - 5 range, multiply to get width
    var size = Math.max(0, (Math.min(5, val))) * 16;
    // Create stars holder
    var $span = $('').width(size);
    // Replace the numerical value with stars
    $(this).html($span);
});

I also added a data attribute by the name of data-rating in the span.

A: DEMO
You can do it with 2 images only. 1 blank stars, 1 filled stars.
Overlay filled image on the top of the other one. and convert rating number into percentage and use it as width of fillter image.

.containerdiv {
  border: 0;
  float: left;
  position: relative;
  width: 300px;
}
.cornerimage {
  border: 0;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
 }
 img{
   max-width: 300px;
 }

A: Try this jquery helper function/file
jquery.Rating.js
//ES5
$.fn.stars = function() {
    return $(this).each(function() {
        var rating = $(this).data("rating");
        var fullStar = new Array(Math.floor(rating + 1)).join('');
        var halfStar = ((rating%1) !== 0) ? '': '';
        var noStar = new Array(Math.floor($(this).data("numStars") + 1 - rating)).join('');
        $(this).html(fullStar + halfStar + noStar);
    });
}

//ES6
$.fn.stars = function() {
    return $(this).each(function() {
        const rating = $(this).data("rating");
        const numStars = $(this).data("numStars");
        const fullStar = ''.repeat(Math.floor(rating));
        const halfStar = (rating%1!== 0) ? '': '';
        const noStar = ''.repeat(Math.floor(numStars-rating));
        $(this).html(`${fullStar}${halfStar}${noStar}`);
    });
}

index.html
   <!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Star Rating</title>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" rel="stylesheet">

A: Here's a solution for you, using only one very tiny and simple image and one automatically generated span element:
CSS
span.stars, span.stars span {
    display: block;
    background: url(stars.png) 0 -16px repeat-x;
    width: 80px;
    height: 16px;
}

span.stars span {
    background-position: 0 0;
}

Image

(source: ulmanen.fi)

Note: do NOT hotlink to the above image! Copy the file to your own server and use it from there.
jQuery
$.fn.stars = function() {
    return $(this).each(function() {
        // Get the value
        var val = parseFloat($(this).html());
        // Make sure that the value is in 0 - 5 range, multiply to get width
        var size = Math.max(0, (Math.min(5, val))) * 16;
        // Create stars holder
        var $span = $('').width(size);
        // Replace the numerical value with stars
        $(this).html($span);
    });
}

If you want to restrict the stars to only half or quarter star sizes, add one of these rows before the var size row:
val = Math.round(val * 4) / 4; /* To round to nearest quarter */
val = Math.round(val * 2) / 2; /* To round to nearest half */

HTML
4.8618164
2.6545344
0.5355
8

Usage
$(function() {
    $('span.stars').stars();
});

Output

(source: ulmanen.fi)

Demo

http://www.ulmanen.fi/stuff/stars.php

This will probably suit your needs. With this method you don't have to calculate any three quarter or whatnot star widths, just give it a float and it'll give you your stars.

A small explanation on how the stars are presented might be in order.
The script creates two block level span elements. Both of the spans initally get a size of 80px * 16px and a background image stars.png. The spans are nested, so that the structure of the spans looks like this:

The outer span gets a background-position of 0 -16px. That makes the gray stars in the outer span visible. As the outer span has height of 16px and repeat-x, it will only show 5 gray stars.
The inner span on the other hand has a background-position of 0 0 which makes only the yellow stars visible.
This would of course work with two separate imagefiles, star_yellow.png and star_gray.png. But as the stars have a fixed height, we can easily combine them into one image. This utilizes the CSS sprite technique.
Now, as the spans are nested, they are automatically overlayed over each other. In the default case, when the width of both spans is 80px, the yellow stars completely obscure the grey stars.
But when we adjust the width of the inner span, the width of the yellow stars decreases, revealing the gray stars.
Accessibility-wise, it would have been wiser to leave the float number inside the inner span and hide it with text-indent: -9999px, so that people with CSS turned off would at least see the floating point number instead of the stars.
Hopefully that made some sense.

Updated 2010/10/22
Now even more compact and harder to understand! Can also be squeezed down to a one liner:
$.fn.stars = function() {
    return $(this).each(function() {
        $(this).html($('').width(Math.max(0, (Math.min(5, parseFloat($(this).html())))) * 16));
    });
}

A: Here's my take using JSX and font awesome, limited on only .5 accuracy, though:

          {Array(Math.floor(rating)).fill()}
          {(rating) - Math.floor(rating)==0 ? ('') : ()}

First row is for whole star and second row is for half star (if any)


text:
Q: Data for the maximum date for an employee I need to to get the value on the maximum date for a particular employee.
Eg: I select 30/06/2017 as the date. But for the employee the Score is 0 on 30/06/2017. But on 28/06/2017 he has a value of 94. So, I need to show this value in my report.
Could anyone help me with this?

A: Found the solution Write filters as TOPN(Date, 1 by Employee) is equal to/is in 1, Score not in (NULL, 0) and Date is prompted. This works.


text:
Q: how do i sync my windows ce 6.0 device with my windows 7 pc I have a PDA device running Windows Embedded CE 6.0, which I need to sync using WMDC (Windows Mobile Device Center) as my system operates on Windows 7 professional. However the WMDC does not detect the device as an active connection in spite of the device being available as a usb mass storage device on the Win 7 system. My query is whether i need to do any specific configuration settings on the PDA to enable detection by the WMDC specifically ?

A: Windows CE provides support for different class profiles for USB client and when you configure your OS Design you may choose which of those profiles you want to support. If the manufacturer of your device did not include ActiveSync/serial (old name for WMDC) support in the image you can't sync your device.
If they did you may be able to change the device behaviour by changing the registry, as described here:
http://msdn.microsoft.com/en-us/library/ms895481.aspx


text:
Q: How to plot two different user defined functions in the same plot in R I need to plot 2 different user defined function in the same R plot.
I vectorize each of them:
Vectorize creates a function wrapper that vectorizes the action of its argument FUN. Vectorize(FUN, vectorize.args = arg.names, SIMPLIFY = TRUE,USE.NAMES = TRUE)
If I plot them separately I get the correct plot, however if I try to plot both functions in the same graph, it does not work.
Here is what I did:
1) first function:
payoff_call <- function(S, K){
  if(S < 0 | K < 0){
    return(print("The input S and K  must be > 0"))
    }else{
      return(max(S-K,0))
    }
  }

2) second function:
myBlackScholes <- function(S, K, tau, r, sigma, type = c("call", "put")) {
  if(S < 0 | K < 0 | tau < 0 | sigma < 0) {
    return(print("The input S , K , tau and sigma must be > 0"))
  } else
    {
    d1 <- (log(S/K) + (r + 0.5*sigma^2)*tau)/(sigma*sqrt(tau))
    d2 <- d1 - sigma*sqrt(tau)
    if(type == "call"){
      output <- cbind(
      V_BS_Call = S*pnorm(d1) - K*exp(-r*(tau))*pnorm(d2), #fair value call
      delta_call = pnorm(d1), #delta call
      vega_call = S*sqrt(tau)*dnorm(d1), #vega call
      theta_call = -S*dnorm(d1)*sigma/(2*sqrt(tau)) - r*K*exp(-r*tau)*pnorm(d2), #theta call
      rho_call = K*tau*exp(-r*tau)*pnorm(d2), #rho call
      kappa_call = -exp(-r*tau)*(pnorm(-d2)-1), #kappa call
      gamma_call = dnorm(d1)/(S*sigma*sqrt(tau)))#gamma call
      return(output)
      } else if(type == "put"){
        output <- cbind(
        V_BS_Put = K*exp(-r*(tau))*pnorm(-d2) - S*pnorm(-d1), #fair value put
        delta_put = pnorm(d1)-1, #delta put
        vega_put =  S*sqrt(tau)*dnorm(d1), #vega put same as vega call
        theta_put = -S*dnorm(d1)*sigma/(2*sqrt(tau)) + r*K*exp(-r*tau)*pnorm(-d2), #theta put
        rho_put = -K*tau*exp(-r*tau)*pnorm(-d2), #rho put
        kappa_put = exp(-r*tau)*pnorm(-d2), #kappa put
        gamma_put = dnorm(d1)/(S*sigma*sqrt(tau))) #gamma put
        return(output)
        } else{
            return(print("Wrong type in input"))
          }
    }
  }

3) I vectorize each function:
vect_payoff_call <- Vectorize(payoff_call)
vect_myBlackScholes <- Vectorize(myBlackScholes)

4) I plot the 2 functions, for S starting at 0 to 100:
plot(x = 0:100, y = vect_payoff_call(0:100, 50),
     type="l", col="blue", lty = 1, lwd = 1,
     main = "Long Call Option Payoff function", xlab = "S", ylab = expression(f(S)))

plot(x = 0:100, y = vect_myBlackScholes(0:100,50, 1, 0.12, 0.3, "call")[1,], type="l", col="green", lty = 1, lwd = 1, add=TRUE)

The first plot is correct, but the second is not.
Any suggestion?

A: Here is how. Note that I use ggplot2 in my example:
library(ggplot2)

x <- seq(0,2, by=0.1)
my_square <- function(x) x^2
my_cube <- function(x) x^3

my_data <- data.frame(argx = x, my_square = my_square(x),
                      my_cube = my_cube(x))

ggplot(my_data) +
  geom_point(aes(argx, my_square, color = 'x^2')) +
  geom_line(aes(argx, my_square, color = 'x^2')) +
  geom_point(aes(argx, my_cube, color = 'x^3')) +
  geom_line(aes(argx, my_cube, color = 'x^3')) +
  theme_bw() +
  labs(x = 'x', y = 'y') +
  scale_color_manual(values = c('x^2' = 'red', 'x^3' = 'green'), name = 'function')

Output


text:
Q: How to retrieve only particular part of string in SQL Server 2012 My data looks like that:
PrimISOcodeGL
99507 - Swimming Pools – installation & service – below ground - 1799 - Hazard 3
18501 - Supermarkets - 5411 - Hazard 1
91580 - Contractors Executive Supervisors  - 1541 - Hazard 2
10073 - Automobile Sales, Repair or Service Shop - 7539 - Hazard 2

How can I retrieve only the name between first and second "-"?
So it should be like that:
PrimISOcodeGL
Swimming Pools
Supermarkets
Contractors Executive Supervisors
Automobile Sales, Repair or Service Shop

I am trying to use function like CHARINDEX, LTRIM, RTRIM, LEN

A: Here's a way using charindex and substring.
ONLINE DEMO
declare @table table (PrimISOcodeGL varchar(256))

insert into @table
values
('99507 - Swimming Pools - installation & service - below ground - 1799 - Hazard 3'),
('18501 - Supermarkets - 5411 - Hazard 1'),
('91580 - Contractors Executive Supervisors  - 1541 - Hazard 2'),
('10073 - Automobile Sales, Repair or Service Shop - 7539 - Hazard 2')

select
    ltrim(substring(substring(PrimISOcodeGL,charindex('-',PrimISOcodeGL) + 1,9999),1,charindex('-',substring(PrimISOcodeGL,charindex('-',PrimISOcodeGL) + 1,9999)) - 1))
from
    @table


text:
Q: How to find the PHP error from Chrome browser for a blank screen? This is a common question for all web developers , i wanted to know about some tools for Chrome browser to find PHP based errors from the browser itself.
Sometimes When we open a page done in php shows blank screen with out any error message or warning.It is is very hard to go through the code line by line if no error or warning message in the screen.
I question is do we have any option in **

Chrome browser

** to check the php error?

A: You can enable error_reporting try adding the following to your code.
I've copied this code from the PHP Website
// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

Just remove the ones you don't need. For example this is all I have inside my file
// Debug - Development Mode
error_reporting(E_ALL);
ini_set("display_errors", 1);

I did a quick Google Search and came back with this for Chrome Report extension: https://chrome.google.com/webstore/detail/php-console/nfhmhhlpfleoednkpnnnkolmclajemef?hl=en

A: Nope you can't check it in Chrome. As you said there is a blank screen so there is nothing returned to the browser, except most probably few headers.
You have to access the server and check the logs. Depending on the way PHP is running on that server and what webserver is used and how is the setup made the file containing PHP errors may be located in different locations.
Please keep in mind that errors, stack trace output etc. contains a lot of information which could be used to attack against the system so it's not recommended to output such information in Production systems.


text:
Q: STATIC files are not showed in Django templates I'm trying to show images/js/css in my Django templates with {{ STATIC_URL }} label. In theory, this works because in browser, when i see the printed code the path to requested file is something like "/static/images/blabla.jpg". But the file is not showed, so i guess the problem is in Django project.
My settings looks like this:
STATIC_ROOT = '/absolute/path/to/static'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    '/absolute/path/to/static'
)

In my urls.py:
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),

But i don't know why all files in static directory are not displayed in templates.
Any tip or advice?
Thanks mates.

A: First, it looks like there is a mistake in your settings. You should understand the django.contrib.staticfiles collectstatic command:

Collects the static files into STATIC_ROOT.
  [...]
  Files are searched by using the enabled finders. The default is to look in all locations defined in STATICFILES_DIRS and in the 'static' directory of apps specified by the INSTALLED_APPS setting.

So, it seems like a mistake that STATICFILES_DIRS contains STATIC_ROOT, since the contents of STATICFILES_DIR is ment to be copied into STATIC_ROOT by collectstatic.
The url is not necessary. You should either:

*

*use runserver with DEBUG=True, in that case django will serve static files by default, in doubt use staticfiles_urlpatterns or

*use a real httpd to serve STATIC_ROOT on STATIC_URL, in that case you should generate STATIC_ROOT from STATICFILES_DIRS (and actually each app's 'static' subdir, which is the point) with the command collectstatic
When in doubt, the findstatic command may also prove useful.
django.contrib.staticfiles might look a little confusing at first, but when you understand it fully you love it <3


text:
Q: using LDAP url in JBOSS oracle-ds.xml Our oracle servers are migrating to LDAP. I use JBOSS connection pooling in my application which looks like
<local-tx-datasource>
    <jndi-name>OracleDB</jndi-name>
    <connection-url>jdbc:oracle:thin:@dbs1:1521:SID</connection-url>
    <driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
    <user-name>osuser</user-name>
    <password></password>
</local-tx-datasource>

Now my DBA gave me a fully qualified LDAP url for the databse that is like server.db.company.com. Can you please suggest how do  I use this url in the oracle-ds.xml?
P.S. I have already tried the URL as jdbc:oracle:thin:@ldap://server.db.company.com. It gives invalid LDAPexception.`


text:
Q: Refused to execute script from bundle.js because its MIME type Hello I'm new to react and I'm trying to attach express framework with react, I followed this tutorial: https://blog.hellojs.org/setting-up-your-react-es6-development-environment-with-webpack-express-and-babel-e2a53994ade but when I run the server I'm getting the following error:

Failed to load resource: the server responded with a status of 404
  (Not Found) localhost/:1
Refused to execute script from
  'http://localhost:3000/dist/bundle.js' because its MIME type
  ('text/html') is not executable, and strict MIME type checking is
  enabled.

I have been searching this error for two days now and I haven't find a solution. I think the problem is that the bundle.js is not being created by webpack, I would like to now why is this happening
My project directory is the following:

My config webpack file:
var webpack = require('webpack');
var path = require('path');

module.exports = {
    entry: './client/index.js',
    output: {
      path: __dirname,
      filename: 'bundle.js',
      publicPath: '/client/assets/'
    },
    module: {
        loaders: [
          {
            test: /\.(js|jsx)$/,
              loader: 'babel-loader',
              include: path.join(__dirname, 'client'),
              exclude: /node_modules/,
              query: {
                presets: ['es2015', 'react', 'stage-0']
              }
            },
            {
              test: /\.css$/,
              loader: 'css-loader'
            }
        ]
    },
};

server.js, where I create the express instance:
const path = require('path')
const express = require('express')

module.exports = {
  app: function () {
    const app = express();
    const indexPath = path.join(__dirname, 'indexDep.html');
    const publicPath = express.static(path.join(__dirname, '../dist'));

    app.use('/dist', publicPath);
    app.get('/', function (_, res) { res.sendFile(indexPath) });

    return app;
  }
}

And app.js, where I'm running the server:
const Server = require('./server.js')
const port = (process.env.PORT || 3000)
const app = Server.app()

if (process.env.NODE_ENV !== 'production') {
  const webpack = require('webpack')
  const webpackDevMiddleware = require('webpack-dev-middleware')
  const webpackHotMiddleware = require('webpack-hot-middleware')
  const config = require('../webpack.dev.config.js')
  const compiler = webpack(config)

  app.use(webpackHotMiddleware(compiler))
  app.use(webpackDevMiddleware(compiler, {
    noInfo: true,
    publicPath: config.output.publicPathdist
  }))
}

app.listen(port)
console.log(`Listening at http://localhost:${port}`)

A: Try this:
// server.js
"use strict"

const path = require('path')
const express = require('express')

module.exports = {
  app(init) {
    const app = express()
    const indexPath = path.join(__dirname, 'indexDep.html')
    const publicPath = express.static(path.join(__dirname, '../dist'))

    if (init != null) init(app)
    app.use('/dist', publicPath)
    app.get('/', function (_, res) { res.sendFile(indexPath) })

    return app
  },
}

// app.js
const Server = require('./server.js')
const port = (process.env.PORT || 3000)

Server.app(app => {
  if (process.env.NODE_ENV !== 'production') {
    const webpack = require('webpack')
    const webpackDevMiddleware = require('webpack-dev-middleware')
    const webpackHotMiddleware = require('webpack-hot-middleware')
    const config = require('../webpack.dev.config.js')
    const compiler = webpack(config)

    app.use(webpackHotMiddleware(compiler))
    app.use(webpackDevMiddleware(compiler, {
      noInfo: true,
      publicPath: config.output.publicPathdist
    }))
  }
})
.listen(port)
console.log(`Listening at http://localhost:${port}`)

Specifically, what this does is two-fold:

*

*It punts your initialization to before Express finally reads its catch-all routes for /dist and /. If you add the middleware after, you'll never see it set up in the first place.

*It retains most of your other logic, without moving a lot of code. Closures are useful for that kind of thing, keeping logic where it belongs while still allowing others to let you hook into their logic.


text:
Q: Как сделать выполнение JS скрипта ДО начала загрузки HTML страницы Делаю браузерное расширение для Chrome (для личных целей, не на продакшен), функционал простой: опустошение содержимого ВСЕХ <script>...</script> на посещаемой странице.
А конкретно хочу, чтобы попадая на сайт в процессе загрузки страницы Не загружалось все то, что заключено в тег скрипт. Пока что получается опустошать все скрипты после загрузки страницы.
Подключаю скрпти в HEAD:
let all_scripts = document.getElementsByTagName("script");

for (let i = 0; i < all_scripts.length; i++) {
    let elem_2 = all_scripts[i];
    elem_2.removeAttribute("src");
    elem_2.innerHTML = "";
}

Работает, все внутренности тегов script исчезают. Но как Вы понимаете, браузер это содержимое уже успел "запомнить"
По этому хочу, чтобы Это все выполнялось ДО загрузки страницы (если возможно)
ЗЫ - Вариант с отключением JS в настройках браузера меня не устраивает. Задача написать расширение для легкой манипуляции (вкл\выкл в одно касание)

A: Попробуйте завязаться на события onCommitted или onDOMContentLoaded
https://developer.chrome.com/docs/extensions/reference/webNavigation/
Или посмотреть как написаны какие-нибудь блокировщики рекламы типа adBlock или Noscript


text:
Q: How to ignore the enablefields in an extbase 1:1 relation Is there any way to ignore enableFields like starttime, endtime, hidden and deleted in a 1:1 relation between two Extbase Domain Objects?
My Situation: My Foo has a Bar and I can get the Bar with Foo->getBar()
My Problem: when Bar is disabled, the ORM won't set that property with the respective model
Even greater Problem: the property is null, so i have no access to the uid to fetch it manually with a BarRepository->findByUidAndIgnoreEnableFields() or so
Something like @ignoreEnableFields for the property would be perfect

A: This is a nice workaround as long as this is not supported:
Save the reference as integer and request it in the getter with a custom repository function that ignores the enableFields.
I set up a gist for it: https://gist.github.com/econic/7302684

A: You just need to setup your repository with setIgnoreEnableFields(true), see http://typo3.org/api/typo3cms/class_t_y_p_o3_1_1_c_m_s_1_1_extbase_1_1_persistence_1_1_generic_1_1_typo3_query_settings.html#ada5704c87dc55f261e4c5f7487125cf6


text:
Q: Generation of sine waves within the audible range using a DAC I am trying to generate up to 20 khz sine wave with the TLC5615 DAC but have only been able to obtain a maximum of 100 hz. I am using a 20 MHZ atmega328 MCU to transfer the required 16 bits (2 padding, 10 bit precision, 4 dummy bits) and also to act as the software defined clock for the device. In order to generate the sine wave I have a lookup table with ~64 values in order to obtain a decent sine wave.
Here is all of the code
int sine[] = {0x7fc ,0x868 ,0x8d4 ,0x93c ,0x9a8 ,0xa10 ,0xa78 ,0xadc
,0xb3c ,0xba0 ,0xbfc ,0xc58 ,0xcb0 ,0xd04 ,0xd58 ,0xda4 ,0xdf0 ,0xe34 ,0xe74
,0xeb0 ,0xee8 ,0xf1c ,0xf4c ,0xf74 ,0xf98 ,0xfb8 ,0xfd0 ,0xfe4 ,0xff0 ,0xff8
,0xffc ,0xff8 ,0xff0 ,0xfe4 ,0xfd0 ,0xfb8 ,0xf98 ,0xf74 ,0xf4c ,0xf1c ,0xee8
,0xeb0 ,0xe74 ,0xe34 ,0xdf0 ,0xda4 ,0xd58 ,0xd04 ,0xcb0 ,0xc58 ,0xbfc ,0xba0
,0xb3c ,0xadc ,0xa78 ,0xa10 ,0x9a8 ,0x93c ,0x8d4 ,0x868 ,0x7fc ,0x794 ,0x728
,0x6bc ,0x654 ,0x5ec ,0x584 ,0x520 ,0x4bc ,0x45c ,0x400 ,0x3a4 ,0x34c ,0x2f4
,0x2a4 ,0x258 ,0x20c ,0x1c8 ,0x188 ,0x148 ,0x110 ,0xe0 ,0xb0 ,0x88 ,0x64 ,0x44
,0x2c ,0x18 ,0xc ,0x0 ,0x0 ,0x0 ,0xc ,0x18 ,0x2c ,0x44 ,0x64 ,0x88 ,0xb0 ,0xe0
,0x110 ,0x148 ,0x188 ,0x1c8 ,0x20c ,0x258 ,0x2a4 ,0x2f4 ,0x34c ,0x3a4 ,0x400
,0x45c ,0x4bc ,0x520 ,0x584 ,0x5ec ,0x654 ,0x6bc ,0x728 ,0x794};

#define samples 120

#define intL 16

void setup(){

  pinMode(11,OUTPUT);
  pinMode(12,OUTPUT);
  pinMode(13,OUTPUT);
}

int j = 0;
int k = intL-1;

unsigned int cval = 0;
int current = 0;

byte currentBit = 0;

void loop(){

  PORTB = B00000000;

   cval = sine[j];

  while(k != 0)
  {
    currentBit = (cval >> k) & 1;

    if(currentBit)
    {
      PORTB = B00010000;
      PORTB = B00110000;
      PORTB = B00010000;
    }
    else
    {
      PORTB = B00100000;
      PORTB = B00000000;
    }

      k--;
  }

   PORTB = B00001000;

  k=intL-1;

  j++;

  if(j == samples)
  {
    j = 0;
  }
}

Within the loop method I maintain a counter of the current value of the wave. I also maintain a counter of the current bit that needs to be written and in order to write in LSb order, that counter has to count backwards. Then I shift the word by that specified amount. After I know the value, I trigger the clock, write the value and set the clock once more. After the word has been shifted into the DAC you have to drive Chip Select input high.
I am afraid this is about performant as it could get using the lookup method, so I would like to know if there are any alternatives or what I need in order to achieve ~20 khz frequencies.

A: If you want to get 20kHz signals, you need to do at least 3 things.
The first is get 50ks/s or more transferred to your DAC. That means running the SPI clock at around 1MHz or more. Reading between the lines, the DAC should be able to accept at least 10MHz SPI clock. The challenge is to find the MCU library that can transmit SPI at 1MHz.
The second is to generate sine samples at the right rate. Having saved 64 samples of a sine wave in your table, you do not need to step through them one at a time, you can do 2 steps at a time, or more. In fact if you were generating a 20kHz signal at 50kHz sampling rate, you would be stepping 0.4 of a circle = 144 degrees = about 25 steps of a 64 entry table.
For a table-less way of doing it, look up CORDIC. You should find a 20MHz atmega328 is fast enough to do that.
The third thing is to design and build an anti-alias filter to go after your DAC, which must pass the fmax of 20kHz, and block all frequencies from (sampling_rate - fmax) upwards. With a 50kHz sample rate, that's pass 20kHz, block 30kHz and up. You can ease the steepness requirement of the filter by increasing the sample rate. At 100kHz, you would only need to block frequencies above 80kHz, a much easier filter to build.
Some audio DACs oversample within the DAC with digital filters to make things much much easier. The DAC you have quoted doesn't do this.


text:
Q: Relation between Dirichlet convolution and Bell series and convolution of functions and the Fourier transform? We define the Dirichlet convolution of two arithmetic functions $a,b:\mathbb{N}\to\mathbb{C}$ to be
$$
(a*b)(n)=\sum_{d\mid n}a(d)b\left(\frac{n}{d}\right).
$$
Given a prime $p$, we define the Bell series of $a$ to be
$$
a_p(x)=\sum_{n=0}^{\infty}a(p^n)x^n.
$$
Both of these definitions are taken from Apostol's Introduction to Analytic Number Theory. It is easy to show that if $c=a*b$, then $c_p(x)=a_p(x)b_p(x)$ for all primes $p$.
There are some pretty obvious cosmetic similarities here between the definition of Dirichlet convolution and this result with Bell series and the usual notion of convolution in analysis and how the Fourier transform interacts with it ($\widehat{f*g}=\hat{f}\cdot\hat{g}$). Are these similarities actually significant?
More specifically, can Dirichlet convolution be viewed somehow as the usual convolution of two functions on some group with a measure? Are Bell series related in any way to Fourier transforms or Fourier coefficients, or is it just nice and convenient to have results about different types of products interacting well with each other?


text:
Q: Also show search results when search string comes close to item names I am making a website, with several products. This webshop sells boat trips. I have a few items with the name 'daytrip'. But when I search for 'daytrips', I get no search results at all.
I would like to get results for 'daytrip', when I am looking for 'daytrips'. How to I achieve this?

A: You can do that by assigning a synonym to the daytrips search keyword.
Go to Catalog->Search terms.
Look for the search term daytrips (if it does not exist, add it), edit it and in the field Synonym For fill in daytrip.


text:
Q: Parallel For Min and Max Threads With using ParallelOptions, How do i specify the Min amount of threads I want? I've sent Max Degree to 50 but when i look sometimes only 17 are open and it doesn't seem like it goes above that.
Advise?

A: The Task Parallel Librabry will decide how much threads are suitable for a given task on a given machine. So only on very rare situations (very high optimization for a specific and well known target machine e.g.) you should give the TPL some more input for the decision. On most scenarios you are better of leaving the TPL doing it's job on it's own.


text:
Q: Bitwise operator that "cancels out" after being applied k times XOR is an operator that "cancels out" after being applied 2 times, in the sense that x ^ x = 0 for any x.
Is it possible to design (perhaps by composing XOR/AND/OR/NOT in some way?) a bitwise operator $, such that x $ x $ ... $ x (k xs in total) evaluates to 0 for any x?

A: Yes, for example if the $ operator is defined such that x $ y = 0 for any x or y, then it will have the property you describe.

A: What about this:
(x1 ^ x2) | (x1 ^ x3) | (x1 ^ x4) | ... | (x1 ^ xk)

This will only return 0 if all the x are the same. Or even simpler replace $ by ==: x == x == x ... if that is allowed... only works mathematically but wouldn't work in Java.


text:
Q: best query to update a big mysql database (rows) against a badword list I have a table with 8 million rows, which needs to be scanned against a huge list of badwords.
My first idea was to:
UPDATE `master` SET `blacklisted`='1' WHERE MATCH (`content-desc`, `content-title`) AGAINST ('
badword1 | badword2 | badword3 | "and many more"' IN BOOLEAN MODE)

unfortunately this version forgot some words and was not case-insensitive!
next try was to
$badwords = array("badword1","badword2","badword3","and-many-more");

foreach($badwords AS $name)
   {
        $sql = "UPDATE `master` SET `blacklisted`='1' WHERE concat(`content-title(mediumtext)`,`content-desc(mediumtext)`)  LIKE '%".$name."%'";

        sleep(6);

// Could limit this query by 100.000 and adding another foreach loop help?
// How would the foreach look like (select count(*) from master?)/100.000

   }

a lot of queries which killed my server immediately!
Maybe the commented idea could help?! (but howto?)
Who has the best idea how to solve this query, without stressing the mysql server too much?
Thank you!

A: Not sure how this will perform on your table, but you can do a case insensitive comparison, as part of a join clause.
So, you have a table that you want to scan (with 8m rows)
CREATE TABLE IF NOT EXISTS haystack (
  word varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Dumping data for table haystack
INSERT INTO haystack (word) VALUES
('a cat is'),
('category'),
('cat'),
('decatur'),
('dog'),
('pigeon'),
('eagle'),
('a beagle'),
('Cat'),
('CAT');
And a table with bad words
CREATE TABLE IF NOT EXISTS needles (
  bad_word varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Dumping data for table needles
INSERT INTO needles (bad_word) VALUES
('cat'),
('eagle');
The following query will JOIN the two tables, case-insensitively, with fuzzy matching.
SELECT * FROM haystack AS h JOIN needles AS n ON h.word COLLATE utf8_general_ci LIKE CONCAT('%' , n.bad_word , '%');
You can of course, perform an update on the results easily enough.  Here are the results I got...  If you do not want to exclude words like "Dickson", "Stitsville", "Assume", it gets much more tricky.
word         bad_word
a cat is     cat
category     cat
cat          cat
decatur      cat
eagle        eagle
a beagle     eagle
Cat          cat
CAT          cat


text:
Q: How to create a 2 variable barplot using ggplot2 in r I have a data frame and i want to plot a bar chart with two numerical values bars side by side namely Mean_dbh and Low_AGC for each given location (SU)
How do i plot this using ggplot2
   SU Mean_dbh   Low_AGC
1   1 16.98921 17.696251
2   2 13.48199  8.108352
3   3 15.97746 14.584501
4   4 12.14046 28.910114
5   5 16.47509 38.047385
6   6 19.80792 31.183069
7   7 17.44469 38.192385
8   8 18.78043 12.138436
9  10 15.68889 24.195719
10 11 17.39620 26.621287
11 15 16.71296 32.219763

A: By using tidyverse and pivot_longer you can merge the two variables. geom_col allows to define SU as the x-axis and the value of merged variable  as the y-axis. The color is defined by fill=name where name is the merged column. Axis are renamed to make things clear.
library(tidyverse)

df <- read.table(text = "   SU Mean_dbh   Low_AGC
1   1 16.98921 17.696251
2   2 13.48199  8.108352
3   3 15.97746 14.584501
4   4 12.14046 28.910114
5   5 16.47509 38.047385
6   6 19.80792 31.183069
7   7 17.44469 38.192385
8   8 18.78043 12.138436
9  10 15.68889 24.195719
10 11 17.39620 26.621287
11 15 16.71296 32.219763", header=T)
df
#>    SU Mean_dbh   Low_AGC
#> 1   1 16.98921 17.696251
#> 2   2 13.48199  8.108352
#> 3   3 15.97746 14.584501
#> 4   4 12.14046 28.910114
#> 5   5 16.47509 38.047385
#> 6   6 19.80792 31.183069
#> 7   7 17.44469 38.192385
#> 8   8 18.78043 12.138436
#> 9  10 15.68889 24.195719
#> 10 11 17.39620 26.621287
#> 11 15 16.71296 32.219763

ggplot(df %>% pivot_longer(cols = Mean_dbh:Low_AGC),
       aes(x=SU, y = value, fill=name)) +geom_col(position = 'dodge') +
  labs(x='Location', y='Mean_dbh or Low_AGC') +
  theme(legend.title = element_blank())


text:
Q: Debian simple-scan inoperative shortcuts I installed Emmabuntus (Debian Buster based) on an ordinosaur computer with LXQt as DE. The simple-scan application v3.30.1.1 is installed by default and works, but the supposed shortcuts ctrl + f and ctrl + m that greatly simplify the scanning task are ineffective. Nothing is happening. The shortcuts seem to be "hard-coded" in the application (they are given from the "Keyboard shortcuts" menu and I couldn't find a config file).
How do I know if the problem is with the application itself or if the system or DE (or whatever) intercepts the shortcut before the application ?
How to make these shortcuts effective ?
Thank you in advance for your expert advice.

A: I answer to myself because I found the solution many weeks ago. The problem has nothing to do with DE or distro or whatever but it is implicit to the application simple-scan itself. We must just run the command by preceding an environment variable like this command XDG_CURRENT_DESKTOP=XFCE simple-scan so ctrl+f shortkey and others are again available (source)
So my problem is resolved :)


text:
Q: Can I ignore error without using try catch()? So I want to now if that possible for .NET languages to ignore error without using try catch construction ?
I can ignore warring with #nowarring 40 for example, can I ignore error ?
Why I want it ?
simply wanted to call system pause with this way
open System.Runtime.InteropServices
[<DllImport(@"msvcrt.dll")>]
extern void system(string str)
system "pause"

but got Error message

unbalanced stack. This is probably
  because the managed PInvoke signature
  does not match the unmanaged target
  signature. Make sure that the calling
  convention and parameters of the
  PInvoke signature match the target
  unmanaged signature.

So I don't care, it works. But can I just ignore this error ? without doing weird stuff like that :
try (system "pause") catch |_->()

Ok , I solved my problem by adding CallingConvention=CallingConvention.Cdecl, but what the question was about skipping exceptions, so and I still don't know if I can do it.
So maybe I need to tell some real reason to not be down-voted hard - sometimes it's matters for program to live even with hard errors occupations, but even sometimes you don't need to catch them. You need just ignore them...
off topic : proof image about using void instead of int :

A: Errors are there for a reason which should usually not be ignored. Your reason is that you are not using correct calling convention. See this answer for more information.
As for compile and runtime errors Graham has already pointed out the difference. If you get an unhandled runtime exception that usually means that your program is in an inconsistent state. If program would be allowed to continue there is no guarantee as to what would happen. It is better for a program to die than to proceed with corrupted data. You can have a look at AppDomain.UnhandledException event, but it only allows you to log the exception and do some cleaning, program will then exit anyway. There may be other options (depending on your programming language) but it is definitely not advisable to use them.

A: No. When you talk about ignoring warnings, these are compiler warnings. You can ignore these if you want, but they're generally warning you about something for a good reason. You can't ignore compiler errors, because when these occur, your code hasn't compiled and you have no binary to run.
When you talk about errors in your question, you're actually referring to exceptions. These are thrown at runtime. The only way to "ignore" them is to have a try/catch block which catches an exception and does nothing with it.
Also, if you really need to ignore an exception, it's best to catch the specific exception you want to ignore, rather than any exception. So, instead of something like this:
try
{
   ...
}
catch
{
}

or
try
{
   ...
}
catch(Exception)
{
}

you should try to use
try
{
   ...
}
catch(SpecificExceptionType)
{
}

A: *

*In C# I don't think there is a way to ignore all exceptions, apart from try ... catch

*In VB.Net there is a way to ignore all exceptions:

VB.Net code:
On Error Resume Next '' all exceptions after this point will be ignored
System("pause")

But it's a dangerous feature. Exceptions should only be ignored if

*

*You are absolutely confident that you understand why they have occurred

*You are absolutely confident that they can be safely ignored.

In my humble opinion, and with no offence meant, from your question I don't think you understand why the error has occurred or why it is dangerous to ignore it.

A: Why don't you declare it like this:
extern int system(string str)

Your compiler is telling you something important here: It is telling you that the system function returns an int and that it doesn't know what to do with it. You have to make sure your signature matches!

A: There is no built in way to ignore exceptions, but you could define your own function to do so:
let ignoreError func defaultValue =
    try func() with _ -> defaultValue

A: Or you could simply turn off the MDA.

A: One approach is to create a method that takes a System.Action object and pass a lambda expression to execute, then whenever you want to execute something and ignore all errors just wrap this method call around it. This is shown below.
    public void IgnoreError(System.Action action)
    {
        try
        {
            action.Invoke();
        }
        catch
        {
        }
    }

    public void SomeMethod()
    {
        IgnoreError(() => { system "pause"; });
    }


text:
Q: Price filter showing prices excluding taxes Facing some issue for pricing filter, Maybe someone has a good solution for this issue https://github.com/magento/magento2/issues/7199.
I would be appreciated if someone could share the temporary fix.