text:
Q: Get id and value of dynamically created elements I'm trying to get the ids of dynamically created elements, now these elements are in the form of input fields that can be modified by the user (the user enters the number of players then he gets input fields to type in their names), I'm trying to get their values as well, here is what I'm trying to do:
// Creating the input fields
const x = localStorage.getItem('playersNum');
const parentDiv = document.getElementById('player-list');
for (let i = 0; i < x; i++) {
  const newInput = document.createElement("INPUT");
  newInput.setAttribute("type", "text");
  newInput.setAttribute("class", "form-control");
  newInput.setAttribute("id", `player${i}`);
  newInput.setAttribute("placeholder", "Player's Name");

  parentDiv.appendChild(newInput);
}

// Trying to access them
const players = document.getElementById('player-list').children;
console.log(players.value);

A: There are a number of ways to go about it:

*

*Add the inputs to an array as you create them

*Add a unique class to each player input then use document.querySelectorAll('.className')

*Select the inputs based on inputs with ID starting with "player"

E.g. the following just adds "Player i" as the value of each input, but it could do other things.

// Creating the input fields
// const x = localStorage.getItem('playersNum');
let x = 3;
let parentDiv = document.getElementById('player-list');
for (let i = 0; i < x; i++) {
  let newInput = document.createElement("INPUT");
  newInput.setAttribute("type", "text");
  newInput.setAttribute("class", "form-control");
  newInput.setAttribute("id", `player${i}`);
  newInput.setAttribute("placeholder", "Player's Name");
  parentDiv.appendChild(newInput);
  parentDiv.appendChild(document.createElement('br'));
}

// Get a static NodeList of inputs with ID starting with "player"
let players = document.querySelectorAll('input[id^=player]');
// Iterate over list, adding a value
players.forEach((player, i) => player.value = 'Player ' + i);
div {border: 1px solid #aaaaaa}

You can reduce your code somewhat by:

*

*The default type is "text" so no need to set it

*Set attributes using property access

*Append inputs as they're created

so:
let newInput = parentDiv.appendChild(document.createElement("INPUT"));
newInput.class = 'form-control';
newInput.id = `player${i}`;
newInput.placeholder = 'Player\'s Name';

I'm not a fan of using a place holder as the label, much better to have an actual label and use the placeholder as a hint, so:
Name player 0:<input id="player0" class="form-control">

or similar.


text:
Q: How do I set up a web server out of my home? I want to run a web server from home, so my family, and clients can see what I am doing.  It would not run a large load, at most 2 or 3 users at a time.
I would like to know how to do it with a Windows machine running IIS.
I have a router from my cable company and it runs through a wireless router to the machine I would want to be a web server.

A: Many ISPs won't allow incoming traffic on port 80, so you might have to run on a nonstandard port. In either case, you can configure your router to forward traffic on port 80 (or whatever you use) to your server computer. Your server will need a static IP address on your LAN (rather than a DHCP assigned address).
If your ISP provides you with a dynamic IP, you'll probably want to use Dynamic DNS. Many routers have DynDns support built in.

A: You should be careful because in most cases, running a web server off of a residential internet connection is listed as a practice against the Terms of Service for many ISPs.

A: You may or may not be able to easily set up a web server at home that is accessible by the internet.  I know that my ISP specifically blocks port 80 inbound so that even if I allow the traffic myself it never gets to my router.  Assuming that this is not an issue what I would do is register with dyndns.org or something similar so that you're able to get to your host regardless of IP changes due to DHCP from the cable company. After that I'd configure the box with IIS and then set up port forwarding to go from the router to the web server on port 80.

A: Here are the basic steps. The specific details depend on what kind of router you have, but the concepts still apply:

*

*Install IIS on the machine you want to be a web server. It is okay to leave it on the standard port 80 in most cases (we'll remap the port later through the firewall since most ISPs disallow incoming traffic on port 80).

*Go to DynDns.org and create yourself a name which maps to your home IP address. This is important because your address will change from time to time (the "D" in DHCP) and you want to have a well-known external name to your home. Using DynDNS is pretty easy and they have good FAQs to help you. If your router supports DynDns automatically, then you will need to log onto your router and supply the dyndns.org username and password. If your router does not support DynDNS, they have a small utility that you should download and install on your IIS machine that runs all the time and detects when your public IP address changes and updates your dyndns host record.

*Logon to your router (typically a website located at 192.168.0.1, or whatever the first IP address of your IP range is). Set a fixed IP address for your IIS machine. Typically this is accomplished by assigning a fixed DHCP address to the MAC address of your IIS machine. Once you do that, your IIS machine will always fetch the same IP address when it requests one via DHCP

*Logon to your router. Add a "port mapping" (or sometimes called a "static route"), mapping public TCP port 8080 incoming to the IP address of your local IIS computer on port 80 (the default port). Note that some routers don't allow you change ports (often time, that's the "static route" option). In that case, you're going to want to reconfigure IIS to listen on port 8080 (or whatever port you want to make public) and just create a route from public TCP port 8080 to port 8080 on your IIS computer.
Obviously, there are several places where this can be misconfigured and troubleshooting is inevitable.

*

*Verify that IIS is working on your local network. Fire up your favorite browser and navigate to the local IP address and port of your IIS computer: http://192.168.0.5:80, or whatever is appropriate. Make sure it works. If not, fix it until it does.

*Verify that your DynDNS record is correctly mapping to your current public IP address. You can figure out your current public IP address by going to http://whatismyipaddress.com. Once you know that, open a command prompt and ping your public name ("ping longhorn213.homeip.net" or whatever name DynDNS gave you) and see if it works. The ping itself may be blocked (many routers block incoming pings), but you should still see the IP address that was looked-up. Make sure it matched your actual public address. If not, work with DynDNS org to get this working.

*If troubleshooting steps 1 and 2 are both working, then the problem is likely to be in the port mapping of your router. That's the hardest to troubleshoot usually. Often times routers have internal logs that you can turn on. Look for incoming traffic logs for the designated port and see what the router is doing with it. You may need to find a forum or support site for your specific router to get this working if you have problems.

A: While it is possible the usefulness is questionable. I have a WHS that runs a website for me to get remote access, runs just fine 24 x 7 x 365. However any actual website that I want to run I use a shared hosting provider.
Most of the time when you purchase a domain it will come with some free hosting. And unless you really want to concern yourself with doing System Administrator for a simple website running out of your house all the time, it is just not worth it.

A: There are several NAS appliances around now that also have web servers built in. some just for thier own admin pages but other with a full LAMP install and an area specifically for adding things like blogs etc. then, if you don't have the ISP issues mentioned, set it up as static IP or reserve a DHCP entry, forward incoming port 80 (or whatever you choose) to the appliance and you're done.
the appliance will usually have a Dynamic DNS updater client built in too

A: Note that IIS isn't your only option. Apache runs just fine on Windows, as does PHP, Perl, Python, and MySQL. If you're sufficiently tech savvy, Apache is a good option since it generally uses less resources than IIS (if you plan on using your system for other tasks at the same time).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot create Sql Compact DB programmatically I am trying to create an MVC4 application that affords the user to create a SQL Server Compact database on the fly.
Here is my code straight out of MSDN:
        string connStr = "Data Source = Test.sdf;";

        SqlCeEngine engine = new SqlCeEngine(connStr);
        engine.CreateDatabase();
        engine.Dispose();
        SqlCeConnection conn = null;

        try
        {
            conn = new SqlCeConnection(connStr);
            conn.Open();

            SqlCeCommand cmd = conn.CreateCommand();
            cmd.CommandText = "CREATE TABLE myTable (col1 int, col2 ntext)";
            cmd.ExecuteNonQuery();
        }

        catch { }

        finally
        {
            conn.Close();
        }

But I receive this error:
Access to the database file is not allowed. [ 1914,File name = Test.sdf,SeCreateFile ]
Running VS 2012 in Admin mode will sove the problem, but will it work once this MVC app is compiled?

A: Try with:
        string connStr = "Data Source = |DataDirectory|\Test.sdf;";


text:
Q: AutoMapper ProjectTo and EF Core Value Conversion for enum stored as string How can we have AutoMapper's ProjectTo work with EF Core's Value Conversion for an enum stored as a string?
The following code prints 0 instead of Blue
using Microsoft.EntityFrameworkCore;
using System.Linq;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using System;

await using var ctx = new MyDbContext(
    new DbContextOptionsBuilder()
    .UseSqlite("datasource=db.sqlite")
    .Options);
ctx.Database.EnsureDeleted();
ctx.Database.EnsureCreated();

ctx.House.Add(new House { Color = Color.Blue });
ctx.SaveChanges();

var config = new MapperConfiguration(_ => _.CreateMap<House, HouseDto>());
var house = ctx.House.ProjectTo<HouseDto>(config).Single();
Console.WriteLine(house.Color);

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions options) : base(options) { }
    public DbSet<House> House { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<House>().Property(_ => _.Color).HasConversion<string>();
    }
}
public class House
{
    public int Id { get; set; }
    public Color Color { get; set; }
}
public enum Color
{
    Blue = 1
}
public class HouseDto
{
    public ColorDto Color { get; set; }
}
public enum ColorDto
{
    Blue = 1
}

csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="AutoMapper" Version="10.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.13" />
  </ItemGroup>
</Project>


text:
Q: How to interpret/report a confidence interval for spearman rho I am doing my thesis in behavioural psychology and could use some stats guidance.
Being a behavioural study, I have a low-n but lots of frequency data.
I am using bootstrap statistics confidence interval for BCa at 95% because of a small sample size. I am trying to interpret confidence intervals for some CIs.
For CI's that cross over 0 e.g., 95% CI [-.03, .86], does this entirely invalidate my correlation coefficient even if it is p=.02? In a report, am I no longer able to call them statistically significant? How would I go about reporting these variables?
I also observed that many studies of my type did not report CI's, which is surprising. I assume they are quite important, especially in low-n. Is this correct?
Is the BCa method useful for small-n? Would there be a better bootstrap method?
Any help would be helpful! I am not sure where to start!
Thank you!


text:
Q: how do I convert classic reactjs to hooks? I am trying to covert the following to hooks, but however I am getting some issues to translate this line this.fetchPlaces = debounce(this.fetchPlaces, 200);  what is the exact match for hooks?
state = {
    q: '',
    places: [],
}
fetchPlaces(q) {
    get(`http://www.example.com/places/`, {
        params: {q}
    }).then(response => {
        this.setState({places: response.data.places});
    });
}
constructor(props) {
    super(props);
    this.fetchPlaces = debounce(this.fetchPlaces, 200);
}```

A: I'd recommend you to go through React Hooks' official guide, by the end of the guide lies a full example of how to use react hooks.
You should use useState hook to manage states and use useEffect hook to load data from network.
const Foo = () =>{
   // all hooks should be used in top level of the function component.
   // orders matter.
   // https://www.reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level
   const [q, setQ] = useState(''); // use hooks to declare q
   const [places, setPlaces] = useState([]); // use hooks to declare places

   // load data from network after React Nodes are rendered
   useEffect(()=>{
      get(`http://www.example.com/places/`, {
        params: {q}
      }).then(response => {
        setPlaces(response.data.places); // call setPlaces to set state
      });
   }
   ,[1]);  // passing a constant to the second Array parameter to strict the hook be called only for once, if left undefined, useEffect will be called after every render.
   return // React Nodes
}

