text:
Q: If-else Refactor I am trying to refactor this block of if else statements. What can be the best optimized version of this code?
`const handlePhoneNumberFormat = (rules, value, callback) => {
    if (value && value.match(phoneNumberRegex)) {
      if (value.includes('-')) {
        if (value.indexOf('-') === 2) {
          if (value.length !== 10) {
            callback('Please enter 7 digits after "-".');
          } else {
            callback();
          }
        } else if (value.indexOf('-') === 3) {
          if (value.length !== 14) {
            callback('Please enter 10 digits after "-".');
          } else {
            callback();
          }
        } else {
          callback();
        }
      } else {
        callback();
      }
    } else {
      callback('');
    }
  };`

A: Here's one solution that probably works just as well as your code
const handlePhoneNumberFormat = (rules, value, callback) => {
    if (value && value.match(phoneNumberRegex)) {
        const pos = value.indexOf('-');
        const length = value.length;
        if (pos === 2 && length !== 10) {
            callback('Please enter 7 digits after "-".');
        } else if (pos === 3 && length !== 14) {
            callback('Please enter 10 digits after "-".');
        } else {
            callback():
        }
    } else {
      callback('');
    }
};

No repetition, each callback is unique ... though if you want smaller code
const handlePhoneNumberFormat = (rules, value, callback) => {
    const t = { "2": 10, "3": 14 };
    if (value && value.match(phoneNumberRegex)) {
        const pos = value.indexOf('-');
        const a = t[pos] || 0;
        if (a && a !== value.length) {
            callback(`Please enter ${a - pos - 1} digits after "-".')`);
        } else {
            callback():
        }
    } else {
      callback('');
    }
};

Though, not much smaller, and harder to read too

A: You may still use if elses conditions but you have to combine some codes like
 value.indexOf('-') and value.includes('-') value && value.match(phoneNumberRegex)

and
value.indexOf('-') === 3 and value.length !== 14

to make your code shorter.

A: One option you've got is to make use of the ternary operator in your function to define the value you are looking at passing:
    var returnValue;

    returnValue = (value && value.match(phoneNumberRegex) && value.includes('-')  && value.indexOf('-') === 2) ? 'Please enter 7 digits after "-".' : returnValue ;

    callback(returnValue);


text:
Q: Responsive Breadcrumbs with CSS Triangles and margin between items I want to make a breadcrumb simulating a progress bar , just like this

By default all items are gray and class " completed" the color green. But I have a problem with the last element , playing with width : spare me a space or skip to the next line .

This is my code (scss & html):

ul.progress-tracker {
  margin: 15px 0;
  padding: 0;
  overflow: hidden;
  &: before, &: after {
    clear: both;
  }
  li {
    list-style: none;
    &: first-child {
      a: before {
        display: none;
      }
    }
    &:last-child {
      padding-right: 8px;
      a {
        margin: 0;
        min-width: 30.09%;
        padding: 3px 0 0 8px;
        &: after {
          display: none;
        }
      }
    }
    a {
      content: "";
      display: block;
      float: left;
      height: 8px;
      background: tint($light-blue, 60%);
      text-align: center;
      padding: 3px 4px 0 8px;
      position: relative;
      margin: 0 10px 0 0;
      text-decoration: none;
      color: #fff;
      min-width: 31%;
      &: before {
        content: "";
        border-color: transparent;
        border-top: 4px solid transparent;
        border-bottom: 4px solid transparent;
        border-left: 4px solid $light-gray;
        position: absolute;
        left: 0;
        top: 0;
      }
      &:after {
        content: "";
        border-top: 4px solid transparent;
        border-bottom: 4px solid transparent;
        border-left: 4px solid tint($light-blue, 60%);
        position: absolute;
        right: -4px;
        top: 0;
        z-index: 1;
      }
    }
    a.completed {
      background-color: $primary-green;
      &: after {
        border-left-color: $primary-green;
      }
    }
  }
}

A: Solved:

