text:
Q: Refactor big switch statement I have the following switch statement:
switch (type) {
  case 1: // 1 BYTE 8-bit unsigned integer
    pointer = count > 4 ? offset : pointer;
    for (let i = 0; i < count; i++) {
      value += dataView.getUint8(pointer + i);
    }
    tag.value = parseInt(value, 10);
    return tag;
  case 3: // 3 SHORT 16-bit unsigned integer
    pointer = count > 2 ? offset : pointer;
    for (let i = 0; i < count; i++) {
      value += dataView.getUint16(pointer + 2 * i, littleEnd);
    }
    tag.value = parseInt(value, 10);
    return tag;
  case 4: // 4 LONG 32-bit unsigned integer
    pointer = count > 1 ? offset : pointer;
    for (let i = 0; i < count; i++) {
      value += dataView.getUint32(pointer + 4 * i, littleEnd);
    }
    tag.value = parseInt(value, 10);
    return tag;
  case 5:
  ...

and so on.
The pattern is every time the same with some small variations. How can I refactor this? I want to refactor the pattern inside the case and I'm also trying to remove the whole switch block. Is that possible?

A: (This probably belongs on the Code Review Stack Exchange.)
Without a bit of larger context it's difficult to provide a reasonable refactoring, or even determine if such a refactoring would be worth the effort and additional maintenance.
The nutshell is that you have a number of type that need to be handled. Rather than a switch, you could implement a command pattern where each type is either a small class, or a simple object. (Using a class makes it marginally easier to pass in an "execution context" that contains the variables not shown in the snippet.)
For the sake of brevity, here's a (very) rough outline.

You'd have a base type handler. This wraps up dataView looping and tag value setting. Since I don't know the context, I'm pretending there's a context you pass in. I include all variables that weren't shown in your snippet.
(I didn't include value, which it looks like you should, but I didn't know the intent.)
class BaseTypeHandler {
  constructor(ctx) {
    this.ctx = ctx
  }

  getPointer  = () => throw new Error('Missing getPointer implementation')
  getViewData = () => throw new Error('Missing getViewData implementation')

  getValueFromDataView = () => {
    let value = 0

    for (let i = 0; i < this.ctx.count; i++) {
      value += this.getViewData(i, pointer)
    }

    return value
  }

  getTag = () => {
    const pointer = this.getPointer()
        , value   = this.getValueFromDataView()

    this.ctx.tag.value = parseInt(value, 10)
    return this.ctx.tag
  }
}

Each subclass implements the required unique functionality, here how to get the pointer, and how to get data from the dataView.
class Type1Handler extends BaseTypeHandler {
  getPointer = () =>
    this.ctx.count > 4 ? this.ctx.offset : this.ctx.pointer

  getViewData = (i, pointer) =>
    this.ctx.dataView.getUint8(pointer + i)
}

class Type3Handler extends BaseTypeHandler {
  getPointer = () =>
    this.ctx.count > 2 ? this.ctx.offset : this.ctx.pointer

  getViewData = (i, pointer) =>
    this.ctx.dataView.getUint16(pointer + 2 * i, littleEnd);
}

Then you wrap those up in an object of type handlers:
const typeHandlers = {
  1: Type1Handler,
  3: Type3Handler,
  4: Type4Handler
}

const handler = new typeHandlers(type)
    , tag = handler.getTag()

TL;DR
Unless you have a tremendous number of these, and you cannot use math to figure out the getPointer and getViewData implementations, you might want to stick with the switch.
Simple objects or immediate functions may be a significantly smaller implementation, although not necessarily easier to reason about. They also have the advantage of being able to close over variables you already have locally.


text:
Q: IIS web server on a Domain can't run ASP.NET application I have my web server on a domain and everything is fine until I try to browse to site.
I have given the DOMAIN\MACHINE$ rights to the virtual directory and the app pool identity is Network Service.
I get this error when I test these settings:

The server is configured to use
  pass-through authentication with a
  built-in account to access the
  specified physical path. However, IIS
  Manager cannot verify whether the
  built-in account has access. Make sure
  that the application pool identity has
  Read access to the physical path. If
  this server is joined to a domain, and
  the application pool identity is
  NetworkService or LocalSystem, verify
  that domain\computer_name$ has Read
  access to the physical path. Then test
  these settings again

A: This sounds like a delegation issue.  I would first enable kernel mode authentication, then make sure that the computer account is trusted for delegation

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simplify a perl script I am debugging a done-by-another-one script.
This is the snippet he did:
 ...
open OUTPUT_FILE, "$makingOutDir/$inputFile";
$_ = <OUTPUT_FILE>;
while ( defined($_) ) {
  $diff_text .= prep_for_output($_);
  $_ = <OUTPUT_FILE>;
}
close OUTPUT_FILE;

print <<EOF
Test $num_test skipped: missing output file for matching
$diff_text
EOF
 ...

I was wondering if is it possible to obtain the same behavior simplifying it doing like this:
 ...
print "Test $num_test skipped: missing output file for matching";
open OUTPUT_FILE, catfile($makingOutDir, $inputFile) or die $!;
while ( <OUTPUT_FILE> ) {
  my $diff = prep_for_output($_);

  print <<EOF
$diff
EOF
}
close OUTPUT_FILE;
 ...

or, in your opinions, there are a better and simpler way?

A: It's not a massive improvement, but something like this, perhaps.
print "Test $num_test skipped: missing output file for matching";

my $filename = catfile($makingOutDir, $inputFile);
open my $out_fh, '<', $filename or die "Can't open $filename: $!";

print prep_for_output($_) while <$out_fh>;

close $out_fh;


text:
Q: Interactive shell script autostart on custom Xubuntu live CD/USB I'm trying to make a live usb which runs an interactive shell script when booting. I'm using Ubuntu Customization Kit (uck), xubuntu-14.04.3-desktop-i386.iso and syslinux (in order uck can build final iso).
This interactive script read answers from command line and runs a graphical application, so xfce4 is one of the custom packages and the way I install my script is creating this file:
/home/xubuntu/.config/autostart/terminal.desktop

(xubuntu is the default user on live cd)
With the content:
[Desktop Entry]
Type=Application
Name=Terminal autoarranque
Exec=xfce4-terminal -e /usr/bin/myscriptfolder/myscript.sh
X-GNOME-Autostart-enabled=true

But as it is said in https://help.ubuntu.com/community/LiveCDCustomization,
"You cannot directly edit defaults for the live cd user (e.g., casper, ubuntu, or user) since that account is created at boot time"
So, I don't know how make the xfce terminal runs in order to launch the interactive script. If I do the former way, the next error appears when booting from usb:
Unable to load a failsafe session

Unable to determine failsaafe session name. Possible causes: xfconfd isn't running (D-Bus setup problem); environment variable $XDG_CONFIG_DIRS is set incorrectly (must include */etc*), or xfce4-session is installed incorrectly.

And if I create terminal.desktop on root folder, when Xubuntu starts, nothing happens as it is not the user session.
Any help please?
Thanks a lot.
(if I test my script on an installed Xubuntu, it runs ok after login)
EDIT:
Is there any way to make the live-cd boots with a custom user?

A: Thanks to sixsixfive (https://forum.xfce.org/viewtopic.php?id=10029), I tried to create desktop file before xfce session starts (I did not know that 'on the fly' home directory of xubuntu user already exists at that point). So, if I add this to /etc/xdg/xfce4/xinitrc file, just before "xfce4-session" command, it works.
mkdir -p /home/xubuntu/.config/autostart
cat > /home/xubuntu/.config/autostart/terminal.desktop <<MYEOF
[Desktop Entry]
Type=Application
Name=Terminal autoarranque
Exec=xfce4-terminal -e /usr/bin/myscriptfolder/myscript.sh
X-GNOME-Autostart-enabled=true
MYEOF
sudo chmod 777 /home/xubuntu/.config/autostart/terminal.desktop


text:
Q: How to download file from gitlab synchronously using NodeJS I need to download a file from a private gitlab server and I need the method to be synchronous. This was by previous async code and it works fine because I was using promises. But I'm having trouble converting it to synchronous. The other posts i've seen on SO either ended up using async code or didn't have options for headers.
            const https = require('https');
            const fs = require('fs');
            const gitlabUrl = 'https://gitlab.custom.private.com';
            const gitlabAcessToken = 'xmyPrivateTokenx';
            const gLfilePath = '/api/v4/projects/1234/repository/files/FolderOne%2Ftest.txt/raw?ref=main';
            const gLfileName='test.txt';

            function downloadFileFromGitlab(filePath, fileName) {
                    return new Promise((resolve, reject) => {
                        var options = {
                            path: filePath,
                            headers: {
                                'PRIVATE-TOKEN': gitlabAccessToken
                            }
                        };

                        var url = gitlabUrl
                        var file = fs.createWriteStream(fileName);

                        const request = https.get(url, options, (response) => {
                            response.pipe(file);
                            file.on('finish', () => {
                                file.close();
                                resolve();
                            });
                            file.on('error', (err) => {
                                file.close();
                                reject(err);
                            });
                        });

                        request.on('error', error => {
                            throw console.error(error);
                        });
                    });
                }

downloadFileFromGitlab(gLfilePath,gLfileName);

A: I was able to figure it out using curl
function downloadFileFromGitlab(filePath, fileName) {
    let curlCommand = "curl -s " + gitlabUrl + filePath + " -H 'PRIVATE-TOKEN:" + gitlabAccessToken +"'";
    let file = child_process.execSync(curlCommand);
    fse.writeFileSync(fileName,file);
}


text:
Q: Why isn't my graphics card good enough when it should be? In my desktop I have a basic graphics card, a 1GB ATI Radeon HD 5450. It's served me well through the years, although I am looking at having to replace it as it can't run games as well as it should.
Take Battlefield 2142 and Crysis. Two games released within a year of each other (2006, 2007). It runs the first (maybe not on full graphics) and is playable with decent frame rates (40+). The system requirements for Battlefield 2142 are 1.7Ghz, 512MB RAM and 128MB Graphics which my desktop (Quad Core 2.8Ghz, 4GB RAM, 1GB Graphics) matches fine. This is also enough for Crysis (2.8Ghz CPU, 1.5GB RAM, 256MB graphics). Also other games like Just Cause 2 and Battlefield Bad Company 2 "should" work, but they are so slow and juddery, and I barely scrape 10 fps out of any of them. The intro scenes for both Bad Company 2 and Just Cause 2 play slowly with the audio/video out of sync.
I realize there's a lot I don't know about graphics cards, but I also realize now that it's not just a case of having a 1GB or 2GB graphics card - what are the things that "matter" in a graphics card: the core clock, the memory, the memory clock?

A:
what are the things that "matter" in a graphics card

There are a whole bunch of factors that determine how good a GPU is. Let's take a look at some of them:

*

*GPU Bus Width: The width of the memory bus interface from the the GPU's memory to the it's processing units. Low end GPUs have low widths, thereby limiting the amount of data that can be transferred, causing a huge bottleneck

*No of stream processors: Stream processors aka Shaders are dedicated units for performing pixel/vertex/geometric shading. Most recent GPUs don't have distinct types of shaders, the shaders are capable of performing pixel/vertex/geometric shading. Higher number of stream processor/shaders, faster the performance will be

*Core clock / Memory clock / Shader Clock: The clock speed of each subsystem of a GPU. Of these, having a higher memory clock would mean faster transfer of data, thereby improving performance immensely. Memory clock is what I tend to improve upon when overclocking, it often results in huge boost.

*Memory type: The type of the memory bus - Generally GDDR5 are known to provide the highest performance. GDDR3, DDR3 and DDR2 follow. There's a common misconception that the GPU memory type must match your main memory type; this is false and people trying to "match" the two memory types often end up with massive performance drops.

*Drivers: Yes, yes, drivers are software, not hardware, but drivers make or break a GPU. I've seen driver updates which boost performance significantly. I'll refrain from mentioning which of the vendors have better drivers - that's another flame war waiting to happen.

You'll notice that I've not mentioned amount of memory anywhere above - that's because unless under extreme cases, the memory size simply doesn't matter. Unlike your RAM where more memory often results in faster performance - this isn't true because the memory in GPU is used as a frame buffer - for texture storage. As a result having 4GB on a low end GPU is worthless because the GPU cannot perform well enough to process those textures.
Other software/driver switches which cause performance drops/improvements:

*

*Texture filtering: Texture filtering is the technique used to determine how good a texture looks. Most recent games would use Trilinear filtering - though Anisotropic filtering is also quite common. The number next to the filtering method : For example, 2x Anisotropic, 4x Anisotropic refers to the number of texture samples used for filtering. Higher number of samples, higher will be the texture quality. Consequently, increasing number of texture samples significantly increases the memory required to process the textures.

*Anti Aliasing: Anti-aliasing is the technique used to smoothen the edges of polygons. There are different anti-aliasing techniques, some vendor specific some not so. Disabling AA is another way to improve performance.

A: Have you tried the latest drivers for your card?
It's also worth checking on updated drivers for your motherboard.
The things that 'matter' with a graphics card are similar to the way your PC works:
GPU clockspeed - the actual processing power for all that rendering, the higher this clockspeed the more work it can do per cycle. Like a CPU.
Graphics memory - 1GB/2GB+ - the amount of RAM available to load all those textures into memory so they can be processed. Like your desktop RAM and opening large images/documents/videos.
Graphics memory speed/clockrate - the speed that things can be loaded into your GPU for processing, or loaded from disk into the GPU RAM area. The same as your desktop RAM speed.
Obviously the higher/larger the better for any of these, but all are very much relative to the costs of the graphics cards themselves. Some video editing based cards will have huge amounts of onboard memory, but not a high clockspeed, much the same way that the amount of RAM within physical Servers can be more important than Processor speed.


text:
Q: javascript() onclick hide element - doesn't work in firefox I have javascript that onclick shows and hides element defining style.display = "inherit";
And style.display = "none";..
' Hide ' function also is running when ESC button is pressed..
Everything works fine in CHROME, OPERA etc.. except FIREFOX..
    window.onload=function() {
    document.body.onkeyup = key_event;
    }

    function showDiv() {
        document.getElementById('PhotoFull').style.display = "inherit";
        event.stopPropagation();
     }

    function hideDiv() {
         var target = event.target || event.srcElement;
         if (event.currentTarget == target) {
                 document.getElementById('PhotoFull').style.display = "none";
         }
     }

    function key_event(e) {
        if (e.keyCode == 27) hideDiv();
        }

showDiv() works, but hideDiv doesn't..
HTML:

            SOME CONTENT

Here is the JSFIDDLE: http://jsfiddle.net/5e6ww93h/2/
Thanks for attention

A: Syntaxically, you have to pass the event obj to your hideDiv function
function hideDiv(event) {
     var target = event.target || event.srcElement;
     if (event.currentTarget == target) {
             document.getElementById('PhotoFull').style.display = "none";
     }
 }

function key_event(e) {
    if (e.keyCode == 27) hideDiv(e);
}

A: Try below
  window.onload=function() {
    document.body.onkeyup = key_event;
    }

    function showDiv() {
        document.getElementById('PhotoFull').style.display = "inherit";
        event.stopPropagation();
     }

    function hideDiv(e) {

         var target = e.target || e.srcElement;

         if (e.currentTarget == target) {
                 document.getElementById('PhotoFull').style.display = "none";
         }
     }

    function key_event(e) {
        if (e.keyCode == 27)
                       hideDiv(e);
               }

fiddler:- http://jsfiddle.net/5e6ww93h/4/


text:
Q: Constructing a instance variable pyparsing matcher from class variable elements With pyparsing I construct a
complex matcher object which is suppose to match slightly different
things depending on a instantiation flag. Here a (simplified) example:
class MyMatcher():

    def __init__( self, special_flag = False):
        self.special_flag = special_flag

        a = pp.Word(pp.alphas)('A')
        if self.special_flag:
            b = pp.Word(pp.alphas)('B')
        else:
            b = pp.Word(pp.nums)('B')
        c = pp.Word(pp.alphas)('C')
        # d = ...
        # e = ...
        # ...

        self.expr = (a + b | b ) + pp.Optional(c) # + ...

    def parse(self, s):
        return self.expr.parseString(s, parseAll=True)

a, b, c,.... are class variables, so that I can reference them
in expr just like that and do not have to prefix them with the
instance reference self (like in self.a). expr has to be an
instance variable because different instantiations of MyMatcher
have to match different things.
The above example works:
mymTrue = MyMatcher(True)
mymFalse = MyMatcher(False)
print (mymTrue.parse("alpha aaaa alpha"))
print (mymFalse.parse("alpha 777 alpha"))

returns as expected:
['alpha', 'aaaa', 'alpha']
['alpha', '777', 'alpha']

My worry is: Does this work even for very complex matchers with lots
of (nested) a, b, c, d, etc... ? Or phrased differently: Is
the full logic (deep-)copied from the class variables to the instance
object expr, so that it doesn't matter that the a, b and c
get overwritten on the next MyMatcher object creation?
Or if this is a problem, is there another way to create varying
matchers with short and beautiful construction like (a + b | b ) +
pp.Optional(c)?

A: The variables a, b, c,.... are not class variables; they are local variables in the __init__ method. References to these variables will be kept alive as long as needed. (See in the Python documentation Scopes and Namespaces in Classes.)


text:
Q: How to get birthday,location and gender from Google+ into android app I am able to get username and email into my app using the follow code, but gender,birthday and location are returning to be null.
// Initializing google plus api client
        mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .addApi(Plus.API)
        .addScope(Plus.SCOPE_PLUS_LOGIN)
        .addScope(Plus.SCOPE_PLUS_PROFILE)
        .build();

this is onActivityResult() method
@Override
    protected void onActivityResult(int requestCode, int responseCode,Intent intent) {
        super.onActivityResult(requestCode, responseCode, intent);
        if (requestCode == RC_SIGN_IN) {
            if (responseCode != RESULT_OK) {
                mSignInClicked = false;
            }

            mIntentInProgress = false;

            if (!mGoogleApiClient.isConnecting()) {
                mGoogleApiClient.connect();
            }
        }
        //fb callback
        callbackManager.onActivityResult(requestCode, responseCode, intent);
    }

This is onConnected() method
   @Override
    public void onConnected(Bundle arg0) {

        mSignInClicked = false;
        Log.e("on connected","on connected");
        try {
            if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {

                Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);

                String personName = currentPerson.getDisplayName();
                String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
                int gender = currentPerson.getGender();
                String birthdate = currentPerson.getBirthday();
                String location = currentPerson.getCurrentLocation();
                Log.e(TAG, "Name: " + personName + ", email: " + email+ ", Gender: " + gender + ", Birthday: " + birthdate + ",Location" + location );

            } else {
                Toast.makeText(getApplicationContext(),
                        "Person information is null", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
        Intent i = new Intent(LoginActivity.this , Categories.class);
        finish();
        startActivity(i);

    }

And this is the response that i am getting after onConnected()
06-18 15:01:12.258: E/LoginActivity(28307): Name: karan mer, email: karan.mer@gmail.com, Gender: 0, Birthday: null,Locationnull


text:
Q: Jenkins gets stuck when switching user within docker container I am running Jenkins within a Docker container on a remote server. In one of my pipelines I am using a Yocto build container to build a image. In this case I have to change the user, because Bitbake does not allow building with root privileges.
Unfortunately when I am switching users Jenkins gets stuck during the build stage:
[Pipeline] {
[Pipeline] sh (hide)
process apparently never started in /home/jenkins/workspace/<project>/durable-01a92f6b
(running Jenkins temporarily with Dorg.jenkinsci.plugins.durabletask.BourneShellScript.LAUNCH_DIAGNOSTICS=true might make the problem clearer)
[Pipeline] }

My pipeline looks something like this
pipeline {
agent {
    docker {
        image '<image>/yocto:dunfell'
        args '-u jenkins'
    }
}
stages {
    stage('Build Image') {
        steps {
            sh label: '', script: '''#!/bin/bash
            source /home/jenkins/yocto/setup-env
            bitbake core-image-minimal
            '''
        }
    }
}
}

The user jenkins is available within the Docker container running Jenkins and within the container performing the Yocto build.
Any ideas on resolving this problem? Thanks!
Edit:
I solved this issue by using a workaround. I removed args '-u jenkins' and the container starts using root. In the script I call the commands which requires no root privileges with
sudo --user=<other-user> /bin/bash -c "<command>"

It works but changing the user beforehand would be preferred.

A: For short story, removing args '-u jenkins' should address your issue.
For long story, In following cases, jenkin automatically extends -u <agent's current user> to start container, and you can only use -u root to override it. Using -u <non-root user> will get pipeline stuck.
Case 1. use docker for pipeline/stage agent
agent {
    docker {
        image '<image>/yocto:dunfell'
        args '-u jenkins' // you can only use root here,
                          // using other user, jenkins get stuck.

    }
}

Case 2. use docker.inside() to start container
docker.image('python:3')
      .inside('-u root') // only root user is allowed.
{
   sh '<put cmd executed in container here>'
}


text:
Q: VBA Vlookup with specific criteria So I am trying to come up with a VBA code that uses a vlookup only if certain criteria is met. The criteria is a bit difficult to me because it somehow needs to traceback and pull information once criteria is met. I need a macro that uses a vlookup on duplicate IDs that have different values. The macro is supposed to ignore if the values of the same ISIN contain all positive numbers. But if one negative number exists amongst the duplicate numbers, all values containing that ISIN including positive should populate.
I understand that this solution will contain if value > 1 but I am unsure how to get the macro to grab all the values from that specific ISIN when a positive number is found
Sub Crit()
'Created through Macro record
    If ("D2") > 1 Then
       Range("N2").Select
       ActiveCell.FormulaR1C1 = _
            "=IF(VLOOKUP(RC[-13],RC[-13]:R[48]C[-9],4,FALSE)<1,RC[-10],"""")"
       Range("N2").Select
       ActiveCell.FormulaR1C1 = _
           "=IF(VLOOKUP(RC[-13],RC[-13]:R[48]C[-9],4,FALSE)>1,RC[-10],"""")"
       Range("N2").Select
End Sub

Expected results would be a button that once data is uploaded in a static fashion, deletes all the rows with the ISINS that contain purely positive numbers and populate the ones that contain positive and negative.Example of what macro should do. But would prefer it delete the rows that are not being populated entirely.


text:
Q: can't connect wifi on ubuntu 16.04 dual boot windows 10 I've just installed ubuntu 16.04 alongside windows 10. Unfortunately I can't connect wifi on ubuntu, but wifi on windows still works. it says wifi disabled and I can't enable wifi. anyone help me to solve this problem?
ps. my wireless card is Qualcomm

A: I think there are similar questions. What I found online says that the problem is with some missing firmware.
sudo apt-get update
sudo apt-get install linux-firmware

Sources:
Ubuntu 14.04 Wireless not working: no network interface. Atheros [168c:003e] device
No Wifi in Qualcom Atheros - Ubuntu 16.04 - Acer Aspire E 15


text:
Q: Symfony2 with Dynamic Elements Is there something like Bundle in Symfony2 that I can do this? I searched a lot.
http://www.thatsquality.com/examples/todo/advanced
Update
I do have table with id and item. I loaded it from the db. All items are shown in a text field, so I can edit them and at the bottom there is an empty text field. If I hit enter or submit all changes are saved to database. The page is going to be reloaded and all items are going to be listed as well with an extra empty bottom text field.

A: There's no bundle that allows you to do this but it's not too hard to develop.
So, you can use Event Subscribers to get the same behavior, Fields will then be generated according to you table content. As long as you click on save, your form will be then generated again, taking into account the last added elements, your Subscriber should also append an extra field to allow adding new elements.


text:
Q: Android: How to force navigation bar to be visible on Samsung Galaxy S8 Is is possible to force an app to always show to navigation bar in an Android app? On Samsung Galaxy S8 it is possible for the user to hide the navbar during "runtime" - which cause some unexpected behaviours in the app (if you are interested; I tried to add a setOnSystemUiVisibilityChangeListener and redraw, invalidate, requestLayout and forceLayout on the view with no luck. Restarting the activity is not applicable as the app is a single-activity-app. I've also looked into WindowInsets with no luck there neither.).
Therefor, I just want to avoid the problem by not allowing the user to remove the navbar. All the resources I can find online is for hiding the navbar. Does anybody how any suggestions on how to make it stay?

A: I am not much sure about Samsung S8, but I had worked on Samsung S7. I had used lean back mode  setSystemUiVisibility() and passed these two flags
1.SYSTEM_UI_FLAG_FULLSCREEN
2.SYSTEM_UI_FLAG_HIDE_NAVIGATION
Also for enabling immersive mode, I had used SYSTEM_UI_FLAG_IMMERSIVE in conjunction.
It was referenced from visibility &
immersive.
Correct me if I am wrong or I didn't understand the question.

A: This worked for me:
        getWindow().getDecorView().setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_IMMERSIVE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);


text:
Q: IntelliJ Idea take a long time to start (JetBrains CertificateException) My IntelliJ take a long time to start.
So when I check the starting log, I can see that they're issues with the jetbrains certificates :
Caused by: java.security.cert.CertificateException: No subject alternative DNS name matching www.jetbrains.com found.

and
Caused by: java.security.cert.CertificateException: No subject alternative DNS name matching plugins.jetbrains.com found.

The slowness could be link at those certificates issues ? How could I fix them?

A: I updated my Intellij and I moved the installation into "program files x86" (instead of "program files") and now it's better. Like suggested the jetbrains helpdesk, it's most likely an IO issue on my PC. Maybe I can also move my settings folder from the usual place to a faster IO place on my hard disk (currently slow because there some backups system on the home).


text:
Q: PHP use loops to avoid repetition of code I have a PHP file that does some basic txt file manipulation and I apply the same thing for all my HTML pages with some very small differences. My question is if there is a way to add some loop or some other solution to solve all this repetition of the code:
     if(isset($_POST['submit'])){

                $second_page_array = file("data/data1.txt",FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                $final_array = [];

                //some shortening of the code
                foreach($first_page_array as $key=>$first_page){
                   $final_array[] = $first_page.''.$second_page_array[$key].''.$ranks_array[$key].''.$time_array[$key]."\n";
                }

                file_put_contents('output.txt',$final_array, FILE_APPEND | LOCK_EX);

                header("Location: main2.html");
              }

     if(isset($_POST['submit2'])){

                $second_page_array = file("data/data2.txt",FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                $final_array = [];

                //some shortening of the code
                foreach($first_page_array as $key=>$first_page){
                   $final_array[] = $first_page.''.$second_page_array[$key].''.$ranks_array[$key].''.$time_array[$key]."\n";
                }

                file_put_contents('output.txt',$final_array, FILE_APPEND | LOCK_EX);

                header("Location: main3.html");
              }

    if(isset($_POST['submit3'])){

            $second_page_array = file("data/data3.txt",FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            $final_array = [];

            //some shortening of the code
            foreach($first_page_array as $key=>$first_page){
               $final_array[] = $first_page.''.$second_page_array[$key].''.$ranks_array[$key].''.$time_array[$key]."\n";
            }

            file_put_contents('output.txt',$final_array, FILE_APPEND | LOCK_EX);

            header("Location: main4.html");
          }

So, the things that change is that submit gets incremented, data.txt and redirection to another page.
Thank you in advance!

A: The only change in your repeated code is a single number. Just add a number to the value of your submit and use that to make the modifications:
if (isset($_POST['submit'])) {
    $num = $_POST['submit'];
    $location = 'main'.$num+1.'.html';

    $second_page_array = file("data/data$num.txt",FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $final_array = [];

    //some shortening of the code
    foreach($first_page_array as $key=>$first_page){
       $final_array[] = $first_page.''.$second_page_array[$key].''.$ranks_array[$key].''.$time_array[$key]."\n";
    }

    file_put_contents('output.txt',$final_array, FILE_APPEND | LOCK_EX);

    header("Location: $location");
  }
}

A: you can keep the below logic in a function and call that function with some parameters when a particular page is submitted
function callPage()
{
    $second_page_array = file("data/data3.txt",FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $final_array = [];

        //some shortening of the code
        foreach($first_page_array as $key=>$first_page){
           $final_array[] = $first_page.''.$second_page_array[$key].''.$ranks_array[$key].''.$time_array[$key]."\n";
        }

        file_put_contents('output.txt',$final_array, FILE_APPEND | LOCK_EX);

        header("Location: main4.html");
}

//Example:
if($_POST[submit1])
{
  echo callPage(1);
}

A: You can create a function and for switch case and pass the data for function according the case value some thing like this.
$submit = $_POST[submitvalue];
switch($submit){
    case 'submit':
         $file = data.txt;
         $headerLocation: file.html;
         functionName($file,$file);
         break;
    case 'submit1':
         $file = data1.txt;
         $headerLocation: file1.html;
         functionName($file,$file);
         break;
}

functionName(arg1,arg2){
    // do yours stuff here
}


text:
Q: Asynquence step that waits for all steps to succeed or fail I have a server-side Node.JS script that handles file uploads by (1) saving the upload to a specific location and (2) recording it in a DB. I have been using the Asynquence library and its gate function (equivalent to Promise.all) to perform these steps in parallel, but I need the sequence to behave so that if either step fails, I undo the other step if it succeeded. Obviously the undoing steps can only execute if its matching step has already succeeded (i.e removing the file or db record)
Gate doesn't seem to work for this case since it fires the error handler if any of the steps fail. Is there a function that waits for all steps to either succeed or fail?

A: If you think of catch as an asynchronous counterpart to try, then you can build a quick wrapper that wraps every value passed to gate or Promise.all and returns a "succeeded" or "failed" result.
function waitForAll(inputArray) {
  // Return Promise.all on an array where for each array value...
  return Promise.all(inputArray.map(function(x)
    // ...we wrap it in a tiny dict with the semantics we want.
    return Promise.resolve(x).then(function(value) {
      return { success: true, value: value };
    }, function(error) {
      return { success: false, error: error };
    });
  }));
}

As a bonus, since you can take any action per-promise in your wrapper, you can even report failure quickly through a separate channel, or start cancelling or rolling back successful actions as soon as any asynchronous step fails.


text:
Q: Where can I find jar for using WSclient class? Is there any jar required to use WSClient class? If yes, can anyone please tell where I can find it?

A: you can use the maven repository to see how to integrate the groovyws lib in diffrent build processes. see: http://mvnrepository.com/artifact/org.codehaus.groovy.modules/groovyws/0.5.2 or download required jar from http://snapshots.repository.codehaus.org/org/codehaus/groovy/modules/groovyws/


text:
Q: derby SQL syntax using union I'm trying the following:
select sum(a.shares*a.cps) - sum(b.shares*b.cps) from
   (select * from transactions
        where usr  = 1
          and type = "C"
           or type = "S") as a
union
   (select * from transactions
                 where usr = 1
                   and type = "W"
                   or  type = "B") as b

and get back:
Error: Syntax error: Encountered "as" at line 10, column 40.

A: Each SELECT statement within UNION must have the same number of columns.
The columns must also have similar data types.
The columns in each SELECT statement must also be in the same order.
select col1,col2 from a
union
select 1,2 from b

but in your query number of column is not same in both query and your query might be like below
select sum(col) from
   ( select shares*cps as col from transactions
    where usr  = 1
     and type = "C"
     or type = "S"
        union
       select shares*cps*(-1) from transactions
        where usr = 1
        and type = "W"
        or  type = "B"
    ) t


text:
Q: Find all open Word Applications from within a VBA EXCEL-Macro In an EXCEL-macro I want to copy a selected range to a WORD-document table. I know how to do this, creating a new WORD-document (target). But I want to check if there are already open WORD-documents from which I can select a target.
I found code for looping through all open EXCEL-Applications from within a EXCEL-Macro. I modified the code from Florent Breheret as given below.
What are the missing class names, indicated by "???" in the code, to look for WORD-documents?
Thank you in advance!  Immanuel
Private Declare PtrSafe Function AccessibleObjectFromWindow Lib "oleacc" ( _
    ByVal hwnd As LongPtr, ByVal dwId As Long, riid As Any, ppvObject As Object) As Long

Private Declare PtrSafe Function FindWindowExA Lib "user32" ( _
    ByVal hwndParent As LongPtr, ByVal hwndChildAfter As LongPtr, _
    ByVal lpszClass As String, ByVal lpszWindow As String) As LongPtr

'Test my code
Private Sub GetWordInstances_Test()
    Dim wd As Word.Application
    Dim i, cnt As Integer

    cnt = 0
    For Each wd In GetWordInstances()
        cnt = cnt + 1
        Debug.Print wd.Application.Name, cnt

        For i = 1 To wd.Documents.Count

            Debug.Print wd.Documents(i).FullName, i
        Next i
    Next
End Sub

'Getting open WORD instances from within EXCEL-VBA
Public Function GetWordInstances() As Collection
    Dim guid&(0 To 3), acc As Object, hwnd, hwnd2, hwnd3
    guid(0) = &H20400
    guid(1) = &H0
    guid(2) = &HC0
    guid(3) = &H46000000

    Set GetWordInstances = New Collection
    Do
        hwnd = FindWindowExA(0, hwnd, "OpusApp", vbNullString)
        If hwnd = 0 Then Exit Do

        hwnd2 = FindWindowExA(hwnd, 0, "???", vbNullString)

        hwnd3 = FindWindowExA(hwnd2, 0, "???", vbNullString)

        'hand over found WORD application to collection
        If AccessibleObjectFromWindow(hwnd3, &HFFFFFFF0, guid(0), acc) = 0 Then
            GetWordInstances.Add acc.Application
        End If
    Loop
End Function

A: This works for me:
1. Add the reference in Excel: Tools->References->Microsoft Word XX.X Object Library
2. Run this code:
Sub openDocs()
Dim openDoc     As Word.Document
Dim docCount    As Long

docCount = Documents.Count

For Each openDoc In Documents
    'do whatever, i.e.:
    ' debug.print openDoc.Name
Next openDoc

If docCount = 0 Then
    MsgBox "There are no open documents."
Else
    MsgBox "There are " & docCount & " open documents."
End If

End Sub

A: Try something like this ...
Sub CheckForWordApp()
Dim wApp As Object
On Error Resume Next
Set wApp = GetObject(, "Word.Application")
If Err.Number = 429 Then
    'Word application is not running so create it
    Set wApp = New Word.Application
    wApp.Visible = True
    'no documents will exist, so do something
Else
    'A Word application exists, make sure it's visible
    wApp.Visible = True
    If wApp.Document.Count > 0 Then
        'There are open documents so do something
    Else
        'No documents are open so do something else
    End If
End If
End Sub

A: See this answer that explains the process to solve your question.
Resuming:
OpusApp ==> _WwF ==> _WwB ==> _WwG.

You must add another layer:
    hwnd = FindWindowExA(0, hwnd, "OpusApp", vbNullString)
    If hwnd = 0 Then Exit Do

    hwnd2 = FindWindowExA(hwnd, 0, "_WwF", vbNullString)

    hwnd3 = FindWindowExA(hwnd2, 0, "_WwB", vbNullString)

    hwnd4 = FindWindowExA(hwnd3, 0, "_WwG", vbNullString)
    'hand over found WORD application to collection
    If AccessibleObjectFromWindow(hwnd4, &HFFFFFFF0, guid(0), acc) = 0 Then
        GetWordInstances.Add acc.Application
    End If


text:
Q: Unable to get a join to pull all records from another table in MySQL I've got this working in MSSQL but I've fallen off and been run over when it comes to MySQL.  I'm trying to search for all records in a group after a certain date in an employee info table.  I can get the records in the employee info table but I also need to return all employee numbers in another table that are part of the same group.  The purpose being to see which employees in the group have submitted some paperwork. Since the table has data from multiple years, it needs to filtered so I can search after a certain date each year.
Here are my two tables
empInfo
--------------------------------------
id             | int
date           | datetime
empNumber      | varchar
grpNumber      | int
active         | int

empReports
--------------------------------------
id             | int
date           | datetime
empNum         | varchar
grpNumber      | int
empFName       | varchar
empLName       | varchar
dateReceived   | varchar
active         | int

The idea is to search for a group number and return all employee IDs from the empInfo table and show which ones have records from the empReports table. The current query is:
SELECT r.dateReceived as Date,
t.empNumber AS Emp,
r.grpNumber AS Grp,
r.empFName,
r.empLName
FROM empInfo t
LEFT JOIN empreports r
ON t.empNumber = r.empNum
WHERE t.grpNumber = 100
AND t.active = 1
AND r.dateReceived > 1587574487
ORDER BY CAST(t.empNumber as UNSIGNED INTEGER) ASC

This returns a single record
    Date    |  Emp  |  Grp  |  empFName  |  empLName
------------------------------------------------------
1589561752  |   1   |  100  |  Fred      |  Derf

What I need to see is more like
    Date    |  Emp  |  Grp  |  empFName  |  empLName
------------------------------------------------------
1589561752  |   1   |  100  |  Fred      |  Derf
    NULL    |   2   |  100  |  NULL      |  NULL
    NULL    |   3   |  100  |  NULL      |  NULL
    NULL    |   4   |  100  |  NULL      |  NULL
    NULL    |   5   |  100  |  NULL      |  NULL

I've tried different joins, swapping the query around and just about anything else I can think of with no joy, so any assistance any MySQL gurus could offer would be greatly appreciated.
Thanks in advance.

A: The problem is this:
If r.dateReceived is NULL, the WHERE r.dateReceived > 1587574487 is never satisfied
What you need to do is check for r.dateReceived in the WHERE clause as well
SELECT r.dateReceived as Date,
t.empNumber AS Emp,
r.grpNumber AS Grp,
r.empFName,
r.empLName
FROM empInfo t
LEFT JOIN empreports r
ON t.empNumber = r.empNum
WHERE t.grpNumber = 100
AND t.active = 1
AND (r.dateReceived > 1587574487 OR r.dateReceived IS NULL)
ORDER BY CAST(t.empNumber as UNSIGNED INTEGER) ASC

GIVE IT A TRY !!!


text:
Q: Count lines between "X"s I want to count the lines between "X"s. This is just an example; I have to apply the code to a complex biological result. I will be thankful if you can suggest some command, preferably using awk, grep or sed as I am familiar with those.
Example:
X
Y
Y
Y
X
Y
Y
Y
Y
X
Y
X

Desired Output:
3
4
1

A: Another simple awk approach which works on OP's sample data and if X was not in first or even in last or repeated Xs.
awk -v RS='X' 'NF{print NF}' infile

Above is correct when there is only one field in each line with default FS any whitespaces, otherwise below is revised in general case for counting linewise. You can input your PATTERN in place of X there.
awk -F'\n' -v RS='X' 'NF>2{print NF-2}'

Sample input:
X
Y YYY Y
YY
YY Y YY YY Y Y
X
Y Y Y
X
Y
Y
X
X

The output is:
3
1
2

A: With awk:
$ awk '!/X/{count++}/X/{print count; count = 0}' input

3
4
1

Increment a count for every line not containing X; print and reset the count for lines containing X.

A: $ awk '/X/ && prev{print NR-prev-1} /X/{prev=NR}' file
3
4
1

How it works:
Awk implicitly reads through input files line by line.

*

*/X/ && prev{print NR-prev-1}
For any line that contains X and if we have previously assigned a value to prev, then print out the number of the current line, NR, minus prev minus one.

*/X/{prev=NR}
For any line that contains X, set the variable prev to the current line number, NR.

A: Most of the answers here match the content of the line to be counted using regular expressions embedded into the Awk program. If you need to match lines with content that may contain special characters (either to Awk or regular expressions) it would be better to actually compare strings for equality. Therefore I propose the following Awk script as a variant of muru's answer:
BEGIN {
    count = 0;
}

{
    if ($0 == needle) {
        if (count) {
            print count;
            count = 0;
        }
    } else {
        count++;
    }
}

Store it as a text file, e. g. count-rows.awk, and invoke it as follows:
awk -f count-rows.awk -v needle=X input

You can adjust the value of needle to your liking. The advantage of this method is that you can invoke the program from a shell script with an arbitrary value for needle without escaping issues:
awk -f count-rows.awk -v needle="$needle" input


text:
Q: Can't get ffmpeg to generate an MP4 file on iOS I'm having serious problems trying to get an iOS app to create an MP4 file from an RTSP stream using ffmpeg.
I can open the stream, decode it, show the video on screen and play the live audio without any issues. The problems arise when I try to output the AV stream to a file.
If I ask ffmpeg to create an MP4 file, it fails, informing me that the audio codec in the stream is incompatible with MP4 files. If I attempt to transcode the audio into acc, then ffmpeg lets me continue, but during the file output I get multiple "aac bitstream error" messages, and the recording is silent.
I also tried having ffmpeg create a mov (Quicktime) file instead of MP4. If I do that, it seems to work: I get a mov file that plays back with audio. That being done, I tried to transcode the mov file to mp4 using AVAssetExportSession. But this doesn't work: it reports that the decode failed.
I'm not sure what to try next.


text:
Q: How to remove choosen item once it is selected and get it back once unselected Hi i problem in achieving choosen select/unselect, i'm using https://harvesthq.github.io/chosen/
Question: i want to remove item from drop-down once selected and get it back once unselected
Here is my image showing problem:

below is my whole choosen code:

$('.chosen-select').chosen({}).change( function(obj, result) {
    //console.debug("changed: %o", arguments);

    console.log("selected: " + result.selected);
});

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css">

<select data-placeholder="Choose a Country..." class="chosen-select" multiple style="width:350px;" tabindex="4">
            <option value=""></option>
            <option value="Any">[Any]</option>
            <option value="United States">United States</option>
            <option value="United Kingdom">United Kingdom</option>
            <option value="Afghanistan">Afghanistan</option>
            <option value="Aland Islands">Aland Islands</option>
            <option value="Albania">Albania</option>
            <option value="Algeria">Algeria</option>
            <option value="American Samoa">American Samoa</option>

          </select>

A: li.result-selected { display:none !important; }

Other stuff I tried did not work, but the CSS change works fine:

$('.chosen-select').chosen({}).change(function(obj, result) {
  console.log("selected: " + result.selected);

  /* None of this works. The CSS does work
      const vals = $(".chosen-select").val();
        $('.chosen-select').find("option[value='"+result.selected+"']").remove()
        console.log(vals)
        $(".chosen-select").val(vals);
            //  $('.chosen-select').trigger("chosen:updated");
  */
});
li.result-selected {
  display: none !important;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css">

  <select data-placeholder="Choose a Country..." class="chosen-select" multiple style="width:350px;" tabindex="4">
    <option value=""></option>
    <option value="Any">[Any]</option>
    <option value="United States">United States</option>
    <option value="United Kingdom">United Kingdom</option>
    <option value="Afghanistan">Afghanistan</option>
    <option value="Aland Islands">Aland Islands</option>
    <option value="Albania">Albania</option>
    <option value="Algeria">Algeria</option>
    <option value="American Samoa">American Samoa</option>

  </select>

Here is a related question jQuery Chosen - update select list without losing selections which did not help


text:
Q: Python programming for exponentiation The cube root of 125 is 5 but in python it gives me 4.9999 as the answer. Here is the code I used
Print(125 ** (1/3))
So I need an explanation
This is under python exponentiation


text:
Q: How do I use the xlib and OpenGL modules together with python? I know it is possible to use Xlib and OpenGL together, with GLX (I've done it myself in C).
The problem is, how do I do this in python? The OpenGL module has GLX functionality [documentation], but it appears to be using C types and I have no idea (nor, it appears does anyone else) how to use the xlib types with PyOpenGL.
I also tried using ctypes and loading libraries directly, but ran into (obvious) problems when trying to use the C macros defined in the Xlib header file, like DefaultRootWindow.
Am I missing something obvious, like PyOpenGL having its own xlib implementation, or is this just not possible without some (compiled) module-writing?

A: You can't use python-xlib types directly with python-opengl.  But you can use the fact that a window XID is just a number to use python-opengl on the same window.
from Xlib import X, display
from OpenGL import GL, GLX
from OpenGL.raw._GLX import struct__XDisplay
from ctypes import *

# some python-xlib code...
pd = display.Display()
pw = pd.screen().root.create_window(50, 50, 200, 200, 0,
                                    pd.screen().root_depth,
                                    X.InputOutput, X.CopyFromParent)
pw.map()

# ensure that the XID is valid on the server
pd.sync()

# get the window XID
xid = pw.__resource__()

# a separate ctypes Display object for OpenGL.GLX
xlib = cdll.LoadLibrary('libX11.so')
xlib.XOpenDisplay.argtypes = [c_char_p]
xlib.XOpenDisplay.restype = POINTER(struct__XDisplay)
d = xlib.XOpenDisplay("")

# use GLX to create an OpenGL context on the same window XID
elements = c_int()
configs = GLX.glXChooseFBConfig(d, 0, None, byref(elements))
w = GLX.glXCreateWindow(d, configs[0], c_ulong(xid), None)
context = GLX.glXCreateNewContext(d, configs[0], GLX.GLX_RGBA_TYPE, None, True)
GLX.glXMakeContextCurrent(d, w, w, context)

# some python-opengl code....
GL.glShadeModel(GL.GL_FLAT)
GL.glClearColor(0.5, 0.5, 0.5, 1.0)

GL.glViewport(0, 0, 200, 200)
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glLoadIdentity()
GL.glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)

GL.glClear(GL.GL_COLOR_BUFFER_BIT)
GL.glColor3f(1.0, 1.0, 0.0)
GL.glRectf(-0.8, -0.8, 0.8, 0.8)

# assume we got a double buffered fbConfig and show what we drew
GLX.glXSwapBuffers(d, w)

# a terrible end to a terrible piece of code...
raw_input()

This is really horrible though. (Error checking and choosing a sensible fbConfig omitted for clarity)
It really should be possible to do all the necessary xlib calls with ctypes though.  Pyglet, for example,  manages somehow, but I'm not sure what specific problem you ran into.


text:
Q: SciPy converting polygon to hull object I have the following code that takes a series of points from a pandas dataframe (x,y) and a scipy.spatial.qhull.ConvexHull object. This returns all points which are within the hull.
def in_hull(points, hull):
    hulleq = hull.equations
    dist = np.array(points[['x', 'y']]) @ hulleq[:, :2].T + hulleq[:, 2]
    return np.all(dist < 0, axis=1)

I'm trying to do the same for a polygon (see below), I would like to reuse the in_hull() function rather than write a point in polygon function. Is there anyway to convert a polygon into a scipy hull object so it can pretend to be a hull object?
POLYGON ((580994.4751 4275268.0318, 580994.8389 4275267.4381, 580994.8673 4275267.3736, 580994.3239 4275266.9655, 580993.7005 4275266.3116, 580993.5152 4275266.1903, 580991.8844 4275265.1638, 580991.7139 4275265.2946, 580991.5705 4275265.4891, 580990.4452 4275267.2628, 580990.1548 4275267.7447, 580990.0031 4275268.0023, 580989.8736 4275268.2297, 580990.164 4275268.4583, 580990.2375 4275268.5093, 580990.4965 4275268.6763, 580990.826 4275268.8845, 580990.8388 4275268.8923, 580991.3172 4275269.1658, 580991.9052 4275269.5398, 580992.3238 4275269.7897, 580992.3515 4275269.8057, 580992.4967 4275269.889, 580992.6127000001 4275269.9522, 580992.8403 4275270.0501, 580993.03 4275270.0662, 580993.3365 4275269.7995, 580993.6424 4275269.3079, 580994.0201 4275268.7661, 580994.4751 4275268.0318))


text:
Q: A challenging horizontal/vertical centering problem I need a box that typesets a kind of compass in a square.
It should look like this figure
 +-----------------+
 |        N        |
 |                 |
 |                 |
 | W      X      E |
 |                 |
 |                 |
 |        S        |
 +-----------------+

The requirements
1) The N and S should be horizontally centered with respect to the left/right side of the frame and at say 0.3em from the top/lower side of the frame.
2) The W and E should be vertically centered with respect to the top/lower side of the frame and at say 0.3em from the left/right side of the frame.
3) The middle of X (normally a 1 or 2 digit number) should be on the crosspoint of the (hor.) midline through W and E AND the (vert.) midline through N and S.
4) enlarging the font size should equally (well more or less) enlarge the compass size, as well as the thickness of the frame. This should work from 'tiny' upto 'HUGE' and also when 'scalefont' is used to change the font size.
5) Important is that the centering (hor. and vert.) is maintained when the size changes.
I tried several implementations, e.g. using a tabular or using raiseboxes.
But every time I got stuck with the vertical alignment.
Does someone know how to do this?
BTW: Requirement 3 is not a mathematical one. It should just look like that.

A: Picture mode!
The side of the square is 5em, because \unitlength is set to 1em (which will take into account the current font). Therefore 0.3 represents a distance of 0.3em, which is what you seem to want. Fix the size according to your taste.
\documentclass{article}
\usepackage{pict2e}

\newcommand{\compass}[1]{%
  \begingroup
  \setlength\unitlength{1em}%
  \linethickness{0.2ex}%
  \begin{picture}(5,5)
  % the frame
  \moveto(0,0)\lineto(0,5)\lineto(5,5)\lineto(5,0)\closepath\strokepath
  % the cardinal points
  \put(2.5,4.7){\makebox[0pt]{\raisebox{-\height}{N}}}
  \put(2.5,0.3){\makebox[0pt]{S}}
  \put(0.3,2.5){\makebox[0pt][l]{\raisebox{-0.5\height}{W}}}
  \put(4.7,2.5){\makebox[0pt][r]{\raisebox{-0.5\height}{E}}}
  % the center
  \put(2.5,2.5){\makebox(0,0){#1}}
  \end{picture}%
  \endgroup
}

\begin{document}

X\compass{1}X\qquad{\footnotesize X\compass{3}X}\qquad{\tiny X\compass{5}X}

\bigskip

{\Large X\compass{12}X}\qquad{\Huge X\compass{24}X}

\end{document}

A: The following is a wild mix between LaTeX stuff and stuff you'd do using plain TeX. Change the default value of the optional argument of \compass to change the overall size. The overall size is not equal to the optional argument, but to #1+.6em+.4ex in width, #1+.3em+.2ex in height and .3em+.2ex in depth.
\documentclass[border=2mm]{standalone}

% this might already be defined depending on included packages
\providecommand\clap[1]{\hbox to 0pt{\hss #1\hss}}

\newcommand\compass[2][10ex]
  {{%
    \fboxrule=.2ex
    \fboxsep=.3em
    \fbox
      {%
        \vbox to #1{\hsize=#1
          \hbox to #1{\hss N\hss}%
          \vss
          \hbox to #1{\rlap{W}\hss \clap{#2}\hss \llap{E}}%
          \vss
          \hbox to #1{\hss S\hss}%
        }%
      }%
  }}

\begin{document}
\compass{1}
\end{document}

Vertically it only aligns the baselines of W x E so if x is recognizable smaller than W and E it would not look vertically centred.
Version that also vertically centres the middle line using $\vcenter{...}$ (and utilizing that the \xlap macros use a \hbox internally so the text is not typeset in math mode):
\documentclass[border=2mm]{standalone}

% this might already be defined depending on included packages
\providecommand\clap[1]{\hbox to 0pt{\hss #1\hss}}

\newcommand\compass[2][10ex]
  {{%
    \fboxrule=.2ex
    \fboxsep=.3em
    \fbox
      {%
        \vbox to #1{\hsize=#1
          \hbox to #1{\hss N\hss}%
          \vss
          \hbox to #1{%
            $\vcenter{\rlap{W}}$\hss
            $\vcenter{\clap{#2}}$\hss
            $\vcenter{\llap{E}}$%
          }%
          \vss
          \hbox to #1{\hss S\hss}%
        }%
      }%
  }}

\begin{document}
\compass{\tiny1}
\end{document}

Version that gives the same distance from the centre of the W and E to the border. Unfortunately it doesn't look as good as I thought.
\documentclass[border=2mm]{standalone}

% this might already be defined depending on included packages
\providecommand\clap[1]{\hbox to 0pt{\hss #1\hss}}

\newbox\myTestbox
\newdimen\myhoffset
\newcommand\compass[2][10ex]
  {{%
    \setbox\myTestbox\hbox{E}%
    \myhoffset=.5\wd\myTestbox
    \setbox\myTestbox\hbox{W}%
    \ifdim\myhoffset<.5\wd\myTestbox
      \myhoffset=.5\wd\myTestbox
    \fi
    \fboxrule=.2ex
    \fboxsep=.3em
    \fbox
      {%
        \vbox to #1{\hsize=#1
          \hbox to #1{\hss N\hss}%
          \vss
          \hbox to #1{%
            \hskip\myhoffset
            $\vcenter{\clap{W}}$\hss
            $\vcenter{\clap{#2}}$\hss
            $\vcenter{\clap{E}}$%
            \hskip\myhoffset
          }%
          \vss
          \hbox to #1{\hss S\hss}%
        }%
      }%
  }}

\begin{document}
\compass[8ex]{\tiny1}
\end{document}

As OP noted, the \vcenter code has a small vertical offset from the middle. Therefore here another version, this time using some \smashs and a calculated \raise amount for #2:
\documentclass[border=2mm]{standalone}

% this might already be defined depending on included packages
\providecommand\clap[1]{\hbox to 0pt{\hss #1\hss}}

\newdimen\myvoffset
\newbox\mytestboxA
\newbox\mytestboxB
\newcommand\compass[2][10ex]
  {{%
    \setbox\mytestboxA\hbox{WE}%
    \setbox\mytestboxB\hbox{#2}%
    \myvoffset=\dimexpr
      \ht\mytestboxA-\ht\mytestboxB+\dp\mytestboxB-\dp\mytestboxA\relax
    \myvoffset=.5\myvoffset
    \fboxrule=.2ex
    \fboxsep=.3em
    \fbox
      {%
        \vbox to #1{\hsize=#1
          \hbox to #1{\hss N\hss}%
          \vss
          \hbox to #1{%
            \smash{\rlap{W}}\hss
            \smash{\clap{\raise\myvoffset\hbox{#2}}}\hss
            \smash{\llap{E}}%
          }%
          \vss
          \hbox to #1{\hss S\hss}%
        }%
      }%
  }}

\begin{document}
\compass[2.5em]{\tiny1}
\end{document}

A: Just for completeness (as this is overkill for the problem) a TikZ based answer (you'll need \usepackage{tikz} in your preamble). The optional argument matches the size
\documentclass[tikz,border=2mm]{standalone}

\newcommand\compass[2][15ex]
  {%
    \begin{tikzpicture}[inner sep=0pt]
      \draw[line width=.2ex,use as bounding box] (0,0) rectangle (#1,#1);
      \node at (0.5*#1,0.5*#1) {#2};
      \node[anchor=north] at (0.5*#1,#1-0.3em) {N};
      \node[anchor=south] at (0.5*#1,0.3em) {S};
      \node[anchor=west] at (0.3em,0.5*#1) {W};
      \node[anchor=east] at (#1-0.3em,0.5*#1) {E};
    \end{tikzpicture}%
  }

\begin{document}
\compass{\tiny1}
\end{document}

A: Tikz version
\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\newcommand\compass[1]{%
  \begin{tikzpicture}[x=1em,y=1em]
    \coordinate (SW);
    \draw[line width=0.1em] (SW) rectangle +(6,6)coordinate(NE);
    \coordinate (Mid) at ($(SW)!0.5!(NE)$);
    \node[inner sep=0.3em,anchor=west] at (Mid -| SW) {W};
    \node[inner sep=0.3em,anchor=east] at (Mid -| NE) {E};
    \node[inner sep=0.3em,anchor=south] at (Mid |- SW) {S};
    \node[inner sep=0.3em,anchor=north] at (Mid |- NE) {N};
    \node[inner sep=0.3em] at (Mid) {#1};
  \end{tikzpicture}}
\begin{document}
A\compass{12}A%
\Huge A\compass{12}A%
\footnotesize A\compass{12}A
\end{document}

A: This is a nice usecase for the xcoffins package:
\documentclass{standalone}
\usepackage{xcoffins}
\NewCoffin\CompassCoffin
\NewCoffin\NorthCoffin
\NewCoffin\SouthCoffin
\NewCoffin\EastCoffin
\NewCoffin\WestCoffin
\NewCoffin\CenterCoffin
\newcommand\compass[1][10ex]{%
  \begingroup
    \SetHorizontalCoffin\NorthCoffin{N}%
    \SetHorizontalCoffin\SouthCoffin{S}%
    \SetHorizontalCoffin\EastCoffin{E}%
    \SetHorizontalCoffin\WestCoffin{W}%
    \SetHorizontalCoffin\CenterCoffin{$+$}%
    \SetVerticalCoffin\CompassCoffin{#1}{%
      \vbox to #1{%
        \hfil\vfil
      }%
    }%
    % Add the north at the *t*op, *h*orizontal *c*enter
    \JoinCoffins
      \CompassCoffin[t,hc]
      \NorthCoffin[t,hc]%
    % Add the east at the *v*ertical *c*enter, *r*ight
    \JoinCoffins
      \CompassCoffin[vc,r]
      \EastCoffin[vc,r]%
    % Add the south at the *b*ottom, *h*orizontal *c*enter
    \JoinCoffins
      \CompassCoffin[b,hc]
      \SouthCoffin[b,hc]%
    % Add the west at the *v*ertical *c*enter, *l*eft
    \JoinCoffins
      \CompassCoffin[vc,l]
      \WestCoffin[vc,l]%
    % Add the center at the *v*ertical *c*enter, *h*orizontal *c*enter
    \JoinCoffins
      \CompassCoffin[vc,hc]
      \CenterCoffin[vc,hc]%
    \setlength\fboxrule{.2ex}%
    \setlength\fboxsep{.3em}%
    \fbox{\TypesetCoffin\CompassCoffin}%
  \endgroup
}
\begin{document}
\noindent\compass\\
\large\compass\\
\footnotesize\compass
\end{document}


text:
Q: What should be the topic in the mqtt where the commands are received in the fiware-orion? I have been trying  to simulate a device communicating with the MQTT protocol, when I send the command to the orion from postman
{
   "on":{
      "type":"command",
      "value":""
   }
}

I create this service
{
   "services":[
      {
         "apikey":"4jggokgpepnvsb2uv4s40d59ov",
         "cbroker":"http://orion:1026",
         "entity_type":"IoT-PublicServices",
         "resource":""
      }
   ]
}

I suscribe to this topic  '/+/streetLight001/cmd', i use the wildcard '+', In the place of the '+' it is supposed to be the apikey but it does not work, could someone tell me what could be wrong?

A: According to the documentation MQTT commands are sent to the following MQTT topic when using an MQTT binding: /<apiKey>/<deviceId>/cmd
Note Measures and commands are sent over different MQTT topics:

*

*Measures are sent northbound on the /<protocol>/<api-key>/<device-id>/attrs topic,

*Commands are sent southbound on the /<api-key>/<device-id>/cmd topic

The reasoning behind this is that when sending measures northbound from device to IoT Agent, it is necessary to explicitly identify which IoT Agent is needed to parse the data. This is done by prefixing the relevant MQTT topic with a protocol, otherwise there is no way to define which agent is processing the measure. This mechanism allows smart systems to connect different devices to different IoT Agents according to need.
For southbound commands, this distinction is unnecessary since the correct IoT Agent has already registered itself for the command during the device provisioning step and the device will always receive commands in an appropriate format


text:
Q: Set text in Active Conversation in iMessage I wrote some code to add text to the Messages.app input field  in my iMessage extension.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"didSelect called");
    NSLog(@"%d", 1);
    [[self activeConversation] insertText:@"https://google.com" completionHandler:^(NSError * error) {
        NSLog(@"Error happened");
        NSLog(@"Error: %@", error);
    }];
    NSLog(@"%d", 2);
}

The strange part is that all of the normal logs are happening. The app will log "didSelect called", "1" and "2". However, the message - the Google url - isn't being inserted, and the error logs aren't being shown. So I don't really have a clue as to what's going wrong. Any idea's what I'm doing wrong?

A: Solution #1

*

*Send correct reference from MessagesViewController to your view controller.

*Check activeConversation value for nil:

if ([self activeConversation] != nil) {
    [[self activeConversation] insertText:@"Some text" completionHandler:^(NSError * _Nullable error) {
        NSLog(@"error: %@", error.localizedDescription);
    }];
} else {
    NSLog(@"Conversation is nil");
}

Solution #2

*

*Create Singleton in iMessage extension name space.

*In MessagesViewController in - (void)viewDidLoad setup reference to
your MSConversation: [[Conversation shared] activeConversation] = [self activeConversation];

*Use [[Conversation shared] activeConversation] insertText: .... ];
for sending messages from any controllers.


text:
Q: How to use ThreadPool in c#? When I run this code then nothing is shown on the console, but when I debug then it displays the output. Please explain why this happen? How I can get info when the Thread completes the task?
public class TestClass
{
    static void Main()
    {
        ThreadPool.SetMaxThreads(5, 5);
        for (int x = 0; x < 10; x++)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(printnum), x);
        }

        Console.ReadKey();
    }

    public static void printnum(object n)
    {
        Console.WriteLine("Call " + n);
        for (int i = 0; i < 10; i++) { Console.WriteLine(i); }
    }
}

A: From the documentation for Console.ReadKey():

The ReadKey method waits, that is, blocks on the thread issuing the
  ReadKey method, until a character or function key is pressed.

What it actually does is acquire a lock on Console.InternalSyncObject, which prevents further operations on the console.
The Console.ReadLine() method does not block the thread in this way. You can use it instead.
Reading this article I'm guessing you have .NET 4.5 installed?

A: The other's are right. If you do not wait for the threads to finish, you need to use Console.ReadLine. But if you do wait - as you asked - you can still use Console.ReadKey. I changed your code accordingly. Also checkout Microsofts example on how to use the ThreadPool.
    static void Main(string[] args)
    {
        const int count = 10;
        var waitHandles = new ManualResetEvent[count];

        ThreadPool.SetMaxThreads(5, 5);
        for (int x = 0; x < count; x++)
        {
            var handle = new ManualResetEvent(false);
            waitHandles[x] = handle;
            var worker = new MyWorker(handle, x);
            ThreadPool.QueueUserWorkItem(new WaitCallback(MyWorker.printnum), worker);
        }

        WaitHandle.WaitAll(waitHandles);

        Console.WriteLine("Press any key to finish");
        Console.ReadKey();
    }

    class MyWorker
    {
        readonly ManualResetEvent handle;
        readonly int number;

        public MyWorker(ManualResetEvent handle, int number)
        {
            this.handle = handle;
            this.number = number;
        }

        public static void printnum(object obj)
        {
            var worker = (MyWorker)obj;
            Console.WriteLine("Call " + worker.number);
            for (int i = 0; i < 10; i++) { Console.WriteLine(i); }

            // we are done
            worker.handle.Set();
        }
    }

The key is that you have to use WaitHandles. Each thread gets one handle which is set to true when the thread finishes. In your main method you have to wait for all handles to be set to true.


text:
Q: Converting data with whitespace into a dataframe
Converted this data from a pdf to a .csv file.
Since it had a lot of whitespace between columns, that tabula had a problem recognizing, I'm left with these 6 columns merged into one.
I was wondering if there's a way to convert them into 6 different columns, corresponding to the values in the rows.

A: You can use tidyr, a package that can help exactly with these problems.
First, install and load tidyr.
install.packages("tidyverse") # a bunch of helpful packages including tidyr
install.packages("tidyr") # or you can just install tidyr
library(tidyr) # load tidyr

From the looks of it, the code you're looking for is:
separate(dataset, 1994_1995_1996_1997_1998_1999, sep = " ", into = c("1994", "1995", "1996", "1997", "1998", "1999")

separate() separates columns based on a separator (in this case, whitespace, corresponding to the sep = " " argument.


text:
Q: IE submit the forms twice I have this problem in IE, sometimes my form is submitting twice. I know the issue of clicking the button twice and that is not the problem. But on my case I only click it once. I checked my records in the database and there are two records.
<input type="button" value="Approve" name="btn_approve" id="btn_approve">
<input type="button" value="Reject"  name="btn_reject" id="btn_reject">

<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.20.custom.min.js"></script>
<script>
$(document).ready(function () {
    $("#btn_approve").click(function () {
        // some validation before submitting the form

        $("#my_form").submit();
    });
});
</script>

A: Assuming that #btn_approve is actually a submit button inside of #my_form, you are triggering the form submission via .submit and the browser is also submitting it normally. Change to:
$("#btn_approve").on('click', function (e) {
   $("#my_form").trigger('submit');

   e.preventDefault();
});

A: Prevent the default behaviour of the button:
<input type="button" value="Approve" name="btn_approve" id="btn_approve">
<input type="button" value="Reject"  name="btn_reject" id="btn_reject">

<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.20.custom.min.js"></script>
<script>
$(document).ready(function () {
    $("#btn_approve").click(function (e) {
        e.preventDefault();
        // some validation before submitting the form

        $("#my_form").submit();
    });
});
</script>

A: I have the same issue.
I time-stamp my records as I save them to the database.
So if a record is submitted for a specific unique user, within 2 seconds from each other, I just ignore the duplicates.
This way I don't need to check for browser types and compatibility on the client side, just handle the issue on the server side, respectively of the browser.
        '' Count the number of submissions, for the user, within the 2 seconds.
        objRS.open "select count(*) as C FROM [ADS].[dbo].[VIP_USERS] where userid = '" & Trim(Request("USERID")) & "' and datediff(ss, created, GETDATE()) <= 2", Application("sConn")


text:
Q: How can I make a named list or vector from environment objects, using the object names? I am trying to take objects in my environment, and put them into a list or vector that is named with the names of the object. Here is an illustration:
a = 1
b = 2

desired <- c(a, b)
names(desired) <- c("a", "b")
desired
#> a b
#> 1 2

My attempts have been variations of the following. I can see why this doesn't work (even if my terminology might not quite be right): it's pausing the evaluation after figuring out that ... is 1, 2. However, I want some way to get it to give a, b so that I can put the names on properly. I am open to any solutions, in base R, rlang or others.
name_list <- function(...){
  names <- enquote(list(...))
  values <- list(...)
  return(names)
}
print(name_list(a, b))
#> quote(list(1, 2))

Created on 2018-07-10 by the reprex package (v0.2.0).

A: You can use match.call to retrieve the names of the arguments being passed in
name_list <- function(...){
  vnames <- as.character(match.call())[-1]
  return(setNames(list(...), vnames))
}
a = 1; b=c(1,2)
name_list(a, b)


text:
Q: c# Access ObservableCollection as base I have a class with base an Observable collection. I am trying to set the Observablecollection from a List of items with the method clone as shown below:
   public class MyObservableCollection : ObservableCollection<Record>
    {
        public void Clone(List<Record> originalEnityList)
        {
            ObservableCollection<Record> cloned = new ObservableCollection<Record>(originalEnityList);
        }
    }

What i would like to do is to copy the cloned collection to the base ObservableCollection like:
    this=  new ObservableCollection<Record>(originalEnityList);
or
    this=cloned;

How can i do that?
I have tried the following without any progress:

*

*ObservableCollection mine = this; mine=cloned;(While the mine collection is set the base collection remains empty).

*I tried to do this from outside the class with no luck also,  like MyObservableCollection coll =  new ObservableCollection<Record>(originalEnityList); But i believe that MyObervableCollection is missing the new constructor that observablecollection has.

PS: I haved tried to use foreach and for to populate the collection but because my collection is really big, it takes too much time.
I am pretty sure that i am missing something really simple here.

A: You could simply add a constructor that takes the source collection as parameter:
public class MyObservableCollection : ObservableCollection<Record>
{
    public MyObservableCollection()
    {
    }

    public MyObservableCollection(List<Record> originalEntityList)
        : base(originalEntityList)
    {
    }
}

With a static Clone methold like
private static List<Record> Clone(List<Record> originalEntityList)
{
    return ...
}

you could write the second constructor like this:
public MyObservableCollection(List<Record> originalEntityList)
    : base(Clone(originalEntityList))
{
}


text:
Q: What is the maximum number of requests that ASP.NET Core WebAPI can handle simultaneously? Wondering is there a limit that can be clearly defined in a ASP.NET Core Web API to handle simultaneously several requests / controllers actions.
AFAIK, every action is handled on a thread from the thread-pool, wondering if that can be increased or decreased with ASP.NET Core?

A: Assuming you are using Kestrel as the underlying web server the default number of concurrent connections in ASP.NET Core 2.2 is defined as unlimited.

*

*MSDN documentation

*Kestrel Fundamentals


text:
Q: How to get Tortoise HG to detect changes in files based on directory again The simplest way I can describe this is that I have a project in Windows 7 under version control with tortoise HG version 2.8.1
using Mercurial-2.6.2, I am using bitbucket.org as my remote repository. When I go to click HG commit on a folder with a red exclamation point on it (meaning files that need to be committed).  It tells me

No files found for this operation

But when I click on files in that directory that have the red exclamation point, It brings up the normal commit menu expecting me to write the normal commit message.
So basically the problem is that it doesn't detect any files need comitting from the directory level when I click commit, despite there being a red exclamation point on the directory.  Maybe this was caused by some other issues. I am sure it has to do with branches or heads, but I really don't understand that stuff as well as I would prefer.
I am willing to grab any info or screenshots from Tortoise HG or Bitbucket to help with the issue, just be sure to explain how to get that info. Here are some screenshots of the issue.

Here is inside the directory.

A: Repository on network share is Bad Idea (tm)
Move repository to local drive


text:
Q: javascript onended audio event I got simple javscript function with play/pause action. Unfortunately he works only with onclick event. Now i need also change icon color when played mp3 ends. Now at the end icon color stay from playing audio. I need to change back to the color when audio is paused (lightgreen).
JavaScript
  function aud_play_pause(object) {
    var myAudio = object.querySelector(".xnine-player");
    var myIcon = object.querySelector(".control");
    if (myAudio.paused) {
      myIcon.className = "control icon-pause";
      myAudio.play();
    } else if (myAudio.onend) {
      myIcon.className = "control icon-play";
    } else {
      myIcon.className = "control icon-play";
      myAudio.pause();
    }
  }

HTML

            <audio class="xnine-player"
                src="http://www.noiseaddicts.com/samples_1w72b820/29.mp3"
            preload="auto"></audio>

         - audio #1

            <audio class="xnine-player"
                src="http://www.noiseaddicts.com/samples_1w72b820/2235.mp3"
            preload="auto"></audio>

         - audio #2

Here is JSFIDDLE

A: You can use the ended event of the Audio API:
audio_element.addEventListener("ended", function() {

Here is what you should add to your code:
document.querySelectorAll('audio').forEach(function(el) {
  el.addEventListener("ended", function() {
    this.parentElement.querySelector('.control').className = 'control icon-play';
  }, true);
})

This is the change to your jsfiddle:
https://jsfiddle.net/71an95pa/4/


text:
Q: Application.sendkeys() does not work when concerned tab (in ribbon) is not visible I have XML mappings & a macro-button in my excel sheet (which fires this macro command) -
Sub Button2_Click()
Application.SendKeys ("%lt") '%lt (alt + L + T) - shortcut to import xml option in Developer tab
'above code opens import xml in Developer tab, enabling the user to import the XML file to map data.
End Sub

When I sent the sheet to my partners, they said the button doesn't work; Later I found out that in my computer's Excel the Developer tab (in ribbon) is visible, and in theirs it's not visible. I temporarily fixed the problem for my partners' computers (I enabled the Dev. tab & then it worked), but obviously I cannot fix for all my users, nor can I ask them to enable the developer tab on their excel. as most of them probably don't know how to enable it...
What should I do in order to invoke the Import XML action through macro (highlighted below), irrespective of whether the user has the Developer tab enabled or not? Kindly guide... Thanks!


text:
Q: While trying to reset root mysql password in ubuntu I get error while running 'sudo mysql -u root' command I have run into a very common problem while setting up a lamp stack in ubuntu. The problem that I got into is, I try to log into phpmyadmin using 'root' as username and a password that I set during instillation, I don't know if the password is wrong or I forget or something  else went wrong, any way I can't login. Now I search For the solution to reset the mysql password and I get the most suggested solution which is like below:
  sudo /etc/init.d/mysql stop
  sudo mysqld_safe --skip-grant-tables &
  sudo mysql -u root

And during this third step I get the error like below:
  ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

And Now I am stuck here, And I cannot reset password: So Help me

A: In /etc/my.cnf, the socket file config may be /tmp/mysql.sock and in /etc/mysql/my.cnf the socket file config may be /var/run/mysqld/mysqld.sock.
So, remove or rename /etc/mysql/my.cnf, let MYSQL use /etc/my.cnf, then the problem may be solved.

A: For me stopping and starting mysql did not help ('sudo /etc/init.d/mysql stop', 'sudo /etc/init.d/mysql start')
Because I had to use the command to stop mysql:
     sudo /etc/init.d/mysql stop
and then run other commands
     sudo mysqld_safe --skip-grant-tables &
     sudo mysql -u root
before starting mysql:
     sudo /etc/init.d/mysql start
But simply restarting my system that is my laptop solved my problem.


text:
Q: Suprema Biomini,How to Generate template from image Is it possible to generate the template from an image using Suprema sdk BioMini V3.7.5?
I have read the documentation but I can not find the option

A: The function is not supported even in the current version.
UFS_Extract and UFS_ExtractEx is for the image captured by using the BioMini device.
The below is just my opinion.

It may be hard to support the function. The resolution of the image is
  very important factor on processing to convert from an image to a
  template.


text:
Q: Google Line Chart show date range even with 'null' values Im having some issues figuring out how to have my Google Line Chart displaying the given date range in its data array, when it all contains null values from a given point.
I have specified data for 1 month, but I only got data up until 2th December. This causes the chart to automatically zoom its view from 12th November up until that date, and truncate the 10 last days.
This is my data:

And this is the chart as it is being displayed:

I could however change the null values to 0, but that would make the lines flatline for the rest of the days, and thats not optimal. However, I do want to visualize to the user, that there are no recorded data for those last 10 days.
Any help would be much appreciated

A: to fill the gaps from null values,
set option:
interpolateNulls: true

to set a specific date range on the x-axis,
use option:
hAxis: {
  viewWindow: {
    min: beginDate,
    max: endDate
  }
}

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = new google.visualization.DataTable();
  data.addColumn('date', 'x');
  data.addColumn('number', 'y');
  data.addRows([
    [new Date(2017, 11, 5), 3],
    [new Date(2017, 11, 6), 4],
    [new Date(2017, 11, 7), 4],
    [new Date(2017, 11, 8), 3],
    [new Date(2017, 11, 9), null],
    [new Date(2017, 11, 10), 4],
    [new Date(2017, 11, 11), null],
    [new Date(2017, 11, 12), 4]
  ]);

  var options = {
    interpolateNulls: true,
    hAxis: {
      viewWindow: {
        max: new Date(2017, 11, 31)
      }
    }
  };

  var chart = new google.visualization.LineChart(
    document.getElementById('chart_div')
  );
  chart.draw(data, options);
});


text:
Q: Material Design vs. Angular-Material vs. CSS-Frameworks I started developing my first website about 6 months ago and primarily used bulma as a css framework for making my life easier when it comes to styling. After using Angular-Material Components I now discovered the Material Design principles and really like them. Since there is a "redesign" planned for the website I would like to use this to use material design for the whole front end. I read a lot on material.io and material.angular.ui but I must say that I am very confused about how to actually use this design method for "simple" things that don't include their components. In bulma there is a css-selector for heading like <h1 class="is-title is-1"> and that's all I needed to do for having a nice heading.

*

*How do I achieve these things in material? Do I need bootstrap-material for that or must I write my own css classes?

*Is there a way to defined my theme ONCE and it works for material design AND angular material?
I basically have trouble finding a bulma-like documentation. It seems I am on the wrong path. If someone can provide a good blog post about my issue or explain a little bit what I REALLY need - that would be awesome.
Thank you a lot :)

A: Angular material and material design basically the same. Material design is abstract for mobile and web. Angular material is implemented for Angular. So if you use "Angular material" you are using "Material design".
Angular material concept predefined design with components and you can override style with non-capsule css.
So if you use <mat-icon> and icon name can be search from here: https://material.io/resources/icons/?style=baseline


text:
Q: Jquery -> Document.Ready -> Doesn't fire I'm running Mac OS 10.6, Chrome 34, and jQuery 2.1.1.
I have this simple code taken from TutsPlus '30 days to learn jQuery'.
I claim there's a bug in jQuery.
Or... you tell me! ;)
This doesn't work:

  <title> Does not work </title>
    //script is in root

Hello

Hello 2

Hello 3

This works:

  <title> </title>

Hello

Hello 2

Hello 3

A: Try to remove that additional parenthesis,
$(document).ready(function()){$('li:first-child').addClass('emphasis');});
//--------------------------^

valid code:
$(document).ready(function() {
  $('li:first-child').addClass('emphasis');
});

A: you mistakenly close the document ready function immedieatly. you closed extra one closed braces that why it will not work
$(document).ready(function() {
             $('li:first-child').addClass('emphasis');
});

A: Change below line

to ( as you got one extra ) after function())

A: You have to remove that close bracket which was added additionally.
$(document).ready(function(){
 $('li:first-child').addClass('emphasis');
});


text:
Q: How do I recompile my kernel without qt3? So I'm trying to recompile my kernel (it doesn't have uinput support but nm that). I followed the instructions on How to install needed Qt packages to build kernel on 14.04?
but
when I run ~/Downloads/linux-2.6.32.68$ make xconfig I get this.
CHECK qt
Unable to find the QT3 installation. Please make sure that the QT3 development package is correctly installed and either install pkg-config or set the QTDIR environment variable to the correct location.
make[1]: *** No rule to make target `scripts/kconfig/.tmp_qtcheck', needed by `scripts/kconfig/qconf.o'.  Stop. make: *** [xconfig] Error 2

I think this may be an upgrade error since even though I have qt5 it complains that it can't find qt3. Asside from Nuke and Pave how can I fix this?

A: Either you need to install some libraries do not exist for Trusty or you have to take the road for which the libraries are not needed.
To use
make xconfig

you have to install the QT3 libraries, and you could download and install the Precise packages. To do this, download libqt3-mt-dev and install with sudo dpkg -i. But you'll have to install many more dependencies.

But ;)
The only reason you need qt3 is because you ran make xconfig. There are other ways of configuring your kernel for compilation that don't require qt3. When I was young, I did it this way:
make menuconfig

Or, really old-shool:
make config

After the configuration steps, run
make -j3

if you have two cores (cores + 1)
make modules_install
make install


text:
Q: Setting dynamic ng-model names in AngularJS There are similar questions here and here, although my use-case is a little different.
I have an object called uniqueLists which looks like this:
$scope.uniqueLists - {
    name: [
            'string1',
            'string2',
            'string3'
            // Lots of strings
    ],
    Category: [
            'string1',
            'string2',
            'string3'
            // Lots of strings
    ],
    designer: [
            'string1',
            'string2',
            'string3'
            // Lots of strings
    ]
}

I'm trying to build a search function out of this list. Currently, I can display all the list items in checkboxes on the page like this (the following code uses Jade templating engine for Node/ExpressJS, it's easy enough to understand even if you're not familiar with it. Indent == child node of the line above it)
div(class="searchNav")
    p(ng-repeat="param in searchParams") {{param[0] + ' = ' + param[1]}}

    div.row-fluid(ng-repeat="(key,val) in uniqueLists")
        form(ng-model="???") {{key}}
            label.checkbox(ng-repeat="value in val")
                input(type="checkbox", ng-model="?????")
                {{value}}

The only part I'm having issues with is the ng-model of my form and checkboxes. I want the form's ng-model == {{key}}. I've tried setting that but it breaks Angular. I've also tried ng-model='uniqueLists[index][0]' but, again, Angular doesn't parse this and just makes every form's model the string uniqueLists[index][0].
Same deal with the input checkboxes, I want their ng-model="{{value}}". Is there a way to do this in my controller perhaps? I can't think of anything that will work inside of ng-repeat.
A small note to anyone who stumbles on this question
As you'll see in the answer/fiddle below, when you refer to object/positions in an ng-model they aren't rendered into their correct names in the DOM, but they seem to work with Angular as though they are.
For instance, in the above code, setting ng-model="uniqueLists[key][val]" renders in the DOM as ng-model="uniqueLists[key][val]", but behaves as though it's ng-model="uniqueLists[name][string1]".
Seems to be a bizarre quirk of Angular, this tripped me up because I was checking the ng-model names in my browser before hooking it up to my controller, and when I saw it wasn't parsing the object for the correct values I assumed it wasn't working.

A: I'm still not totally sure I understood all your problem, but I'll still give you this code : http://jsfiddle.net/DotDotDot/7AU6A/1/
To explain a bit, I used a slightly modified data sample (in order to have unique strings), and instead of creating a model simply equal to a defined {{value}} I've put all the models in an object, so you can easily go to object[key][value] (in your case it would be something like object['name']['string1']) and I associated those values to the checkboxes. The only thing I had to do is to create it from the data sample object, so it forces the controller to parse all the data once.
It's quite siple when you see it in action (the values are displayed at the bottom of the fiddle). Let's say you click on the checkbox name=> string2, the value of object['name']['string2'] will correspond to the state of the checkbox, which will be automatically watched by the ng-model.
When you have this, it's quite easy to modify each checkbox with your controller, so I added a little search function in order to show it in action, you can search a list of words separated with a space in the search box, then clicking on search will check the matching checkboxes
On the HTML side it's not a big modification (sorry I'm not familiar with your templates, it will be straight HTML)

       <form name='{{key}}'>
       {{key}}

                <input type='checkbox' ng-model='selectedData[key][value]' />{{value}}

        </form>

And on the controller side, this is how I initialize the models :
$scope.selectedData={};
for (var i in $scope.uniqueLists)
{
 $scope.selectedData[i]={}
     for(var j in $scope.uniqueLists[i])
     {
         $scope.selectedData[i][$scope.uniqueLists[i][j]]=false;
     }
}

The last part, the search function is only made of loops to iterate all the search/model values, I think this is what you will have to modify in order to match your own search controller
Is that what you wanted ?

A: @DotDotDot
I am faced with the same pb with _dynamic_names_, and fully understand the author of Q. With you example almost everything works fine EXCEPT (!) submitting. Please take a look into attached Screenshot.
With this example the ng-model  have to be dynamic, like:  selectedData_A_1,  selectedData_B_2,  selectedData_C_3, e.t.c ...
...only then, in case of using the HTML-Form-Submit will be able to decode the value of checkbox in relation with the name.


text:
Q: Jabber-Net release build fails to connect to XMPP Server I downloaded jabber-net source from http://code.google.com/p/jabber-net/. Open the .sln file (2005-jabber-net.sln) in VS 2005/08, set "2005-Example" as active project, build it in Debug mode, connect to a XMPP Server, after connect() method is called, the callback jc_OnAuthenticate() gets called which means the application is connected to XMPP Server.

Then i build the .sln in Release Mode, ran the same example again, this time after connect() call nothing happens, the callback jc_OnAuthenticate() doesn't get called ever. Is it a known issue with jabber-net?

A: There is some code in Debug.Assert statements such as:
\jabber\protocol\EnumParser.cs(184):
Debug.Assert(map.TryGetValue(value, out val));

I rewrote to:
bool b = map.TryGetValue(value, out val);
Debug.Assert(b);

Works (at least for me).


text:
Q: Replace images that does not exist in htaccess After series of search on stackoverflow, i got these two working htaccess codes, however, i'm confused which one is better.
Actually both works fine but is there any difference in performance or speed?
<FilesMatch "\.(jpg|jpeg|png|gif)$">
ErrorDocument 404 "/no_profile_picture.png"
</FilesMatch>

and
RewriteEngine On
RewriteCond %{REQUEST_URI} \.(jpg|jpeg|gif|png|ico)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* /no_profile_picture.png [L]

A: Both directives will serve the core purpose of showing /no_profile_picture.png when an image with jpg|jpeg|gif|png|ico extensions is not found inside your site root. However there is a subtle difference.
<FilesMatch "\.(jpg|jpeg|png|gif)$">
ErrorDocument 404 "/no_profile_picture.png"
</FilesMatch>

This directive will also return 404 (Http NotFound) status to browser/client but the other block will still return 200 (Http OK) status back to clients. So I suggest going with FilesMatch block for correctly showing desired non-found image and returning 404 to clients.


text:
Q: How to get into TextBox which is placed inside of repeater? So, I have a repeater that prints out category names from database, each of those category names have under it TextBox and button, so that I could edit its name If I would like to, but... yeah, there is always one but. I simple can't reach the TextBox which is repeated, it tells me that TextBox_Update does not exist in current context.
    protected void Button1_Click(object sender, EventArgs e)
{

    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
    {
        SqlCommand cmd = new SqlCommand();

        cmd.Connection = conn;
        cmd.CommandText = @"UPDATE [categories] SET [category_name] = @category_name WHERE [category_id] = @category_id";
        cmd.Parameters.AddWithValue("@category_name", TextBox1.Text);
        cmd.Parameters.AddWithValue("@category_id", Request["id"]);
        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
    }
    Response.Redirect("default.aspx");

}

This is the way I tried to update it but... tells me that textbox does not exist at all.
Here is how it looks like in html
<asp:Repeater ID="Repeater_Categories" runat="server" >
    <HeaderTemplate>

Categories

    </HeaderTemplate>
    <ItemTemplate>

<%# Eval("category_name") %>

                    <asp:TextBox ID="TextBox1" runat="server"     ValidationGroup="3"></asp:TextBox>

                    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" ValidationGroup="3" />
                    <a href="?action=delete&id=<%# Eval("category_id") %>">Del

    </ItemTemplate>
    <FooterTemplate>

    </FooterTemplate>
</asp:Repeater>

Probably doing something terribly wrong, I'm desperated for help ;<
@Edit
Fixed TextBox names..

A: You should search for the TextBox to get a reference, and then use that reference to update its properties.
TextBox txt1 = Repeater_Categories.FindControls("TextBox1") as TextBox;