I've used react hooks for a while, you can checkout my full example here.
https://github.com/ShinChven/bootcamp/blob/master/console/src/pages/Admin/Users/Users.tsx
I do not see why you should call network with debounce, but here's a post for that.
https://www.freecodecamp.org/news/debounce-and-throttle-in-react-with-hooks/

A: const fetchPlaces = (q) => {
    get(`http://www.example.com/places/`, {
        params: {q}
    }).then(response => {
        setPlaces(response.data.places);
    });
}

const deboucedFetchPlaces = debounce(fetchPlaces, 200)

Then in your code you can call deboucedFetchPlaces

A: You can do it like this.
const fetchMore = _.debounce(fetchPlaces, 500);

fetchPlaces(q) {
    get(`http://www.example.com/places/`, {
        params: {q}
    }).then(response => {
        this.setState({places: response.data.places});
    });
}

fetchMore();


text:
Q: Iteratee input from Standard IO I'm using scalaz 6.0 with scala.  I'm using iteratees to read from an input stream.
Here's the simple file called simple.txt I have.

This
  Is
  A test

My iteratee will build up an io monad to print the lines
def printLines: IterV[String, IO[Unit]] = {
  def step(currentIO: IO[Unit])(input: Input[String]): IterV[String, IO[Unit]] =
    input match {
      case El(x) => Cont(
          step(
              currentIO.flatMap(_ => putStrLn(x))
          )
      )
      case IterV.Empty() => Cont(step(currentIO))
      case EOF() => Done(currentIO, EOF[String])
    }
  Cont(step(io()))
}

When I use the enumeratorM
getFileLines(new File(".../simple.txt"))(printLines).flatMap(_.run).unsafePerformIO

I retrieve the correct output.
When I try to use
getLines(printLines).flatMap(_.run).unsafePerformIO

I only get "This" back to the console.  getLines uses the standard input stream. I've added debug statements to the iteratee and getLines seems to send EOF() after the first line and I haven't been able to resolve it.

A: This is a bug in the definition of getReaderLines. Compare the current version:
/** Enumerate the lines from a BufferedReader */
def getReaderLines(r: => BufferedReader): EnumeratorM[IO, String] =
  new EnumeratorM[IO, String] {
    def apply[A](it: IterV[String, A]) = {
      def loop(i: IterV[String, A]): IO[IterV[String, A]] = i.fold(
        done = (_,_) => io { i },
        cont = k => for {
          s <- rReadLn(r)
          a <- s.map(l => loop(k(El(l)))).getOrElse(io(i))
        } yield a
      )
      loop(it)
    }
  }

With one that works:
/** Enumerate the lines from a BufferedReader */
def getReaderLines(r: => BufferedReader): EnumeratorM[IO, String] =
  new EnumeratorM[IO, String] {
    lazy val reader = r

    def apply[A](it: IterV[String, A]) = {
      def loop(i: IterV[String, A]): IO[IterV[String, A]] = i.fold(
        done = (_,_) => io { i },
        cont = k => for {
          s <- rReadLn(reader)
          a <- s.map(l => loop(k(El(l)))).getOrElse(io(i))
        } yield a
      )
      loop(it)
    }
  }