ul.progress-tracker {
  padding: 0;
  overflow: hidden;
}
ul.progress-tracker:before, ul.progress-tracker:after {
  clear: both;
}
ul.progress-tracker li {
  list-style: none;
  float: left;
  min-width: calc(100% / 3);
  padding-right: 5px;
}
ul.progress-tracker li:first-child a:before {
  display: none;
}
ul.progress-tracker li:last-child {
  padding-right: 0px;
}
ul.progress-tracker li:last-child a {
  margin: 0;
}
ul.progress-tracker li:last-child a:after {
  display: none;
}
ul.progress-tracker li a {
  content: "";
  display: block;
  height: 8px;
  background: #bcc3c4;
  text-align: center;
  position: relative;
  text-decoration: none;
  color: #fff;
}
ul.progress-tracker li a:before {
  content: "";
  border-color: transparent;
  border-top: 4px solid transparent;
  border-bottom: 4px solid transparent;
  border-left: 4px solid #EAF3E3;
  position: absolute;
  left: 0;
  top: 0;
}
ul.progress-tracker li a:after {
  content: "";
  border-top: 4px solid transparent;
  border-bottom: 4px solid transparent;
  border-left: 4px solid #bcc3c4;
  position: absolute;
  right: -4px;
  top: 0;
  z-index: 1;
}
ul.progress-tracker li a.completed {
  background-color: #8ABD2E;
}
ul.progress-tracker li a.completed:after {
  border-left-color: #8ABD2E;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: npx react-native run-android doesn't start emulator and doesn't run if emulator is running I've created a new project using react-native 0.63
and when I run on ios simulator everything works fine
but when try to run it on android, it does not work and gives me this error
FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:installDebug'.
> SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at '/Volumes/SSD2/developer/MyProject/AwesomeProject/android/local.properties'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Run CLI with --verbose flag for more details.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081

i install react-native like
react-native Setting up
and this is the output from my react-native doctor
✓ Node.js
 ✓ npm
 ✓ Watchman - Used for watching changes in the filesystem when in development mode

Android
 ✓ JDK
 ✓ Android Studio - Required for building and installing your app on Android
 ✖ Android SDK - Required for building and installing your app on Android
   - Versions found: N/A
   - Version supported: 29.0.2
 ✖ ANDROID_HOME

iOS
 ✓ Xcode - Required for building and installing your app on iOS
 ✓ CocoaPods - Required for installing iOS dependencies
 ✓ ios-deploy - Required for installing your app on a physical device with the CLI

Errors:   2
Warnings: 0

and if I run npx react-native start then the application runs from android studio smoothly.
Edit
if i run project from terminal source .bash_profile
emulator start but project not run
"--no-jetifier" flag.
Jetifier found 5194 file(s) to forward-jetify. Using 12 workers...
info JS server already running.
info Installing the app...
env: sh\r: No such file or directory

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Run CLI with --verbose flag for more details.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
env: sh\r: No such file or directory

A: Looks like you need to set the ANDROID_HOME environment variable.
Add the following lines to your $HOME/.bash_profile or $HOME/.bashrc (if you are using zsh then ~/.zprofile or ~/.zshrc) config file:
export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools

Type source $HOME/.bash_profile for bash or source $HOME/.zprofile to load the config into your current shell. Verify that ANDROID_HOME has been set by running echo $ANDROID_HOME and the appropriate directories have been added to your path by running echo $PATH.
Please make sure you use the correct Android SDK path. You can find the actual location of the SDK in the Android Studio "Preferences" dialog, under Appearance & Behavior → System Settings → Android SDK.
References:

*

*https://reactnative.dev/docs/environment-setup 3. Configure the ANDROID_HOME environment variable

A: Configure the ANDROID_HOME environment variable
The React Native tools require some environment variables to be set up in order to build apps with native code.
Go to Home directory and show hidden files then add the following lines to your ~/.zprofile or ~/.zshrc (if you are using bash terminal, then ~/.bash_profile or ~/.bashrc) config file:
export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools

Run source ~/.zprofile or source ~/.zshrc  (or source ~/.bash_profile  or source ~/.bashrc for bash) in your root terminal to load the config into your current shell. Verify that ANDROID_HOME has been set by running echo $ANDROID_HOME and the appropriate directories have been added to your path by running echo $PATH.
Restart your system if still error persists.


text:
Q: Windows service starts again after manually stopping it. Why? I have a Windows service that is a custom API, it is running on Windows Server 2019.
When I manually stop it, it stops, but about 30 seconds later it restarts. The restarted service has a new PID. Setting the service to Automatic or Manual makes no difference: it still restarts. If I install the service on a different machine, a Windows 10, when I stop it, it stops permanently.
I have read that a manual service can be triggered to start, could this be what is happening? How might I find what triggers it?
Any idea what may be restarting it? How can I find what is restarting it? In the event log I notice there is always BITS activity around the Start/Stop events. Is this a coincidence?

A: A service can be started by another service which uses it. Have you check in the services configuration applet if your custom service is related with BITS or with any other service that could be using it?
Check in the recovery tab for your service configuration if the options there could be restarting it.
Is hard to affirm if BITS service is related with your custom service, but if there is a service dependence then that could be the reason for it be restarted. In your windows 10 computer, it can be disabled or the service dependence is not present. You can read more about BITS service here.
I found this and this documents about how to create a windows service application. I hope they could be helpful if there is something to check in your custom service.


text:
Q: Filtering Out Output I'm trying to make my command but don't know how to filter this output. This is the code:
@client.command()
async def userjoindate(ctx, username):
    user = await roblox.get_user_by_username(username)
    response = requests.get(f'https://users.roblox.com/v1/users/{user.id}')
    json_data = json.loads(response.text)
    joindate = json_data['created']
    await ctx.send(joindate)

If the user's id is for example 1 it will show this output:

2006-02-27T21:06:40.3Z

I want it just to be 2006-02-27

A: Use slice all characters after the date.
slice(None, 10, None)


text:
Q: checkemail validator parsley i use parsley Validator v2.9.2 and i want create custom validator to check if email is exist  on DB or!
I try this code:
window.Parsley
        .addValidator('checkemail',
        { requirementType: 'string',
         validateString:function (value, requirement) {
            var response = false;

            $.ajax({
                url: "<?php echo base_url('ajax/valid_user_email')?>",
                data: {username: value},
                dataType: 'json',
                type: 'post',
                async: false,
                success: function(data) {
                    response = true;
                },
                error: function() {
                    response = false;
                }
            });
            return response;
        },
        messages: {
  en: 'This value should be a multiple of %s',
  fr: 'Cette valeur doit être un multiple de %s'
}

});
But is not working! how i can fix this?
Thanks


text:
Q: Python Dictionary: removing extra list and convert into integer I have a dictionary like:
D = {0: [[' 11', '3', '6', '8']], \
     1: [[' 2']], \
     2: [[' 0', '2734', '394']], \
     3: [[' 1', '1163', '1216', '13', '181', '33', '379']]}

Things I want to do:

*

*Remove extra list from its value

*convert each element from its value into integer.

I tried a little like:

for k,v in D.items():
        D[k] = [i.split(',') for i in D[k] int(i) ]

But it does not work.

A: Try this
for k,v in D.items(): D[k] = [int(i.strip()) for i in v[0]]

v should be [[' 11', '3', '6', '8']] and v[0] should be the inner list [' 11', '3', '6', '8'].

A: Seems what you want is a dictionary with the value list unwrapped and converted to integers;
{x:[int(z) for z in y[0]] for x,y in D.iteritems()}

D.iteritems() returns all key/value pairs to iterate over, the key goes to x, the value goes to y. We iterate over y[0] (the inner list) to get the integer value for all elements, and turn them back into a list, resulting in;
{x:[int(z) for z in y[0]] for x,y in D.iteritems()}
# {0: [11, 3, 6, 8],
#  1: [2],
#  2: [0, 2734, 394],
#  3: [1, 1163, 1216, 13, 181, 33, 379]}

A: If each value in the dictionary is a nested list with the same number of nestings, the following list comprehension works (works with your sample data):
for item in D:
    D[item] = [int(numb) for numb in D[item][0]]


text:
Q: What scripting language to use for utility scripts? I am currently working on a large project and will relatively soon need a scripting language for utility scripts, like deploying the project in full from source, checking and fixing the database, building a ready to deploy bundle, and so on. The project is written in PHP and I thought about using it, but I dismissed that as not suitable for the task.
What I would mainly require would be, ordered by improtance:

*

*Portable across the top three OSs: Windows, Linux and OS X

*Lots of good libraries available, raging from file and directory manipulation to database access. GUI is not needed, though networking might be (download some stuff via FTP or HTTP). A big plus would be ability to natively checkout a Subversion repository.

*Good community support is required. Both Python and Ruby are excellent in this area.

*Extendability: if there is no good library available to do something, how easy is it for me to implement one or to use a native solution (execute a program, call a native function).

*Ease of deployment: how easy is it to get up and running on Windows (XP & 7, Server 2003+), Linux (CentOS 5.2, Ubuntu & Ubuntu Server 8.04+) and OS X (10.5+).

*Easiness of learning. While all scripting languages are not hard to learn for any programmer worth his salt, I'm interested in one that's rather quick and easy to learn.

That's all I can think of for now. I have reviewed Python and Ruby; Python satisfies all the requirements, and Ruby seems to as well, though I am not sure about ease of deployment on Windows and the availability of libraries. However, I am also looking for your experiences with using this sort of scripts written in the language of your choice.

A: Ruby is decent, but python is excellent. Python comes with great documentation, is easy to learn, has a large community, sports a very useful standard library, will be pre-installed on most unix-like systems, and is not too painful to install on Windows.

A: You said it: Python meets all the requirements.  That's my "vote" though I may be somewhat biased.
Edit: (on my first hand experience, in the context of tasks described in question)

*

*I have no experience with building releases from Python (I find Ant or even Make a better tool for this particular task).

*"Messing" with databases : a breeze !

*Moving files around, inspecting directories etc.  : a breeze!

A the risk of seeming either cocky or inexperienced, with regards to scripting-type activities, I've never painted myself in corner that Python didn't allow me to get out of.
A possible "critique" of Python however is, somewhat paradoxically, its extensive package library (in addition to its generous standard library); while it's nice to have all theses "3rd party" libraries, it can be sometimes difficult to gage the maturity, and effectiveness of some of these packages, and one sometimes wastes some time selecting these (or deciding whether to write "from scratch").  Yet, such evaluations can be fast enough however, thanks to the interactive nature of the interpreter.

A: http://ant.apache.org/
I use it for both Java and PHP projects. And to answer to your points:

*

*portability: 100%

*libraries for db, networking, i/o, svn: yes, some are built in, for the rest you use extensions

*community: many books and online resources

*extendability: yes, ant was designed to be extensible

*installation: dead easy

*easiness of learning: pretty easy

A: Python is a great scripting language and very portable.  It's my choice when portability of my scripts is the main issue.
But portability is seldom my main issue.  Most of my scripts deal rather intimately with OS issues.  So when I know I'm running on Windows and may not have python available, I use JScript under Windows Script Host.

A: Python, without a doubt. It meets all of your objectives and has the benefits of being concise and easy to learn.

A: iconiK,
This answer is only peripherally related to your question, but you're gathering more information than you need to solve this problem.  Your analysis and preliminary research are pretty impressive, and the cost of postponing your decision is higher than the marginal value of Python over Ruby or vice versa.

I am also looking for your experiences

My experience is that there's a limit to the amount you can learn about a technology through research, and my gut tells me you've already reached that limit.  You'll be better off if you stop researching and get on with your project.  If you can do a small pilot project, that will be great, but if not, you are at the point where you will learn more by just diving in than you can possibly learn by asking questions.
Probably my most recent salient experience is that in 1999 I had to decide whether a major compiler project would be written in Objective Caml or Haskell.  We choose Caml, and there have been many times I wished I had chosen Haskell, but in fact in 1999 Caml was probably the better choice, and certainly we did a lot of good work with that compiler.  The worst choice of all would have been to wait to gather more information.
I think the other lesson here is that because no technology is perfect, whatever technology you choose, you will have regrets.  Just because you have regrets does not mean you made the "wrong" choice.
Code in good health!

A: I use both Perl and Python extensively for scripting on Windows, so I wouldn't hesitate to use either for deployment. I would choose Python for its smoother learning curve.

A: Perl, except maybe for the learning curve. Portability is not a problem, for libraries there is CPAN, the community is perfect, calling external programs is not problem and you can always wrap a C library and installation is a no-brainer.

A: Python is really great for this kind of thing. I just wanted to draw your attention to Tcl which is absolutely awesome for general purpose scripting and file handling. Wikipedia entry about Tcl


text:
Q: how to list all files starting with How lists all files in the directory /usr/bin with names starting with "g" followed by "o" put the result inside new file under a directory
I'm tried to do this ls -al go* /usr/bin but this list all the files without the specified characters

A: ls takes a list of things to list.
ls -al go* /usr/bin means "List everything in the current directory starting with go and everything in /usr/bin".
You need to specify the one thing you want to list:
ls -al /usr/bin/go*

A: What about:
$ ls -al /usr/bin/go*
lrwxrwxrwx 1 root root     7 Apr 25  2017 /usr/bin/gold -> ld.gold
-rwxr-xr-x 1 root root 10304 Feb  7  2013 /usr/bin/gouldtoppm

A: cd /usr/bin
ls -al go* > file

or if you want to do it in a single command:ls -al /usr/bin/go* > file


text:
Q: LDAP - Use of wildcard on MemberOf filter I need to get all users and their groups from a specific category.
Examples of users :
user  | memberof
user1 | CN=group_1,OU=Groupes,OU=CR 1,DC=zcam,DC=ztech
user1 | CN=group_2,OU=Groupes,OU=CR 1,DC=zcam,DC=ztech
user2 | CN=group_2,OU=Groupes,OU=CR 1,DC=zcam,DC=ztech
user3 | CN=group_3,OU=Groupes,OU=CR 2,DC=zcam,DC=ztech

I need to get every user where memberof contains OU=Groupes,OU=CR 1,DC=zcam,DC=ztech (user1 and user2 from my example)
Following this doc (https://learn.microsoft.com/fr-fr/windows/desktop/ADSI/search-filter-syntax) I tried the following syntaxes :
DirectoryEntry ldap = new DirectoryEntry("LDAP://xxx.xxx.xxx.xxx");
using (DirectorySearcher searcher = new DirectorySearcher(ldap))
{
    // Works but return everything
    searcher.Filter = "(&(objectClass=user)(memberof=*))";

    // Works but only for one group
    searcher.Filter = "(&(objectClass=user)(memberof=CN=group_1,OU=Groupes,OU=CR 1,DC=zcam,DC=ztechh))";

    // Doesn't work because searcher.FindAll().Count returns 0
    searcher.Filter = "(&(objectClass=user)(memberof=*,OU=Groupes,OU=CR 1,DC=zcam,DC=ztechh))";

    // searcher.FindAll().Count returns 0
    foreach (SearchResult result in searcher.FindAll())
    {
        [...]
    }

Following this (https://community.servicenow.com/community?id=community_question&sys_id=00d29fa1db101fc01dcaf3231f96197f) I tried to change the wildcard * by a % but it didn't changed the result.

A:
I need to get every user where memberof contains OU=Groupes,OU=CR 1,DC=zcam,DC=ztech (user1 and user2 from my example)

If I understand correctly, I think that sentence sums up what you're trying to do. You want to find all users who are a member of any group in that OU.
Active Directory doesn't let you use wildcards on any attribute that takes a distinguishedName. That includes member and memberOf. So the only way to do this is in two steps:

*

*Find the distinguishedName of all groups in that OU.

*Search for all users whose memberOf includes one of the values found in step 1.

Something like this (I haven't tested this against AD, so you might need to tweak it):
var groupSearch = new DirectorySearcher(
    new DirectoryEntry("LDAP://OU=Groupes,OU=CR 1,DC=zcam,DC=ztech"), //notice the OU
    "(objectClass=group)");

//if you don't do this, it will return *every* attribute, which is slower
groupSearch.PropertiesToLoad.Add("distinguishedName");

//build a user query with all the groups
var userFilter = new StringBuilder("(&(objectClass=user)(|");
using (var results = groupSearch.FindAll()) {
    foreach (SearchResult result in results) {
        userFilter.Append($"(memberOf={result.Properties["distinguishedName"][0]})");
    }
}
userFilter.Append(")");

var userSearch = new DirectorySearcher(
    new DirectoryEntry("LDAP://DC=zcam,DC=ztech"),
    userFilter.ToString());

//userSearch.PropertiesToLoad.Add(""); //add only the attributes you need to make it quicker

using (var results = userSearch.FindAll()) {
    foreach (SearchResult result in results) {
        //do something
    }
}

Note that this will only find direct members of those groups. It won't return users that are in nested groups (when a user is in a group that is a member of one of these groups). If you want that, you can adjust the filter to include a special flag that tells AD to search recursively:
userFilter.Append($"(memberOf:1.2.840.113556.1.4.1941:={result.Properties["distinguishedName"][0]})");

Depending on your domain, you might want to be aware of two things:

*

*This will not return users who have one of these groups as their primary group, since that relationship is not stored using member/memberOf.

*If these groups have members from external trusted domains, then you'll end up finding Foreign Security Principal objects, instead of their actual user objects. That's a whole other thing to deal with, if it's an issue for you.

I've written a few articles on the subject, if you're curious. Start with this one: Active Directory: What makes a member a member?

A: edited version; extend for all your group_X
(
&(objectClass=user)
(|(memberof=CN=group_1,OU=Groupes,OU=CR 1,DC=zcam,DC=ztechh)
(memberof=CN=group_2,OU=Groupes,OU=CR 1,DC=zcam,DC=ztechh))
)

A: Finally I have found another way to do.
In fact, this property OU=CR 1 in the memberof correspond to the division in my AD.
So I just filter like this :
DirectoryEntry ldap = new DirectoryEntry("LDAP://xxx.xxx.xxx.xxx");
using (DirectorySearcher searcher = new DirectorySearcher(ldap))
{
    searcher.Filter = "(&(objectClass=user)(division=CR 1))";

    foreach (SearchResult result in searcher.FindAll())
    {
        [...]
    }

Thanks everyone for your help.


text:
Q: Limit of quotients of polynomials at fixed value Let $0<t<1$ be a parameter. Let $n\in\mathbb{Z}$, $n>0$. For $i\in\{0,1,\dots,2^n-1\}$, we always consider $i$ as having $n$ binary digits (positions $1$ to $n$), putting $0$s if necessary. Let $f(i)$ be the number of times the $j+1$-th binary digit of $i$ is different from the $j$-th digit, $1\leq j\leq n-1$. Let $g(i)$ be the number of $1$s in the binary expansion of $i$. We consider
$$
p(t,n)=\frac{\sum_{\substack{i=0\\i\equiv 1 \bmod 2}}^{2^n-1}(1/2)(1-t)^{n+f(i)-g(i)}(t)^{n-1-f(i)+g(i)}}{\sum_{i=0}^{2^n-1}(1/2)(1-t)^{n+f(i)-g(i)}(t)^{n-1-f(i)+g(i)}}.
$$
Numerical evidence shows that $p(3/4,n) \rightarrow \sqrt{3}/2$ as $n\rightarrow \infty$. May it be possible to inquire on how to prove it? Thanks very much.
(Perhaps this is similar to various limits involving binomial coefficients such as in the question "A limit involving binomial coefficients?" , but I don't know much about this subject. Thanks!)

A: First, cancelling common factors we get
$$p(t,n) = \frac{ \sum_{i=0\atop i\equiv 1\pmod{2}}^{2^n-1} \left(\frac{t}{1-t}\right)^{g(i)-f(i)} }{ \sum_{i=0}^{2^n-1} \left(\frac{t}{1-t}\right)^{g(i)-f(i)} }$$
Clearly, $f(i)$ is the number of 2-mers "01" and "10", while $g(i)$ is the number of 2-mers $10$ and $11$ in the binary representation of $i$. Then $g(i)-f(i)$ is the number of $11$ minus the number of $01$.
Let $w = \frac{t}{1-t}$. Consider the de Bruijn graph $G$ on the nodes $\{ 00, 01, 10, 11\}$, where all the arcs are weighted as follows:

*

*arcs incoming to $11$ have weight $w$;

*arcs incoming to $01$ have weight $w^{-1}$;

*the other arcs have weight 1.

That is, the adjacency matrix of $G$ is
$$A = \begin{bmatrix}
1 & w^{-1} & 0 & 0 \\
0 & 0 & 1 & w \\
1 & w^{-1} & 0 & 0 \\
0 & 0 & 1 & w
\end{bmatrix}.
$$
We interpret each $n$-bit integer (prepended and appended by "0") as a walk of length $n$ in $G$ starting at nodes $00$ or $01$ and ending at nodes $00$ or $10$.
Then the numerator of $p(t,n)$ is the total weight of all walks of length $n$ from node $01$ to node $00$ or $10$, while the denominator of $p(t,n)$ is the total weight of all walks of length $n$ from node $00$ or $01$ to node $00$ or $10$. That is,
$$p(t,n) = \frac{[0,1,0,0]\cdot A^n\cdot [1,0,1,0]^T}{[1,1,0,0]\cdot A^n\cdot [1,0,1,0]^T}.$$
From here, one can get an explicit formula for $p(t,n)$, but for the purpose of the question it's enough to consider $t=\frac{3}{4}$ and $w=3$. It follows that
$$p(\frac{3}{4},n) = \frac{\sqrt{3}}{2}\cdot \left(1+O\left(\left(\frac{3-\sqrt{3}}{3+\sqrt{3}}\right)^n\right)\right).$$


text:
Q: Why AMP with structured data requires at least 1200 pixels wide image? AMP pages that have structured data need at least 1200 pixels wide marked-up image. But the NON-AMP version only need 696 pixels wide image.
Any reason why the mobile search result needs such a large image?
Doc: Link to AMP DOC

A: If I were to make a guess I would say it is to ensure the images are crisp when viewed on a high DPI screen. 696px might look fine on something that has a fairly low DPI, but on a higher quality screen with a high DPI 696px may be fuzzy and probably show some JPG artifacts. Where as a 1200px image scaled down will remain crisp on all displays.


text:
Q: Annual return from monthly return I want to calculate annual return from the monthly returns. For example,
Annual Return=(1+ret_m1)*(1+ret_m2)+.....+(1+ret_m12)-1
How should I calculate in Stata?
  * Example generated by -dataex-. To install: ssc install dataex
clear
input double permno long date str8(ncusip cusip) double vwretd
10001 10255 "39040610" "36720410"    .04488041
10001 10286 "39040610" "36720410"    .05169475
10001 10317 "39040610" "36720410"   -.01659759
10001 10346 "39040610" "36720410"    .01099083
10001 10378 "39040610" "36720410"   .000447785
10001 10408 "39040610" "36720410"    .05145973
10001 10437 "39040610" "36720410"  -.007271962
10001 10470 "39040610" "36720410"   -.02800588
10001 10500 "39040610" "36720410"    .03720232
10001 10531 "39040610" "36720410"    .01764623
10001 10561 "39040610" "36720410"   -.01641204
10001 10591 "39040610" "36720410"    .02107465
10001 10623 "39040610" "36720410"    .06610259
10001 10651 "39040610" "36720410"   -.01644639
10001 10682 "39040610" "36720410"    .02146523
10001 10710 "39040610" "36720410"    .04820446
10001 10743 "39040610" "36720410"    .03933809
10001 10773 "39040610" "36720410"  -.004866142
10001 10804 "39040610" "36720410"    .07713073
10001 10835 "39040610" "36720410"     .0221267
10001 10864 "39040610" "36720410"  -.001474362
10001 10896 "39040610" "36720410"   -.02928529
10001 10926 "39040610" "36720410"     .0178139
10001 10955 "39040610" "36720410"    .01829512
10001 10988 "39040610" "36720410"   -.07011517
10001 11016 "39040610" "36720410"    .01490096
10001 11046 "39040610" "36720410"    .02414006
10001 11077 "39040610" "36720410"    -.0282857
10001 11108 "39040610" "36720410"    .08893429
10001 11137 "39040610" "36720410"  -.004196256
10001 11169 "39040610" "36720410"  -.009402919
10001 11200 "39040610" "36720410"   -.09190542
10001 11228 "39040610" "36720410"   -.05384322
10001 11261 "39040610" "36720410"   -.01250398
10001 11291 "39040610" "36720410"    .06574359
10001 11322 "39040610" "36720410"    .02951265
10001 11353 "39040610" "36720410"    .04907785
10001 11381 "39040610" "36720410"    .07584678
10001 11409 "39040610" "36720410"    .02892273
10001 11442 "39040610" "36720410"   .003314882
10001 11473 "39040610" "36720410"     .0407327
10001 11501 "39040610" "36720410"   -.04402925
10001 11534 "39040610" "36720410"    .04679512
10001 11564 "39040610" "36720410"     .0268165
10001 11595 "39040610" "36720410"   -.01097486
10001 11626 "39040610" "36720410"    .01781452
10001 11655 "39040610" "36720410"   -.03727527
10001 11687 "39040610" "36720410"     .1067778
10001 11718 "39040610" "36720410"  -.001182341
10001 11746 "39040610" "36720410"    .01335434
10001 11778 "39040610" "36720410"   -.02369961
10001 11808 "39040610" "36720410"    .01341884
10001 11837 "39040610" "36720410"   .006438549
10001 11869 "39040610" "36720410"   -.01927053
10001 11900 "39040610" "36720410"    .03989998
10001 11931 "39040610" "36720410"   -.02081965
10001 11961 "39040610" "36720410"    .01244722
10001 11991 "39040610" "36720410"    .01098552
10001 12022 "39040610" "36720410"    .04019304
10001 12053 "39040610" "36720410"    .01776835
10001 12082 "39040610" "36720410"    .01264374
10001 12110 "39040610" "36720410"   .005402277
10001 12143 "39040610" "36720410"     .0251157
10001 12173 "39040610" "36720410"   -.02540042
10001 12201 "39040610" "36720410"    .02959926
10001 12234 "39040610" "36720410"   .005440016
10001 12264 "39040610" "36720410" -.0007919354
10001 12296 "39040610" "36720410"    .03947853
10001 12326 "39040610" "36720410"  .0006406767
10001 12355 "39040610" "36720410"    .01806427
10001 12387 "29274A10" "36720410"   -.01760636
10001 12418 "29274A10" "36720410"    .01951495
10001 12449 "29274A10" "36720410"    .03146612
10001 12477 "29274A10" "36720410"   -.02422607
10001 12508 "29274A10" "36720410"   -.04579477
10001 12537 "29274A10" "36720410"   .009477681
10001 12569 "29274A10" "36720410"   .009360213
10001 12599 "29274A10" "36720410"   -.02790886
10001 12628 "29274A10" "36720410"    .03063324
10001 12661 "29274A10" "36720410"    .04259737
10001 12691 "29274A10" "36720410"   -.01836337
10001 12722 "29274A10" "36720410"    .01451999
10001 12752 "29274A10" "36720410"   -.03721879
10001 12782 "29274A10" "36720410"    .01260929
10001 12814 "29274A10" "36720410"    .02039915
10001 12842 "29274A10" "36720410"    .03961473
10001 12873 "29274A10" "36720410"    .02704092
10001 12901 "29274A10" "36720410"    .02504808
10001 12934 "29274A10" "36720410"    .03400705
10001 12964 "29274A10" "36720410"    .03117276
10001 12995 "29274A10" "36720410"    .04078258
10001 13026 "29274A10" "36720410"   .009303724
10001 13055 "29274A10" "36720410"     .0363627
10001 13087 "29274A10" "36720410"   -.01131678
10001 13117 "29274A10" "36720410"    .04280756
10001 13146 "29274A10" "36720410"    .01519028
10001 13179 "29274A10" "36720410"     .0281413
10001 13208 "29274A10" "36720410"    .01631008
10001 13237 "29274A10" "36720410"    .01092697
10001 13269 "29274A10" "36720410"    .02551078
end
format %d date

A: You can use asrol (from SSC) for this task. See
Code:
ssc install asrol
gen year = yofd(date)
bys permno year : asrol vwretd, s(product) add(1)


text:
Q: Find element and see if its active/hasClass I am trying to access a button in my leaflet map. The button is created using a plugin "easy-button".
My main goal is to see if the button has been clicked (is active), I will use it for validation in another function, not shown here.
This is how the html for the button looks like in the browser debugger (I believe the html is created by the plugin?).
Before it's clicked
<button class="easy-button-button leaflet-bar-part leaflet-interactive add-markers-active" title="Vis crosshair">

</button>

After it's clicked
<button class="easy-button-button leaflet-bar-part leaflet-interactive remove-markers-active" title="Fjern crosshair">

</button>

This click function access the button and show 'Button was clicked' but the if statement does not pass. I got to the button using Copy CSS path in the browser, but it seem really long.
$("div.leaflet-bar.easy-button-container.leaflet-control > button > span").click(function(){
        alert("Button was clicked");
        if
        ($('span').hasClass('fa fa-crosshair fa-lg'))
        {
            alert('My button has active class')
        }
});

Any advice on what I am doing wrong?

A: This
if($('span').hasClass('fa fa-crosshair fa-lg'))

Will not target the span you are expecting it to.
You wanted
if($('span',this).hasClass('fa fa-crosshair fa-lg'))

To target the child span of the span you clicked on

A: Run this example, hope it helps:

$(document).ready(function() {
  // My example to trigger the click on buttons..
  $("button > span > span").click(function(){

    alert("Button was clicked");

    if (
      //$(this).hasClass('fa') && <-- You don't need it, both have it
      $(this).hasClass('fa-crosshairs') &&
      $(this).hasClass('fa-lg')
    ) {
      alert('My button has active class');
    } else {
      alert('Ops..');
    }
  });
});

<button class="easy-button-button leaflet-bar-part leaflet-interactive add-markers-active" title="Vis crosshair">

        click me

</button>

<button class="easy-button-button leaflet-bar-part leaflet-interactive remove-markers-active" title="Fjern crosshair">

        clicked

</button>


text:
Q: Email reply-to not working We have an application for sending emails with the reply-to address.
When we reply to the email, the reply-to email address is inserted in To(target) column only if the email was received from Gmail server but not working if I use any other mail server.
And the message details are :-
For Gmail-
*smtp.mailfrom=abhishek.manav09@gmail.com;
Date: Thu, 23 Aug 2018 15:54:41 +0530 (IST)
From: Email <abhishek.manav09@gmail.com>
Reply-To: akshaykhurana97@gmail.com
To: akshaykumar@drishti-soft.com
Message-ID: <213945436.1.1535019881781@localhost>
Subject: CaseId-1535007334511:hello drishti
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="----=_Part_0_459502358.1535019879250"

------=_Part_0_459502358.1535019879250
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: 7bit*

For other mail server -
*smtp.mailfrom=support@nirmalbang.com
Received: from cc.nirmalbang.com (unknown [192.168.51.88]) (Authenticated sender: support) by mumbai.nirmalbang.com (Postfix) with ESMTPA id B8FAF9C1D4E for <akshaykumar@drishti-soft.com>; Thu, 23 Aug 2018 17:02:57 +0530 (IST)
X-Intloopheader: 0
Date: Thu, 23 Aug 2018 17:02:45 +0530 (IST)
From: support <support>
Reply-To: rajeshyadav@nirmalbang.com
To: akshaykumar@drishti-soft.com
Message-ID: <373728699.19.1535023965631@cc.nirmalbang.com>
Subject: CaseId-1534767184816:meramera
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="----=_Part_18_1180661698.1535023965621"
X-Netcore-MailScanner-Information: Please contact the ISP for more information
X-Netcore-MailScanner-ID: B8FAF9C1D4E.AB6D7
X-Netcore-MailScanner: Found to be cleanenter code here
X-MailScanner-From: support@nirmalbang.com
X-Spam-Status: No*


text:
Q: N2N VPN + Client VPN - recommended technology and network architecture? I have 2 networks
HOSTED: 10.0.1.0/24 (hosted server infrastructure (web-apps, databases, etc))

OFFICE: 10.0.2.0/24 (office infrastructure (file & print, databases))

Each has an ubuntu (NAT+Proxy) based firewall at 10.0.[12].1. (10.04 LTS server).
Each firewall has a second interface to the Internet (Internet-routable static IP presented on a standard ethernet interface).
Server infrastructure on both HOSTED and OFFICE is VMware ESXi-based.
Networks are not heavily used - it's a 35-person company, so we're not needing a full, enterprise-class solution here.
Workstations are MacOSX, Windows, Linux, and Windows VPN clients, in particular, need to be idiot-proof.
I want do the following:

*

*Connect both these networks together over a VPN (routed rather than bridged, I guess(?)) such that all hosts in the HOSTED and OFFICE networks can readily communicate with hosts on the other network (N2N VPN) regardless of where the connection was initiated from.

*Provide generic VPN services to mobile users such that these users can access both the HOSTED and OFFICE network once their VPN clients have logged in. (CLIENT-VPN).
Question: Using free or cheap technologies, how should I best set this up? My thoughts so far have been:

*

*OpenVPN VMWare images, one on each network - this looks affordable and looks impressive, but seems to be CLIENT-VPN centric, rather than N2N centric. Also, it looks as if the VPN software needs to run on my firewall hosts in order to do the N2N VPN. I'm not keen to replace my firewalls with these OpenVPN virtual machines.

*Hand-roll only the N2N VPN (how?) on my existing firewall machines, and then deploy the OpenVPN VMware image on my OFFICE network behind my current firewall, and have this manage only the CLIENT VPN traffic (via port forwarding on the OFFICE firewall).

*Use DD-WRT or similar?

I don't have a view on the relative benefits of PPTP, IPSec, SSL-VPN although I think the latter is probably best (gut-feel). I don't run WINS or anything other than IP on the networks, so I don't think bridging is needed. I will probably set up some kind of split-brain DNS infrastructure on the 2 networks to provide name services on the 10.x.x.x networks.
I'd welcome any suggestions on network architecture, VPN platform selection and solution design.
Thanks

A: OpenVPN is definitely versatile enough for network-to-network as well as client-to-network VPN in one installation - we've done it at numerous occasions with good results. The beauty of using OpenVPN lies in the option of having it set up redundantly with dynamic routing protocols - something that is not done as easily with IPSEC solutions.
But OpenVPN clients might be not as foolproof as your users would require it to be - you'd need to do some user acceptancy tests beforehand.
Whether you use ESXi VMs or separate router devices with DD-WRT or OpenWRT is a question of your performance, management and availability requirements - technically, you would run Linux and OpenVPN in either case.


text:
Q: How to loop with random.choice and alternation? I'm trying to create a random name generator where the length of the name is 8 characters long. I want it to alternate between 1-2 vowels and then 1-2 consonants until it reaches the 8 character length.
Answer found, messed up the update to the code on here so i had to delete it, but the checkmark is the right way.

A: You should use while loop instead if statement.
import random

vowels=('a', 'e', 'i', 'o', 'u', 'y')
consonants=('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p',
            'q', 'r', 's', 't', 'v', 'w', 'x', 'z')

full_name = random.choice(vowels) + random.choice(consonants)

while len(full_name) < 8:
    full_name += random.choice(vowels) + random.choice(consonants)
else:
    print(full_name)


text:
Q: Get data from other component in react I have a constant that receives a json with a fetch like this:
const [user, setUser] = useState([]);
 async function users()  { const result = await fetch (My API `,{
})
const data = await result.json();
setUser(data);`

and i wanted to show her data in another component, for example just the name or just the id.
I want to put only the name on this little blue block : this is the other component
more of the second component

A: The first component is the one where you obtain the data and the second the one you display it since your an receiving the user data by props
function FirstComponent(){
const [user, setUser] = useState([]);

 return (
   <SecondComponent user={user} />
 )
}

function SecondComponent({user}){
 console.log(user)

 return (
   //Here the code of the image you show
 )
}


text:
Q: java -version cannot be recognized, while PATH and JAVA_HOME are both set, windows 8 I am using windows 8, and have tried to set JAVA_HOME as

 C:\Program Files\Java\jdk1.8.0_05

And PATH as

%JAVA_HOME%\bin

When I reopen the console, PATH still gives me:

PATH = C:\Program Files .....; C:\Program Files\Java\jdk1.8.0_05\bin

When I do cd %JAVA_HOME%, it guides me to the java directory:
C:\Program Files\Java\jdk1.8.0_05
but when I open another new console and type java -version javac or 'jar', it reports error of "java/javac/jar" is not recognized as an internal or external command operable program or batch file....
So are there anything else that I didn't do? Isn't PATH clear enough to give the path to find "java"?
THanks!

A: The bin dir of your JAVA_HOME directory needs to be on your path.  Try
    echo %PATH%

to confirm whether or not this is the case.

A: Try setting the PATH and JAVA_HOME system environment variables.
See this.


text:
Q: Display full width tab underline in syncfusion angular I am using syncfusion angular for UI in our application i am stucked with some UI thing . I need to display full width underline tabs like show in below image.

But i can only develop like this.

i need to display that tab underline full width like shown in first picture. please help me with this.

*

*syncfusion html

<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#0d6efd" class="bi bi-arrow-left" viewBox="0 0 16 16">
          <path fill-rule="evenodd" d="M15 8a.5.5 0 0 0-.5-.5H2.707l3.147-3.146a.5.5 0 1 0-.708-.708l-4 4a.5.5 0 0 0 0 .708l4 4a.5.5 0 0 0 .708-.708L2.707 8.5H14.5A.5.5 0 0 0 15 8z"/>
        </svg> Back to Previous

        <ejs-tab #tab id="element" heightAdjustMode='Auto' overflowMode='popup' (selected)='onTabSelect($event)'
          [selectedItem]="item" >
          <e-tabitems>
              <e-tabitem [header]='headerText[0]' ></e-tabitem>
              <e-tabitem [header]='headerText[1]'></e-tabitem>
              <e-tabitem [header]='headerText[2]'></e-tabitem>
              <e-tabitem [header]='headerText[3]'></e-tabitem>
              <e-tabitem [header]='headerText[4]'></e-tabitem>
              <e-tabitem [header]='headerText[5]'></e-tabitem>
              <e-tabitem [header]='headerText[6]'></e-tabitem>
              <e-tabitem [header]='headerText[7]'></e-tabitem>
              <e-tabitem [header]='headerText[8]'></e-tabitem>
          </e-tabitems>
        </ejs-tab>

A: Give border-bottom to "Back to previous" div?

A: It is not possible to show full tab underline for tabs using property (or) methods. Also, we have prepared sample to replicate your issue based on the shared snippets. But, custom element and tab not rendered in same row.
Can you please share the below details which will help us to provide
solution using customized style if possible?

*

*Replicate the issue in below sample (or) share issue replicating
sample if possible

*Share all the style related code snippets
https://stackblitz.com/edit/angular-tab-full-width?file=app.component.html


text:
Q: How to write where Between query in Yii2 with integer as a second parameter I have this query in PostgreSQL that I want to implement in my model in Yii2:
SELECT *
FROM some_table
WHERE 1492257600 BETWEEN start AND end

start and end are attributes of some_table.
In my model, I tried the following but, no matter how I write it, it keeps throwing the same error.
$results = static::find()->where(['between', 1492257600, 'start', 'end'])
                ->all();

This is the error I'm getting:

Undefined column: 7 ERROR:  column \"1492257600\" does not exist
The SQL being executed was: SELECT * FROM \"some_table\" WHERE \"1492257600\" BETWEEN 'start' AND 'end'"

When the query is built, these symbols " " are added to the integer, so PostgreSQL thinks it is a column of the table.
Can anyone tell me how to write the where between correctly?

A: There is dedicated BetweenColumnsCondition expression for such cases:
use yii\db\conditions\BetweenColumnsCondition;

$results = static::find()
    ->where(new BetweenColumnsCondition(1492257600, 'BETWEEN', 'start', 'end'))
    ->all();

It automatically quotes column names and escapes value, so it should be more convenient than simple yii\db\Expression.

Also note that WHERE 1492257600 BETWEEN start AND end may be slower than WHERE 1492257600 >= start AND 1492257600 <= end, I suggest to do some performance test if your table may grow big and usage indexes is crucial.

A: I don't have experience with postgresql but this will work same as between,
$results = self::find()
   ->where(['>=', 'start', 1492257600])
   ->andWhere(['<=', 'end', 1492257600])
   ->all();

A: Refer to this: Yii2 Doc
When an Expression object is embedded within a SQL statement or fragment, it will be replaced with the $expression property value without any DB escaping or quoting.
so You'll have something like this:
$expression = new \yii\db\Expression('1492257600 BETWEEN start AND end');
$results = self::find()->where($expression)
            ->all();


text:
Q: Add blend Button to visual Studio project I draged style->simple button and copied the xml and placed in my visual studio xml every thing is resolved except one
<Button Content="Button" Margin="814,496,22,29" Style="{DynamicResource SimpleButton}"/>

xml gives error at DynamicResource and says not resource not found where as if i see this line by opening the solution made in blend and mouse over it says it is
MS.Internal.Design.Metadata.ReflectionTypeNode

so surely this is missing but cannot find it to add
please help

A: In the Blend project you should have a file called "Simple Styles.xaml". Copy it to your Visual Studio project and add reference to it in your App.xaml:
<Application
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="MyApplication.App">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Simple Styles.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>


text:
Q: Current Leakage calculations regarding shock hazard. A complete picture? There is a quantity called current leakage which has always confused me. By reading various definitions, it seems to be the current flowing through the ground circuit of a device (whether this be an actual safety circuit for class I appliances, or the human body in the case of class II appliances). Some sources say it's the current flowing through the insulation, and when a human contacts a conductive part; the current leakage flows through the human.
My question is; how exactly does this quantity come into play when compared to the typical way of thinking about electric shocks (the applied voltage divided by resistance, then refer to a table of safe current limits)
I found this post interesting What is the right way to understand the behaviour of shocking voltage?
Considering all this information, something doesn't feel quite right. The issues I have are the following :
1) Is current leakage simply the maximum current that would pass through the body? (If that's the case, how would you work out the actual current passed through the body?)
2) How is current leakage related to the 'applied voltage' from above? If currentleakage x insulation resistance = 'applied voltage', this would lead to ridiculous results such as dying if you touch plastic.
3) can the body be treated simply as a parallel resistor? I've followed through with some of these calculations and the numbers don't make sense. And current leakage seemed to be made redundant/irrelevant even though it's clearly not due to PAT testing.
4)What ever happened to the law of 'current is the same in series'? When you touch an insulator, you are in series with it (if you are connected to the ground)?

A: Leakage currents are usually currents that are capacitively coupled to (for example) a chassis.  If a user could touch the chassis, AND the chassis is not grounded, then the potential on the chassis could cause a current to flow in the user and cause a shock.  Remember, two conductors separated by an insulator form a capacitor and it will conduct AC current according to I=C*dv/dt.
One example of this is the Y-capacitors used in power supplies for EMI filters.  Both sides of the line are connected through capacitors to chassis ground to filter the high frequency conducted EMI.  Now, if the ground prong on the AC cord is not connected (for whatever reason) the Y-Caps will cause the potential on the chassis to rise and you can feel a tingle if you get between the chassis and ground.
Regulatory requirements are such that the Y capacitors should not pass enough current to cause danger, but there are other potential paths for leakage currents as well.  A switching transistor mounted with an insulator to a grounded heatsink also capacitively couples currents into the chassis.
There's no violation of Kirchoff's current law in any of this.


text:
Q: Block write access to table from an application in mysql We have a CMS plugin that writes statistics to 1 table, this creates performance issues on the entire platform. We decided to use another statistics plugin which can connect to a different database server (the first plugin couldn't!) however we need parts of the first plugin.
I want to lock the statistics table to prevent misusage (not allowed to drop it by the developer), so I was wondering if a lock table could do this or if I can implement some sort of read only table?

A: *

*you could use the 'grant' command to restrict access to the table .. but the app might not like that!

no matter what you do, it would be best to prevent that plugin from writing (config options? less verbosity etc)


text:
Q: variable is not set & form submission error question Having a little bit of trouble with this section of code:
if(!empty($_POST['RemoveRequest']) && isset($_POST['RemoveRequest'])){ $action = $_POST['RemoveRequest']; }
echo '<form method="post" action="'.$page_name.'">
<input type="submit" value="[Remove Request]" name="RemoveRequest" /></form>	'
.'

';

if($action == 'RemoveRequest'){

$sql = "DELETE FROM ".TBL_FACTION_REQUESTS." WHERE r_id=$id LIMIT 1";
mysql_query($sql);
header("Location: ".$page_name."");

}

This form and server code is throwing this error:

Notice: Undefined variable: action in C:\xampp.. on line 97.

Then the record isn't deleted from my DB.
I'm really confused at what i'm doing wrong here? Tried a bit of debugging myself, but haven't had any luck yet. Hoping someone can help me out!

A: It looks your opening condition isn't evaluating to true -
if(!empty($_POST['RemoveRequest']) && isset($_POST['RemoveRequest']))

If this statement doesn't evaluate to true, $action doesn't get set. The warning you're seeing ("Undefined variable..") means that the first time $action is being encountered in the above script flow it hasn't had any value set
// action hasn't been set by here..
if($action == 'RemoveRequest'){

If $action isn't being set, then it obviously won't evaluate to RemoveRequest, so the block of code with your db query will never run.
When debugging it, try to print out the value of $action and $_POST['RemoveRequest'] on the second line of your code. It may be that the variables are not getting set in the way you anticipate by the form which is posting to this script.

A: Have you tried wrapping the if command like so:
if( !(empty($_POST['RemoveRequest'])) && (isset($_POST['RemoveRequest'])) ){
   $action = $_POST['RemoveRequest'];
}

That's the only thing that will stop your variable from not being defined. Also, you may want to change value="[Remove Request]" because it will never evaluate true for if ($action =='RemoveRequest')

A:
error is of level E_NOTICE. Need to
  add this code before the code:

 $action = "";


text:
Q: IFERROR Vlookup outputs 0, How to avoid this =IFERROR(VLOOKUP(AS:AS,'Data'!B:G,6,FALSE),"")

This formula outputs value 0 when there is no item to vlookup in column AS:AS, How do I avoid the 0, to output only blank?

A: Try passing in NA if the cell value be missing:
=IFERROR(VLOOKUP(IF(AS:AS="",NA(),AS:AS),'Data'!B:G,6,FALSE),"")

The idea here is that empty cells would pass #N/A to VLOOKUP thereby causing an error, and causing the error message to print (in your case you have chosen empty string).

A: A formula will always output 0 from a blank cell.
You can fix it by:

*

*Use cell formatting such as 0;-0;;@

*Use =T(...) if you're expecting text

A: I'd advise you to use a single cell as a lookup value and the specific range for your lookup array so that there's no possibility of the formula returning zero unless that's a valid result from your table, e.g. in row 2 copied down if required
=IFERROR(VLOOKUP(AS2,'Data'!B$2:G$100,6,FALSE),"")


text:
Q: Simple pattern rule in make I've written a simple make to test with pattern rule. Here it is:
default:
    echo This is default target
%.o:%.c
    gcc -c $< -o $@
clean:
    rm -f *.o

I have a three *.c files in pwd. After make command I have:
echo This is default target
This is default target

but I expected that any *.c file in pwd will be compiled.

A: The first target in the makefile is the one that is built when you do not specify a specific target name.
In your makefile, default is first, so it is created.
Often, you'll create a target all as the first target, and list the programs that should be built by some more or less devious means.
.PHONY: default all clean

default:
    @echo "You must specify which program you want built (or specify all)"

SRCS = $(wildcard *.c)
PROGS = ${SRCS:.c=}

all: ${PROGS}

%.o:%.c
    gcc -c $< -o $@

clean:
    rm -f *.o

The .PHONY target specifies that default, all and clean are not real files but phony targets.
I have a directory with many source files in it, and I have a default rule similar to the above as the first target, but I also have an all target so that make all works sensibly.
I prefer to use the ${...} notation around make variables, which make has always accepted; many people use $(...) notation the whole time.

A: I think default is your program target, but it did not link any objects? see my makefile:
SRCS = $(wildcard *.c)
OBJS = $(patsubst %.c, %.o, $(SRCS))

default:
    @echo This is default target
Program: $(OBJS)
    gcc $^ -o $@
$(OBJS): $(SRCS)
    gcc -c $^
clean:
    rm -f $(OBJS) $(Program)

if you type make, it just echo This is default target, if you want to make real target, you can type make Program


text:
Q: python - generate a unique integer even if multiple scripts are running simultaneously? I have a function that rapidly inserts data into a database and I need to also store a unique integer for each function.
I was considering using rounded microtime however since there are multiple scripts running at the same time I'm worried about running into conflicts.
Can someone recommend a solution?

A: You should indeed prefer a mechanism to generate the ID by the database incrementingly.
You could have a look at the uuid module to generate random IDs on the Python side:

This module provides immutable UUID objects (the UUID class) and the functions uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5 UUIDs as specified in RFC 4122.

As per RFC 4122 [emphasis mine]:

This specification defines a Uniform Resource Name namespace for
     UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally
     Unique IDentifier).  A UUID is 128 bits long, and can guarantee
     uniqueness across space and time.  UUIDs were originally used in the
     Apollo Network Computing System and later in the Open Software
     Foundation's (OSF) Distributed Computing Environment (DCE), and then
     in Microsoft Windows platforms.
This specification is derived from the DCE specification with the
     kind permission of the OSF (now known as The Open Group).
     Information from earlier versions of the DCE specification have been
     incorporated into this document.

A: There are several possible approaches:

*

*Delegate the generation of unique ids to the database engine. Many engines provide such a facility.

*Have a centralized service of your own that would generate the ids, and have your scripts talk to that service.

*Have each script generate its own ids; to ensure uniqueness, incorporate into the id a token that's unique to the script (e.g. process id and/or IP or MAC address).


text:
Q: Stock Returns comparsion in R I have two return series in R. I want to compare the each observation in these series. The problem is that if I compare two observations with negative signs, It gives the results that minimum value is greater than maximum. For example if I have -0.5 and -1.2 as returns for a particular month. It will term -0.5 as greater value. Mathematically this is right. But in financial terms if a stock delivers -0.5% and another -1.2%, stock with -1.2% produce greater losses, that stock should be selected. Suggest how this problem can be solved. I have try to replicate the code. Please check below code
library(Lock5Data)
library(lubridate)
library(tbl2xts)
options(scipen = 999)
SandP500$Date<-mdy(SandP500$Date)
SandP500<-tbl_xts(SandP500)
SandP500<-SandP500[,4]
SandP500$logret_1<-diff(log(SandP500),lag=1)
SandP500_data<-SandP500[,1]
SandP500_log36ret<-diff(log(SandP500_data),lag=36)
SandP500_fulldata<-cbind(SandP500,SandP500_log36ret)
names(SandP500_fulldata)<-c("close","log1","lag36")
SandP500_fulldata<-SandP500_fulldata[-1:-36,]

ifelse(SandP500_fulldata$lag36>SandP500_fulldata$log1,"normal","abnormal")["2014-08-12"]
## Check observation on
SandP500_fulldata["2014-08-12"]

A: You could try using abs(). For example,
ifelse(SandP500_fulldata$lag36<0 & SandP500_fulldata$log1<0,
               (ifelse((abs(SandP500_fulldata$lag36))>(abs(SandP500_fulldata$log1)),"normal","abnormal")),
               (ifelse((SandP500_fulldata$lag36)>(SandP500_fulldata$log1),"normal","abnormal")))

gives,
           lag36
2014-08-12 "normal"

Here is a very clear explanation of the nested ifelse:
https://stackoverflow.com/a/18016872/13249862.


text:
Q: Coefficient of function with general argument I would like to obtain the coefficients of a general function f in a list. For example, the coefficient list of
testList = {{2 f[2] + 3 f[3]},{2 f[1]}, {Sqrt[2] f[4]}}

should be the list
{{2,3},{2},{Sqrt[2]}}

I've tried the obvious solution
CoefficientList[testList, Variables[testList]]

But this gives me a lot of extra information, plus requires a few more array operations to write it in the correct form. I was wondering if there was a more efficient way to do this, since my lists will be eventually very large?

A: Cases can be used to extract a value that's part of a pattern:
Cases[#, x_ f[_] -> x, Infinity] & /@ testList

Out:
{{2, 3}, {2}, {Sqrt[2]}}


text:
Q: how use laravel 7 passport with mongodb? I installed jenssegers/laravel package to use mongodb in my Laravel project, but when I try to install passport I get this error :

Call to a member function prepare() on null

I tried to use designmynight package, but it seems it is not compatible with jenssegers v4 that I use for Laravel 7 .
Any idea how to fix this problem?

A: It's Very Simple.Without any extra package it's possible.
Only edit AuthCode.php,PersonalAccessClient.php,Client.php and Token.php in this path:
"/vendor/laravel/passport/src/"
replace this line:
use Jenssegers\Mongodb\Eloquent\Model;

by this line:
use Illuminate\Database\Eloquent\Model;

Notice:if you use multi connection specific your mongo connection in all of top Model,like this:
protected $connection = 'mongodb';

A: Currently I'm using Laravel 8 with Jessengers V4 and I had the same issue
Inside vendor of passport just replace with:
use Jenssegers\Mongodb\Eloquent\Model

Instead
   use Illuminate\Database\Eloquent\Model;

Everything works properly. I recommend write a script which automatically replace, maybe using command "sed" or fork the project.

A: this is worked for me

*

*create passport models in Models folder Authcode,Client,PersonalAccessClient,Token

*copy original code from /vendor/laravel/passport/src/ and paste

*edit namespace and replace use Jenssegers\Mongodb\Eloquent\Model
Instead use Illuminate\Database\Eloquent\Model;

*Add the following code to boot() method in AppServiceProvider.php

$loader = AliasLoader::getInstance();
$loader->alias(\Laravel\Passport\AuthCode::class,\App\Models\Passport\AuthCode::class);
$loader->alias(\Laravel\Passport\Client::class,\App\Models\Passport\Client::class);
$loader->alias(\Laravel\Passport\Token::class,\App\Models\Passport\Token::class);
$loader->alias(\Laravel\Passport\PersonalAccessClient::class,\App\Models\Passport\PersonalAccessClient::class);


text:
Q: How to return an array using awk through Bash script from a remote server SCENARIO
A file users.yml contains several usernames and passwords. Some of the usernames and passwords are repeating. For instance...
xxxxx
username: abc
password: abcpwd
xxxxx
xxxxx
username: adam
password: adampwd
xxxxx
xxxxx
username: adam
password: adampwd
xxxxx

A script file script.sh is trying to get all the line numbers where usernames from the users.yml matches the criteria.
username='adam'
filepath='/etc/myServer/users.yml'

#Gets the line number for the username
userNameLineNumbers=`awk -v line='^.*username: '$username'' '$0~line {print NR}' $filepath`

echo "username line number: "$userNameLineNumbers  #output: username line number: 6 10

This script is working fine if I run the script on the same machine where the users.yml is resided. However, the problem is...
PROBLEM
The script does not work if I keep the script on another server and try to get the line numbers from the file remotely.
I tried several ways to get the line numbers using ssh but unable to do it. I am not an expert on bash scripting, but still tried the following command in different ways and each time it gives some weird results instead of giving me line numbers from the file.
script="sudo awk -v line='^.*username: '$username'' '$0~line {print NR}' $filepath"
userNameLineNumbers=$(ssh -o "StrictHostKeyChecking no" -tty -i "$PEM_FILE" "user@remotehost.xyz" $script )

DESIRED OUTPUT
Looking for a solution to get the line numbers as an array from a file on a remote server where awk matches the criteria.

A: Two changes I can think of:

*

*use eval for running the command inside $script variable

*Escape $ in $0. Otherwise it gets expanded to the value of $0, which gives the command used to invoke current shell (eg. -bash)
script="sudo awk -v line='^.*username: '$username'' '\$0~line {print NR}' $filepath"
userNameLineNumbers=$(ssh -o "StrictHostKeyChecking no" -tty -i "$PEM_FILE" "user@remotehost.xyz" eval $script )


text:
Q: CRM Explorer does not show plug-in assemblies I'm using Visual Studio 2015 with Microsoft Dynamics 365 Developer Toolkit and 365 SDK.
Everithing was fine developing plug-ins but since last week CRM explorer does not show plug-in assemblies.
There are no errors, I connect CRM explorer to my organization, select a solution and it loads.
I can see entities and the rest of things but when I click on Plug-in Assemblies to expand it, It keeps loading for a few seconds and nothing appears.
Does anyone know what happens to my CRM Explorer?
Thanks in advance.

A: I noticed this too. I had a plugin project with ILMerge, and the CRM explorer wouldn't load plugins, if Microsoft.Xrm.Sdk was not merged into the plugin dll. Even though it's not required when deploying to online.
Update: I found out that if you copy just the Microsoft.Xrm.Sdk.dll in the build folder with the plugin dll, CRM explorer will load plugins just fine. So no need to merge it.


text:
Q: swf every time reloading in iframe in AngularJs I am using AngularJs 1.6.3 version for my project. Here i faced one problem while displaying flash swf in iframe.
Here i have one html file and its controller. Here that html file has one iframe to load flash swf file.
I have one button, whenever i click that button it will create one angular js state with that html and its controller. Each state included by ng-include in one single div.
When i am switching to one state to another state every time that flash swf reloaded it happening in FireFox browser only, in chrome its working fine.
Other websites link also i put in iframe that also not reloading everytime.
I have spent full day for this but it could not find solution.
You guys have any idea or solution please share here it will help a lot to me.
Thanks,
Selvam

A:

*

*"Html file has one iframe to load flash swf file...  Every time that Flash SWF reloaded"

*"Other websites link also i put in iframe that also not reloading everytime."

Try embedding the SWF inside HTML file (see example code)...
Then simply load the same (container) HTML file inside your <iframe>.


text:
Q: OpenShift Pro - Tomcat Running But App Not Started I've upgraded to OpenShift Pro and I am trying to get one of my own web apps to work.
The source code is on GitHub and any code I push from my local IDE causes a build, so that all seems ok.
Tomcat is running, I can see that when I enter the url /docs. But my app is not running.
The logs show (abbreviated for clarity):
Starting Servlet Engine: Apache Tomcat/8.0.18
Deploying web application directory /deployments/manager
Deployment of web application directory /deployments/manager has finished in 1,762 ms
Deploying web application directory /deployments/docs
Deployment of web application directory /deployments/docs has finished in 514 ms
Deploying web application directory /deployments/host-manager
Deployment of web application directory /deployments/host-manager has finished in 471 ms
Starting ProtocolHandler ["http-apr-8080"]
Server startup in 2815 ms

As you can see, manager, docs and host-manager have all started but I was expecting to see something like the following after the Starting Servlet Engine line:
Deploying web application archive /deployments/ROOT.war
Deployment of web application archive /deployments/ROOT.war has finished in 2,560 ms

Please note that the OpenShift App name is not the same as my local Eclipse Project name. When I run this Eclipse Project locally the context is 'stripes', and a request looks like localhost:8080/stripes/Test.action
Any ideas?
Have I missed something out?
Any help would be much appreciated...

A: It looks like that in this case, the built ROOT.war was not found in the /tmp/src/target directory and deployed automatically by the s2i image.
This could be somehow tricky to spot, as the build log is just missing one line in that case. If the built war file is in the correct location, you should see a message in the log that the ROOT.war file (or any other name, if not deploying in the root context) has been copied into the /opt/webserver/webapps/ directory, right under the "Copying all target war artifacts from..." line, such as:
(...)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1:02.946s
[INFO] Finished at: Fri Sep 08 13:59:42 UTC 2017
[INFO] Final Memory: 18M/288M
[INFO] ------------------------------------------------------------------------
Copying all target war artifacts from /home/jboss/source/target directory into /opt/webserver/webapps for later deployment...
'/home/jboss/source/target/ROOT.war' -> '/opt/webserver/webapps/ROOT.war'
(...)


text:
Q: Customizing locals based on Devise scopes I have a User and a Client model setup to use Devise with different sign-up workflows. I want to customize the locals based on the resource (Client or User). For example, instead of using the default devise message in config/locals/devise.en.yml for unconfirmed accounts
unconfirmed: 'You have to confirm your account before continuing.'

I want two separate messages for Client and Users.
Is there a way to do this by setting up two different locales? e.g., something like,
devise.user.en.yml

and
devise.client.en.yml

A: It can be done in one file like this:
 en:
      devise:
        sessions:
          user:
            signed_in: 'Welcome user, you are signed in.'
          admin:
            signed_in: 'Hello admin!'

Where user and admin are the resources. Clients and users in your case.
https://github.com/plataformatec/devise


text:
Q: Passing parameters to method, for accessing a CoreData attribute I have customized the CoreDataBooks sample app and am adding a whole host of Bools. Essentially, I am turning it into a restaurant app, so I want to have Bool values for things like "Dinner" "Seafood" "Cocktails" "Kid Friendly" etc..
In my Detailview Controller, I have selected an item (book) and can alter the Bool values in CoreData - for an attribute named seafood, like this -
     self.book.seafood = NO;

or
     self.book.seafood = YES;

These values are each toggled with their own button (actually looks like a checkbox in my app)
However, because there may be 60 or 80 Bools, and I'd like to add more later, I'd like to write one function which I can use for all of them that uses a tag or passes a parameter. I'd like to write something like this, but I feel like I am missing a step. It clearly won't let me pass a parameter in to self.book.button:
      -(IBAction) switchValue:(*UIButton)button{

      tmpBool = self.book.button

     if (tempBool == YES) {
            self.book.button = NO;

            UIImage *buttonImage = [UIImage imageNamed:@"checkOff.png"];
            [self.button setImage:buttonImage forState:UIControlStateNormal];

            NSLog(@"nwSwitched to NO");
        }
        else{

            self.book.button = YES;

            UIImage *buttonImage = [UIImage imageNamed:@"checkOn.png"];
            [self.button setImage:buttonImage forState:UIControlStateNormal];

            NSLog(@"nwSwitched to YES");
        }

As it stands now, the only way I can make it work is with a huge series of if/thens or with switch, but I know there must be a more elegant way.

A: As Carl said, this was an inelegant approach. I instead switched and now keep all the tags in one CoreData attribute called "tags". To add and subtract them I simply add to the string or find a replace with @" ", to remove them. I can then search against them later.
In order to manage the long list of tags, and to add to them easily, I used a PickerView, which is set using an NSMutableArray, which I store in NSUserDefaults. (You have to make a mutable copy when you re-load it.)
Yes, you could keep the list of tags in CoreData, but this seemed easier for my purposes.


text:
Q: Enable SSL in Mongo 3.0.5 I have been able to start mongo in ssl mode with the following command:
mongod --sslMode requireSSL --sslPEMKeyFile ~/datastore.pem --sslCAFile ~/datastore.ca-bundle
datastore.pem was created by combining .crt (issued by comodo ssl) and .key (used during generating csr)
I am trying to connect to my mongo instance with the below command:
mongo --ssl --sslPEMKeyFile ~/datastore.pem --sslCAFile ~/datastore.ca-bundle
I get the following message when I try to connect:
MongoDB shell version: 3.0.5
connecting to: test
2015-08-10T03:35:43.456+0000 E NETWORK  SSL peer certificate validation failed:certificate not trusted
2015-08-10T03:35:43.458+0000 E QUERY    Error: socket exception [CONNECT_ERROR] for
    at connect (src/mongo/shell/mongo.js:179:14)
    at (connect):1:6 at src/mongo/shell/mongo.js:179
I am very new to SSL setup in mongo, any pointers to successfully connect to mongo using SSL would be helpful, I have read the security section of 10gen multiple times but no direct answer.


text:
Q: coq- Prove some expressions do not terminate I need to prove this theorem.
        Theorem expr_not_terminate:
          ~(forall (e : expr) (s : state),
            exists (v : value),
              evalExpr e s v).
        Proof.
          unfold not.
          intros.

As soon as I do 'intros' it brings  'H : forall (e : expr) (s : state), exists v : value, evalExpr e s v' in the hypothesis. and I am not able to do anything on that. How do I break the hypothesis? ANy idea?

A: You can exhibit a particular expression and a particular state that falsify the claim, and instantiate your hypothesis with those using eg the specialize tactic. Then use that hypothesis in the context (probably with induction) to drive a contradiction, allowing you to show false.


text:
Q: Firebase app distribution: How to add testers to tester group automatically with command? I am using the below Firebase command to invite testers to my Firebase app as per the documentation here: https://firebase.google.com/docs/app-distribution/ios/distribute-cli
firebase appdistribution:testers:add anothertester@email.com moretesters@email

We maintain two tester groups for these testers for our app. The above command only adds testers to our app's portal but not to the tester groups.
Is there a command/way to add the testers to a particular tester group automatically?
Things I have tried so far:

*

*Tried using --group and --groups flag which are used in firebase appdistribution:distribute command but got the error: unknown option '--groups'

*Also tried using the Firebase App distribution API POST call and getting the same result:

POST /v1/{project=projects/*}/testers:batchAdd


text:
Q: Expected time to find $k$ distinguished elements amongst $n$ Suppose you have a set of $n$ balls, $k$ of them are black and the other are white. At each step, you take one ball at random, without replacement.
How much steps do you need to get all the $k$ black balls, in expectation?
Actually, I am fine with an upper bound on this expectation rather than an exact formula.
Motivation. The question I try to answer is the following: Given a polynomial of degree $d$ over a finite field $\mathbb F_q$, say with exactly $d$ distinct roots in $\mathbb F_q$, how long does it take you to discover all these roots if you tste all the $q$ elements in random order. This is the exact same question with $k=d$ and $n=q$.

A: The expected value is:
$$\frac{\sum_{j=k}^n j\binom{j-1}{k-1}}{\binom{n}{k}}$$
Now:
$$j\binom{j-1}{k-1} = \frac{j!}{(j-k)!(k-1)!} = k\binom{j}{k}$$
and:
$$\sum_{j=k}^n \binom{j}{k} =\binom{n+1}{k+1}$$
So the expected value is:
$$\frac{k\binom{n+1}{k+1}}{\binom{n}{k}} = \frac{k(n+1)}{k+1}$$
I'm guessing there is a more "intuitive" way of showing this result.


text:
Q: Can I usue dash_cytoscape with plotly? or other similar network visualisation libraries? I've looked at https://dash.plotly.com/cytoscape and was trying to figure out if I can use this in plotly standard.
I also found this page:
https://plotly.com/python/network-graphs/
which seems to indicate no - but wanted to check given I know dash and plotly are very interdependent.
Unfortunately for my usecase I can't use dash as it's running in a cloud jupyter style notebook where I can plot using plotly but can't use tools like jupyter-dash.
Alternatively if someone has a python network visualisation happy to see that as an answer to the question of interactive network visualisation in python.


text:
Q: Can an assertion guard clause also return a value? I want to make an asserts style guard clause that can also return a value.  Is this possible?  Here's my dream.
// this return type gives a compiler error
export function assertString(input: any): ((asserts input is string) & string) {
    if (typeof input != "string") throw "Expected string, got " + input;
    return input;
}

It could be used flexibly.
function getLength(arg: any) {
    assertString(arg);
    return arg.length;
}

// but also
function getLength2(arg: any) {
    return assertString(arg).length;
}

Is this possible in typescript?

A: As of today (April 15 2020) the answer is no.
There is a GitHub issue https://github.com/microsoft/TypeScript/issues/34636
Until this issue is resolved you can use a conditional return type like so:
function assertString<T>(input: T): T extends string ? string : never {
    if (typeof input !== "string") throw "Expected string, got " + input;
    return (input as any);
}


text:
Q: Using chartjs v2 to show categorical values on axis instead of numeric In chartjs v2 is there a way to change the numeric values on the axis to categorical text labels instead (low, medium, high) for example ?

A: If you want to change just the tick labels use the callback property of ticks. For example
...
options: {
  scales: {
    yAxes: [{
      ticks: {
        callback: function(value) {
          if (value === 20)
            return 'Low';
          else if (value === 50)
            return 'Medium';
          else if (value === 80)
            return 'High';
          else
            return '';
        }
      }
    }]
  }
}

Fiddle - http://jsfiddle.net/1gfu0tfg/


text:
Q: Find a subset of points such xs sum at most A and ys sum at least B I'm solving a problem and I reduced it to the following one:
Given n points (x1, y1), ..., (xn, yn) (0 <= xi, yi), and two integers A and B (0 <= A, B) I need to find a subset of those points such that:
1) The sum of the x values is at most A (SUM(x) <= A).
2) The sum of the y values is at least B (SUM(y) >= B).
I'm struggling with this problem and I cannot find a solution other than combining. I would appreciate some ideas.
UPD: xi and A are rationals (represented as floats/double). yi and B are integers.

A: Depending on the distribution and the space available, we could create a "merge sort" segment tree, where the segments divide the X range and the tree array-nodes are sorted by y values. Then test partitions of A such that we can choose multiple xs maxed by the right-bound of each part, choosing the top y values in O(log n) from the segment tree.


text:
Q: When I try to run Th3inspector tool in termux it is showing error
*

*Ihave installed all the packages of Th3inspector tool and since it is written in perl language i type "perl Th3inspector.pl" to run it. But instead it is showing some error that http:: request module not found.

I tried to run Th3inspector tool in termux using the command perl Th3inspector.pl.
Expecting
Th3inspector tool should open listing all its options.
//This is the error

Results  Can't locate HTTP/Request.pm in @INC (you may need to install
the HTTP::Request module) (@INC contains:
/data/data/com.termux/files/usr/lib/perl5/site_perl/5.36.0/aarch64-android
/data/data/com.termux/files/usr/lib/perl5/site_perl/5.36.0
/data/data/com.termux/files/usr/lib/perl5/5.36.0/aarch64-android
/data/data/com.termux/files/usr/lib/perl5/5.36.0) at Th3inspector.pl
line 5. BEGIN failed--compilation aborted at Th3inspector.pl line 5

A: You have to run this command in Termux:
cpan HTTP::Request


text:
Q: Config parameter not reading from other locations The parameter is not read from files other than the run.py . run.py is the Flask startup script
from run.py :
from flask import Flask
app = Flask(__name__)
print(app.config["PARAMETER"])

From any other python file in project following error is returned :
KeyError: 'PARAMETER'

How to read configuration file from other locations within project other than startup script file ?
Update :
Reading config file :
app.config.from_pyfile(os.path.join(".", "myconfig.conf"))

Contents of myconfig.conf :
PARAMETER = "test"

A: I think you just simply missed loading parameters.
If you do inline loadign of parameters, you would specifiy it as:
from flask import Flask
app = Flask(__name__)
app.config['PARAMETER_1'] = 'test'
assert app.config["PARAMETER_1"] == 'test'

The code above works, now how can one load similar data from file?
# prepare file
from pathlib import Path
Path("myconfig.conf").write_text("PARAMETER_2 = 'test2'\n")

# load it
app.config.from_pyfile("myconfig.conf")
# test it
assert app.config["PARAMETER_2"] == 'test2'

A: You can't print the PARAMETER key after the creation of the app because there is no any key into its configuration object which its name is PARAMETER. In order to do it, first create the app, import a simple object which holds the configuration and then use app.config.from_object(Config)
#config.py
class Config(object):
    PARAMETER = 'my-parameter-value'
    #you can add another keys
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'

#__init__.py
from config import Config

app = Flask(__name__);
app.config.from_object(Config)


text:
Q: Populating jsTree based on XML data uploaded to server folder tl:dr How can I populate jsTree based on a folder location instead of an exact XML url?
I'm looking for a little direction on this project.
Currently I am trying to copy file structures of hard drives as XML files and recreate them using jsTree on the webserver for a completely independent version of the file structure. I have some python script that outputs XML files that are formed to jsTree and automatically uploads to a folder on the server. The problem is now I am a little lost because I have to manually enter each XML file into jsTree code for it to display so I have multiple entries like this:
 $("#tree1")
   .jstree({
       "plugins" : [ "themes", "xml_data", "ui", "search", "types" ],
        "xml_data" : {
            "ajax" : {
                "url" : "./XML_DATA/DRIVE1.xml"
                     },
                        "xsl" : "nest"
                     },

I see in the documentation that instead of populated by the direct file the folders are populated by "server.php" but no where in the php code  does it point to any directories or files. After considering the problem I thought of a few solutions and could use some advice on them:
Should I be trying to write php code to automatically look through my XML_DATA folder to upload each XML file? Should I just upload all the XML to mySQL and populate my tree based on that? Should the javascript be the code looking through the server's folder for XML files?
All the XML is formed the same way but the number of XML files on the server will increase and will have to be refreshed as well as they will be overwritten with changes.
Any direction would be appreciated, thanks.

A: What functions of jstree are you trying to use?
If you're just wanting to have an expandable tree matching what's on your filesystem.  Then you can either point to a php page that reads your file structure and outputs an <UL><LI> based tree and then apply jstree to it.
But since it sounds like you already wrote the XML generator in python, why not just add python support to your webserver, and serve up that XML file to the jstree instance?
The last worst option is to simply point to the generated XML file on your webserver.  You won't have any dynamic abillity, but you'll get the XML file in jstree.


text:
Q: QString and some Qt classes are recognized as incomplete types My code looks like this:
a.h
#include <QString>

namespace foo {
  QString bar(QString a);
}

a.cc
#include "a.h"

namespace foo {
  QString bar(QString a) { return QString(); }
}

The issue is in a.cc, QString might be taken as foo::QString, thus results in incomplete type compilation error, 'cause we didn't and never want to define a QString class in foo namespace.
Note that I have CMakeLists.txt containing below lines:
set(CMAKE_AUTOMOC ON)
find_package(Qt5 COMPONENTS widgets REQUIRED)
set(Qt_LIBRARIES Qt5::Widgets)
target_link_libraries(a Qt_LIBRARIES)

Any idea? Thanks!

Kuba Ober have pointed my problem exactly.
Actually I have a header file with 500 lines code. Say a.h looks like this

Note that the braces for foo is not closed. While due to too much lines and the compiler (VS2013) doesn't complaint it with red underscores, I just didn't detect it.
Then in a.cc, we have code like this

'Cause we include a.h in a.cc, even the std is wrapped under the suri namespace. Thus the QString might be wrapped under suri too, resulting in recognized as incomplete type compilation error.
This is the whole story. Thank you, guys!

A: The code you show is correct. The following demonstrates that there's no problem with such code. According to the standard, there's no way QString used here would be ambiguous: there's only one namespace visible from each point of use where that identifier exists.
// main.cpp
#include <QString>

namespace foo {
  QString bar(QString a);
  QString bar(QString) { return QString(); }
}

int main() {}

Whatever is the source of your problem, it isn't what you're showing to us. At the very least, you have a mistake somewhere that declares a foo::QString identifier, or declares QString in another visible namespace and makes the lookup ambiguous. Perhaps you even suffer from the most vexing parse, but in reverse (you meant a function, but got a member named QString instead)?
A bug that reproduces a similar problem reads:
// main.cpp
#include <QString>

namespace foo {
  QString bar(QString a);
  int QString(); // BUG: introduce foo::QString as an identifier

  // Doesn't compile since QString is ambiguous
  QString bar(QString) { return QString(); }
  // Compiles OK, indicates presence of the BUG
  ::QString bar(::QString) { return ::QString(); }
}

int main() {}

You could also be inadvertently wrapping Qt includes into a namespace, e.g. on my particular platform (OS X 10.9), the following code produces the exact same error as you see:
#include <cstddef>
#include <cstring>
#include <cstdint>
#include <algorithm>
#include <string>
using namespace std;
class QString;
namespace z {
#include <QString>
}

namespace foo {
  QString bar(QString a);
  QString bar(QString) { return QString(); }
}

int main() {}

Compiler output:
../test2/main.cpp:15:11: error: incomplete result type 'QString' in function definition
  QString bar(QString) { return QString(); }
          ^
../test2/main.cpp:8:7: note: forward declaration of 'QString'
class QString;
      ^
../test2/main.cpp:15:22: error: variable has incomplete type 'QString'
  QString bar(QString) { return QString(); }
                     ^
../test2/main.cpp:8:7: note: forward declaration of 'QString'
class QString;
      ^
../test2/main.cpp:15:33: error: invalid use of incomplete type 'QString'
  QString bar(QString) { return QString(); }
                                ^~~~~~~~~
../test2/main.cpp:8:7: note: forward declaration of 'QString'
class QString;
      ^
3 errors generated.


text:
Q: NullPointerException - Trouble with an array of strings I am having a problem with a getter like :
    String[] T2;
    T2=Ti.getT();

Where getT() is :
    public class MyClass {

        public final String[] T=new String[3];

        MyClass(){

           this.T[0]="...";
           this.T[1]="...";
           this.T[2]="...";

        }

        public String[] getT() {
            return T;
        }

    }

I am getting the message java.lang.NullPointerException in the  T2=Ti.getT(); line.
Can anyone give me a clue? Am I using the array correctly?
Thank you.

A: Based on what you have posted; Ti is null. Make sure you declare and initialize Ti before you try and access it. You need something like
MyClass Ti = new MyClass();

and you might consider
String[] T2 = null;
if (Ti != null) {
    T2 = Ti.getT();
}


text:
Q: peltier driver using AMP OP and MOSFET i'm in trouble trying to figure it out how to properly control a peltier cell using current control principle .
I'm using a sine wave to figure circuit behavior through 0 to 6V and 0.5HZ .
Take a look
The problem is that the output voltage(BLUE) do not follow its input troughout (YELLOW) .

i wonder if the discharge of mosfet capacitance is taking too much time to happen? how do i fix that? i've tried vary its gate resistor but nothing changes .
Thanks for your help ..

A: If you want to control the current in the Peltier device it should be in the drain  circuit of the mosfet and a resistor in the source (where you currently have the peltier device).
Your circuit is currently feeding back the voltage across the Peltier device.
Also if there is any temperature difference across the Peltier device it will generate voltage even when unpowered - that is probably what you are seeing right now.


text:
Q: How to merge two large datasets of different lengths by location? I have 2 data sets

*

*Birth-related outcomes (150k records)

*Causes of death (320k records)

Both these data sets have location and year in common. I'm unsure of how to merge these data sets into one. The goal is to merge these data sets and provide a visualization by comparing the birth-related outcome and causes of death based on location.
I'm trying to do this via R. But since the size is different, I couldn't proceed further.
How to merge the data with R or Excel or any suitable data cleaning tool?

A: Actually, the need being merging both data sets to have columns form each, the size difference is not a problem as we are not juxtaposing columns, we are merging them based on the values of the year and location fields from each data sets. So the merging will have a multivariable merging key (or we can simply concatenate them into one variable to have a simpler key). In all cases we can have 3 different cases:

*

*key=(year, location) in both D1 and D2

*key=(year, location) in D1 but not in D2

*key=(year, location) in D2 but not in D1

I presume that the visualisation needs the columns from both D1 and D2 (the first bullet point): an inner join of the data sets is then needed.
to perform it in R, we can use the data.table package which have a very simple syntax.
library(data.table)
# Extract the data in a data.table format
    # can be replaced by reading from a file using fread or any other command to have both data sets as data tables.
dt1 <- as.data.table(df1)
dt2 <- as.data.table(df2)

# set the merging key in each data table
setkey(dt1, "year", "location")
setkey(dt2, "year", "location")
# merge data tables
dt.result <- merge(dt1, dt2) # keep the default settings (inner join)


text:
Q: Moving table to new database in sql server Heres what I want to do:
I am working with one database, for simplicity I will name it "d1". and I only need to query two tables from this database. I need to isolate only last years data from this database though(that is the only info that is relevant for what I want to do - Auditors Report for 2012:/ ). Keep in mind that the database I am working with has an easy 50 tables in it with at least 6 or 7 years worth of data in it.
Possible Solution/s:
1. Copy database into new database, delete everything except 2012 data.
2. Copy both tables and throw them into a new database, delete all rows except 2012 data.
The I.T. guy before me created a database for 2011 and was able to create the auditors report. I however, have never done this type of task before. Any help would greatly be appreciated and I will be watching this question til 4pm EST time. Hopefully I was specific in my request, but if not, I will be right here waiting to reply to you:). THANKS!

A: I'm not entirely knowledgeable on the utilities available for SQL Server, but based on utilities otherwise available,

*

*Find a dump utility to export the data on the tables.
Often such export utilities will allow specifying the table names,
and often will take where conditions.
The export will be in SQL, and can be used to populate a new database.

*Create the new database on the same server as the source database.
Do a cross-database update.
So, create a database db2012.
Using database db2012, run the following update statement:

.
update table1
(select * from d1.table1 where year(timestamp_x) = 2012)

A: The simplest thing is:
select t.*
into newdb..t
from olddb..t
where <from the last two years>

For each of the tables.  This will get the data.
If you need other things (indexes, contraints, etc.), then script out the table definitions, recreate them in the new database, and insert the data from the existing tables.


text:
Q: Pythonic Way to set Multiple Properties Based on another class Is there an elegant way to handle all get requests of a class when I just want to pass the get to another object?
This is a Django project where I have a Video model; the Video can be from different sites (e.g., YouTube, Vimeo, etc).  The model is generic and will grab the appropriate backend to parse the data (which will be repr differently depending on the site).  All Videos will have the same properties but I have a different backend to parse them correctly.  Here is the example:
BACKEND_VIDEO_TYPE = (
    (1, 'YouTube'),
    (2, 'Vimeo'),
)

class Video(ItemBase):
    video_id = models.CharField(max_length=25)
    video_type = models.PositiveIntegerField(choices=BACKEND_VIDEO_TYPE)
    video_data = models.TextField(editable=False)

    class Meta:
        unique_together = ("video_id", "video_type")

    def __init__(self, *args, **kwargs):
        super(Video, self).__init__(*args, **kwargs)

        for k, v in BACKEND_VIDEO_TYPE:
            if k == self.video_type:
                VideoBackend = import_string( 'video.backends.' + v )
                # load the backend that matches the video type and supply it with the data to parse
                self.backend = VideoBackend(self.video_id, self.video_data)

    @property
    def link(self):
        return self.backend.link

    @property
    def thumbnail(self):
        return self.backend.thumbnail

    @property
    def is_public(self):
        return self.backend.is_public()

    @property
    def duration(self):
        return self.backend.duration

I don't feel like this is the best way to handle this but I am too new to know what to look for.  AFter I identify which backend class to implement, is there an easy way to return self.backend.property without having to add each property that is in the backend?  The list is going to get rather long.  A generic __get__ or similar?
Thanks for your help.

A: You could override __getattr__ on the Video class so that it fetches an attribute of backend.
def __getattr__(self, attr):
    try:
        return getattr(self.backend, attr)
    except:
        raise AttributeError('No attribute named ' + attr)

__getattr__ will only call if the attribute is not found on the Video object (e.g. it wouldn't call at all if the user asked for Video.video_id) so it's a neat way to extend the exposed attributes of the Video class. The downside is that it may not be obvious which attributes are available, or it may expose some attributes you don't wish to. You could get around this by having the VideoBackend class provide a list of allowed attributes.
def __getattr__(self, attr):
    if attr in self.backend.get_allowed_attr():
        return getattr(self.backend, attr)
    else:
        raise AttributeError('No attribute named ' + attr)