The issue is that r is a by-name parameter, which means that given the way that getLines is defined, the current version creates a new reader wrapping standard input on every loop.
Until this gets fixed in the library (and I doubt there'll be much of a rush to get 6.0.5 out the door), the simplest fix is to write your own getLines:
val getLines: EnumeratorM[IO, String] = {
  val r = new BufferedReader(new InputStreamReader(System.in))
  getReaderLines(r)
}

This will work as expected.


text:
Q: An R function to perform t-test to compare means and output result in a tidy way I have dataframes with the following structure (one character and 3 numeric), but the names of numeric columns varies:
structure(list(treatment = c("product", "product", "product", "product", "product", "control", "control", "control", "control", "control"), t0 = 1:10, t1 = c(1, 3, 5, 7, 9, 11, 13, 15, 17, 19), t2 = c(1, 4, 7, 10, 13, 16, 19, 22, 25, 28)), class = c("tbl_df",  "tbl", "data.frame"), row.names = c(NA, -10L))

 treatment    t0    t1    t2
   <chr>     <int> <dbl> <dbl>
 1 product       1     1     1
 2 product       2     3     4
 3 product       3     5     7
 4 product       4     7    10
 5 product       5     9    13
 6 control       6    11    16
 7 control       7    13    19
 8 control       8    15    22
 9 control       9    17    25
10 control      10    19    28

I would like to set a function to be able to perform t-test and compare means (t1 vs t0 and t2 vs t0). However this function needs to be able to work in all dataframes I have, that is, including those where numeric columns are not called t0, t1, t2. So I thought it might work by calling the column numbers inside the function, but t.test function seems to not accept that. In addition, it would be nice to have the results of the function in a tidy way. In the end, it would work like:
my_ttest_func(df)

 t1_t0        t     estimate   p_value
  <chr>     <dbl>    <dbl>     <dbl>
1 product   5.94     7.19    0.0000104
2 control   1.98     2.32    0.0327

 t2_t0        t     estimate  p_value
  <chr>     <dbl>    <dbl>    <dbl>
1 product   4.20     5.86   0.000339
2 control   1.95     2.55   0.0343

I got results close to the way I expect by pivoting the df to a long format but only works by calling the levels I want to compare. Also gives only one comparison, so I should call the function two times. As the structure of my dataframes are always the same I could put the following code inside my_ttest_func() but need to refer to time levels in a universal way.
df %>% pivot_longer(!treatment, names_to = "time", values_to = "values") %>%
  group_by(treatment) %>%
  summarise(across(.cols = values, ~ list(broom::tidy(t.test(.[time == "t2"],
                                                             .[time == "t0"],
                                                             alternative = "greater",
                                                             paired=TRUE)) %>%
             select(statistic, estimate, p.value)))) %>%
  unnest(values)

  treatment statistic estimate  p.value
  <chr>         <dbl>    <dbl>    <dbl>
1 control        9.90       14 0.000292
2 product        2.83        4 0.0237

Thanks in advance

A: You could use a nested map-function:
library(purrr)
library(dplyr)

df %>%
  split(~treatment) %>%
  map_dfr(
    ~.x %>%
      summarise(
        across(
          3:4,
          ~t.test(.x,
                  !!sym(colnames(df)[2]),
                  alternative = "greater",
                  paired=TRUE) %>%
            broom::tidy() %>%
            select(statistic, estimate, p.value)
          )
        ) %>%
        map_dfr(bind_rows, .id = "name"),
    .id = "treatment") %>%
  arrange(name, treatment)

This returns
# A tibble: 4 x 5
  treatment name  statistic estimate  p.value
  <chr>     <chr>     <dbl>    <dbl>    <dbl>
1 control   t1         9.90        7 0.000292
2 product   t1         2.83        2 0.0237
3 control   t2         9.90       14 0.000292
4 product   t2         2.83        4 0.0237

which is not exactly your desired output but something you could work on.
Since your t0 column is always in second place, we could use the column name as an input for t.test inside the summarise(across(...)) construct.
The new column name contains the variable t0 is tested with.


text:
Q: What happens when unplugging a network cable in 18.04? How do I replicate this behaviour in 20.04? I understand that network management changed between 18.04 and 20.04.
For connecting to a special network I have a script that sets up multiple vlans and virtual interfaces using a mix of ifconfig, vconfig, and ip. (Yes, those first 2 are now deprecated. I don't maintain this script.). I became used to the effects of this script being undone when the network cable is unplugged in 18.04. After unplugging the virtual interfaces are no longer present in the output of ifconfig.
However in 20.04 the changes made by the script persist when the network cable is unplugged and are preserved until rebooting. How can I achieve effects similar to 18.04 in 20.04? What all exactly gets cleared in 18.04?
I can manually run sudo ip link del dev eth0.2 and so on to remove the virtual interfaces. What else do I need to clear?


text:
Q: invalid syntax while importing mne package in python/Atom I'd like to know if any of you could help me with this issue.
I am trying to get to use the MNE package in python to analyze EEG data. I run on Linux 18.04.
I installed Atom last version and MNE by PIP + all the scientific packages(numpy,pandas,etc).
I opened Atom and typed:
    import mne

Then I ran it and I obtained the following error:
Traceback (most recent call last):
  File "/tmp/atom_script_tempfiles/9b375e90-191b-11ea-b755-49276afb2bfa", line 3, in <module>
    import mne
  File "/home/vmh/.local/lib/python2.7/site-packages/mne/__init__.py", line 22, in <module>
    from .utils import (set_log_level, set_log_file, verbose, set_config,
  File "/home/vmh/.local/lib/python2.7/site-packages/mne/utils/__init__.py", line 19, in <module>
    from .config import (set_config, get_config, get_config_path, set_cache_dir,
  File "/home/vmh/.local/lib/python2.7/site-packages/mne/utils/config.py", line 539
    print(out, end='', file=fid)
                  ^
SyntaxError: invalid syntax

Does anybody know how to fix it?
Thanks in advance.

A: The statement in the last part the traceback print(out, end='', file=fid) isn't compatible in python 2.7.
Also from the projects github page (https://github.com/mne-tools/mne-python)

Note that MNE-Python 0.17 was the last release to support Python 2. MNE-Python 0.18 only works under Python 3, and MNE-Python 0.19 requires Python 3.5 or higher.

Since python 2.7 will be unsupported soon (https://pythonclock.org), I would suggest you update to python 3. If you cannot upgrade to python 3, use MNE version 0.17 instead.

A: This error is resolved by using python3.


text:
Q: Service starts on boot when it should not I have a toggle, when clicked a notification with battery level starts. This is a service that register a broadcast receiver. When the toggle is in false state the notification disappear. Well, even if the state is false if i boot the device the notification, so the service, starts. I can't understand the problem but i i saw in the logCat that when i turn off the toggle it displays this error:
12-18 14:15:03.149: E/ActivityThread(337): Service com.dd.androreboot.NotificationService has leaked IntentReceiver com.dd.androreboot.NotificationService$1@44eecef0 that was originally registered here. Are you missing a call to unregisterReceiver()?
12-18 14:15:03.149: E/ActivityThread(337): android.app.IntentReceiverLeaked: Service com.dd.androreboot.NotificationService has leaked IntentReceiver com.dd.androreboot.NotificationService$1@44eecef0 that was originally registered here. Are you missing a call to unregisterReceiver()?
12-18 14:15:03.149: E/ActivityThread(337):  at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:805)
12-18 14:15:03.149: E/ActivityThread(337):  at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:606)
12-18 14:15:03.149: E/ActivityThread(337):  at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1430)
12-18 14:15:03.149: E/ActivityThread(337):  at android.app.ContextImpl.registerReceiver(ContextImpl.java:1410)
12-18 14:15:03.149: E/ActivityThread(337):  at android.app.ContextImpl.registerReceiver(ContextImpl.java:1404)
12-18 14:15:03.149: E/ActivityThread(337):  at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:467)
12-18 14:15:03.149: E/ActivityThread(337):  at com.dd.androreboot.NotificationService.onCreate(NotificationService.java:105)
12-18 14:15:03.149: E/ActivityThread(337):  at android.app.ActivityThread.handleCreateService(ActivityThread.java:2572)
12-18 14:15:03.149: E/ActivityThread(337):  at android.app.ActivityThread.access$1800(ActivityThread.java:135)
12-18 14:15:03.149: E/ActivityThread(337):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
12-18 14:15:03.149: E/ActivityThread(337):  at android.os.Handler.dispatchMessage(Handler.java:102)
12-18 14:15:03.149: E/ActivityThread(337):  at android.os.Looper.loop(Looper.java:136)
12-18 14:15:03.149: E/ActivityThread(337):  at android.app.ActivityThread.main(ActivityThread.java:5017)
12-18 14:15:03.149: E/ActivityThread(337):  at java.lang.reflect.Method.invokeNative(Native Method)
12-18 14:15:03.149: E/ActivityThread(337):  at java.lang.reflect.Method.invoke(Method.java:515)
12-18 14:15:03.149: E/ActivityThread(337):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
12-18 14:15:03.149: E/ActivityThread(337):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
12-18 14:15:03.149: E/ActivityThread(337):  at dalvik.system.NativeStart.main(Native Method)

Could be the problem? This is the service:
public class NotificationService extends Service {
    public static final int FM_NOTIFICATION_ID = 1;
    public static int SHOW_TEMP = 1; // whether to show temperature in status bar
    public static int SHOW_HEALTH = 1; // whether to show battery health in status bar
    public static int SHOW_VOLTAGE = 1; // whether to show voltage in status bar
    public static int SHOW_VOLTAGE_MILLIVOLT = 1; // whether to show millivolts in status bar
    public static int SHOW_STATUS = 1; // whether to show Charging/Not Charging, etc
    public static int SHOW_PERIODIC_TOASTS = 10; // whether to show periodic toast messages with charge level

    @Override
    public IBinder onBind(Intent arg0) {
          return null;
    }

    private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
        @SuppressWarnings({ "unused" })
        @Override
        public void onReceive(Context context, Intent intent) {
            int level = intent.getIntExtra("level", 0);
            int temp = intent.getIntExtra("temperature", 0) / 10;
            int voltage = intent.getIntExtra("voltage", 0);
            int status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
            int scale = intent.getIntExtra("scale", -1);
            int health = intent.getIntExtra("health", -1);
            boolean isPresent = intent.getBooleanExtra("present", false);
            String strStatus;
            String strHealth = "Health: ";

            // Calculate level
            if (level >= 0 && scale > 0) {
                level = (level * 100) / scale;
            }

            if(SHOW_PERIODIC_TOASTS == 10){
                Toast.makeText(context, String.valueOf(level + "%"), Toast.LENGTH_SHORT).show();
            }

            // Determine battery status
            switch(status){
                case BatteryManager.BATTERY_STATUS_CHARGING : strStatus = getResources().getString(R.string.charging); break;
                case BatteryManager.BATTERY_STATUS_DISCHARGING : strStatus = getResources().getString(R.string.discharging); break;
                case BatteryManager.BATTERY_STATUS_NOT_CHARGING : strStatus = getResources().getString(R.string.discharging); break;
                case BatteryManager.BATTERY_STATUS_FULL : strStatus = "Full"; break;
                default : strStatus = "Status Unknown";
            }

            // Determine battery health
            switch(health){
                case BatteryManager.BATTERY_HEALTH_COLD : strHealth += "Cold"; break;
                case BatteryManager.BATTERY_HEALTH_DEAD : strHealth += "Dead"; break;
                case BatteryManager.BATTERY_HEALTH_GOOD : strHealth += "Good"; break;
                case BatteryManager.BATTERY_HEALTH_OVERHEAT : strHealth += "Overheat"; break;
                case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE : strHealth += "Over Voltage"; break;
                case BatteryManager.BATTERY_HEALTH_UNKNOWN : strHealth += "Unknown"; break;
                case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE : strHealth += "Unspc Failure"; break;
                default : strStatus = "Health Unknown";
            }

            // The initial call out notification
            String NotificationTicket = getResources().getString(R.string.notifistart);

            // The status user sees upon pulling notification bar down
            String NotificationTitle = level + "%";
            if(SHOW_STATUS == 1){ NotificationTitle += " "+ getResources().getString(R.string.and) +" " + strStatus; }

            // The content show underneath the battery percentage
            String NotificationContent = "";
            if(SHOW_TEMP == 1) { NotificationContent += temp + "°C  "; }
            if(SHOW_VOLTAGE == 1) {
                if(SHOW_VOLTAGE_MILLIVOLT == 1){
                    NotificationContent += voltage + "mV  ";
                } else {
                    NotificationContent += voltage / 1000 + "V  ";
                }
            }
            if(SHOW_HEALTH == 1) { NotificationContent += strHealth; }

            Bitmap largeIcon = (Bitmap)BitmapFactory.decodeResource(context.getResources(), R.drawable.notification);

            addNotification(NotificationTitle, NotificationContent, NotificationTicket, largeIcon, level);
        }
    };

    @Override
    public void onCreate() {
          super.onCreate();
          this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

    @Override
    public void onDestroy() {
          Toast.makeText(this, getResources().getString(R.string.notifistop), Toast.LENGTH_SHORT).show();
          removeNotification();
          super.onDestroy();
    }

    // Start notification
    private void addNotification(String title, String body, String ticker, Bitmap largeIcon, int iconLevel) {
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.levellist, iconLevel)
                .setLargeIcon(largeIcon)
                .setContentTitle(title)
                .setContentText(body)
                .setOngoing(true)
                .setNumber(iconLevel)
                .setTicker(ticker);

        Intent notificationIntent = new Intent(this, MainNavDrawer.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);

        // Add as notification
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(FM_NOTIFICATION_ID, builder.build());
    }

    // Remove notification
    private void removeNotification() {
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(FM_NOTIFICATION_ID);
    }
}

The 105 line is:
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

A: For Service:
You should unregister the reciever in onDestroy()
@Override
    protected void onDestroy() {
    unregisterReceiver(mBatInfoReceiver);
   }

For Activity:
Register the reciever in onResume()
@Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

You should unregister the reciever in onpause()
@Override
    protected void onPause() {
    unregisterReceiver(mBatInfoReceiver);
   }


text:
Q: P/Invoking a defined-length C char* array in a struct I've looked for a while, but found no article that provides an answer to this so hopefully it isn't a duplicate.
I've been doing some P/Invoking with a struct, which is nice and everything, but then I saw this:
char* infoString[SIDTUNE_MAX_CREDIT_STRINGS];
where SIDTUNE_MAX_CREDIT_STRINGS is defined as 10.
So inlining everything, the struct member is defined as:
char* infoString[10]
Now this is where it gets slightly different from the other issues I've looked through to try and solve this.
The char* array contains pointers to other C strings.
In this specific case, only 3 of the indexes are used while the rest are reserved. The indexes are as follows:

*

*infoString[0] = Song title

*infoString[1] = Artist name

*infoString[2] = Copyright/Publisher.
How would I P/Invoke this in a way I can access each of those strings from C#? Making C++ functions that return each one individually is not an option.

A: Assuming the function something like GetSongInfo(int songID, LPInfostring songinfo), you can define the struct as having an array of IntPtr.  However, you will have to watch out for memory leaks as the calling function may expect you to free the memory allocated for the strings returned.
target.h:
typedef struct SongInfo
{
    char* infoString[10];
} *LPSongInfo;

extern "C" __declspec(dllexport) int GetSongInfo(int songID, LPSongInfo info);

target.c:
extern "C" __declspec(dllexport) int GetSongInfo(int songID, LPSongInfo demo)
{
    demo->infoString[0] = "Hello world";
    demo->infoString[1] = "Hello 1";
    demo->infoString[2] = "Hello 2";

    return TRUE;
}

P/Invoke Signature:
[DllImport("PInvokeDll.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int GetSongInfo(int songID, out SongInfo ts);

[StructLayout(LayoutKind.Sequential)]
struct SongInfo
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
    public IntPtr[] infoString;
};

Example Use:
SongInfo siStruct;
var num2 = GetSongInfo(101, out siStruct);

// copy the results to managed memory
var results = new string[10];
for (int i = 0; i < 10; i++)
{
    if (siStruct.infoString[i] != IntPtr.Zero)
    {
        // if these were Unicode strings, this would change to PtrToSTringUni
        results[i] = Marshal.PtrToStringAnsi(siStruct.infoString[i]);
    }
}

// results now holds the .Net strings
// if there is an expectation of the caller to free the struct
// strings, that should happen now

As an alternative for functions which do not allocate memory, you can use a struct like the following to marshal the strings automatically.  However, it will free the unmanaged memory unconditionally, which may or may not be desirable.
[StructLayout(LayoutKind.Sequential)]
struct SongInfo2
{
    [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.LPStr, SizeConst = 10)]
    public string[] infoString;
};


text:
Q: When I create any object in Parse, the createdAt attribute is not the correct time of creation. I just created a user in Parse.com and the createdAt attribute is actually 7 hours ahead of the actual time of creation of that object. This is happening for any object that's being created. How can I fix this issue in a Parse? The createdAt attribute is really important to the functionality of my application.

A: The 'createdAt' field is supposed to contain the right value, unless they have a specific bug, in which case, it will probably be resolved shortly. The more likely scenario, is that the 'createdAt' field contains the right value, only in a different time zone than the one you expected, which gives you the impressions that it's the wrong value. Can you please try to test that? For example, create three different objects at three different times, and see if the delta between the time you created them and the 'createdAt' time match? Maybe it's always off by 2 hours, due to a different timezone than the one you expected.


text:
Q: React: TypeError Cannot read properties of undefined (reading '0') I am working on a React App, and i'm trying to get some data using an axios GET request from my node backend.
the Api Endpoint i'm currently using that regard this problem is the following:
// NodeJS Backend
app.get('/v1/companys/user/:user_uuid', verify, (req, res) => { // GET - Company by User UUID
    const selectQuery = 'SELECT * FROM companys WHERE uuid = (SELECT company_uuid FROM users WHERE uuid = ?)';
    connection.query(selectQuery, [req.params.user_uuid], (err, results) => {
        if(err) {
            res.send(err)
        } else if (results.length === 0) {
            res.json({status: 404, message: 'Company not found'})
        } else {
            res.json({data: results})
        }
    });
});

This is my Front End:
// ReactJS FrontEnd
const companyLogo = userCompany ? userCompany.logo_url : null;

  console.log(userCompany);

  useEffect(() => {
    const getUserCompany = async () => {
      try {
        await axios.get(process.env.REACT_APP_API_URL + 'companys/user/' + userUuid).then((response) => {
          console.log("response "+ response);
          let res = response.data.data[0];
          console.log(res);
          setUserCompany(res);
        });
      } catch (error) {
        console.log(error);
      }
    };
    getUserCompany();
  }, [userUuid]);

There app works fine, but on the console the following error appear:
The object below the error is in fact the thing that i need (companyLogo)
I was wondering if someone know what am I doing wrong on my frontend to fix the TypeError.
Thanks for the help!

A: If you use optional chaining (?.) to catch possible null/undefined values, you'll most likely fix the issue.
So like this: let res = response.data.data?.[0];


text:
Q: TeamCity REST API: Who broke the build? In our office we use a custom Geckoboard to display information about our current build status from our TeamCity 8 build server.
We display recent check-ins/changes, using the following REST query: http://teamcity.internal.com:8080/httpAuth/app/rest/changes?project:ProjectName&locator=count:10
We also calculate the last time the build was broken with this REST query: http://teamcity.internal.com:8080/httpAuth/app/rest/builds?locator=project:ProjectName
However what we've not just been able to do is link the two.
In other words:

*

*For recent changes to determine if the checkin lead to a broken build

*For the last time the build was broken determine who made that checkin

A: Based on the source code here and documentation here
I believe you want something like the following
http://teamcity.internal.com:8080/httpAuth/app/rest/changes?locator=build:(status:FAILED,project:ProjectName,lookupLimit:1)

This should return the changes associated with the last FAILED build, I haven't tested because I don't use TeamCity.
Also see the following StackOverflow question in order to get changes for a specific build.


text:
Q: Hacking the WordPress Category Widget The default WordPress categories widget does not allow excluding named categories.
I've created a plugin which creates adds a Customized category widget to the "Available Widgets" listing which gives me some control over the items I want to exclude. Code is below...
<?php
/*
Plugin Name: Custom Categories Widget
Plugin URI: http://mysite.com
Description: Removes the Specified Categories from the Default Categories Listing
Author: Me
Version: 1.0
Author URI: http://mysite.com
*/

function widget_my_categories()
{
    wp_list_categories('exclude=1');
}

function my_categories_init()
{
  register_sidebar_widget(__('Custom Categories Widget'), 'widget_my_categories');
}

add_action("plugins_loaded", "my_categories_init");
?>

However, I want the generated code to emulate the same look and feel as the default categories widget (ie, the word "categories" appears as a bullet in my widget, but as an h4 level heading element in the default categories widget. I want the same structure to be applied to my custom widget as the default categories widget has.
I'd also like to give the user the options to specify the title of the categories listing (just as they can do in the default categories widget).
btw, I'm using id 1 which is the default "uncategorized" category and assigning items to that category that I don't want to appear in the listing.
Any help much appreciated! :)

A: The code for the categories widget is in wp-includes/default_widgets.php. Just copy the WP_Widget_Categories class, rename it and add your extra arguments to the wp_list_categories call.
Alternatively you can modify the arguments for the wp_list_categories call in the widget using the widget_categories_args filter, although that will apply to all instances of the widget.


text:
Q: java - method and passing variable from jInternalFrame to jFrame and I have the following problem.
i am new in java and i am trying to send a variable which is user_id, from JInternalFrame to JFrame.
I can't use constructor because JFrame is the main program activated at startup and containing jDesktoPane
so i was trying to use the methods, however, can't do it (i posted the two methods, both of which I tried but did not work)
Method A)
Code in jFrame (Main_window)
public javax.swing.JTextField getID() {
  return jTextField_id;
}

public void setID(javax.swing.JTextField ID)
{
jTextField_id = ID;
}

code in jInternalFrame
Main_window send = new Main_window();
send.getID().setText("123");

Method B)
Code in jFrame (Main_window)
USER_ID is a variable accesible in any place of jFrame
public void setID(String ID)
{
USER_ID = ID;
}

code in jInternalFrame
Main_window send = new Main_window();
send.setID("123");

both method don't change anything but have no errors in compilation
if there is any other way of doing it pls tell me :)
sorry for my language and grammar.
if this help i use Eclipse compilator
this code worked for me, ty for help
public void set_ID(String ID)
{
    Test_JF mainWindow = (Test_JF) this.getTopLevelAncestor();;
    mainWindow.setID(ID);
}

activated by set_ID("1234");

A: Try this in your JInternalFrame class:
JFrame mainWindow = (JFrame)this.getTopLevelAncestor();
mainWindow.setID("123");

A: ok so here is smaller version of my program
"Test_JF" is a main JFrame and "Test_JIF" is a JInternalFrame
here is TestJF
public class Test_JF extends JFrame {

private JPanel contentPane;
private JTextField user_id;

String USER_ID;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Test_JF frame = new Test_JF();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public Test_JF() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 750, 500);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    user_id = new JTextField();
    user_id.setBounds(338, 11, 86, 20);
    contentPane.add(user_id);
    user_id.setColumns(10);

    JButton button_user_id = new JButton("fill user id");
    button_user_id.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            user_id.setText(USER_ID);
        }
    });
    button_user_id.setBounds(239, 10, 89, 23);
    contentPane.add(button_user_id);

    JDesktopPane desktopPane = new JDesktopPane();
    desktopPane.setBounds(10, 56, 714, 395);
    contentPane.add(desktopPane);

    addWindowListener(new WindowAdapter() {
        @Override
        public void windowOpened(WindowEvent arg0) {
            Test_JIF Open = new Test_JIF();
            desktopPane.add(Open);
            Open.show();
        }
    });

}

public void setID(String ID)
{
USER_ID = ID;
}}

here is TestJIF
public class Test_JIF extends JInternalFrame {

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Test_JIF frame = new Test_JIF();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public Test_JIF() {
    Test_JF mainWindow = (Test_JF)this.getTopLevelAncestor();
    setBounds(100, 100, 328, 199);
    getContentPane().setLayout(null);

    JButton button_send = new JButton("New button");
    button_send.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            mainWindow.setID("123");
        }
    });
    button_send.setBounds(111, 73, 89, 23);
    getContentPane().add(button_send);

}}

i clear imports here(on web) so it will be cleaner


text:
Q: Warning detected during compilation When compiling my document, I have several warnings which are detected but I do not understand them all
my preamble :
  \documentclass{article}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[french]{babel}
\usepackage[left=1.5cm, right=1.5cm, top=1.5cm, bottom=1.5cm]{geometry}

\usepackage{array}
\usepackage{enumitem}  %pour l'option [resume] qui permet de reprendre la numérotation
\usepackage{pifont}
\usepackage{tabularx}
\usepackage{tabulary}
\usepackage[export]{adjustbox}
\usepackage{verbatim}
\usepackage{multicol}
\usepackage{appendix}

\usepackage{graphicx}
\usepackage{picinpar}

\usepackage[european, straightvoltages]{circuitikz}
\usepackage{siunitx}
\usetikzlibrary{babel}
\renewcommand{\thesection}{\Roman{section}}
\renewcommand{\thesubsubsection}{\Roman{section}.\arabic{subsection}.\alph{subsubsection}}

*

*LaTeX Font Warning: Font shape `T1/cmr/m/n' in size <6.49994> not available
(Font)              size <6> substituted on input line 908.
\item '{A} l'aide du 1\ier{} volume équivalent $V_{eq1}$, calculer la concentration en acide chlorhydrique.

*LaTeX Font Warning: Size substitutions with differences
(Font)              up to 0.49994pt have occurred.
Can you help me to understand them (and solve them).
Thanks


text:
Q: In C, what does a variable declaration with two asterisks (**) mean? I am working with C and I'm a bit rusty.  I am aware that * has three uses:

*

*Declaring a pointer.

*Dereferencing a pointer.

*Multiplication

However, what does it mean when there are two asterisks (**) before a variable declaration:
char **aPointer = ...

Thanks,
Scott

A: It declares aPointer as a pointer to a pointer to char.
Declarations in C are centered around the types of expressions; the common name for it is "declaration mimics use".  As a simple example, suppose we have a pointer to int named p and we want to access the integer value it's currently pointing to.  We would dereference the pointer with the unary * operator, like so:
x = *p;

The type of the expression *p is int, so the declaration of the pointer variable p is
int *p;

In this case, aPointer is a pointer to a pointer to char; if we want to get to the character value it's currently pointing to, we would have to dereference it twice:
c = **aPointer;

So, going by the logic above, the declaration of the pointer variable aPointer is
char **aPointer;

because the type of the expression **aPointer is char.
Why would you ever have a pointer to a pointer?  It shows up in several contexts:

*

*You want a function to modify a pointer value; one example is the strtol library function, whose prototype (as of C99) is

long strtol(const char * restrict str, char ** restrict ptr, int base);

The second argument is a pointer to a pointer to char; when you call strtol, you pass the address of a pointer to char as the second argument, and after the call it will point to the first character in the string that wasn't converted.

*Remember that in most contexts, an expression of type "N-element array of T" is implicitly converted to type "pointer to T", and its value is the address of the first element of the array.  If "T" is "pointer to char", then an expression of type "N-element array of pointer to char" will be converted to "pointer to pointer to char".  For example:

    void foo(char **arr)
    {
      size_t i = 0;
      for (i = 0; arr[i] != NULL; i++)
        printf("%s\n", arr[i]);
    }

    void bar(void)
    {
      char *ptrs[N] = {"foo", "bar", "bletch", NULL};
      foo(ptrs); // ptrs decays from char *[N] to char **
    }

*You want to dynamically allocate a multi-dimensional array:

#define ROWS ...
#define COLS ...
...
char **arr = malloc(sizeof *arr * ROWS);
if (arr)
{
  size_t i;
  for (i = 0; i < ROWS; i++)
  {
    arr[i] = malloc(sizeof *arr[i] * COLS);
    if (arr[i])
    {
      size_t j;
      for (j = 0; j < COLS; j++)
      {
        arr[i][j] = ...;
      }
    }
  }
}

A: It means that aPointer points to a char pointer.
So
aPointer: pointer to char pointer

*aPointer :pointer to char

**aPointer: char

An example of its usage is creating a dynamic array of c strings
char **aPointer = (char**) malloc(num_strings);
aPointer gives you a char, which can be used to represent a zero-terminated string.
*aPointer = (char*)malloc( string_len + 1); //aPointer[0]
*(aPointer + 1) = (char*)malloc( string_len + 1); //aPointer[1]

A: It declares a pointer to a char pointer.
The usage of such a pointer would be to do such things like:
void setCharPointerToX(char ** character) {
   *character = "x"; //using the dereference operator (*) to get the value that character points to (in this case a char pointer
}
char *y;
setCharPointerToX(&y); //using the address-of (&) operator here
printf("%s", y); //x

Here's another example:
char *original = "awesomeness";
char **pointer_to_original = &original;
(*pointer_to_original) = "is awesome";
printf("%s", original); //is awesome

Use of ** with arrays:
char** array = malloc(sizeof(*array) * 2); //2 elements

(*array) = "Hey"; //equivalent to array[0]
*(array + 1) = "There";  //array[1]

printf("%s", array[1]); //outputs There

The [] operator on arrays does essentially pointer arithmetic on the front pointer, so, the way array[1] would be evaluated is as follows:
array[1] == *(array + 1);

This is one of the reasons why array indices start from 0, because:
array[0] == *(array + 0) == *(array);

A: C and C++ allows the use of pointers that point to pointers (say that five times fast). Take a look at the following code:
char a;
char *b;
char **c;

a = 'Z';
b = &a; // read as "address of a"
c = &b; // read as "address of b"

The variable a holds a character. The variable b points to a location in memory that contains a character. The variable c points to a location in memory that contains a pointer that points to a location in memory that contains a character.
Suppose that the variable a stores its data at address 1000 (BEWARE: example memory locations are totally made up). Suppose that the variable b stores its data at address 2000, and that the variable c stores its data at address 3000. Given all of this, we have the following memory layout:
MEMORY LOCATION 1000 (variable a): 'Z'
MEMORY LOCATION 2000 (variable b): 1000 <--- points to memory location 1000
MEMORY LOCATION 3000 (variable c): 2000 <--- points to memory location 2000

A: This is a pointer to a pointer to char.


text:
Q: How do I generate a string like a Api key? I am making an API & seeking help to find a way to generate a random string that will work as an API key.
Let's say you are making an account with News API. You signed up and you would get an API key. How would you generate that same key, but randomly?
Thanks!

A: You can use the UUID package or generate-api-key package to generate a random string.


text:
Q: Update cache when query string change in workbox routing Really don't find an answer to my question :(
I created a worker service like this to manage my css stored on a CDN
workbox.routing.registerRoute(
    new RegExp('https://static.domain.com/css/.*'),
    workbox.strategies.staleWhileRevalidate({cacheName: 'static-css-v0'}),
);

My url are like this, the query string is used to reload the style
https://static.domain.com/css/style.css?1

I can see that my css is well saved in the cache static-css-v0 with the name
/css/style.css

But my question, is my style well updated when the url is changed to https://static.domain.com/css/style.css?1 ?
What happen in this case, is the file in the cache updated?
Not clear in the documentation, I don't see sample with query string :(
Thanks for your comments

A: maybe this will help you "ignoresearch : true"
https://github.com/GoogleChrome/workbox/issues/805


text:
Q: Find and delete folder + files within I got a directory structure like this:
/backups/
/backups/db/
/backups/db/01.01.2020/domain_a.sql.gz, domain_b.sql.gz, domain_c.sql.gz
/backups/db/02.01.2020/domain_a.sql.gz, domain_b.sql.gz, domain_c.sql.gz
/backups/db/03.01.2020/domain_a.sql.gz, domain_b.sql.gz, domain_c.sql.gz
/backups/db/04.01.2020/domain_a.sql.gz, domain_b.sql.gz, domain_c.sql.gz

Now Im running this command:
find /backups/db/ -mindepth 1 -mtime +2 -delete && rsync ...

When I execute this command directly in the shell, it works and the result is:
/backups/
/backups/db/
/backups/db/03.01.2020/domain_a.sql.gz, domain_b.sql.gz, domain_c.sql.gz
/backups/db/04.01.2020/domain_a.sql.gz, domain_b.sql.gz, domain_c.sql.gz

If I run this command by a cronjob, the directories wont be deleted and the result is:
/backups/
/backups/db/
/backups/db/01.01.2020/
/backups/db/02.01.2020/
/backups/db/03.01.2020/domain_a.sql.gz, domain_b.sql.gz, domain_c.sql.gz
/backups/db/04.01.2020/domain_a.sql.gz, domain_b.sql.gz, domain_c.sql.gz

This happens cause find first delete the files within these (2) folders and this action change the date of these folders, so that they dont match anymore the -mtime +2.
Is there any solution? I mean I could go with something like this, but I usually dont like to work with rm if its not necessary.
find /backups/db/ -mindepth 1 -mtime +6 -type d -exec rm -r {} +

find (GNU findutils) 4.7.0-git

A: I would suggest that you do this in two steps, and that you only delete files in the first step:
find /backups/db -mindepth 1 -type f -mtime +2 -delete

Then delete empty directories:
find /backups/db -mindepth 1 -type d -empty -delete

This way you don't compare timestamps on directories at all.
You could possibly combine the two operations into
find /backups/db -mindepth 1 \
    \( \( -type f -mtime +2 \) -o \
       \( -type d -empty    \) \) -delete

... but you may want to check without -delete that it does the correct thing first.


text:
Q: WPF DataGrid SelectedRow only text in data cells is highlighted I have a simple DataGrid in my WPF app (Window) and when a row is selected only the text in the data cells of the row is highlighted (background color) and not the whole row.
How can I get the whole row to be have a background color when highlighted?

XAML for the DataGrid:
<DataGrid Name="dgPodatki"
          ItemsSource="{Binding}"
          AutoGenerateColumns="False"
          SelectionMode="Single"
          SelectionChanged="dgPodatki_SelectionChanged"
          MouseDoubleClick="dgPodatki_MouseDoubleClick"
          CanUserAddRows="false"
          IsReadOnly="True">
    <DataGrid.ColumnHeaderStyle>
        <Style TargetType="{x:Type DataGridColumnHeader}">
            <Setter Property="FontSize" Value="14"/>
        </Style>
    </DataGrid.ColumnHeaderStyle>
    <DataGrid.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
            <Setter Property="FontSize" Value="14"></Setter>
        </Style>
    </DataGrid.CellStyle>
    <DataGrid.Columns>

        ...

    </DataGrid.Columns>
</DataGrid>

A: If you want to apply style to individual columns, set your style to :
<DataGridTextColumn.CellStyle>
    <Style>
        <Setter Property="TextBlock.TextAlignment" Value="Right" />
    </Style>
</DataGridTextColumn.CellStyle>

Alternatively, you can change your CellStyle to:
<DataGrid.CellStyle>
    <Style TargetType="{x:Type DataGridCell}">
        <Setter Property="FontSize" Value="14" />
        <Setter Property="TextBlock.TextAlignment" Value="Right" />
    </Style>
</DataGrid.CellStyle>


text:
Q: Enviar e Receber pacotes (packets) em NodeJS Bom, vou tentar explicar a situação:
Estou estudando NodeJS e para isso resolvi reescrever o código do lado servidor de uma aplicação que originalmente foi escrito em C/C++, e esse servidor recebe pacotes (packets) em hexadecimal da aplicação client, a questão é: como receber esses pacotes (packets) em NodeJS ?
Cheguei a criar um socket para a conexão mas dei uma travada, segue o código feito:
var port = process.env.PORT || 8281;
var io = require('socket.io')(port);

io.on('connection', function (socket) {
     var address = socket.handshake;
    console.log('Nova conexão de: ' + JSON.stringify(address, null, 4));
});

A: A classe básica do node.js utilizada para comunicação em TCP chama-se "net".
Abaixo um exemplo de servidor e cliente feitos com a classe "net". O original (com comentários) está em http://www.hacksparrow.com/tcp-socket-programming-in-node-js.html

server
var net = require('net');

var HOST = '127.0.0.1';
var PORT = 6969;

net.createServer(function(sock) {
    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
    sock.on('data', function(data) {
        console.log('DATA ' + sock.remoteAddress + ': ' + data);
        sock.write('You said "' + data + '"');
    });
    sock.on('close', function(data) {
        console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
    });

}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);

client
var net = require('net');

var HOST = '127.0.0.1';
var PORT = 6969;

var client = new net.Socket();
client.connect(PORT, HOST, function() {
    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    client.write('I am Chuck Norris!');
});

client.on('data', function(data) {
    console.log('DATA: ' + data);
    client.destroy();
});

client.on('close', function() {
    console.log('Connection closed');
});


text:
Q: how to get fields foreign key(table and field) php mysqli How can i get foreign key field like in phpMyAdmin using php and mysqli?
see photo:

A: All the constraints are listed in INFORMATION_SCHEMA.TABLE_CONSTRAINTS:
mysql> create table test.foo (id int primary key);
mysql> create table test.bar (fooid int, foreign key (fooid) references foo(id));

mysql> select * from information_schema.table_constraints
    where constraint_schema = 'test'\G
*************************** 1. row ***************************
CONSTRAINT_CATALOG: def
 CONSTRAINT_SCHEMA: test
   CONSTRAINT_NAME: bar_ibfk_1
      TABLE_SCHEMA: test
        TABLE_NAME: bar
   CONSTRAINT_TYPE: FOREIGN KEY
*************************** 2. row ***************************
CONSTRAINT_CATALOG: def
 CONSTRAINT_SCHEMA: test
   CONSTRAINT_NAME: PRIMARY
      TABLE_SCHEMA: test
        TABLE_NAME: foo
   CONSTRAINT_TYPE: PRIMARY KEY

And all the columns in those constraints are in INFORMATION_SCHEMA.KEY_COLUMN_USAGE:
mysql> select * from information_schema.key_column_usage
    where constraint_schema = 'test'\G
*************************** 1. row ***************************
           CONSTRAINT_CATALOG: def
            CONSTRAINT_SCHEMA: test
              CONSTRAINT_NAME: bar_ibfk_1
                TABLE_CATALOG: def
                 TABLE_SCHEMA: test
                   TABLE_NAME: bar
                  COLUMN_NAME: fooid
             ORDINAL_POSITION: 1
POSITION_IN_UNIQUE_CONSTRAINT: 1
      REFERENCED_TABLE_SCHEMA: test
        REFERENCED_TABLE_NAME: foo
       REFERENCED_COLUMN_NAME: id
*************************** 2. row ***************************
           CONSTRAINT_CATALOG: def
            CONSTRAINT_SCHEMA: test
              CONSTRAINT_NAME: PRIMARY
                TABLE_CATALOG: def
                 TABLE_SCHEMA: test
                   TABLE_NAME: foo
                  COLUMN_NAME: id
             ORDINAL_POSITION: 1
POSITION_IN_UNIQUE_CONSTRAINT: NULL
      REFERENCED_TABLE_SCHEMA: NULL
        REFERENCED_TABLE_NAME: NULL
       REFERENCED_COLUMN_NAME: NULL


text:
Q: Check if folder can be deleted I'm working on a script that will delete files & folders after a certain age and will create a log about the action.
For Each oFile In fso.GetFolder(C.Value).Files

    If DateDiff("h", GetFileAge(oFile.Path), Now) > DelAfterH Then
        If IsFileWriteable(oFile.Path) Then
            Call LogResults(oFile.Path, "File deleted!")
            Logged = True
            Kill oFile
        Else
            Call LogResults(oFile.Path, "File protected!")
            Logged = True
        End If

    End If

Next oFile

A possible issue that can appear is when a file is opened at someone and becomes write protected, so the script should just skip it.
I can easily verify this with a function I found:
Function IsFileWriteable(strFile As String) As Boolean

Dim i As Integer
i = FreeFile
On Error Resume Next
Open strFile For Binary Access Write As #i
Close #i
IsFileWriteable = (Err = 0)

End Function

Folders are a different story however. Whenever someone has a file opened in the folder, the script will just halt with Run-time error '75'.
Also the same function can not be used in this case.
Is there a way to test the folder with a similar method before trying to delete?
Or I'm just stuck with error handling?

A: You can offload the delete operation to a helper function that returns true if the file/folder was deleted and false if not.
The function itself suspends error reporting, tries to delete the file and returns a boolean based on the error number. If zero, no error raised.
Private Function TryToDelete(ByVal path As String) As Boolean
    On Error Resume Next
    Kill path
    TryToDelete = Err.Number = 0 'if failed, it would be > 0, i.e. 75
End Function

For Each oFile In fso.GetFolder(C.Value).Files

    If DateDiff("h", GetFileAge(oFile.Path), Now) > DelAfterH Then
        If TryToDelete(oFile.Path) Then
            Call LogResults(oFile.Path, "Deleted!")
        Else
            Call LogResults(oFile.Path, "Could not delete.")
        End If
        Logged = True
    End if
Next oFile


text:
Q: Get content of tiny mce with many textareas on page      var inst, contents = new Object();

      for (inst in tinyMCE.editors) {
         if (tinyMCE.editors[inst].getContent)
             contents[inst] = tinyMCE.editors[inst].getContent();

I have 3 textareas on my page with 3 different id: #id1; #id2;#id3.
How can i make work that code for #id3? i've tried to replace inst with id3, but this didn't work.

A: It is suffiecient to call
var contents = new Object();

for (var i = 0; i < tinymce.editors.length; i++) {
    contents[i] = tinymce.editors[i].getContent();
}


text:
Q: Access VBA: how to dump OLE field content into bytes I have a table containing OLE fields  and I would like to see the content of some fields as bytes. I only can view it in the Watch window with BinData array so far .
I tried to convert it to a byte array using CByte function but it
gives an "Type mismatch" error.
Is there any way to obtain the OLE field content as a byte array?
My code which reads byte by byte field content into Bindata array:
Sub DumpField()

Dim BinData(100) As Variant
Dim r As ADODB.Recordset
Dim i As Integer

Set r = New ADODB.Recordset
With r
.CursorType = adOpenStatic
.LockType = adLockReadOnly
.Open "SELECT [fBinary] FROM tbDesc WHERE ID=100", CurrentProject.Connection
If .BOF Then MsgBox "No Records"
Exit Sub
End If

For i = 0 To r.Fields(0).ActualSize - 1
BinData(i) = r.Fields(0).GetChunk(1)
Next i

End With
End Sub

A: The OLE field content is a byte array. Using CByte, however, attempts to convert something to a single byte, and fails.
You can print individual bytes in the following way:
Debug.Print r.Fields(0).Value(0) 'First byte

Or store a byte array in one of the following ways:
1: just use a variant
Dim BinData As Variant
BinData = r.Fields(0).Value

2: create a byte array of the appropriate size, then set the byte array to the OLE objects value
Dim BinData() As Byte
Dim objSize As Long
objSize = UBound(r.Fields(0).Value)
Redim BinData(0 To objSize)
BinData = r.Fields(0).Value


text:
Q: Getting this error Premature end of file I am facing the problem of Premature end of file but not all the time only sometimes am facing this issue. Please help me to resolve this issue.
InputStreamReader isr=new InputStreamReader(httpConn.getInputStream);
BufferedReader in = new BufferedReader(isr);
while ((responseString = in.readLine()) != null) {
            outputString = outputString + responseString;
         }
 if (outputString != null && !"".equalsIgnoreCase(outputString))
         {
            Document document = parseXmlFile(outputString);
            String userName = document.getElementsByTagName("UserID").item(0).getTextContent();
            if(!userName.equalsIgnoreCase("")&&userName!=null&&userName.equalsIgnoreCase(deptUserId))
            {
              String signbaseData = document.getElementsByTagName("Sign").item(0).getTextContent();
              if(signbaseData!=null&&!"".equalsIgnoreCase(signbaseData))
              {
                signData=new Base64().decodeBase64(signbaseData.getBytes());
              }
            }
        }

this is the parseXMLFile
public Document parseXmlFile(String in) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(in));
        return db.parse(is);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }catch (Exception ex) {
        throw new RuntimeException(ex);

}
    }
Thanks.


text:
Q: Mysql architecture of log tables I need 3 tables for logging user activity -> create, login and his device activity.
Is it better to have 1 general table with common columns (ip, date, type_of_log, external_id_of_log) and 3 tables with additional data
or
have only 3 tables with same columns (+ additional data) and getting data (ordered by date) thanks to UNION command?

A: It all depends on what you goal is.  A unified (denormalized) table means you will have better performance, at the expense of sparse data (and all the complexity of handling nulls).  A normalized table gives you more concise data, better relational integrity, etc, at the cost of lower performance.
There is no "correct" answer here, it all depends on what you are trying to achieve.  As a default, I usually start with fully normalized tables until I come up with a reason to denormalize.


text:
Q: Complex query constraint on queryScope in laravel users table have the following columns:

*

*created_at (timestamp)

*last_order (timestamp)

when new users is created then last_order is null and created_at is current timestamp.
When user place an order then last order column is updated with timestamp of order placing time.
Now I want to retrieve all users who didn't place any order last 7 days. I define my user model as follows:
class User extends Model
{
    /**
     * @var string The database table used by the model.
     */
    public $table = 'users';

    /**
     * @var array Validation rules
     */
    public $rules = [
    ];
    public $hasMany  = [
        'voucher' => ['ItScholarBd\Api\Models\Voucher'],
        'order' => ['ItScholarBd\Api\Models\OrderLog']
    ];

   public function scopeCustomer($query)
    {
        return $query->where('role_id', '=', 5);
    }
   public function scopeNew($query,$days)
    {
        return $query->where('created_at', '>=', Carbon::now()->subDays($days));
    }
   public function scopeIdle($query,$days)
   {

       $dayOffset = Carbon::now()->subDays($days);

      return $query->where(function($q,$dayOffset){
        $q->whereNull('last_order')
          ->where('created_at','<',$dayOffset);
       })->orWhere(function($q,$days){
        $q->whereNotNull('last_order')
        ->whereRaw("DATEDIFF(created_at,last_order)>$days");
       });

   }

}

Here scopeNew() is working perfectly but scopeIdle() is throwing the following error:
Type error: Too few arguments to function App\User::App\{closure}(),
  1 passed in .\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Builder.php on line 222 and exactly 2 expected

A: You don't get to make up parameters for functions you don't control. The closure will be passed a single argument, and you need to import any other variables with use:

public function scopeIdle($query, $days)
{
    $dayOffset = Carbon::now()->subDays($days);

    return $query
        ->where(function ($q) use ($dayOffset) {
            $q->whereNull('last_order')
                ->where('created_at', '<', $dayOffset);
        })
        ->orWhere(function ($q) use ($days) {
            $q->whereNotNull('last_order')
                ->whereRaw("DATEDIFF(created_at, last_order) > ?", [$days]);
       });
}

Note the use of parameters in the whereRaw statement, which can save you from SQL injection. You will also find your code easier to work on if you consistently indent and space it.

A: Try using a closure:
return $query->where(function($q) use ($dayOffset){


text:
Q: How to make table cells responsive in iOS Mail App I'm currently developing an email that has a 2-column layout in various places. I initially used
 tags for each column, which worked great in every email client except older versions of Outlook (columns would render at 100% width, regardless of screen size).
To fix the Outlook problem, I simply changed the
 tags into 's. Now, I have a problem in the iOS mail app (10.1.1) where 's refuse to go full-width on smaller screens. In my code below, you can see that both of the  elements have a fixed width of 300px, yet when I open the email in the iOS mail app then both of those elements are exactly 50% screen width. Here's a screenshot: http://imgur.com/a/0XsGz
Has anyone else run into this issue with the iOS mail app? I can't figure out why my inline styles and media queries are being ignored, simply because the elements are now table-cells instead of divs.
HTML (sorry, tried my best to clean it up):

Pledges to Ipsum fall short

Abby Bruell | Jun 2015

Despite good intentions, donors to the London conference have failed to follow through will the pledges they made to aid Syrian refugees. Now, millions of women and children face the consequences of their inaction.

                          READ MORE

Pledges to Ipsum fall short

Abby Bruell | Jun 2015

Despite good intentions, donors to the London conference have failed to follow through will the pledges they made to aid Syrian refugees. Now, millions of women and children face the consequences of their inaction.

                          READ MORE

CSS media query:
@media screen and (max-width: 650px) and (max-device-width: 650px) {
     .col-6-article {
         width: 100% !important;
         display: block !important;
     }
}

A: You have dueling !important tags; you don't need to include !important in the inline css. Change this:

To this:

Once the !important is removed from the body's inline css, the media query code can override the 300px width and change it to 100% or whatever you want.


text:
Q: How to get the angle between two vectors in pygame? I want my player to look towards some certain coordinates in pygame. I tried to do this by getting the angle between the position of the player and the coordinates and then rotating it the player by that angle. I used a function for this ,the function works properly when I need my player to look towards the coordinates of the mouse , but fails when i use the same function to make a zombie look towards the player.
This was the function that is used.
def rotate_char(khiladi,vector,old_center,angle=False) :
x1, y1 = vector
x2, y2 = khiladi.pos
dx, dy = x2 - x1, y2 - y1

rads = atan2(dx, dy)
degs = degrees(rads)

r_khiladi = pygame.transform.rotate(khiladi.image, degs)

R_k = r_khiladi.get_rect()
R_k.center = old_center
screen.blit(r_khiladi, (R_k))
if angle : return degs

I used another method that used numpy
v1_u = list(khiladi.pos / linalg.norm(khiladi.pos))
v2_u = list(vector / linalg.norm(vector))
v1_u[1] , v2_u[1] = -v1_u[1] , -v2_u[1]
c_angle =  degrees(arccos(clip(dot(v1_u, v2_u), -1.0, 1.0)))

When I tried to print the angles they were totally off mark and didn't even showed any pattern.
Please Help

A: I recommend to use pygame.math.Vector2 / angle_to() to compute the angle between 2 vectors in degrees.
If (x1, y1) and (x2, y2) are 2 vectors, then the angle between the vectors is:
v1 = pygame.math.Vector2(x1, y1)
v2 = pygame.math.Vector2(x2, y2)
angle_v1_v2_degree = v1.angle_to(v2)

In general The dot product of 2 vectors is equal the cosine of the angle between the 2 vectors multiplied by the magnitude (length) of both vectors.
dot( A, B ) == | A | * | B | * cos( angle_A_B )

This follows, that the dot product of 2 unit vectors is equal the cosine of the angle between the 2 vectors, because the length of a unit vector is 1.
uA = normalize( A )
uB = normalize( B )
cos( angle_A_B ) == dot( uA, uB )

Hence the angle between 2 vectors can be computed by math.acos of the dot product of the 2 normalized vectors (normalize()):
v1 = pygame.math.Vector2(x1, y1)
v2 = pygame.math.Vector2(x2, y2)
v1u_dot_v2u = v1.normalize().dot(v2.normalize())
angle_v1_v2_radian = math.acos(v1u_dot_v2u)


text:
Q: Solving $ \{ \varnothing, \{ x\} \} = \{ y, \{ \varnothing \} \}$. The equation is:
$$ \{ \varnothing, \{ x\} \} = \{ y, \{ \varnothing \} \}$$
where $ \varnothing $ denotes empty set.
I guess I need to break this into cases for each side. Help me get started.

A: Well, you have to look at several cases:

*

*Since $\varnothing$ is a member of the left-hand side, then it is also a member of the right-hand side.

*Since the members of the right-hand side are $y$ and $\left\{\varnothing\right\}$, then $\varnothing=\left\{\varnothing\right\}$ or $\varnothing=y$.

*However, $\varnothing\in\left\{\varnothing\right\}$, whereas $\varnothing\not\in\varnothing$. Therefore $\varnothing\neq\left\{\varnothing\right\}$.

*By 2. and 3., the only possibility is $\varnothing=y$.
Now do a similar analysis for $\left\{x\right\}$, knowing that $y=\varnothing$, and conclude that $x=\varnothing$.

A: Two sets are equal if they have exactly the same elements.
so, $\emptyset$ must be in $\{y,\{\emptyset\}\}$
but, it is known that
$\emptyset \ne \{\emptyset\}$
thus
$$\emptyset=y$$
and
$$\{x\}=\{\emptyset\}$$
which means that
$$x=\emptyset=y$$

A: Break things into cases!
Two sets are equal iff they have the same elements. In particular, we have $$\{a,b\}=\{u,v\}\quad\iff\quad \mbox{EITHER ($a=u$ and $b=v$) OR ($a=v$ and $b=u$).}$$
(NOTE: this isn't an exclusive "or," since we could have $a=b=u=v$.)
In this case, this tells us that in order to have the desired equality we must have one of the following:

*

*$\emptyset=y$, $\{x\}=\{\emptyset\}$.

*$\color{red}{\emptyset=\{\emptyset\}}$, $y=\{x\}$.
Note the red clause: $\emptyset=\{\emptyset\}$ is not true (this is important to understand), so that second bulletpoint can't hold.
So our only option is the first bulletpoint. That is, $$x=y=\emptyset.$$

A: If two sets are equal, then they have exactly the same elements in each. Since $\emptyset$ is an element of the LHS, it is an element of the RHS. It cannot be $\{\emptyset\}$, since that is not empty, so $y=\emptyset$. It follows that $\{x\}=\{\emptyset\}$, which implies that $x=\emptyset$ also.


text:
Q: Update Iteration Capacity without Project Administator Role In our company, only users with a Project Amin role can update the Iteration Capacity in TFS.  Is there a setting we can add to a Contributor role to allow each individual to update their own Capacity for a given Iteration?  We do not want to give everyone Admin role as they can change everything on the site, but need every individual to go update their own capacity and add their vacation days ahead of the sprint planning session.

A: Actually users in your team do not need full Project Admin role to update Iteration Capacity.
You could simply follow below  prerequisites:

*

*You must connect to a team project. If you don't have a team project    yet, create one in TFS/VSTS.

*You must be a member of the Contributors group or be granted    Stakeholder access to add or modify work items. Or, you must have
  your View work items in this node, and your Edit work items in this
  node permissions set to Allow.

*If you haven't been added to a team project or team, get added now.

As you can see, you just need to assign the users in contributors group or modify work item in this node permission to allow. More details please take a look at this tutorial--  Set your team's capacity, the same for Iteration.


text:
Q: Regex pattern if string contains characters Sorry for being an absolute beginner, when it comes to Javascript and Regex,
I have a Codepen: http://codepen.io/anon/pen/dNJNvK
What I want to accomplish is to validate, if a String contains some special UTF-8 characters. That's why I work with RegExp. The pattern I have here will return false only if the string to test equals one of the characters. But I want to return false if it contains one of these characters.
How can I accomplish this, I know it should be quite easy, but I wasn't able to get it working.

var regEx = new RegExp('[\u0001-\u00FF]');

console.log("This should be true: " + regEx.test("Tes"));
console.log("This should be false: " + regEx.test("Tes�"));

console.log("This returns false, because the string equals a special character: " + regEx.test("�"));

A: Why not the other way around?
See Regular expression to match non-English characters?
Also your test could be match instead or a test of the WHOLE string

var regEx = /[\x00-\x7F]/g; // can be added to
function okChar(str) {
  var res = str.match(regEx);
  if (res===null) return false;
  return res.length===str.length;
}
console.log("This should be true: " + okChar("Tes"))
console.log("This should be false: " + okChar("Tesú"));

console.log("This returns false, because the string equals a special character: " + okChar("ú"));

A: as @Gabriel commented, it's returning true because there's at least one character in the string that matches your range
what you want to do is check that every character is within the range
/^[\u0001-\u00FF]+$/

or that any character is not within the range
[^\u0001-\u00FF]

in the second case you'd have true when a special character is used and false when all characters are safe, so you probably have to flip the checks you do afterward


text:
Q: Line graph customization (add circles, colors) With data
value <- c(9, 4, 10, 7, 10,
           10, 10, 4, 10,
           4, 10, 2, 5, 5, 4)

names  <-  c("a","b",
             "c","d","e",
             "f", "g","h",
             "i","j","k","l",
             "m","n","p")

df <- data.frame(value, names)
df$names <- as.character(df$names)

p <- ggplot(data = df, aes(y = value,x= names,group=1))+
  geom_point(color = I("red"),shape=23, lwd=3,fill="red")+
  geom_line(group = I(1),color = I("red"))+
  theme_bw()+
  coord_flip()
p + xlab("") +ylab("")

I produce this

But now I would like to create plot similar picture below, where "a", "b", "c" and "D" would be x aes labels and belong to PART 1 and names "p", "n", "m", "i", "k" would belong in PART 2 (and so on). the key part here is how to add circles inside plot.
I've also looked here
How can I add freehand red circles to a ggplot2 graph?
but no luck.

If this in upper pocture is not possible, than I would like my output to be like below picture

A: In order to achieve the facetting by part as in your last plot you can create a new column that groups your values, e.g.:
df$part <- rep(c("part3", "part2", "part1"), each = 5)

In order to plot the open circles you can add another geom_point() layer. I created a new data frame that consists of all combinations of names and value for each part:
library(dplyr)
library(tidyr)

df2 <- df %>%
  group_by(part, names) %>%
  expand(value = min(df$value):max(df$value))

Then you plot a facetted plot with circles:
ggplot() +
  geom_point(data = df2, aes(x = value, y = names),
             shape = 1) +
  geom_point(data = df, aes(y = names, x = value, group = 1), colour = I("red"), shape = 23, lwd = 3, fill = "red") +
  geom_line(data = df, aes(y = names, x = value, group = 1), group = I(1),color = I("red")) +
    theme_bw() +
  facet_wrap(~part, ncol = 1, scales = "free_y")

Note that I swapped x and y values as coord_flip() cannot be used with scales = "free_y" which is however necessary if you want only those names which have values in the respective facet.


text:
Q: Title of the theorem in my paper the text inside theorem is italic while the word Theorem 1 is bold and not italic. I would like to have a title of the theorem also not italic. The example is here:
Theorem 1. (The title) Let the set...
How can I do it? I tried to type
\begin{theorem}{title here}
but it doesn't work.

A: You might like to test
   \newtheorem{theorem}{\textit{Theorem}}
before \begin{document} then
    \begin{theorem}
     Some statement
    \end{theorem}

A: Usually
\begin{theorem}[The title]
Some statement
\end{theorem}

should do what you want. The standard LaTeX setting prints in boldface also the title, which doesn't happen when amsthm is loaded.


text:
Q: Worklight-related error while using the Worklight iOS Native API I am getting an error in Xcode when trying to connect to Worklight using the iOS native API:
[ERROR] Worklight: +[WLCookieManager persistentStoreCoordinator]:326::Unresolved error creating persistent store Error Domain=NSCocoaErrorDomain Code=134130 "The operation couldn't be completed. (Cocoa error 134130.)" UserInfo=0x1e59d0d0 {URL=/iPhone%20Simulator/6.1/Applications/2C2E0482-7F42-4574-B998-A9FB5479F4B1/Library/Application%20Support/Cookies.sqlite, metadata={
    NSPersistenceFrameworkVersion = 419;
    NSStoreModelVersionHashes =     {
        Cookie = <3c2e440d 9fb3ea81 60146cf8 2bcb8ffe 10b2df20 0d907eea 018c6ade eeefb9c7>;
        UserDictionaryEntry = <f0c9025b 602122f9 37a4e274 bdaacec1 b9a66f83 fca5c43b bed5e80a 6baee338>;
    };
    NSStoreModelVersionHashesVersion = 3;
    NSStoreModelVersionIdentifiers =     (
        ""
    );
    NSStoreType = SQLite;
    NSStoreUUID = "0F344BFF-833C-4009-9867-13973A5291F1";
    "_NSAutoVacuumLevel" = 2;
}, reason=Can't find model for source store}, {
    URL = "file:///iPhone%20Simulator/6.1/Applications/2C2E0482-7F42-4574-B998-A9FB5479F4B1/Library/Application%20Support/Cookies.sqlite";
    metadata =     {
        NSPersistenceFrameworkVersion = 419;
        NSStoreModelVersionHashes =         {
            Cookie = <3c2e440d 9fb3ea81 60146cf8 2bcb8ffe 10b2df20 0d907eea 018c6ade eeefb9c7>;
            UserDictionaryEntry = <f0c9025b 602122f9 37a4e274 bdaacec1 b9a66f83 fca5c43b bed5e80a 6baee338>;
        };
        NSStoreModelVersionHashesVersion = 3;
        NSStoreModelVersionIdentifiers =         (
            ""
        );
        NSStoreType = SQLite;
        NSStoreUUID = "0F344BFF-833C-4009-9867-13973A5291F1";
        "_NSAutoVacuumLevel" = 2;
    };
    reason = "Can't find model for source store";
}

This happens when I try to call this line:
[[WLClient sharedInstance] wlConnectWithDelegate:connectListener];

It was working fine and I was able to connect to my Worklight server without any issue, but now it keeps throwing this error. The only change I made was to try and show a dialog from the application. After reverting this change I still get the error.

A: This happens when all of the files required aren't built into your app bundle.  In the build target for your application make sure that all the (non-source) files that are part of the worklight native SDK appear in the 'Copy Files' section.
Here is a link to the docs

A: Did you changed something in your web app that the application is now trying to save a cookie? Or getting one passed to it. It looks like WL is trying to store a cookie and that's not going well. Can you isolate the part of the app where this is triggered? Does it compile. Take a look at how this code is probably being used:
http://mobile.tutsplus.com/tutorials/iphone/core-data_schema-versioning-and-lightweight-migrations/
http://46424.com/question/133999#.USJnGVprP4Y


text:
Q: Owl carousel customised image preview pagination not working I am taking a look at this neat creation by Yunus Gaziev but there is one major problem with it - the pagination is removed as soon as you adjust the viewport, which seems to be caused by Owl, and I do not know why.
var owl;

$(document).ready(function() {
    owl = $("#owl-demo");
    owl.owlCarousel({
        navigation: false,
        slideSpeed: 300,
        paginationSpeed: 400,
        singleItem: true,
        afterInit: afterOWLinit
    });

    function afterOWLinit() {
        ...
    }

});

A: I have tried debug the javascript but could not find the cause. I do think that this pagination is not recreating on the changes of viewport in owl.carousel.js
This is where it tries to recreate the pagination

*

*base.updatePagination();

*base.checkNavigation();
Check it out. I hope this will help you and others to find the root cause.

A: The problem was that the owlCarousel initialiser needed to have afterUpdate: afterOWLinit declared so that whenever the viewport was resized, it would fire the customised pagination script again.
I have refactored the existing code thoroughly, an example may be viewed here - my version can be cloned from here.


text:
Q: Access Undisposed Resource of a Disposable Object Outside of Using Block The code below is perfectly legal.
DisposableObject disposableObject;
...
using (disposableObject = new DisposableObject(...))
{
     disposableObject.UseDisposableResource();
}
...
var result = disposableObject.AccessUndisposedResource();

Q Make use of it or stay clear?

A: I would absolutely steer clear of that. The usual convention is to introduce the variable in the scope of the using statement only, so doing otherwise is asking for developer confusion and hard to find bugs.
If developers expect this, by convention:
using (DisposableObject disposableObject = new DisposableObject())
{
    ...
}

Then breaking convention will lead odd looking code at best, and strange behaviour/bugs at worst.
The typical usage of the using statement, in my experience, is very similar in developer expectation to the following (even though it is a scope change, not a nulling of an object):
DisposableObject disposableObject = new DisposableObject();

...
disposableObject.Dispose();
disposableObject = null;

If a developer under my care ever did such a thing, I would tell them to cease and desist! I would also change all instances I found of it, since it has such a code smell and so much potential for causing hard to find/understand bugs.

A: There are a couple of norms / expectations involved here:

*

*A disposed object is considered generally finished with and is assumed unusable after disposal (although not compiler-enforced)

*using variables are usually declared within the using statement, which exlicitly prevents usage when they have been disposed (again, not compiler-enforced)

Your code violates both these norms - you have a disposed object which is still expected to be usable, as well as a using block which disposes an external variable which remains in scope after the block. The result? Confusion and hard-to-read-and-maintain code.
So yes, steer well clear.

A: I would not make use of it, as anyone reading your code will think the usage of disposableObject after the using is of a usable object.
I would keep the scope of the disposable object within the confines of the using block as others have suggested.

A: In this case the usage of using-block is a bit misleading. I'd personally use the disposableObject only inside the block, and split the AccessUndisposedResource()-logics to some other object.
Maybe something like this:
ResultType result = null;
using (DisposableObject disposableObject = new DisposableObject(...))
{
   disposableObject.UseDisposableResource();
   ...
   result = disposableObject.AccessUndisposedResource();
}
...
// Now we can access the undisposed resource here with 'result'-variable


text:
Q: Is it polite to ask teacher "Wasn't it supposed to start 30 minutes ago"? An poster is trying to ask their teacher the following question, who seems late for class.

Wasn't it supposed to start 30 minutes ago

Is it polite to ask the teacher that way?

A: I think in this case the politeness will depend more on the context than the particular grammar used.
Posing a question in the negative ("Wasn't it...?") does more strongly imply that you believe that yes, it was supposed to start 30 minutes ago (which could in turn possibly be interpreted as accusing the teacher of being late, rather than just asking a question).
If you want to be more careful, there are some other ways to phrase the question which are less likely to be interpreted negatively:

I thought it was supposed to start 30 minutes ago?
  Was I early or was it supposed to start 30 minutes ago?

Both of these are presented basically as "me" questions, and so are essentially asking "was I wrong?" instead of "are you wrong?"  This helps to soften the question and make it less likely to be perceived as an attack or impolite.


text:
Q: Is there is any way to pass the timeout value for aws lambda function programmatically? I am working on getting snapshot API using aws lambda. I wan to pass the timeout value for lambda function  depends on number of snapshots to be taken. So, Is there is any way to pass the timeout value to aws function runtime?

A: As far as I'm aware you cannot set the timeout function dynamically for each invocation. Is there a reason you aren't just setting the timeout high, and relying on the function to properly exit when it is finished?


text:
Q: Python changes are not reflected I have a example.py file. loaded on a linux server. I put some prints in this file and saved it.
When I call this .py file I am not getting these changes.
Do I need to do something (Like for C we need to compile the .c file and put the .so to LD_LIBRARY_PATH) for python also.
Thanks,

A:
I have a example.py file. loaded on a linux server.

Many linux servers including Apache and Nginx load the files they need to serve when they start for performance sake. So, you may need to restart the server to pickup the latest python file.


text:
Q: proof of $\lim_\limits{m\to\infty}\frac1m\sum_\limits{n=1}^m f(an)=\int_\limits{0}^1fdx$ I have taken a compact seminar about Fourier analysis and someone mentioned the following: Let $f\in C(\mathbb R)$ with period 1. Let $a$ be an arbitrary irrational number. Then
$$
\lim_{m\to\infty}\frac1m\sum_{n=1}^m f(an)=\int_\limits{0}^1fdx
$$
Since it wasn't mentioned any proof, I've tried to verify the equation by showing it first for $f(x)=\exp(2\pi ikx)$ but didn't get far. Anybody could help using Fourier?

A: This result is known as Weyl's ergodic theorem.
Using Fejér's theorem, $f$ is a uniformly approximate by elements in $\textrm{Vect}(\{e^{2i\pi n\cdot};n\in\mathbb{Z}\})$. Hence, it suffices to prove that for all $n\in\mathbb{N}$, one has: $$\lim_{m\to+\infty}\frac{1}{m}\sum_{k=0}^{m-1}e^{2i\pi kn\theta}=0.$$
To see that, notice that $n\theta$ is not an integer, so that $e^{2i\pi n\theta}\neq 1$. Hence using a geometric summation, one has: $$\left|\sum_{k=0}^{m-1}e^{2i\pi k\theta}\right|\leqslant\frac{2}{|1-e^{2i\pi n\theta}|}.$$

A: The statement is called 'ergodic theorem'. Pointwisely the statement is true. Since the function is continuous, it is true for every given point. Prove first that $Tx=ax$ holds ergodicity. Then use ergodic theorem is one kind of proof.

A: Not a complete answer, hopefully it helps though:
If $f$ is constant, then we are done. If $f$ is of the form above ($exp(2 \pi i k)$ for $k$ not equal to zero) then the sum divided by $m$ you have written should go to zero when $m$ gets large - the sum can be seen as a geometric series + there you see why $a$ needs to be irrational!. If you approximate $f$ by a nice function (I think $K_N*f$ should work) and consider its Fourier coefficients, the first coefficient will be, up to epsilon, $\int_0^1 f(x)$. This one you will recover, the rest will disappear as desired. So its an epsilon & triangle inequality business


text:
Q: How to make filter products on laravel correctly? I have scope on my model Product:
public function scopeAttrSearch($query, $ids)
{
    $query->whereHas('attribute.attribute', function ($q) use ($ids) {
        foreach ($ids as $category => $values) {
            $q->whereIn('attribute_value_id', $values);
        }
    });

    return $query;
}

And I have filters on page with multiple checkboxes. Each group checkboxes have a category of filter. When user click on checkboxes I send id category of filter and id value of this checkbox. Variable ids have this structure:
array:2 [
    1 => array:2 [
            0 => "1"
            1 => "3"
    ],

    3 => array:2 [
        0 => "5"
        1 => "6"
    ]
 ]

Where 1 and 3 id of category filters. And arrays to them - this is id values checkboxes of filter.
On controller I call this scope:
    if (@$request->data['attrs']) {
        $_products = $_products->attrSearch($request->data['attrs']);
    }

And return on page already filtered products in template:
return $_products;

I have a problem. Filter working. But if I check checkboxes from different categories I get empty results. If I check checkboxes from same category - all working, I get filtered products. How I can fix this problem with different category?
Model relations in Product:
public function attribute()
{
    return $this->hasMany('App\Models\ProductAttribute');
}

ProductAttribute:
public function attribute()
{
    return $this->belongsTo('App\Models\AttributeValue', 'attribute_value_id');
}

Category id of filter have column attribute_id


text:
Q: Having both Visual Studio Professional and Ultimate Installed can I remove only the professional? I want to free a Visual Studio 2010 Professional license, so my company can use it on another computer, by removing it from "Add/Remove Programs". But I fear it can damage my Ultimate installation. What is the safest way of doing that?

A: Yes you can!
I had two versions of VS2012 installed that I could see clearly in Control Panel's Program Features:

*

*Microsoft Visual Studio Premium 2012

*Microsoft Visual Studio Ultimate 2012

A year ago, when I installed Ultimate 2012, I don't know why MS had them be installed side-by-side, rather than just upgrading VS Premium 2012.
After uninstalling VS Premium 2012 (via their uninstall tool), VS Ultimate 2012 still worked for me.  I also saw reclaimed hard drive space, though not as much as I thought I should have seen.
Hope this helps! Good question.

A: Visual Studio does not use activation, so you would be fine with having both versions inatalled.


text:
Q: How can I optimize this order_by query in Django? I have the following models:
class Movie(models.Model):
    item = models.OneToOneField(Item, primary_key=True)

class Item(models.Model):
    ...

class Popularity(models.Model):
    item = models.OneToOneField(Item, primary_key=True)
    today = models.IntegerField(default=0, db_index=True)

I want to execute the following query:
movies = Movie.objects.order_by('-item__popularity__today') \
                      .values(...)
paginator = Paginator(movies, 12)

However, with about 52,000 rows in the database, this takes 500-700ms to run.  Is there any way to make this faster?  What I want to do is to get the 12 most popular movies in the database.

A: This isn't something you can do in Django. The way to optimize this is in the database.
Run EXPLAIN against the actual query that this generates - in fact, the Django debug toolbar can do that for you - and note whether the relevant subqueries and JOINs are using indexes, rather than full-table scans. You'll probably need to create an index for the Paginator table on item, today to start with.